diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/gen_audio_microfrontend_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/gen_audio_microfrontend_op.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4c1b41fa0ea371416e6416743d5ea458e1f294 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/ops/gen_audio_microfrontend_op.py @@ -0,0 +1,423 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +TV_AudioMicrofrontend_out_type = TypeVar("TV_AudioMicrofrontend_out_type", _atypes.Float32, _atypes.UInt16) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('audio_microfrontend') +def audio_microfrontend(audio: Annotated[Any, _atypes.Int16], sample_rate:int=16000, window_size:int=25, window_step:int=10, num_channels:int=32, upper_band_limit:float=7500, lower_band_limit:float=125, smoothing_bits:int=10, even_smoothing:float=0.025, odd_smoothing:float=0.06, min_signal_remaining:float=0.05, enable_pcan:bool=False, pcan_strength:float=0.95, pcan_offset:float=80, gain_bits:int=21, enable_log:bool=True, scale_shift:int=6, left_context:int=0, right_context:int=0, frame_stride:int=1, zero_padding:bool=False, out_scale:int=1, out_type:TV_AudioMicrofrontend_out_type=_dtypes.uint16, name=None) -> Annotated[Any, TV_AudioMicrofrontend_out_type]: + r"""Audio Microfrontend Op. + + This Op converts a sequence of audio data into one or more + feature vectors containing filterbanks of the input. The + conversion process uses a lightweight library to perform: + + 1. A slicing window function + 2. Short-time FFTs + 3. Filterbank calculations + 4. Noise reduction + 5. PCAN Auto Gain Control + 6. Logarithmic scaling + + Arguments + audio: 1D Tensor, int16 audio data in temporal ordering. + sample_rate: Integer, the sample rate of the audio in Hz. + window_size: Integer, length of desired time frames in ms. + window_step: Integer, length of step size for the next frame in ms. + num_channels: Integer, the number of filterbank channels to use. + upper_band_limit: Float, the highest frequency included in the filterbanks. + lower_band_limit: Float, the lowest frequency included in the filterbanks. + smoothing_bits: Int, scale up signal by 2^(smoothing_bits) before reduction. + even_smoothing: Float, smoothing coefficient for even-numbered channels. + odd_smoothing: Float, smoothing coefficient for odd-numbered channels. + min_signal_remaining: Float, fraction of signal to preserve in smoothing. + enable_pcan: Bool, enable PCAN auto gain control. + pcan_strength: Float, gain normalization exponent. + pcan_offset: Float, positive value added in the normalization denominator. + gain_bits: Int, number of fractional bits in the gain. + enable_log: Bool, enable logarithmic scaling of filterbanks. + scale_shift: Integer, scale filterbanks by 2^(scale_shift). + left_context: Integer, number of preceding frames to attach to each frame. + right_context: Integer, number of preceding frames to attach to each frame. + frame_stride: Integer, M frames to skip over, where output[n] = frame[n*M]. + zero_padding: Bool, if left/right context is out-of-bounds, attach frame of + zeroes. Otherwise, frame[0] or frame[size-1] will be copied. + out_scale: Integer, divide all filterbanks by this number. + out_type: DType, type of the output Tensor, defaults to UINT16. + + Returns + filterbanks: 2D Tensor, each row is a time frame, each column is a channel. + + Args: + audio: A `Tensor` of type `int16`. + sample_rate: An optional `int`. Defaults to `16000`. + window_size: An optional `int`. Defaults to `25`. + window_step: An optional `int`. Defaults to `10`. + num_channels: An optional `int`. Defaults to `32`. + upper_band_limit: An optional `float`. Defaults to `7500`. + lower_band_limit: An optional `float`. Defaults to `125`. + smoothing_bits: An optional `int`. Defaults to `10`. + even_smoothing: An optional `float`. Defaults to `0.025`. + odd_smoothing: An optional `float`. Defaults to `0.06`. + min_signal_remaining: An optional `float`. Defaults to `0.05`. + enable_pcan: An optional `bool`. Defaults to `False`. + pcan_strength: An optional `float`. Defaults to `0.95`. + pcan_offset: An optional `float`. Defaults to `80`. + gain_bits: An optional `int`. Defaults to `21`. + enable_log: An optional `bool`. Defaults to `True`. + scale_shift: An optional `int`. Defaults to `6`. + left_context: An optional `int`. Defaults to `0`. + right_context: An optional `int`. Defaults to `0`. + frame_stride: An optional `int`. Defaults to `1`. + zero_padding: An optional `bool`. Defaults to `False`. + out_scale: An optional `int`. Defaults to `1`. + out_type: An optional `tf.DType` from: `tf.uint16, tf.float32`. Defaults to `tf.uint16`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `out_type`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AudioMicrofrontend", name, audio, "sample_rate", sample_rate, + "window_size", window_size, "window_step", window_step, + "num_channels", num_channels, "upper_band_limit", upper_band_limit, + "lower_band_limit", lower_band_limit, "smoothing_bits", + smoothing_bits, "even_smoothing", even_smoothing, "odd_smoothing", + odd_smoothing, "min_signal_remaining", min_signal_remaining, + "enable_pcan", enable_pcan, "pcan_strength", pcan_strength, + "pcan_offset", pcan_offset, "gain_bits", gain_bits, "enable_log", + enable_log, "scale_shift", scale_shift, "left_context", left_context, + "right_context", right_context, "frame_stride", frame_stride, + "zero_padding", zero_padding, "out_scale", out_scale, "out_type", + out_type) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_audio_microfrontend( + (audio, sample_rate, window_size, window_step, num_channels, + upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing, + odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength, + pcan_offset, gain_bits, enable_log, scale_shift, left_context, + right_context, frame_stride, zero_padding, out_scale, out_type, + name,), None) + if _result is not NotImplemented: + return _result + return audio_microfrontend_eager_fallback( + audio, sample_rate=sample_rate, window_size=window_size, + window_step=window_step, num_channels=num_channels, + upper_band_limit=upper_band_limit, + lower_band_limit=lower_band_limit, smoothing_bits=smoothing_bits, + even_smoothing=even_smoothing, odd_smoothing=odd_smoothing, + min_signal_remaining=min_signal_remaining, enable_pcan=enable_pcan, + pcan_strength=pcan_strength, pcan_offset=pcan_offset, + gain_bits=gain_bits, enable_log=enable_log, scale_shift=scale_shift, + left_context=left_context, right_context=right_context, + frame_stride=frame_stride, zero_padding=zero_padding, + out_scale=out_scale, out_type=out_type, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + audio_microfrontend, (), dict(audio=audio, + sample_rate=sample_rate, + window_size=window_size, + window_step=window_step, + num_channels=num_channels, + upper_band_limit=upper_band_limit, + lower_band_limit=lower_band_limit, + smoothing_bits=smoothing_bits, + even_smoothing=even_smoothing, + odd_smoothing=odd_smoothing, + min_signal_remaining=min_signal_remaining, + enable_pcan=enable_pcan, + pcan_strength=pcan_strength, + pcan_offset=pcan_offset, + gain_bits=gain_bits, + enable_log=enable_log, + scale_shift=scale_shift, + left_context=left_context, + right_context=right_context, + frame_stride=frame_stride, + zero_padding=zero_padding, + out_scale=out_scale, + out_type=out_type, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_audio_microfrontend( + (audio, sample_rate, window_size, window_step, num_channels, + upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing, + odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength, + pcan_offset, gain_bits, enable_log, scale_shift, left_context, + right_context, frame_stride, zero_padding, out_scale, out_type, + name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if sample_rate is None: + sample_rate = 16000 + sample_rate = _execute.make_int(sample_rate, "sample_rate") + if window_size is None: + window_size = 25 + window_size = _execute.make_int(window_size, "window_size") + if window_step is None: + window_step = 10 + window_step = _execute.make_int(window_step, "window_step") + if num_channels is None: + num_channels = 32 + num_channels = _execute.make_int(num_channels, "num_channels") + if upper_band_limit is None: + upper_band_limit = 7500 + upper_band_limit = _execute.make_float(upper_band_limit, "upper_band_limit") + if lower_band_limit is None: + lower_band_limit = 125 + lower_band_limit = _execute.make_float(lower_band_limit, "lower_band_limit") + if smoothing_bits is None: + smoothing_bits = 10 + smoothing_bits = _execute.make_int(smoothing_bits, "smoothing_bits") + if even_smoothing is None: + even_smoothing = 0.025 + even_smoothing = _execute.make_float(even_smoothing, "even_smoothing") + if odd_smoothing is None: + odd_smoothing = 0.06 + odd_smoothing = _execute.make_float(odd_smoothing, "odd_smoothing") + if min_signal_remaining is None: + min_signal_remaining = 0.05 + min_signal_remaining = _execute.make_float(min_signal_remaining, "min_signal_remaining") + if enable_pcan is None: + enable_pcan = False + enable_pcan = _execute.make_bool(enable_pcan, "enable_pcan") + if pcan_strength is None: + pcan_strength = 0.95 + pcan_strength = _execute.make_float(pcan_strength, "pcan_strength") + if pcan_offset is None: + pcan_offset = 80 + pcan_offset = _execute.make_float(pcan_offset, "pcan_offset") + if gain_bits is None: + gain_bits = 21 + gain_bits = _execute.make_int(gain_bits, "gain_bits") + if enable_log is None: + enable_log = True + enable_log = _execute.make_bool(enable_log, "enable_log") + if scale_shift is None: + scale_shift = 6 + scale_shift = _execute.make_int(scale_shift, "scale_shift") + if left_context is None: + left_context = 0 + left_context = _execute.make_int(left_context, "left_context") + if right_context is None: + right_context = 0 + right_context = _execute.make_int(right_context, "right_context") + if frame_stride is None: + frame_stride = 1 + frame_stride = _execute.make_int(frame_stride, "frame_stride") + if zero_padding is None: + zero_padding = False + zero_padding = _execute.make_bool(zero_padding, "zero_padding") + if out_scale is None: + out_scale = 1 + out_scale = _execute.make_int(out_scale, "out_scale") + if out_type is None: + out_type = _dtypes.uint16 + out_type = _execute.make_type(out_type, "out_type") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AudioMicrofrontend", audio=audio, sample_rate=sample_rate, + window_size=window_size, + window_step=window_step, + num_channels=num_channels, + upper_band_limit=upper_band_limit, + lower_band_limit=lower_band_limit, + smoothing_bits=smoothing_bits, + even_smoothing=even_smoothing, + odd_smoothing=odd_smoothing, + min_signal_remaining=min_signal_remaining, + enable_pcan=enable_pcan, + pcan_strength=pcan_strength, + pcan_offset=pcan_offset, gain_bits=gain_bits, + enable_log=enable_log, scale_shift=scale_shift, + left_context=left_context, + right_context=right_context, + frame_stride=frame_stride, + zero_padding=zero_padding, out_scale=out_scale, + out_type=out_type, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + audio_microfrontend, (), dict(audio=audio, sample_rate=sample_rate, + window_size=window_size, + window_step=window_step, + num_channels=num_channels, + upper_band_limit=upper_band_limit, + lower_band_limit=lower_band_limit, + smoothing_bits=smoothing_bits, + even_smoothing=even_smoothing, + odd_smoothing=odd_smoothing, + min_signal_remaining=min_signal_remaining, + enable_pcan=enable_pcan, + pcan_strength=pcan_strength, + pcan_offset=pcan_offset, + gain_bits=gain_bits, + enable_log=enable_log, + scale_shift=scale_shift, + left_context=left_context, + right_context=right_context, + frame_stride=frame_stride, + zero_padding=zero_padding, + out_scale=out_scale, + out_type=out_type, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("sample_rate", _op._get_attr_int("sample_rate"), "window_size", + _op._get_attr_int("window_size"), "window_step", + _op._get_attr_int("window_step"), "num_channels", + _op._get_attr_int("num_channels"), "upper_band_limit", + _op.get_attr("upper_band_limit"), "lower_band_limit", + _op.get_attr("lower_band_limit"), "smoothing_bits", + _op._get_attr_int("smoothing_bits"), "even_smoothing", + _op.get_attr("even_smoothing"), "odd_smoothing", + _op.get_attr("odd_smoothing"), "min_signal_remaining", + _op.get_attr("min_signal_remaining"), "enable_pcan", + _op._get_attr_bool("enable_pcan"), "pcan_strength", + _op.get_attr("pcan_strength"), "pcan_offset", + _op.get_attr("pcan_offset"), "gain_bits", + _op._get_attr_int("gain_bits"), "enable_log", + _op._get_attr_bool("enable_log"), "scale_shift", + _op._get_attr_int("scale_shift"), "left_context", + _op._get_attr_int("left_context"), "right_context", + _op._get_attr_int("right_context"), "frame_stride", + _op._get_attr_int("frame_stride"), "zero_padding", + _op._get_attr_bool("zero_padding"), "out_scale", + _op._get_attr_int("out_scale"), "out_type", + _op._get_attr_type("out_type")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "AudioMicrofrontend", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +AudioMicrofrontend = tf_export("raw_ops.AudioMicrofrontend")(_ops.to_raw_op(audio_microfrontend)) +_dispatcher_for_audio_microfrontend = audio_microfrontend._tf_type_based_dispatcher.Dispatch + + +def audio_microfrontend_eager_fallback(audio: Annotated[Any, _atypes.Int16], sample_rate: int, window_size: int, window_step: int, num_channels: int, upper_band_limit: float, lower_band_limit: float, smoothing_bits: int, even_smoothing: float, odd_smoothing: float, min_signal_remaining: float, enable_pcan: bool, pcan_strength: float, pcan_offset: float, gain_bits: int, enable_log: bool, scale_shift: int, left_context: int, right_context: int, frame_stride: int, zero_padding: bool, out_scale: int, out_type: TV_AudioMicrofrontend_out_type, name, ctx) -> Annotated[Any, TV_AudioMicrofrontend_out_type]: + if sample_rate is None: + sample_rate = 16000 + sample_rate = _execute.make_int(sample_rate, "sample_rate") + if window_size is None: + window_size = 25 + window_size = _execute.make_int(window_size, "window_size") + if window_step is None: + window_step = 10 + window_step = _execute.make_int(window_step, "window_step") + if num_channels is None: + num_channels = 32 + num_channels = _execute.make_int(num_channels, "num_channels") + if upper_band_limit is None: + upper_band_limit = 7500 + upper_band_limit = _execute.make_float(upper_band_limit, "upper_band_limit") + if lower_band_limit is None: + lower_band_limit = 125 + lower_band_limit = _execute.make_float(lower_band_limit, "lower_band_limit") + if smoothing_bits is None: + smoothing_bits = 10 + smoothing_bits = _execute.make_int(smoothing_bits, "smoothing_bits") + if even_smoothing is None: + even_smoothing = 0.025 + even_smoothing = _execute.make_float(even_smoothing, "even_smoothing") + if odd_smoothing is None: + odd_smoothing = 0.06 + odd_smoothing = _execute.make_float(odd_smoothing, "odd_smoothing") + if min_signal_remaining is None: + min_signal_remaining = 0.05 + min_signal_remaining = _execute.make_float(min_signal_remaining, "min_signal_remaining") + if enable_pcan is None: + enable_pcan = False + enable_pcan = _execute.make_bool(enable_pcan, "enable_pcan") + if pcan_strength is None: + pcan_strength = 0.95 + pcan_strength = _execute.make_float(pcan_strength, "pcan_strength") + if pcan_offset is None: + pcan_offset = 80 + pcan_offset = _execute.make_float(pcan_offset, "pcan_offset") + if gain_bits is None: + gain_bits = 21 + gain_bits = _execute.make_int(gain_bits, "gain_bits") + if enable_log is None: + enable_log = True + enable_log = _execute.make_bool(enable_log, "enable_log") + if scale_shift is None: + scale_shift = 6 + scale_shift = _execute.make_int(scale_shift, "scale_shift") + if left_context is None: + left_context = 0 + left_context = _execute.make_int(left_context, "left_context") + if right_context is None: + right_context = 0 + right_context = _execute.make_int(right_context, "right_context") + if frame_stride is None: + frame_stride = 1 + frame_stride = _execute.make_int(frame_stride, "frame_stride") + if zero_padding is None: + zero_padding = False + zero_padding = _execute.make_bool(zero_padding, "zero_padding") + if out_scale is None: + out_scale = 1 + out_scale = _execute.make_int(out_scale, "out_scale") + if out_type is None: + out_type = _dtypes.uint16 + out_type = _execute.make_type(out_type, "out_type") + audio = _ops.convert_to_tensor(audio, _dtypes.int16) + _inputs_flat = [audio] + _attrs = ("sample_rate", sample_rate, "window_size", window_size, + "window_step", window_step, "num_channels", num_channels, + "upper_band_limit", upper_band_limit, "lower_band_limit", lower_band_limit, + "smoothing_bits", smoothing_bits, "even_smoothing", even_smoothing, + "odd_smoothing", odd_smoothing, "min_signal_remaining", + min_signal_remaining, "enable_pcan", enable_pcan, "pcan_strength", + pcan_strength, "pcan_offset", pcan_offset, "gain_bits", gain_bits, + "enable_log", enable_log, "scale_shift", scale_shift, "left_context", + left_context, "right_context", right_context, "frame_stride", frame_stride, + "zero_padding", zero_padding, "out_scale", out_scale, "out_type", out_type) + _result = _execute.execute(b"AudioMicrofrontend", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "AudioMicrofrontend", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9cfe21e667f8b1a5cf45fc5b6caaad013b6eea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/experimental/microfrontend/python/ops/audio_microfrontend_op.py @@ -0,0 +1,110 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""AudioMicrofrontend Op creates filterbanks from audio data.""" + +from tensorflow.lite.experimental.microfrontend.ops import gen_audio_microfrontend_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import load_library +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import resource_loader + +_audio_microfrontend_op = load_library.load_op_library( + resource_loader.get_path_to_datafile("_audio_microfrontend_op.so")) + + +def audio_microfrontend(audio, + sample_rate=16000, + window_size=25, + window_step=10, + num_channels=32, + upper_band_limit=7500.0, + lower_band_limit=125.0, + smoothing_bits=10, + even_smoothing=0.025, + odd_smoothing=0.06, + min_signal_remaining=0.05, + enable_pcan=True, + pcan_strength=0.95, + pcan_offset=80.0, + gain_bits=21, + enable_log=True, + scale_shift=6, + left_context=0, + right_context=0, + frame_stride=1, + zero_padding=False, + out_scale=1, + out_type=dtypes.uint16): + """Audio Microfrontend Op. + + This Op converts a sequence of audio data into one or more + feature vectors containing filterbanks of the input. The + conversion process uses a lightweight library to perform: + + 1. A slicing window function + 2. Short-time FFTs + 3. Filterbank calculations + 4. Noise reduction + 5. PCAN Auto Gain Control + 6. Logarithmic scaling + + Args: + audio: 1D Tensor, int16 audio data in temporal ordering. + sample_rate: Integer, the sample rate of the audio in Hz. + window_size: Integer, length of desired time frames in ms. + window_step: Integer, length of step size for the next frame in ms. + num_channels: Integer, the number of filterbank channels to use. + upper_band_limit: Float, the highest frequency included in the filterbanks. + lower_band_limit: Float, the lowest frequency included in the filterbanks. + smoothing_bits: Int, scale up signal by 2^(smoothing_bits) before reduction. + even_smoothing: Float, smoothing coefficient for even-numbered channels. + odd_smoothing: Float, smoothing coefficient for odd-numbered channels. + min_signal_remaining: Float, fraction of signal to preserve in smoothing. + enable_pcan: Bool, enable PCAN auto gain control. + pcan_strength: Float, gain normalization exponent. + pcan_offset: Float, positive value added in the normalization denominator. + gain_bits: Int, number of fractional bits in the gain. + enable_log: Bool, enable logarithmic scaling of filterbanks. + scale_shift: Integer, scale filterbanks by 2^(scale_shift). + left_context: Integer, number of preceding frames to attach to each frame. + right_context: Integer, number of preceding frames to attach to each frame. + frame_stride: Integer, M frames to skip over, where output[n] = frame[n*M]. + zero_padding: Bool, if left/right context is out-of-bounds, attach frame of + zeroes. Otherwise, frame[0] or frame[size-1] will be copied. + out_scale: Integer, divide all filterbanks by this number. + out_type: DType, type of the output Tensor, defaults to UINT16. + + Returns: + filterbanks: 2D Tensor, each row is a time frame, each column is a channel. + + Raises: + ValueError: If the audio tensor is not explicitly a vector. + """ + audio_shape = audio.shape + if audio_shape.ndims is None: + raise ValueError("Input to `AudioMicrofrontend` should have known rank.") + if len(audio_shape) > 1: + audio = array_ops.reshape(audio, [-1]) + + return gen_audio_microfrontend_op.audio_microfrontend( + audio, sample_rate, window_size, window_step, num_channels, + upper_band_limit, lower_band_limit, smoothing_bits, even_smoothing, + odd_smoothing, min_signal_remaining, enable_pcan, pcan_strength, + pcan_offset, gain_bits, enable_log, scale_shift, left_context, + right_context, frame_stride, zero_padding, out_scale, out_type) + + +ops.NotDifferentiable("AudioMicrofrontend") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..9f9617540ea33c4cac4a85285f9a526c7794d70f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer.py @@ -0,0 +1,105 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""This tool analyzes a TensorFlow Lite graph.""" + +import os + +# pylint: disable=g-import-not-at-top +if not os.path.splitext(__file__)[0].endswith( + os.path.join("tflite_runtime", "analyzer")): + # This file is part of tensorflow package. + from tensorflow.lite.python import wrap_toco + from tensorflow.lite.python.analyzer_wrapper import _pywrap_analyzer_wrapper as _analyzer_wrapper + from tensorflow.python.util.tf_export import tf_export as _tf_export +else: + # This file is part of tflite_runtime package. + from tflite_runtime import _pywrap_analyzer_wrapper as _analyzer_wrapper + + def _tf_export(*x, **kwargs): + del x, kwargs + return lambda x: x + + +@_tf_export("lite.experimental.Analyzer") +class ModelAnalyzer(): + """Provides a collection of TFLite model analyzer tools. + + Example: + + ```python + model = tf.keras.applications.MobileNetV3Large() + fb_model = tf.lite.TFLiteConverterV2.from_keras_model(model).convert() + tf.lite.experimental.Analyzer.analyze(model_content=fb_model) + # === TFLite ModelAnalyzer === + # + # Your TFLite model has ‘1’ subgraph(s). In the subgraph description below, + # T# represents the Tensor numbers. For example, in Subgraph#0, the MUL op + # takes tensor #0 and tensor #19 as input and produces tensor #136 as output. + # + # Subgraph#0 main(T#0) -> [T#263] + # Op#0 MUL(T#0, T#19) -> [T#136] + # Op#1 ADD(T#136, T#18) -> [T#137] + # Op#2 CONV_2D(T#137, T#44, T#93) -> [T#138] + # Op#3 HARD_SWISH(T#138) -> [T#139] + # Op#4 DEPTHWISE_CONV_2D(T#139, T#94, T#24) -> [T#140] + # ... + ``` + + WARNING: Experimental interface, subject to change. + """ + + @staticmethod + def analyze(model_path=None, + model_content=None, + gpu_compatibility=False, + **kwargs): + """Analyzes the given tflite_model with dumping model structure. + + This tool provides a way to understand users' TFLite flatbuffer model by + dumping internal graph structure. It also provides additional features + like checking GPU delegate compatibility. + + WARNING: Experimental interface, subject to change. + The output format is not guaranteed to stay stable, so don't + write scripts to this. + + Args: + model_path: TFLite flatbuffer model path. + model_content: TFLite flatbuffer model object. + gpu_compatibility: Whether to check GPU delegate compatibility. + **kwargs: Experimental keyword arguments to analyze API. + + Returns: + Print analyzed report via console output. + """ + if not model_path and not model_content: + raise ValueError("neither `model_path` nor `model_content` is provided") + if model_path: + print(f"=== {model_path} ===\n") + tflite_model = model_path + input_is_filepath = True + else: + print("=== TFLite ModelAnalyzer ===\n") + tflite_model = model_content + input_is_filepath = False + + if kwargs.get("experimental_use_mlir", False): + print( + wrap_toco.wrapped_flat_buffer_file_to_mlir(tflite_model, + input_is_filepath)) + else: + print( + _analyzer_wrapper.ModelAnalyzer(tflite_model, input_is_filepath, + gpu_compatibility)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0181580f660c3cbf48ec64de0449d42161f0bf92 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/analyzer_wrapper/_pywrap_analyzer_wrapper.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def ModelAnalyzer(arg0: str, arg1: bool, arg2: bool) -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/authoring.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/authoring.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a8df467327cf5d855653367452a5ed79413b66 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/authoring/authoring.py @@ -0,0 +1,303 @@ +# 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. +# ============================================================================== +"""TensorFlow Authoring tool package for TFLite compatibility. + +WARNING: The package is experimental and subject to change. + +This package provides a way to check TFLite compatibility at model authoring +time. + +Example: + @tf.lite.experimental.authoring.compatible + @tf.function(input_signature=[ + tf.TensorSpec(shape=[None], dtype=tf.float32) + ]) + def f(x): + return tf.cosh(x) + + result = f(tf.constant([0.0])) + + > COMPATIBILITY WARNING: op 'tf.Cosh' require(s) "Select TF Ops" for model + > conversion for TensorFlow Lite. + > Op: tf.Cosh + > - tensorflow/python/framework/op_def_library.py:xxx + > - tensorflow/python/ops/gen_math_ops.py:xxx + > - simple_authoring.py:xxx +""" +import functools + + +# pylint: disable=g-import-not-at-top +from tensorflow.lite.python import convert +from tensorflow.lite.python import lite +from tensorflow.lite.python.metrics import converter_error_data_pb2 +from tensorflow.python.util.tf_export import tf_export as _tf_export + + +_CUSTOM_OPS_HDR = "Custom ops: " +_TF_OPS_HDR = "TF Select ops: " +_AUTHORING_ERROR_HDR = "COMPATIBILITY ERROR" +_AUTHORING_WARNING_HDR = "COMPATIBILITY WARNING" +_FUNC_GRAPH_SRC_PATH = "tensorflow/python/framework/func_graph.py" + + +class CompatibilityError(Exception): + """Raised when an error occurs with TFLite compatibility.""" + pass + + +class _Compatible: + """A decorator class to check TFLite compatibility created by `lite.experimental.authoring.compatible`.""" + + def __init__(self, + target, + converter_target_spec=None, + converter_allow_custom_ops=None, + raise_exception=False): + """Initialize the decorator object. + + Here is the description of the object variables. + - _func : decorated function. + - _obj_func : for class object, we need to use this object to provide `self` + instance as 1 first argument. + - _verified : whether the compatibility is checked or not. + + Args: + target: decorated function. + converter_target_spec : target_spec of TFLite converter parameter. + converter_allow_custom_ops : allow_custom_ops of TFLite converter + parameter. + raise_exception : to raise an exception on compatibility issues. + User need to use get_compatibility_log() to check details. + """ + functools.update_wrapper(self, target) + self._func = target + self._obj_func = None + self._verified = False + self._log_messages = [] + self._raise_exception = raise_exception + self._converter_target_spec = converter_target_spec + self._converter_allow_custom_ops = converter_allow_custom_ops + + def __get__(self, instance, cls): + """A Python descriptor interface.""" + self._obj_func = self._func.__get__(instance, cls) + return self + + def _get_func(self): + """Returns decorated function object. + + For a class method, use self._obj_func to provide `self` instance. + """ + if self._obj_func is not None: + return self._obj_func + else: + return self._func + + def __call__(self, *args, **kwargs): # pylint: disable=g-doc-args + """Calls decorated function object. + + Also verifies if the function is compatible with TFLite. + + Returns: + A execution result of the decorated function. + """ + + if not self._verified: + model = self._get_func() + concrete_func = model.get_concrete_function(*args, **kwargs) + converter = lite.TFLiteConverterV2.from_concrete_functions( + [concrete_func], model) + # Set provided converter parameters + if self._converter_target_spec is not None: + converter.target_spec = self._converter_target_spec + if self._converter_allow_custom_ops is not None: + converter.allow_custom_ops = self._converter_allow_custom_ops + try: + converter.convert() + except convert.ConverterError as err: + self._decode_error(err) + finally: + self._verified = True + + return self._get_func()(*args, **kwargs) + + def get_concrete_function(self, *args, **kwargs): + """Returns a concrete function of the decorated function.""" + return self._get_func().get_concrete_function(*args, **kwargs) + + def _get_location_string(self, location): + """Dump location of ConveterError.errors.location.""" + callstack = [] + for single_call in reversed(location.call): + if (location.type == + converter_error_data_pb2.ConverterErrorData.CALLSITELOC): + callstack.append( + f" - {single_call.source.filename}:{single_call.source.line}") + else: + callstack.append(str(single_call)) + callstack_dump = "\n".join(callstack) + return callstack_dump + + def _dump_error_details(self, ops, locations): + """Dump the list of ops and locations.""" + for i in range(0, len(ops)): + callstack_dump = self._get_location_string(locations[i]) + err_string = f"Op: {ops[i]}\n{callstack_dump}\n" + self._log(err_string) + + def _decode_error_legacy(self, err): + """Parses the given legacy ConverterError for OSS.""" + for line in str(err).splitlines(): + # Check custom op usage error. + if line.startswith(_CUSTOM_OPS_HDR): + custom_ops = line[len(_CUSTOM_OPS_HDR):] + err_string = ( + f"{_AUTHORING_ERROR_HDR}: op '{custom_ops}' is(are) not natively " + "supported by TensorFlow Lite. You need to provide a custom " + "operator. https://www.tensorflow.org/lite/guide/ops_custom") + self._log(err_string) + # Check TensorFlow op usage error. + elif line.startswith(_TF_OPS_HDR): + tf_ops = line[len(_TF_OPS_HDR):] + err_string = ( + f"{_AUTHORING_WARNING_HDR}: op '{tf_ops}' require(s) \"Select TF " + "Ops\" for model conversion for TensorFlow Lite. " + "https://www.tensorflow.org/lite/guide/ops_select") + self._log(err_string) + + def _decode_converter_error(self, err): + """Parses the given ConverterError which has detailed error information.""" + custom_ops = [] + custom_ops_location = [] + tf_ops = [] + tf_ops_location = [] + gpu_not_compatible_ops = [] + for err in err.errors: + # Check custom op usage error. + if err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_NEEDS_CUSTOM_OPS: + custom_ops.append(err.operator.name) + custom_ops_location.append(err.location) + # Check TensorFlow op usage error. + elif err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_NEEDS_FLEX_OPS: + tf_ops.append(err.operator.name) + tf_ops_location.append(err.location) + # Check GPU delegate compatibility error. + elif err.error_code == converter_error_data_pb2.ConverterErrorData.ERROR_GPU_NOT_COMPATIBLE: + gpu_not_compatible_ops.append(err.operator.name) + # Log the first line of ConveterError.errors.error_message only + # since the seond line is "Error code: xxxx" + self._log(err.error_message.splitlines()[0]) + self._log(self._get_location_string(err.location) + "\n") + else: + # Log other errors. + self._log(f"{_AUTHORING_ERROR_HDR}: {err.error_message}") + self._log(self._get_location_string(err.location) + "\n") + + if custom_ops: + custom_ops_str = ", ".join(sorted(custom_ops)) + err_string = ( + f"{_AUTHORING_ERROR_HDR}: op '{custom_ops_str}' is(are) not natively " + "supported by TensorFlow Lite. You need to provide a custom " + "operator. https://www.tensorflow.org/lite/guide/ops_custom") + self._log(err_string) + self._dump_error_details(custom_ops, custom_ops_location) + + if tf_ops: + tf_ops_str = ", ".join(sorted(tf_ops)) + err_string = ( + f"{_AUTHORING_WARNING_HDR}: op '{tf_ops_str}' require(s) \"Select TF" + " Ops\" for model conversion for TensorFlow Lite. " + "https://www.tensorflow.org/lite/guide/ops_select") + self._log(err_string) + self._dump_error_details(tf_ops, tf_ops_location) + + if gpu_not_compatible_ops: + not_compatible_ops_str = ", ".join(sorted(gpu_not_compatible_ops)) + err_string = ( + f"{_AUTHORING_WARNING_HDR}: op '{not_compatible_ops_str}' aren't " + "compatible with TensorFlow Lite GPU delegate. " + "https://www.tensorflow.org/lite/performance/gpu") + self._log(err_string) + + def _decode_error(self, err): + """Parses the given ConverterError and generates compatibility warnings.""" + if hasattr(err, "errors"): + self._decode_converter_error(err) + else: + self._decode_error_legacy(err) + + if self._raise_exception and self._log_messages: + raise CompatibilityError(f"CompatibilityException at {repr(self._func)}") + + def _log(self, message): + """Log and print authoring warning / error message.""" + self._log_messages.append(message) + print(message) + + def get_compatibility_log(self): + """Returns list of compatibility log messages. + + WARNING: This method should only be used for unit tests. + + Returns: + The list of log messages by the recent compatibility check. + Raises: + RuntimeError: when the compatibility was NOT checked. + """ + if not self._verified: + raise RuntimeError("target compatibility isn't verified yet") + return self._log_messages + + +@_tf_export("lite.experimental.authoring.compatible") +def compatible(target=None, converter_target_spec=None, **kwargs): + """Wraps `tf.function` into a callable function with TFLite compatibility checking. + + Example: + + ```python + @tf.lite.experimental.authoring.compatible + @tf.function(input_signature=[ + tf.TensorSpec(shape=[None], dtype=tf.float32) + ]) + def f(x): + return tf.cosh(x) + + result = f(tf.constant([0.0])) + # COMPATIBILITY WARNING: op 'tf.Cosh' require(s) "Select TF Ops" for model + # conversion for TensorFlow Lite. + # Op: tf.Cosh + # - tensorflow/python/framework/op_def_library.py:748 + # - tensorflow/python/ops/gen_math_ops.py:2458 + # - :6 + ``` + + WARNING: Experimental interface, subject to change. + + Args: + target: A `tf.function` to decorate. + converter_target_spec : target_spec of TFLite converter parameter. + **kwargs: The keyword arguments of the decorator class _Compatible. + + Returns: + A callable object of `tf.lite.experimental.authoring._Compatible`. + """ + if target is None: + def wrapper(target): + return _Compatible(target, converter_target_spec, **kwargs) + return wrapper + else: + return _Compatible(target, converter_target_spec, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/conversion_metadata_schema_py_generated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/conversion_metadata_schema_py_generated.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab45ced7be90efda8ba507b1143886b1ad6bd7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/conversion_metadata_schema_py_generated.py @@ -0,0 +1,554 @@ +import flatbuffers + +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: tflite + +from flatbuffers.compat import import_numpy +np = import_numpy() + +class ModelType(object): + NONE = 0 + TF_SAVED_MODEL = 1 + KERAS_MODEL = 2 + TF_CONCRETE_FUNCTIONS = 3 + TF_GRAPH_DEF = 4 + TF_SESSION = 5 + JAX = 6 + + +class ModelOptimizationMode(object): + PTQ_FLOAT16 = 1001 + PTQ_DYNAMIC_RANGE = 1002 + PTQ_FULL_INTEGER = 1003 + PTQ_INT16 = 1004 + QUANTIZATION_AWARE_TRAINING = 2000 + RANDOM_SPARSITY = 3001 + BLOCK_SPARSITY = 3002 + STRUCTURED_SPARSITY = 3003 + + +class Environment(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Environment() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsEnvironment(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # Environment + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Environment + def TensorflowVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Environment + def ApiVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Environment + def ModelType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def EnvironmentStart(builder): + builder.StartObject(3) + +def EnvironmentAddTensorflowVersion(builder, tensorflowVersion): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(tensorflowVersion), 0) + +def EnvironmentAddApiVersion(builder, apiVersion): + builder.PrependUint32Slot(1, apiVersion, 0) + +def EnvironmentAddModelType(builder, modelType): + builder.PrependInt32Slot(2, modelType, 0) + +def EnvironmentEnd(builder): + return builder.EndObject() + + + +class EnvironmentT(object): + + # EnvironmentT + def __init__(self): + self.tensorflowVersion = None # type: str + self.apiVersion = 0 # type: int + self.modelType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + environment = Environment() + environment.Init(buf, pos) + return cls.InitFromObj(environment) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, environment): + x = EnvironmentT() + x._UnPack(environment) + return x + + # EnvironmentT + def _UnPack(self, environment): + if environment is None: + return + self.tensorflowVersion = environment.TensorflowVersion() + self.apiVersion = environment.ApiVersion() + self.modelType = environment.ModelType() + + # EnvironmentT + def Pack(self, builder): + if self.tensorflowVersion is not None: + tensorflowVersion = builder.CreateString(self.tensorflowVersion) + EnvironmentStart(builder) + if self.tensorflowVersion is not None: + EnvironmentAddTensorflowVersion(builder, tensorflowVersion) + EnvironmentAddApiVersion(builder, self.apiVersion) + EnvironmentAddModelType(builder, self.modelType) + environment = EnvironmentEnd(builder) + return environment + + +class SparsityBlockSize(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SparsityBlockSize() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSparsityBlockSize(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # SparsityBlockSize + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SparsityBlockSize + def Values(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # SparsityBlockSize + def ValuesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint32Flags, o) + return 0 + + # SparsityBlockSize + def ValuesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SparsityBlockSize + def ValuesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def SparsityBlockSizeStart(builder): + builder.StartObject(1) + +def SparsityBlockSizeAddValues(builder, values): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0) + +def SparsityBlockSizeStartValuesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SparsityBlockSizeEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class SparsityBlockSizeT(object): + + # SparsityBlockSizeT + def __init__(self): + self.values = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + sparsityBlockSize = SparsityBlockSize() + sparsityBlockSize.Init(buf, pos) + return cls.InitFromObj(sparsityBlockSize) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, sparsityBlockSize): + x = SparsityBlockSizeT() + x._UnPack(sparsityBlockSize) + return x + + # SparsityBlockSizeT + def _UnPack(self, sparsityBlockSize): + if sparsityBlockSize is None: + return + if not sparsityBlockSize.ValuesIsNone(): + if np is None: + self.values = [] + for i in range(sparsityBlockSize.ValuesLength()): + self.values.append(sparsityBlockSize.Values(i)) + else: + self.values = sparsityBlockSize.ValuesAsNumpy() + + # SparsityBlockSizeT + def Pack(self, builder): + if self.values is not None: + if np is not None and type(self.values) is np.ndarray: + values = builder.CreateNumpyVector(self.values) + else: + SparsityBlockSizeStartValuesVector(builder, len(self.values)) + for i in reversed(range(len(self.values))): + builder.PrependUint32(self.values[i]) + values = builder.EndVector() + SparsityBlockSizeStart(builder) + if self.values is not None: + SparsityBlockSizeAddValues(builder, values) + sparsityBlockSize = SparsityBlockSizeEnd(builder) + return sparsityBlockSize + + +class ConversionOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ConversionOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsConversionOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # ConversionOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ConversionOptions + def ModelOptimizationModes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # ConversionOptions + def ModelOptimizationModesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # ConversionOptions + def ModelOptimizationModesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ConversionOptions + def ModelOptimizationModesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # ConversionOptions + def AllowCustomOps(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ConversionOptions + def EnableSelectTfOps(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ConversionOptions + def ForceSelectTfOps(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ConversionOptions + def SparsityBlockSizes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = SparsityBlockSize() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # ConversionOptions + def SparsityBlockSizesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ConversionOptions + def SparsityBlockSizesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + +def ConversionOptionsStart(builder): + builder.StartObject(5) + +def ConversionOptionsAddModelOptimizationModes(builder, modelOptimizationModes): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(modelOptimizationModes), 0) + +def ConversionOptionsStartModelOptimizationModesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ConversionOptionsAddAllowCustomOps(builder, allowCustomOps): + builder.PrependBoolSlot(1, allowCustomOps, 0) + +def ConversionOptionsAddEnableSelectTfOps(builder, enableSelectTfOps): + builder.PrependBoolSlot(2, enableSelectTfOps, 0) + +def ConversionOptionsAddForceSelectTfOps(builder, forceSelectTfOps): + builder.PrependBoolSlot(3, forceSelectTfOps, 0) + +def ConversionOptionsAddSparsityBlockSizes(builder, sparsityBlockSizes): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(sparsityBlockSizes), 0) + +def ConversionOptionsStartSparsityBlockSizesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ConversionOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class ConversionOptionsT(object): + + # ConversionOptionsT + def __init__(self): + self.modelOptimizationModes = None # type: List[int] + self.allowCustomOps = False # type: bool + self.enableSelectTfOps = False # type: bool + self.forceSelectTfOps = False # type: bool + self.sparsityBlockSizes = None # type: List[SparsityBlockSizeT] + + @classmethod + def InitFromBuf(cls, buf, pos): + conversionOptions = ConversionOptions() + conversionOptions.Init(buf, pos) + return cls.InitFromObj(conversionOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, conversionOptions): + x = ConversionOptionsT() + x._UnPack(conversionOptions) + return x + + # ConversionOptionsT + def _UnPack(self, conversionOptions): + if conversionOptions is None: + return + if not conversionOptions.ModelOptimizationModesIsNone(): + if np is None: + self.modelOptimizationModes = [] + for i in range(conversionOptions.ModelOptimizationModesLength()): + self.modelOptimizationModes.append(conversionOptions.ModelOptimizationModes(i)) + else: + self.modelOptimizationModes = conversionOptions.ModelOptimizationModesAsNumpy() + self.allowCustomOps = conversionOptions.AllowCustomOps() + self.enableSelectTfOps = conversionOptions.EnableSelectTfOps() + self.forceSelectTfOps = conversionOptions.ForceSelectTfOps() + if not conversionOptions.SparsityBlockSizesIsNone(): + self.sparsityBlockSizes = [] + for i in range(conversionOptions.SparsityBlockSizesLength()): + if conversionOptions.SparsityBlockSizes(i) is None: + self.sparsityBlockSizes.append(None) + else: + sparsityBlockSize_ = SparsityBlockSizeT.InitFromObj(conversionOptions.SparsityBlockSizes(i)) + self.sparsityBlockSizes.append(sparsityBlockSize_) + + # ConversionOptionsT + def Pack(self, builder): + if self.modelOptimizationModes is not None: + if np is not None and type(self.modelOptimizationModes) is np.ndarray: + modelOptimizationModes = builder.CreateNumpyVector(self.modelOptimizationModes) + else: + ConversionOptionsStartModelOptimizationModesVector(builder, len(self.modelOptimizationModes)) + for i in reversed(range(len(self.modelOptimizationModes))): + builder.PrependInt32(self.modelOptimizationModes[i]) + modelOptimizationModes = builder.EndVector() + if self.sparsityBlockSizes is not None: + sparsityBlockSizeslist = [] + for i in range(len(self.sparsityBlockSizes)): + sparsityBlockSizeslist.append(self.sparsityBlockSizes[i].Pack(builder)) + ConversionOptionsStartSparsityBlockSizesVector(builder, len(self.sparsityBlockSizes)) + for i in reversed(range(len(self.sparsityBlockSizes))): + builder.PrependUOffsetTRelative(sparsityBlockSizeslist[i]) + sparsityBlockSizes = builder.EndVector() + ConversionOptionsStart(builder) + if self.modelOptimizationModes is not None: + ConversionOptionsAddModelOptimizationModes(builder, modelOptimizationModes) + ConversionOptionsAddAllowCustomOps(builder, self.allowCustomOps) + ConversionOptionsAddEnableSelectTfOps(builder, self.enableSelectTfOps) + ConversionOptionsAddForceSelectTfOps(builder, self.forceSelectTfOps) + if self.sparsityBlockSizes is not None: + ConversionOptionsAddSparsityBlockSizes(builder, sparsityBlockSizes) + conversionOptions = ConversionOptionsEnd(builder) + return conversionOptions + + +class ConversionMetadata(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ConversionMetadata() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsConversionMetadata(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # ConversionMetadata + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ConversionMetadata + def Environment(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = Environment() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # ConversionMetadata + def Options(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = ConversionOptions() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def ConversionMetadataStart(builder): + builder.StartObject(2) + +def ConversionMetadataAddEnvironment(builder, environment): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(environment), 0) + +def ConversionMetadataAddOptions(builder, options): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(options), 0) + +def ConversionMetadataEnd(builder): + return builder.EndObject() + + +try: + from typing import Optional +except: + pass + +class ConversionMetadataT(object): + + # ConversionMetadataT + def __init__(self): + self.environment = None # type: Optional[EnvironmentT] + self.options = None # type: Optional[ConversionOptionsT] + + @classmethod + def InitFromBuf(cls, buf, pos): + conversionMetadata = ConversionMetadata() + conversionMetadata.Init(buf, pos) + return cls.InitFromObj(conversionMetadata) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, conversionMetadata): + x = ConversionMetadataT() + x._UnPack(conversionMetadata) + return x + + # ConversionMetadataT + def _UnPack(self, conversionMetadata): + if conversionMetadata is None: + return + if conversionMetadata.Environment() is not None: + self.environment = EnvironmentT.InitFromObj(conversionMetadata.Environment()) + if conversionMetadata.Options() is not None: + self.options = ConversionOptionsT.InitFromObj(conversionMetadata.Options()) + + # ConversionMetadataT + def Pack(self, builder): + if self.environment is not None: + environment = self.environment.Pack(builder) + if self.options is not None: + options = self.options.Pack(builder) + ConversionMetadataStart(builder) + if self.environment is not None: + ConversionMetadataAddEnvironment(builder, environment) + if self.options is not None: + ConversionMetadataAddOptions(builder, options) + conversionMetadata = ConversionMetadataEnd(builder) + return conversionMetadata + + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..1483aea0982b6e523f339ebc077764244e6adab7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert.py @@ -0,0 +1,1206 @@ +# 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. +# ============================================================================== +"""Converts a frozen graph into a TFLite FlatBuffer.""" + +import distutils.spawn +import enum +import hashlib +import os as _os +import platform as _platform +import subprocess as _subprocess +import tempfile as _tempfile +from typing import Optional +import warnings + +from tensorflow.compiler.mlir.quantization.stablehlo import quantization_options_pb2 as quant_opts_pb2 +from tensorflow.lite.python import lite_constants +from tensorflow.lite.python import util +from tensorflow.lite.python import wrap_toco +from tensorflow.lite.python.convert_phase import Component +from tensorflow.lite.python.convert_phase import convert_phase +from tensorflow.lite.python.convert_phase import ConverterError +from tensorflow.lite.python.convert_phase import SubComponent +from tensorflow.lite.python.metrics import converter_error_data_pb2 +from tensorflow.lite.python.metrics.wrapper import metrics_wrapper as _metrics_wrapper +from tensorflow.lite.toco import model_flags_pb2 as _model_flags_pb2 +from tensorflow.lite.toco import toco_flags_pb2 as _conversion_flags_pb2 +from tensorflow.lite.toco import types_pb2 as _types_pb2 +from tensorflow.lite.tools import flatbuffer_utils +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.platform import resource_loader as _resource_loader +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export as _tf_export + + +def _is_quantized_input_stats_required( + conversion_flags: _conversion_flags_pb2.TocoFlags, +) -> bool: + """Checks if the `quantized_input_stats` flag is required for conversion. + + Args: + conversion_flags: A protocol buffer describing the conversion process. + + Returns: + True, if the `inference_type` or the `inference_input_type` is a quantized + type and it is not post training quantization, else False. + """ + quantized_inference_types = [ + _types_pb2.QUANTIZED_UINT8, + _types_pb2.QUANTIZED_INT8, + ] + return ( + conversion_flags.inference_type in quantized_inference_types + or conversion_flags.inference_input_type in quantized_inference_types + ) and not conversion_flags.post_training_quantize + + +def convert_tensor_tf_type_to_tflite_type( + tf_type: dtypes.DType, usage: str = "" +) -> _types_pb2.IODataType: + """Convert tensor type from tf type to tflite type. + + Args: + tf_type: TensorFlow type. + usage: Text describing the reason for invoking this function. + + Raises: + ValueError: If `tf_type` is unsupported. + + Returns: + tflite_type: TFLite type. Refer to lite/toco/types.proto. + """ + mapping = { + dtypes.float16: _types_pb2.FLOAT16, + dtypes.float32: _types_pb2.FLOAT, + dtypes.float64: _types_pb2.FLOAT64, + dtypes.int8: _types_pb2.INT8, + dtypes.int16: _types_pb2.INT16, + dtypes.uint16: _types_pb2.UINT16, + dtypes.int32: _types_pb2.INT32, + dtypes.int64: _types_pb2.INT64, + dtypes.uint8: _types_pb2.UINT8, + dtypes.uint32: _types_pb2.UINT32, + dtypes.uint64: _types_pb2.UINT64, + dtypes.string: _types_pb2.STRING, + dtypes.bool: _types_pb2.BOOL, + dtypes.complex64: _types_pb2.COMPLEX64, + dtypes.complex128: _types_pb2.COMPLEX128, + } + tflite_type = mapping.get(tf_type) + if tflite_type is None: + raise ValueError( + "Unsupported TensorFlow type `{0}` provided for the {1}".format( + tf_type, usage + ) + ) + return tflite_type + + +# Only a few restricted tensor types are allowed for explicitly setting +# inference/input/output types. +def convert_inference_tf_type_to_tflite_type( + tf_type: dtypes.DType, usage: str = "" +) -> _types_pb2.IODataType: + """Convert inference type from tf type to tflite type. + + Args: + tf_type: TensorFlow type. + usage: Text describing the reason for invoking this function. + + Raises: + ValueError: If `tf_type` is unsupported. + + Returns: + tflite_type: TFLite type. Refer to lite/toco/types.proto. + """ + mapping = { + dtypes.float32: _types_pb2.FLOAT, + dtypes.uint8: _types_pb2.QUANTIZED_UINT8, + dtypes.int8: _types_pb2.QUANTIZED_INT8, + dtypes.int16: _types_pb2.QUANTIZED_INT16, + } + tflite_type = mapping.get(tf_type) + if tflite_type is None: + raise ValueError( + "Unsupported TensorFlow type `{0}` provided for the {1}".format( + tf_type, usage + ) + ) + return tflite_type + + +# Find the deprecated conversion binary using the resource loader if using from +# bazel, otherwise we are in a pip where console_scripts already has the tool. +if lite_constants.EXPERIMENTAL_USE_TOCO_API_DIRECTLY: + _deprecated_conversion_binary = "" +else: + _deprecated_conversion_binary = _resource_loader.get_path_to_datafile( + "../toco/python/toco_from_protos" + ) + if not _os.path.exists(_deprecated_conversion_binary): + _deprecated_conversion_binary = "toco_from_protos" + + +def _try_convert_to_unicode(output): + if output is None: + return "" + + if isinstance(output, bytes): + try: + return output.decode("utf-8") + except UnicodeDecodeError: + pass + return output + + +@_tf_export("lite.OpsSet") +class OpsSet(enum.Enum): + """Enum class defining the sets of ops available to generate TFLite models. + + WARNING: Experimental interface, subject to change. + """ + + # Convert model using TensorFlow Lite builtin ops. + TFLITE_BUILTINS = "TFLITE_BUILTINS" + + # Convert model using TensorFlow ops. Not all TensorFlow ops are available. + # WARNING: Experimental interface, subject to change. + SELECT_TF_OPS = "SELECT_TF_OPS" + + # Convert model using only TensorFlow Lite quantized int8 operations. + # Specifying this will throw an error for operations that do not yet have + # quantized implementations. + TFLITE_BUILTINS_INT8 = "TFLITE_BUILTINS_INT8" + + # Convert model using only TensorFlow Lite operations with quantized int8 + # weights, int16 activations and int64 bias. + # Specifying this will throw an error for operations that do not yet have + # quantized implementations. + # This quantization mode may be used in models for super-resolution, + # audio signal processing or image de-noising. It improves accuracy + # significantly, but only slightly increases the model size. + # WARNING: These ops are currently experimental and have not yet been + # finalized. + # They are only compatible with CPU execution, and have not been optimized for + # production. + EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8 = ( + "EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8" + ) + + # Convert model using only stablehlo ops. + # This option can not be combined with other OpsSets. + # The feature is in early development. + # The code to execute StableHLO ops in the runtime is to be implemented + # and the serialization format is not stabilized yet. + EXPERIMENTAL_STABLEHLO_OPS = "EXPERIMENTAL_STABLEHLO_OPS" + + def __str__(self): + return str(self.value) + + @staticmethod + def get_options(): + """Returns a list of OpsSet options as a list of strings.""" + return [str(option) for option in list(OpsSet)] + + +@convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.QUANTIZE) +def mlir_quantize( + input_data_str, + disable_per_channel=False, + fully_quantize=False, + inference_type=_types_pb2.QUANTIZED_INT8, + input_data_type=dtypes.float32, + output_data_type=dtypes.float32, + enable_numeric_verify=False, + enable_whole_model_verify=False, + denylisted_ops=None, + denylisted_nodes=None, + enable_variable_quantization=False, +): + """Quantize `input_data_str` with calibration results. + + Args: + input_data_str: Input data in serialized form (e.g. a TFLITE model with + calibration results). + disable_per_channel: Bool indicating whether to do per-channel or per-tensor + quantization + fully_quantize: Bool indicating whether to fully quantize the model. Besides + model body, the input/output will be quantized as well. + inference_type: Data type for the activations. The default value is int8. + input_data_type: Data type for the inputs. The default value is float32. + output_data_type: Data type for the outputs. The default value is float32. + enable_numeric_verify: Experimental. Subject to change. Bool indicating + whether to add NumericVerify ops into the debug mode quantized model. + enable_whole_model_verify: Experimental. Subject to change. Bool indicating + whether to add verification for layer by layer, or on whole model. When + disabled (per-layer) float and quantized ops will be run from same input + (output of previous quantized layer). When enabled, float and quantized + ops will run with respective float and quantized output of previous ops. + denylisted_ops: Experimental. Subject to change. Set of ops to denylist. + denylisted_nodes: Experimental. Subject to change. Set of notes to denylist. + enable_variable_quantization: Experimental. Subject to change. Bool + indicating whether to enable quantization of the residual variables + remaining after the variable freezing pass. + + Returns: + Quantized model in serialized form (e.g. a TFLITE model) with floating-point + inputs and outputs. + """ + return wrap_toco.wrapped_experimental_mlir_quantize( + input_data_str, + disable_per_channel, + fully_quantize, + inference_type, + convert_tensor_tf_type_to_tflite_type(input_data_type), + convert_tensor_tf_type_to_tflite_type(output_data_type), + enable_numeric_verify, + enable_whole_model_verify, + denylisted_ops, + denylisted_nodes, + enable_variable_quantization, + ) + + +@convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.SPARSIFY) +def mlir_sparsify(input_data_str): + """Sparsify `input_data_str` to encode sparse tensor with proper format. + + Args: + input_data_str: Input data in serialized form (e.g. a TFLITE model). + + Returns: + Sparsified model in serialized form (e.g. a TFLITE model). + """ + return wrap_toco.wrapped_experimental_mlir_sparsify(input_data_str) + + +def register_custom_opdefs(custom_opdefs_list): + """Register the given custom opdefs to the TensorFlow global op registry. + + Args: + custom_opdefs_list: String representing the custom ops OpDefs that are + included in the GraphDef. + + Returns: + True if the registration is successfully completed. + """ + return wrap_toco.wrapped_register_custom_opdefs(custom_opdefs_list) + + +def convert( + model_flags: _model_flags_pb2.ModelFlags, + conversion_flags: _conversion_flags_pb2.TocoFlags, + input_data_str: Optional[str] = None, + debug_info_str: Optional[str] = None, + enable_mlir_converter: bool = True, +): + """Converts `input_data_str` to a TFLite model. + + Args: + model_flags: Proto describing model properties, see `model_flags.proto`. + conversion_flags: Proto describing conversion properties, see + `toco/toco_flags.proto`. + input_data_str: Input data in serialized form (e.g. a graphdef is common, or + it can be hlo text or proto) + debug_info_str: Serialized `GraphDebugInfo` proto describing logging + information. + enable_mlir_converter: Enables MLIR-based conversion. + + Returns: + Converted model in serialized form (e.g. a TFLITE model is common). + Raises: + ConverterError: When conversion fails in TFLiteConverter, usually due to + ops not being supported. + RuntimeError: When conversion fails, an exception is raised with the error + message embedded. + """ + # Historically, deprecated conversion failures would trigger a crash, so we + # attempt to run the converter out-of-process. The current MLIR conversion + # pipeline surfaces errors instead, and can be safely run in-process. + if enable_mlir_converter or not _deprecated_conversion_binary: + try: + return wrap_toco.wrapped_toco_convert( + model_flags.SerializeToString(), + conversion_flags.SerializeToString(), + input_data_str, + debug_info_str, + enable_mlir_converter, + ) + except Exception as e: + converter_error = ConverterError(str(e)) + + for error_data in _metrics_wrapper.retrieve_collected_errors(): + converter_error.append_error(error_data) + # Seldom we encounter the case where an unsupported + # `StatefulPartitionedCallOp` is not inlined and remains in the final + # IR. If this occurs we can set `guarantee_all_funcs_one_use` and retry. + # This makes the converter copy functions definitions called by + # multiple StatefulPartitionedCall, thus allowing them to be properly + # inlined. + if ( + error_data.error_code + == converter_error_data_pb2.ConverterErrorData.ERROR_STATEFUL_PARTITIONED_CALL_IN_FINAL_IR + and not conversion_flags.guarantee_all_funcs_one_use + ): + conversion_flags.guarantee_all_funcs_one_use = True + return convert( + model_flags, + conversion_flags, + input_data_str, + debug_info_str, + enable_mlir_converter, + ) + raise converter_error + + return _run_deprecated_conversion_binary( + model_flags.SerializeToString(), + conversion_flags.SerializeToString(), + input_data_str, + debug_info_str, + ) + + +@convert_phase( + Component.CONVERT_TF_TO_TFLITE_MODEL, + SubComponent.CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER, +) +def _run_deprecated_conversion_binary( + model_flags_str, conversion_flags_str, input_data_str, debug_info_str=None +): + """Convert `input_data_str` using deprecated conversion binary. + + Args: + model_flags_str: Serialized proto describing model properties, see + `model_flags.proto`. + conversion_flags_str: Serialized proto describing TFLite converter + properties, see `toco/toco_flags.proto`. + input_data_str: Input data in serialized form (e.g. a graphdef is common) + debug_info_str: Serialized `GraphDebugInfo` proto describing logging + information. (default None) + + Returns: + Converted model in serialized form (e.g. a TFLITE model is common). + Raises: + ConverterError: When cannot find the deprecated conversion binary. + RuntimeError: When conversion fails, an exception is raised with the error + message embedded. + """ + if distutils.spawn.find_executable(_deprecated_conversion_binary) is None: + raise ConverterError("""Could not find `toco_from_protos` binary, make sure +your virtualenv bin directory or pip local bin directory is in your path. +In particular, if you have installed TensorFlow with --user, make sure you +add the install directory to your path. + +For example: +Linux: export PATH=$PATH:~/.local/bin/ +Mac: export PATH=$PATH:~/Library/Python//bin + +Alternative, use virtualenv.""") + # Windows and TemporaryFile are not that useful together, + # since you cannot have two readers/writers. So we have to + # make the temporaries and close and delete them explicitly. + conversion_filename: str = None + model_filename: str = None + input_filename: str = None + output_filename: str = None + try: + # Build all input files + with _tempfile.NamedTemporaryFile( + delete=False + ) as fp_conversion, _tempfile.NamedTemporaryFile( + delete=False + ) as fp_model, _tempfile.NamedTemporaryFile( + delete=False + ) as fp_input, _tempfile.NamedTemporaryFile( + delete=False + ) as fp_debug: + conversion_filename = fp_conversion.name + input_filename = fp_input.name + model_filename = fp_model.name + debug_filename = fp_debug.name + + fp_model.write(model_flags_str) + fp_conversion.write(conversion_flags_str) + fp_input.write(input_data_str) + debug_info_str = debug_info_str if debug_info_str else "" + # if debug_info_str contains a "string value", then the call to + # fp_debug.write(debug_info_str) will fail with the following error + # + # TypeError: a bytes-like object is required, not 'str' + # + # Some of the subtests within the "convert_test" unit-test fail + # with the error shown above. So watch out for that scenario and + # convert debug_info_str to bytes where needed + if not isinstance(debug_info_str, bytes): + fp_debug.write(debug_info_str.encode("utf-8")) + else: + fp_debug.write(debug_info_str) + + # Reserve an output file + with _tempfile.NamedTemporaryFile(delete=False) as fp: + output_filename = fp.name + + # Run + cmd = [ + _deprecated_conversion_binary, + model_filename, + conversion_filename, + input_filename, + output_filename, + "--debug_proto_file={}".format(debug_filename), + ] + cmdline = " ".join(cmd) + is_windows = _platform.system() == "Windows" + proc = _subprocess.Popen( + cmdline, + shell=True, + stdout=_subprocess.PIPE, + stderr=_subprocess.STDOUT, + close_fds=not is_windows, + ) + stdout, stderr = proc.communicate() + exitcode = proc.returncode + if exitcode == 0: + with open(output_filename, "rb") as fp: + return fp.read() + else: + stdout = _try_convert_to_unicode(stdout) + stderr = _try_convert_to_unicode(stderr) + raise ConverterError("See console for info.\n%s\n%s\n" % (stdout, stderr)) + finally: + # Must manually cleanup files. + for filename in [ + conversion_filename, + input_filename, + model_filename, + output_filename, + ]: + try: + _os.unlink(filename) + except (OSError, TypeError): + pass + + +def build_model_flags( + change_concat_input_ranges=False, + allow_nonexistent_arrays=False, + saved_model_dir=None, + saved_model_version=0, + saved_model_tags=None, + saved_model_exported_names=None, + **_ +): + """Builds the model flags object from params. + + Args: + change_concat_input_ranges: Boolean to change behavior of min/max ranges for + inputs and outputs of the concat operator for quantized models. Changes + the ranges of concat operator overlap when true. (default False) + allow_nonexistent_arrays: Allow specifying array names that don't exist or + are unused in the final graph. (default False) + saved_model_dir: Filepath of the saved model to be converted. This value + will be non-empty only when the saved model import path will be used. + Otherwises, the graph def-based conversion will be processed. + saved_model_version: SavedModel file format version of The saved model file + to be converted. This value will be set only when the SavedModel import + path will be used. + saved_model_tags: Set of string saved model tags, formatted in the + comma-separated value. This value will be set only when the SavedModel + import path will be used. + saved_model_exported_names: Names to be exported (default: export all) when + the saved model import path is on. This value will be set only when the + SavedModel import path will be used. + + Returns: + model_flags: protocol buffer describing the model. + """ + model_flags = _model_flags_pb2.ModelFlags() + model_flags.change_concat_input_ranges = change_concat_input_ranges + model_flags.allow_nonexistent_arrays = allow_nonexistent_arrays + if saved_model_dir: + model_flags.saved_model_dir = saved_model_dir + model_flags.saved_model_version = saved_model_version + if saved_model_tags: + model_flags.saved_model_tags.extend(saved_model_tags) + if saved_model_exported_names: + model_flags.saved_model_exported_names.extend(saved_model_exported_names) + return model_flags + + +def build_conversion_flags( + inference_type=dtypes.float32, + inference_input_type=None, + input_format=lite_constants.TENSORFLOW_GRAPHDEF, + output_format=lite_constants.TFLITE, + default_ranges_stats=None, + drop_control_dependency=True, + reorder_across_fake_quant=False, + allow_custom_ops=False, + post_training_quantize=False, + quantize_to_float16=False, + dump_graphviz_dir=None, + dump_graphviz_video=False, + target_ops=None, + conversion_summary_dir=None, + select_user_tf_ops=None, + allow_all_select_tf_ops=False, + enable_tflite_resource_variables=True, + unfold_batchmatmul=False, + legalize_custom_tensor_list_ops=False, + lower_tensor_list_ops=True, + default_to_single_batch_in_tensor_list_ops=False, + accumulation_type=None, + allow_bfloat16=False, + unfold_large_splat_constant=False, + supported_backends=None, + disable_per_channel_quantization=False, + enable_mlir_dynamic_range_quantizer=False, + tf_quantization_mode=None, + disable_infer_tensor_range=False, + use_fake_quant_num_bits=False, + enable_dynamic_update_slice=False, + preserve_assert_op=False, + guarantee_all_funcs_one_use=False, + enable_mlir_variable_quantization=False, + disable_fuse_mul_and_fc=False, + quantization_options: Optional[quant_opts_pb2.QuantizationOptions] = None, + mlir_dump_dir=None, + mlir_dump_pass_regex=None, + mlir_dump_func_regex=None, + mlir_enable_timing=None, + mlir_print_ir_before=None, + mlir_print_ir_after=None, + mlir_print_ir_module_scope=None, + mlir_elide_elementsattrs_if_larger=None, + use_buffer_offset=False, + reduce_type_precision=False, + **_ +): + """Builds protocol buffer describing a conversion of a model. + + Typically this is to convert from TensorFlow GraphDef to TFLite, in which + case the default `input_format` and `output_format` are sufficient. + + Args: + inference_type: Data type of numeric arrays, excluding the input layer. + (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8}) + inference_input_type: Data type of the numeric arrays in the input layer. If + `inference_input_type` is in {tf.int8, tf.uint8}, then + `quantized_input_stats` must be provided. (default is the value assigned + to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8}) + input_format: Type of data to read. (default TENSORFLOW_GRAPHDEF, must be in + {TENSORFLOW_GRAPHDEF}) + output_format: Output file format. (default TFLITE, must be in {TFLITE, + GRAPHVIZ_DOT}) + default_ranges_stats: Tuple of integers representing (min, max) range values + for all arrays without a specified range. Intended for experimenting with + quantization via "dummy quantization". (default None) + drop_control_dependency: Boolean indicating whether to drop control + dependencies silently. This is due to TFLite not supporting control + dependencies. (default True) + reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant + nodes in unexpected locations. Used when the location of the FakeQuant + nodes is preventing graph transformations necessary to convert the graph. + Results in a graph that differs from the quantized training graph, + potentially causing differing arithmetic behavior. (default False) + allow_custom_ops: Boolean indicating whether to allow custom operations. + When false any unknown operation is an error. When true, custom ops are + created for any op that is unknown. The developer will need to provide + these to the TensorFlow Lite runtime with a custom resolver. (default + False) + post_training_quantize: Boolean indicating whether to quantize the weights + of the converted float model. Model size will be reduced and there will be + latency improvements (at the cost of accuracy). (default False) If + quantization_options is set, all quantization arg will be ignored. + quantize_to_float16: Boolean indicating whether to convert float buffers to + float16. (default False) + dump_graphviz_dir: Full filepath of folder to dump the graphs at various + stages of processing GraphViz .dot files. Preferred over + --output_format=GRAPHVIZ_DOT in order to keep the requirements of the + output file. (default None) + dump_graphviz_video: Boolean indicating whether to dump the graph after + every graph transformation. (default False) + target_ops: Experimental flag, subject to change. Set of OpsSet options + indicating which converter to use. (default set([OpsSet.TFLITE_BUILTINS])) + conversion_summary_dir: A string, the path to the generated conversion logs. + select_user_tf_ops: List of user's defined TensorFlow ops need to be + supported in the TensorFlow Lite runtime. These ops will be supported as + select TensorFlow ops. + allow_all_select_tf_ops: If True, automatically add all TF ops (including + custom TF ops) to the converted model as flex ops. + enable_tflite_resource_variables: Experimental flag, subject to change. + Enables conversion of resource variables. (default False) + unfold_batchmatmul: Whether to unfold tf.BatchMatMul to a set of + tfl.fully_connected ops. If not, translate to tfl.batch_matmul. + legalize_custom_tensor_list_ops: Whether to legalize `tf.TensorList*` ops to + tfl custom if they can all be supported. + lower_tensor_list_ops: Whether to lower tensor list ops to builtin ops. If + not, use Flex tensor list ops. + default_to_single_batch_in_tensor_list_ops: Whether to force to use batch + size one when the tensor list ops has the unspecified batch size. + accumulation_type: Data type of the accumulators in quantized inference. + Typically used for float16 quantization and is either fp16 or fp32. + allow_bfloat16: Whether the converted model supports reduced precision + inference with the bfloat16 type. + unfold_large_splat_constant: Whether to unfold large splat constant tensors + in the flatbuffer model to reduce size. + supported_backends: List of TFLite backends which needs to check + compatibility. + disable_per_channel_quantization: Disable per-channel quantized weights for + dynamic range quantization. Only per-tensor quantization will be used. + enable_mlir_dynamic_range_quantizer: Enable MLIR dynamic range quantization. + If False, the old converter dynamic range quantizer is used. + tf_quantization_mode: Indicates the mode of TF Quantization when the output + model is used for TF Quantization. + disable_infer_tensor_range: Disable infering tensor ranges. + use_fake_quant_num_bits: Allow quantization parameters to be calculated from + num_bits attribute. + enable_dynamic_update_slice: Enable to convert to DynamicUpdateSlice op. + (default: False). + preserve_assert_op: Whether to preserve `TF::AssertOp` (default: False). + guarantee_all_funcs_one_use: Whether to clone functions so that each + function only has a single use. This option will be helpful if the + conversion fails when the `PartitionedCall` or `StatefulPartitionedCall` + can't be properly inlined (default: False). + enable_mlir_variable_quantization: Enable MLIR variable quantization. There + is a variable freezing pass, but some variables may not be fully frozen by + it. This flag enables quantization of those residual variables in the MLIR + graph. + disable_fuse_mul_and_fc: Disable fusing input multiplication with + fullyconnected operations. Useful when quantizing weights. + quantization_options: Config to indicate quantization options of each + components (ex: weight, bias, activation). This can be a preset method or + a custom method, and allows finer, modular control. This option will + override any other existing quantization flags. We plan on gradually + migrating all quantization-related specs into this option. + mlir_dump_dir: A string specifying the target directory to output MLIR dumps + produced during conversion. If populated, enables MLIR dumps. + mlir_dump_pass_regex: A string containing a regular expression for filtering + the pass names to be dumped. Effective only if `mlir_dump_dir` is + populated. + mlir_dump_func_regex: A string containing a regular expression for filtering + the function names to be dumped. Effective only if `mlir_dump_dir` is + populated. + mlir_enable_timing: A boolean, if set to true reports the execution time of + each MLIR pass. + mlir_print_ir_before: A string containing a regular expression. If + specified, prints MLIR before passes which match. + mlir_print_ir_after: A string containing a regular expression. If specified, + prints MLIR after passes which match. + mlir_print_ir_module_scope: A boolean, if set to true always print the + top-level operation when printing IR for print_ir_[before|after]. + mlir_elide_elementsattrs_if_larger: An int, if specified elides + ElementsAttrs with '...' that have more elements than the given upper + limit. + use_buffer_offset: Force the model use buffer_offset & buffer_size fields + instead of data. i.e. store the constant tensor and custom op binaries + outside of Flatbuffers + reduce_type_precision: Convert some tensor types to a lower precision if all + values within that tensor are within the range of the lower precision. + This could have side effects e.g. reduced flatbuffer size. + + Returns: + conversion_flags: protocol buffer describing the conversion process. + Raises: + ValueError, if the input tensor type is unknown. + """ + conversion_flags = _conversion_flags_pb2.TocoFlags() + conversion_flags.inference_type = convert_inference_tf_type_to_tflite_type( + inference_type, usage="inference_type flag" + ) + if inference_input_type: + conversion_flags.inference_input_type = ( + convert_inference_tf_type_to_tflite_type( + inference_input_type, usage="inference_input_type flag" + ) + ) + else: + conversion_flags.inference_input_type = conversion_flags.inference_type + conversion_flags.input_format = input_format + conversion_flags.output_format = output_format + if default_ranges_stats: + conversion_flags.default_ranges_min = default_ranges_stats[0] + conversion_flags.default_ranges_max = default_ranges_stats[1] + conversion_flags.drop_control_dependency = drop_control_dependency + conversion_flags.reorder_across_fake_quant = reorder_across_fake_quant + conversion_flags.allow_custom_ops = allow_custom_ops + conversion_flags.post_training_quantize = post_training_quantize + conversion_flags.quantize_to_float16 = quantize_to_float16 + if dump_graphviz_dir: + conversion_flags.dump_graphviz_dir = dump_graphviz_dir + conversion_flags.dump_graphviz_include_video = dump_graphviz_video + if target_ops: + if OpsSet.SELECT_TF_OPS in target_ops: + conversion_flags.enable_select_tf_ops = True + if set(target_ops) == {OpsSet.SELECT_TF_OPS}: + conversion_flags.force_select_tf_ops = True + if OpsSet.EXPERIMENTAL_STABLEHLO_OPS in target_ops: + conversion_flags.convert_to_stablehlo = True + if OpsSet.EXPERIMENTAL_STABLEHLO_OPS in target_ops and len(target_ops) > 1: + raise ValueError( + "StableHLO Ops set can not be specified with other Ops set together" + ) + if conversion_summary_dir: + conversion_flags.conversion_summary_dir = conversion_summary_dir + if select_user_tf_ops: + conversion_flags.select_user_tf_ops.extend(select_user_tf_ops) + conversion_flags.allow_all_select_tf_ops = allow_all_select_tf_ops + conversion_flags.enable_tflite_resource_variables = ( + enable_tflite_resource_variables + ) + conversion_flags.unfold_batchmatmul = unfold_batchmatmul + conversion_flags.legalize_custom_tensor_list_ops = ( + legalize_custom_tensor_list_ops + ) + conversion_flags.lower_tensor_list_ops = lower_tensor_list_ops + conversion_flags.default_to_single_batch_in_tensor_list_ops = ( + default_to_single_batch_in_tensor_list_ops + ) + if accumulation_type: + conversion_flags.accumulation_type = convert_tensor_tf_type_to_tflite_type( + accumulation_type, usage="accumulation_type flag" + ) + conversion_flags.allow_bfloat16 = allow_bfloat16 + conversion_flags.unfold_large_splat_constant = unfold_large_splat_constant + if supported_backends: + conversion_flags.supported_backends.extend(supported_backends) + conversion_flags.disable_per_channel_quantization = ( + disable_per_channel_quantization + ) + conversion_flags.enable_mlir_dynamic_range_quantizer = ( + enable_mlir_dynamic_range_quantizer + ) + conversion_flags.enable_dynamic_update_slice = enable_dynamic_update_slice + conversion_flags.preserve_assert_op = preserve_assert_op + conversion_flags.guarantee_all_funcs_one_use = guarantee_all_funcs_one_use + if tf_quantization_mode: + conversion_flags.tf_quantization_mode = tf_quantization_mode + conversion_flags.disable_infer_tensor_range = disable_infer_tensor_range + conversion_flags.use_fake_quant_num_bits = use_fake_quant_num_bits + conversion_flags.enable_mlir_variable_quantization = ( + enable_mlir_variable_quantization + ) + conversion_flags.disable_fuse_mul_and_fc = disable_fuse_mul_and_fc + if quantization_options: + conversion_flags.quantization_options.CopyFrom(quantization_options) + + # Transfer debug options. Check for existence before populating in order to + # leverage defaults specified in proto definition. + if mlir_dump_dir is not None: + conversion_flags.debug_options.mlir_dump_dir = mlir_dump_dir + if mlir_dump_pass_regex is not None: + conversion_flags.debug_options.mlir_dump_pass_regex = mlir_dump_pass_regex + if mlir_dump_func_regex is not None: + conversion_flags.debug_options.mlir_dump_func_regex = mlir_dump_func_regex + if mlir_enable_timing is not None: + conversion_flags.debug_options.mlir_enable_timing = mlir_enable_timing + if mlir_print_ir_before is not None: + conversion_flags.debug_options.mlir_print_ir_before = mlir_print_ir_before + if mlir_print_ir_after is not None: + conversion_flags.debug_options.mlir_print_ir_after = mlir_print_ir_after + if mlir_print_ir_module_scope is not None: + conversion_flags.debug_options.mlir_print_ir_module_scope = ( + mlir_print_ir_module_scope + ) + if mlir_elide_elementsattrs_if_larger is not None: + conversion_flags.debug_options.mlir_elide_elementsattrs_if_larger = ( + mlir_elide_elementsattrs_if_larger + ) + + if use_buffer_offset is not None: + conversion_flags.use_buffer_offset = use_buffer_offset + if reduce_type_precision is not None: + conversion_flags.reduce_type_precision = reduce_type_precision + return conversion_flags + + +@convert_phase( + Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_GRAPHDEF +) +def convert_graphdef_with_arrays( + input_data, + input_arrays_with_shape, + output_arrays, + control_output_arrays, + **kwargs +): + """Convert a frozen GraphDef that can't be loaded in TF. + + Conversion can be customized by providing arguments that are forwarded to + `build_model_flags` and `build_conversion_flags` (see documentation). + + Args: + input_data: Input data (i.e. often `sess.graph_def`), + input_arrays_with_shape: Tuple of strings representing input tensor names + and list of integers representing input shapes (e.g., [("foo" : [1, 16, + 16, 3])]). Use only when graph cannot be loaded into TensorFlow and when + `input_tensors` is None. + output_arrays: List of output tensors to freeze graph with. Use only when + graph cannot be loaded into TensorFlow and when `output_tensors` is None. + control_output_arrays: Control output node names. This is used when + converting a Graph with no output tensors. For example, if the graph's + last operation is a Print op, just specify that op's name in this field. + This can be used together with the `output_arrays` parameter. + **kwargs: See `build_model_flags` and `build_conversion_flags`. + + Returns: + The converted data. For example if TFLite was the destination, then + this will be a tflite flatbuffer in a bytes array. + + Raises: + Defined in `build_conversion_flags`. + """ + model_flags = build_model_flags(**kwargs) + conversion_flags = build_conversion_flags(**kwargs) + enable_mlir_converter = kwargs.get("enable_mlir_converter", True) + quantized_input_stats = kwargs.get("quantized_input_stats", None) + + for idx, (name, shape) in enumerate(input_arrays_with_shape): + input_array = model_flags.input_arrays.add() + if _is_quantized_input_stats_required(conversion_flags): + if quantized_input_stats: + input_array.mean_value, input_array.std_value = quantized_input_stats[ + idx + ] + else: + raise ValueError( + "The `quantized_input_stats` flag must be defined when either " + "`inference_type` flag or `inference_input_type` flag is set to " + "tf.int8 or tf.uint8." + ) + input_array.name = name + input_array.shape.dims.extend(list(map(int, shape))) + + if output_arrays: + for name in output_arrays: + model_flags.output_arrays.append(name) + if control_output_arrays: + for name in control_output_arrays: + model_flags.control_output_arrays.append(name) + + data = convert( + model_flags, + conversion_flags, + input_data.SerializeToString(), + debug_info_str=None, + enable_mlir_converter=enable_mlir_converter, + ) + return data + + +@convert_phase( + Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_GRAPHDEF +) +def convert_graphdef(input_data, input_tensors, output_tensors, **kwargs): + """Convert a frozen GraphDef model using the TF Lite converter. + + Conversion can be customized by providing arguments that are forwarded to + `build_model_flags` and `build_conversion_flags` (see documentation). + + Args: + input_data: Input data (i.e. often `sess.graph_def`), + input_tensors: List of input tensors. Type and shape are computed using + `foo.shape` and `foo.dtype`. + output_tensors: List of output tensors (only .name is used from this). + **kwargs: See `build_model_flags` and `build_conversion_flags`. + + Returns: + The converted data. For example if TFLite was the destination, then + this will be a tflite flatbuffer in a bytes array. + + Raises: + Defined in `build_conversion_flags`. + """ + model_flags = build_model_flags(**kwargs) + conversion_flags = build_conversion_flags(**kwargs) + saved_model_dir = kwargs.get("saved_model_dir", None) + input_shapes = kwargs.get("input_shapes", None) + enable_mlir_converter = kwargs.get("enable_mlir_converter", True) + quantized_input_stats = kwargs.get("quantized_input_stats", None) + debug_info = kwargs.get("debug_info", None) + + for idx, input_tensor in enumerate(input_tensors): + input_array = model_flags.input_arrays.add() + if saved_model_dir: + input_array.name = input_tensor.name + else: + input_array.name = util.get_tensor_name(input_tensor) + input_array.data_type = convert_tensor_tf_type_to_tflite_type( + input_tensor.dtype, usage="input type of the TensorFlow model" + ) + + if _is_quantized_input_stats_required(conversion_flags): + if quantized_input_stats: + input_array.mean_value, input_array.std_value = quantized_input_stats[ + idx + ] + else: + # We should ideally raise an error here, but we don't as it would break + # several models/projects that depend on this workflow. + warnings.warn( + "Statistics for quantized inputs were expected, but not " + "specified; continuing anyway." + ) + + if input_shapes is None: + shape = input_tensor.shape + else: + shape = input_shapes[idx] + + if shape.rank is not None: + # Create shapes with -1 for unknown dimensions. + dims = [] + for dim in shape: + if dim is None or ( + isinstance(dim, tensor_shape.Dimension) and dim.value is None + ): + dims.append(-1) + else: + dims.append(int(dim)) + input_array.shape.dims.extend(dims) + input_array.shape.unknown_rank = False + else: + input_array.shape.unknown_rank = True + + for output_tensor in output_tensors: + if saved_model_dir: + model_flags.output_arrays.append(output_tensor.name) + else: + model_flags.output_arrays.append(util.get_tensor_name(output_tensor)) + + data = convert( + model_flags, + conversion_flags, + input_data.SerializeToString(), + debug_info_str=debug_info.SerializeToString() if debug_info else None, + enable_mlir_converter=enable_mlir_converter, + ) + return data + + +@convert_phase( + Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_SAVED_MODEL +) +def convert_saved_model(**kwargs): + """Converts a SavedModel using TF Lite converter.""" + model_flags = build_model_flags(**kwargs) + conversion_flags = build_conversion_flags(**kwargs) + data = convert( + model_flags, + conversion_flags, + input_data_str=None, + debug_info_str=None, + enable_mlir_converter=True, + ) + return data + + +@convert_phase( + Component.CONVERT_TF_TO_TFLITE_MODEL, SubComponent.CONVERT_JAX_HLO +) +def convert_jax_hlo(input_content, input_names, is_proto_format, **kwargs): + """Converts a Jax hlo-based model using TFLite converter.""" + model_flags = _model_flags_pb2.ModelFlags() + model_flags.use_hlo_import = True + if is_proto_format: + model_flags.hlo_file_type = _model_flags_pb2.ModelFlags.HLO_PROTO + else: + model_flags.hlo_file_type = _model_flags_pb2.ModelFlags.HLO_TEXT + + # Build input names. + for input_name in input_names: + input_array = model_flags.input_arrays.add() + input_array.name = input_name + + conversion_flags = build_conversion_flags(**kwargs) + data = convert( + model_flags, + conversion_flags, + input_data_str=input_content, + debug_info_str=None, + enable_mlir_converter=True, + ) + return data + + +@_tf_export(v1=["lite.toco_convert"]) +@deprecation.deprecated(None, "Use `lite.TFLiteConverter` instead.") +def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs): + """Convert a TensorFlow GraphDef to TFLite. + + This function is deprecated. Please use `tf.lite.TFLiteConverter` API instead. + Conversion can be customized by providing arguments that are forwarded to + `build_model_flags` and `build_conversion_flags` (see documentation for + details). + Args: + input_data: Input data (i.e. often `sess.graph_def`). + input_tensors: List of input tensors. Type and shape are computed using + `foo.shape` and `foo.dtype`. + output_tensors: List of output tensors (only .name is used from this). + *args: See `build_model_flags` and `build_conversion_flags`. + **kwargs: See `build_model_flags` and `build_conversion_flags`. + + Returns: + The converted TensorFlow Lite model in a bytes array. + + Raises: + Defined in `convert`. + """ + kwargs["enable_mlir_converter"] = kwargs.get("enable_mlir_converter", False) + return convert_graphdef( + input_data, input_tensors, output_tensors, *args, **kwargs + ) + + +def deduplicate_readonly_buffers(tflite_model): + """Generates a new model byte array after deduplicating readonly buffers. + + This function should be invoked after the model optimization toolkit. The + model optimization toolkit assumes that each tensor object owns its each + buffer separately. + + Args: + tflite_model: TFLite flatbuffer in a byte array to be deduplicated. + + Returns: + TFLite flatbuffer in a bytes array, processed with the deduplication method. + """ + # Load TFLite Flatbuffer byte array into an object. + model = flatbuffer_utils.convert_bytearray_to_object(tflite_model) + + # Get all the read-only buffers, which can be modified without causing any + # issue in the graph invocation stage. + read_only_buffer_indices = set() + for subgraph in model.subgraphs: + # To get all the read-only buffers: + # (1) Get all read-only input tensors. + # (2) Discard intermediate or output tensors. + # (3) Discard the subgraph's input/output tensors. + # (4) Gather the buffers of the read-only input tensors. + + # (1) Get read-only input tensors. + read_only_input_tensor_indices = set() + for op in subgraph.operators: + if op.inputs is None: + continue + for i, input_tensor_idx in enumerate(op.inputs): + # Ignore mutable tensors. + if op.mutatingVariableInputs is not None: + # Ignore invalid tensors. + if ( + i < len(op.mutatingVariableInputs) + and op.mutatingVariableInputs[i] + ): + continue + # Ignore variable tensors. + if subgraph.tensors[input_tensor_idx].isVariable: + continue + read_only_input_tensor_indices.add(input_tensor_idx) + + # (2) Discard intermediate or output tensors. + for op in subgraph.operators: + if op.outputs is not None: + for output_tensor_idx in op.outputs: + read_only_input_tensor_indices.discard(output_tensor_idx) + if op.intermediates is not None: + for intermediate_tensor_idx in op.intermediates: + read_only_input_tensor_indices.discard(intermediate_tensor_idx) + + # (3) Discard the subgraph's input and output tensors. + if subgraph.inputs is not None: + for input_tensor_idx in subgraph.inputs: + read_only_input_tensor_indices.discard(input_tensor_idx) + if subgraph.outputs is not None: + for output_tensor_idx in subgraph.outputs: + read_only_input_tensor_indices.discard(output_tensor_idx) + + # (4) Gather the buffers of the read-only input tensors. + for tensor_idx in read_only_input_tensor_indices: + read_only_buffer_indices.add(subgraph.tensors[tensor_idx].buffer) + + # Ignore invalid negative index or zero-sized buffers. + for buffer_idx in read_only_buffer_indices.copy(): + if buffer_idx < 0 or ( + model.buffers[buffer_idx].data is None + or isinstance(model.buffers[buffer_idx].data, list) + or model.buffers[buffer_idx].data.size == 0 + ): + read_only_buffer_indices.discard(buffer_idx) + + class BufferIndex: + """A class to store index, size, hash of the buffers in TFLite model.""" + + def __init__(self, idx, size, hash_value): + self.idx = idx + self.size = size + self.hash_value = hash_value + + read_only_buffers = list( + map( + lambda index: BufferIndex( # pylint: disable=g-long-lambda + index, + model.buffers[index].data.size, + hashlib.md5(model.buffers[index].data.data.tobytes()).hexdigest(), + ), + read_only_buffer_indices, + ) + ) + + # Sort read_only_buffers by buffer size & hash in descending order. + read_only_buffers = sorted( + read_only_buffers, + key=lambda buffer: (buffer.size, buffer.hash_value), + reverse=True, + ) + + # Create a map of duplicate buffers (same size and same type). + # eg: In [1, 2, 3, 4, 5, 6] if (1, 4, 6) and (2, 5) are each, groups of buffer + # indices of the same size and type, then the map would be {4:1, 6:1, 5:2} + duplicate_buffer_map = {} + for i, buffer_i in enumerate(read_only_buffers): + # This buffer is a duplicate. + if buffer_i.idx in duplicate_buffer_map: + continue + # This buffer is unique. Scan rest of the list to find duplicates + # of this buffer and mark them accordingly. + for buffer_j in read_only_buffers[i + 1 :]: + if buffer_j.idx in duplicate_buffer_map: + continue + if buffer_i.size != buffer_j.size: + break + if buffer_i.hash_value != buffer_j.hash_value: + continue + # Found duplicate. Nullify j-th buffer and use i-th buffer instead. + duplicate_buffer_map[buffer_j.idx] = buffer_i.idx + + # Make the duplicated tensors use the single shared buffer index. + for subgraph in model.subgraphs: + for op in subgraph.operators: + if op.inputs is None: + continue + for input_tensor in op.inputs: + buffer_idx = subgraph.tensors[input_tensor].buffer + if buffer_idx in duplicate_buffer_map: + subgraph.tensors[input_tensor].buffer = duplicate_buffer_map[ + buffer_idx + ] + + # Nullify the unused buffers. + for idx in duplicate_buffer_map: + model.buffers[idx].data = None + + # Return a TFLite flatbuffer as a byte array. + return flatbuffer_utils.convert_object_to_bytearray(model) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_phase.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_phase.py new file mode 100644 index 0000000000000000000000000000000000000000..2fb367aef35e2e735789f25c4925b23d608f2e30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_phase.py @@ -0,0 +1,219 @@ +# 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. +# ============================================================================== +"""Utilities for collecting TFLite metrics.""" + +import collections +import enum +import functools +from typing import Text + +from tensorflow.lite.python.metrics import converter_error_data_pb2 +from tensorflow.lite.python.metrics import metrics + + +class Component(enum.Enum): + """Enum class defining name of the converter components.""" + # Validate the given input and prepare and optimize TensorFlow Model. + PREPARE_TF_MODEL = "PREPARE_TF_MODEL" + + # Convert to TFLite model format. + CONVERT_TF_TO_TFLITE_MODEL = "CONVERT_TF_TO_TFLITE_MODEL" + + # RUN quantization and sparsification. + OPTIMIZE_TFLITE_MODEL = "OPTIMIZE_TFLITE_MODEL" + + +SubComponentItem = collections.namedtuple("SubComponentItem", + ["name", "component"]) + + +class SubComponent(SubComponentItem, enum.Enum): + """Enum class defining name of the converter subcomponents. + + This enum only defines the subcomponents in Python, there might be more + subcomponents defined in C++. + """ + + def __str__(self): + return self.value.name + + @property + def name(self): + return self.value.name + + @property + def component(self): + return self.value.component + + # The subcomponent name is unspecified. + UNSPECIFIED = SubComponentItem("UNSPECIFIED", None) + + # Valid the given input and parameters. + VALIDATE_INPUTS = SubComponentItem("VALIDATE_INPUTS", + Component.PREPARE_TF_MODEL) + + # Load GraphDef from SavedModel. + LOAD_SAVED_MODEL = SubComponentItem("LOAD_SAVED_MODEL", + Component.PREPARE_TF_MODEL) + + # Convert a SavedModel to frozen graph. + FREEZE_SAVED_MODEL = SubComponentItem("FREEZE_SAVED_MODEL", + Component.PREPARE_TF_MODEL) + + # Save a Keras model to SavedModel. + CONVERT_KERAS_TO_SAVED_MODEL = SubComponentItem( + "CONVERT_KERAS_TO_SAVED_MODEL", Component.PREPARE_TF_MODEL) + + # Save Concrete functions to SavedModel. + CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL = SubComponentItem( + "CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL", Component.PREPARE_TF_MODEL) + + # Convert a Keras model to a frozen graph. + FREEZE_KERAS_MODEL = SubComponentItem("FREEZE_KERAS_MODEL", + Component.PREPARE_TF_MODEL) + + # Replace all the variables with constants in a ConcreteFunction. + FREEZE_CONCRETE_FUNCTION = SubComponentItem("FREEZE_CONCRETE_FUNCTION", + Component.PREPARE_TF_MODEL) + + # Run grappler optimization. + OPTIMIZE_TF_MODEL = SubComponentItem("OPTIMIZE_TF_MODEL", + Component.PREPARE_TF_MODEL) + + # Convert using the old TOCO converter. + CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER = SubComponentItem( + "CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTER", + Component.CONVERT_TF_TO_TFLITE_MODEL) + + # Convert a GraphDef to TFLite model. + CONVERT_GRAPHDEF = SubComponentItem("CONVERT_GRAPHDEF", + Component.CONVERT_TF_TO_TFLITE_MODEL) + + # Convert a SavedModel to TFLite model. + CONVERT_SAVED_MODEL = SubComponentItem("CONVERT_SAVED_MODEL", + Component.CONVERT_TF_TO_TFLITE_MODEL) + + # Convert a Jax HLO to TFLite model. + CONVERT_JAX_HLO = SubComponentItem("CONVERT_JAX_HLO", + Component.CONVERT_TF_TO_TFLITE_MODEL) + + # Do quantization by the deprecated quantizer. + QUANTIZE_USING_DEPRECATED_QUANTIZER = SubComponentItem( + "QUANTIZE_USING_DEPRECATED_QUANTIZER", Component.OPTIMIZE_TFLITE_MODEL) + + # Do calibration. + CALIBRATE = SubComponentItem("CALIBRATE", Component.OPTIMIZE_TFLITE_MODEL) + + # Do quantization by MLIR. + QUANTIZE = SubComponentItem("QUANTIZE", Component.OPTIMIZE_TFLITE_MODEL) + + # Do sparsification by MLIR. + SPARSIFY = SubComponentItem("SPARSIFY", Component.OPTIMIZE_TFLITE_MODEL) + + +class ConverterError(Exception): + """Raised when an error occurs during model conversion.""" + + def __init__(self, message): + super(ConverterError, self).__init__(message) + self.errors = [] + self._parse_error_message(message) + + def append_error(self, + error_data: converter_error_data_pb2.ConverterErrorData): + self.errors.append(error_data) + + def _parse_error_message(self, message): + """If the message matches a pattern, assigns the associated error code. + + It is difficult to assign an error code to some errrors in MLIR side, Ex: + errors thrown by other components than TFLite or not using mlir::emitError. + This function try to detect them by the error message and assign the + corresponding error code. + + Args: + message: The error message of this exception. + """ + error_code_mapping = { + "Failed to functionalize Control Flow V1 ops. Consider using Control " + "Flow V2 ops instead. See https://www.tensorflow.org/api_docs/python/" + "tf/compat/v1/enable_control_flow_v2.": + converter_error_data_pb2.ConverterErrorData + .ERROR_UNSUPPORTED_CONTROL_FLOW_V1, + } + for pattern, error_code in error_code_mapping.items(): + if pattern in message: + error_data = converter_error_data_pb2.ConverterErrorData() + error_data.error_message = message + error_data.error_code = error_code + self.append_error(error_data) + return + + +def convert_phase(component, subcomponent=SubComponent.UNSPECIFIED): + """The decorator to identify converter component and subcomponent. + + Args: + component: Converter component name. + subcomponent: Converter subcomponent name. + + Returns: + Forward the result from the wrapped function. + + Raises: + ValueError: if component and subcomponent name is not valid. + """ + if component not in Component: + raise ValueError("Given component name not found") + if subcomponent not in SubComponent: + raise ValueError("Given subcomponent name not found") + if (subcomponent != SubComponent.UNSPECIFIED and + subcomponent.component != component): + raise ValueError("component and subcomponent name don't match") + + def report_error(error_data: converter_error_data_pb2.ConverterErrorData): + # Always overwrites the component information, but only overwrites the + # subcomponent if it is not available. + error_data.component = component.value + if not error_data.subcomponent: + error_data.subcomponent = subcomponent.name + tflite_metrics = metrics.TFLiteConverterMetrics() + tflite_metrics.set_converter_error(error_data) + + def report_error_message(error_message: Text): + error_data = converter_error_data_pb2.ConverterErrorData() + error_data.error_message = error_message + report_error(error_data) + + def actual_decorator(func): + + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except ConverterError as converter_error: + if converter_error.errors: + for error_data in converter_error.errors: + report_error(error_data) + else: + report_error_message(str(converter_error)) + raise converter_error from None # Re-throws the exception. + except Exception as error: + report_error_message(str(error)) + raise error from None # Re-throws the exception. + + return wrapper + + return actual_decorator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_saved_model.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_saved_model.py new file mode 100644 index 0000000000000000000000000000000000000000..6d968c37007910d43109f577ce80b1fe5ec68086 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/convert_saved_model.py @@ -0,0 +1,186 @@ +# 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. +# ============================================================================== +"""Functions to convert SavedModel to frozen GraphDefs.""" + +from tensorflow.lite.python import util +from tensorflow.lite.python.convert_phase import Component +from tensorflow.lite.python.convert_phase import convert_phase +from tensorflow.lite.python.convert_phase import SubComponent +from tensorflow.python.client import session +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import constants +from tensorflow.python.saved_model import loader + + +def get_meta_graph_def(saved_model_dir, tag_set): + """Validate saved_model and extract MetaGraphDef. + + Args: + saved_model_dir: saved_model path to convert. + tag_set: Set of tag(s) of the MetaGraphDef to load. + + Returns: + The meta_graph_def used for tflite conversion. + + Raises: + ValueError: No valid MetaGraphDef for given tag_set. + """ + with session.Session(graph=ops.Graph()) as sess: + return loader.load(sess, tag_set, saved_model_dir) + + +def get_signature_def(meta_graph, signature_key): + """Get the signature def from meta_graph with given signature_key. + + Args: + meta_graph: meta_graph_def. + signature_key: signature_def in the meta_graph_def. + + Returns: + The signature_def used for tflite conversion. + + Raises: + ValueError: Given signature_key is not valid for this meta_graph. + """ + signature_def_map = meta_graph.signature_def + signature_def_keys = set(signature_def_map.keys()) + logging.info( + "The given SavedModel MetaGraphDef contains SignatureDefs with the " + "following keys: %s", signature_def_keys) + if signature_key not in signature_def_keys: + raise ValueError("No '{}' in the SavedModel\'s SignatureDefs. Possible " + "values are '{}'.".format(signature_key, + ",".join(signature_def_keys))) + return signature_def_map[signature_key] + + +def get_inputs_outputs(signature_def): + """Get inputs and outputs from SignatureDef. + + Args: + signature_def: SignatureDef in the meta_graph_def for conversion. + + Returns: + The inputs and outputs in the graph for conversion. + """ + inputs_tensor_info = signature_def.inputs + outputs_tensor_info = signature_def.outputs + + def gather_names(tensor_info): + return [tensor_info[key].name for key in tensor_info] + + inputs = gather_names(inputs_tensor_info) + outputs = gather_names(outputs_tensor_info) + return inputs, outputs + + +def _get_tensors(graph, signature_def_tensor_names=None, + user_tensor_names=None): + """Gets the tensors associated with the tensor names. + + Either signature_def_tensor_names or user_tensor_names should be provided. If + the user provides tensors, the tensors associated with the user provided + tensor names are provided. Otherwise, the tensors associated with the names in + the SignatureDef are provided. + + Args: + graph: GraphDef representing graph. + signature_def_tensor_names: Tensor names stored in either the inputs or + outputs of a SignatureDef. (default None) + user_tensor_names: Tensor names provided by the user. (default None) + + Returns: + List of tensors. + + Raises: + ValueError: + signature_def_tensors and user_tensor_names are undefined or empty. + user_tensor_names are not valid. + """ + tensors = [] + if user_tensor_names: + # Sort the tensor names. + user_tensor_names = sorted(user_tensor_names) + + tensors = util.get_tensors_from_tensor_names(graph, user_tensor_names) + elif signature_def_tensor_names: + tensors = [ + graph.get_tensor_by_name(name) + for name in sorted(signature_def_tensor_names) + ] + else: + # Throw ValueError if signature_def_tensors and user_tensor_names are both + # either undefined or empty. + raise ValueError( + "Specify either signature_def_tensor_names or user_tensor_names") + + return tensors + + +@convert_phase(Component.PREPARE_TF_MODEL, SubComponent.FREEZE_SAVED_MODEL) +def freeze_saved_model(saved_model_dir, input_arrays, input_shapes, + output_arrays, tag_set, signature_key): + """Converts a SavedModel to a frozen graph. + + Args: + saved_model_dir: SavedModel directory to convert. + input_arrays: List of input tensors to freeze graph with. Uses input arrays + from SignatureDef when none are provided. + input_shapes: Dict of strings representing input tensor names to list of + integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}). + Automatically determined when input shapes is None (e.g., {"foo" : None}). + output_arrays: List of output tensors to freeze graph with. Uses output + arrays from SignatureDef when none are provided. + tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to + analyze. All tags in the tag set must be present. + signature_key: Key identifying SignatureDef containing inputs and outputs. + + Returns: + frozen_graph_def: Frozen GraphDef. + in_tensors: List of input tensors for the graph. + out_tensors: List of output tensors for the graph. + graph: `Graph` object. + + Raises: + ValueError: + SavedModel doesn't contain a MetaGraphDef identified by tag_set. + signature_key is not in the MetaGraphDef. + assets/ directory is in the MetaGraphDef. + input_shapes does not match the length of input_arrays. + input_arrays or output_arrays are not valid. + """ + # Read SignatureDef. + meta_graph = get_meta_graph_def(saved_model_dir, tag_set) + signature_def = get_signature_def(meta_graph, signature_key) + inputs, outputs = get_inputs_outputs(signature_def) + + # Check SavedModel for assets directory. + collection_def = meta_graph.collection_def + if constants.ASSETS_KEY in collection_def: + raise ValueError("SavedModels with assets/ directory are not supported.") + + graph = ops.Graph() + with session.Session(graph=graph) as sess: + loader.load(sess, meta_graph.meta_info_def.tags, saved_model_dir) + + # Gets input and output tensors. + # TODO(zhixianyan): Use TFLite supported Op list to filter outputs. + in_tensors = _get_tensors(graph, inputs, input_arrays) + out_tensors = _get_tensors(graph, outputs, output_arrays) + util.set_tensor_shapes(in_tensors, input_shapes) + + frozen_graph_def = util.freeze_graph(sess, in_tensors, out_tensors) + return frozen_graph_def, in_tensors, out_tensors, sess.graph diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..ee50145345ebd1e052cdae168fa19afeb52cb893 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter.py @@ -0,0 +1,994 @@ +# 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. +# ============================================================================== +"""Python TF-Lite interpreter.""" +import ctypes +import enum +import os +import platform +import sys + +import numpy as np + +# pylint: disable=g-import-not-at-top +if not os.path.splitext(__file__)[0].endswith( + os.path.join('tflite_runtime', 'interpreter')): + # This file is part of tensorflow package. + from tensorflow.lite.python.interpreter_wrapper import _pywrap_tensorflow_interpreter_wrapper as _interpreter_wrapper + from tensorflow.lite.python.metrics import metrics + from tensorflow.python.util.tf_export import tf_export as _tf_export +else: + # This file is part of tflite_runtime package. + from tflite_runtime import _pywrap_tensorflow_interpreter_wrapper as _interpreter_wrapper + from tflite_runtime import metrics_portable as metrics + + def _tf_export(*x, **kwargs): + del x, kwargs + return lambda x: x + + +# pylint: enable=g-import-not-at-top + + +class Delegate: + """Python wrapper class to manage TfLiteDelegate objects. + + The shared library is expected to have two functions, + tflite_plugin_create_delegate and tflite_plugin_destroy_delegate, + which should implement the API specified in + tensorflow/lite/delegates/external/external_delegate_interface.h. + """ + + def __init__(self, library, options=None): + """Loads delegate from the shared library. + + Args: + library: Shared library name. + options: Dictionary of options that are required to load the delegate. All + keys and values in the dictionary should be serializable. Consult the + documentation of the specific delegate for required and legal options. + (default None) + + Raises: + RuntimeError: This is raised if the Python implementation is not CPython. + """ + + # TODO(b/136468453): Remove need for __del__ ordering needs of CPython + # by using explicit closes(). See implementation of Interpreter __del__. + if platform.python_implementation() != 'CPython': + raise RuntimeError('Delegates are currently only supported into CPython' + 'due to missing immediate reference counting.') + + self._library = ctypes.pydll.LoadLibrary(library) + self._library.tflite_plugin_create_delegate.argtypes = [ + ctypes.POINTER(ctypes.c_char_p), + ctypes.POINTER(ctypes.c_char_p), ctypes.c_int, + ctypes.CFUNCTYPE(None, ctypes.c_char_p) + ] + # The return type is really 'TfLiteDelegate*', but 'void*' is close enough. + self._library.tflite_plugin_create_delegate.restype = ctypes.c_void_p + + # Convert the options from a dictionary to lists of char pointers. + options = options or {} + options_keys = (ctypes.c_char_p * len(options))() + options_values = (ctypes.c_char_p * len(options))() + for idx, (key, value) in enumerate(options.items()): + options_keys[idx] = str(key).encode('utf-8') + options_values[idx] = str(value).encode('utf-8') + + class ErrorMessageCapture: + + def __init__(self): + self.message = '' + + def report(self, x): + self.message += x if isinstance(x, str) else x.decode('utf-8') + + capture = ErrorMessageCapture() + error_capturer_cb = ctypes.CFUNCTYPE(None, ctypes.c_char_p)(capture.report) + # Do not make a copy of _delegate_ptr. It is freed by Delegate's finalizer. + self._delegate_ptr = self._library.tflite_plugin_create_delegate( + options_keys, options_values, len(options), error_capturer_cb) + if self._delegate_ptr is None: + raise ValueError(capture.message) + + def __del__(self): + # __del__ can not be called multiple times, so if the delegate is destroyed. + # don't try to destroy it twice. + if self._library is not None: + self._library.tflite_plugin_destroy_delegate.argtypes = [ctypes.c_void_p] + self._library.tflite_plugin_destroy_delegate(self._delegate_ptr) + self._library = None + + def _get_native_delegate_pointer(self): + """Returns the native TfLiteDelegate pointer. + + It is not safe to copy this pointer because it needs to be freed. + + Returns: + TfLiteDelegate * + """ + return self._delegate_ptr + + +@_tf_export('lite.experimental.load_delegate') +def load_delegate(library, options=None): + """Returns loaded Delegate object. + + Example usage: + + ``` + import tensorflow as tf + + try: + delegate = tf.lite.experimental.load_delegate('delegate.so') + except ValueError: + // Fallback to CPU + + if delegate: + interpreter = tf.lite.Interpreter( + model_path='model.tflite', + experimental_delegates=[delegate]) + else: + interpreter = tf.lite.Interpreter(model_path='model.tflite') + ``` + + This is typically used to leverage EdgeTPU for running TensorFlow Lite models. + For more information see: https://coral.ai/docs/edgetpu/tflite-python/ + + Args: + library: Name of shared library containing the + [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates). + options: Dictionary of options that are required to load the delegate. All + keys and values in the dictionary should be convertible to str. Consult + the documentation of the specific delegate for required and legal options. + (default None) + + Returns: + Delegate object. + + Raises: + ValueError: Delegate failed to load. + RuntimeError: If delegate loading is used on unsupported platform. + """ + try: + delegate = Delegate(library, options) + except ValueError as e: + raise ValueError('Failed to load delegate from {}\n{}'.format( + library, str(e))) + return delegate + + +class SignatureRunner: + """SignatureRunner class for running TFLite models using SignatureDef. + + This class should be instantiated through TFLite Interpreter only using + get_signature_runner method on Interpreter. + Example, + signature = interpreter.get_signature_runner("my_signature") + result = signature(input_1=my_input_1, input_2=my_input_2) + print(result["my_output"]) + print(result["my_second_output"]) + All names used are this specific SignatureDef names. + + Notes: + No other function on this object or on the interpreter provided should be + called while this object call has not finished. + """ + + def __init__(self, interpreter=None, signature_key=None): + """Constructor. + + Args: + interpreter: Interpreter object that is already initialized with the + requested model. + signature_key: SignatureDef key to be used. + """ + if not interpreter: + raise ValueError('None interpreter provided.') + if not signature_key: + raise ValueError('None signature_key provided.') + self._interpreter = interpreter + self._interpreter_wrapper = interpreter._interpreter + self._signature_key = signature_key + signature_defs = interpreter._get_full_signature_list() + if signature_key not in signature_defs: + raise ValueError('Invalid signature_key provided.') + self._signature_def = signature_defs[signature_key] + self._outputs = self._signature_def['outputs'].items() + self._inputs = self._signature_def['inputs'] + + self._subgraph_index = ( + self._interpreter_wrapper.GetSubgraphIndexFromSignature( + self._signature_key)) + + def __call__(self, **kwargs): + """Runs the SignatureDef given the provided inputs in arguments. + + Args: + **kwargs: key,value for inputs to the model. Key is the SignatureDef input + name. Value is numpy array with the value. + + Returns: + dictionary of the results from the model invoke. + Key in the dictionary is SignatureDef output name. + Value is the result Tensor. + """ + + if len(kwargs) != len(self._inputs): + raise ValueError( + 'Invalid number of inputs provided for running a SignatureDef, ' + 'expected %s vs provided %s' % (len(self._inputs), len(kwargs))) + + # Resize input tensors + for input_name, value in kwargs.items(): + if input_name not in self._inputs: + raise ValueError('Invalid Input name (%s) for SignatureDef' % + input_name) + self._interpreter_wrapper.ResizeInputTensor( + self._inputs[input_name], np.array(value.shape, dtype=np.int32), + False, self._subgraph_index) + # Allocate tensors. + self._interpreter_wrapper.AllocateTensors(self._subgraph_index) + # Set the input values. + for input_name, value in kwargs.items(): + self._interpreter_wrapper.SetTensor(self._inputs[input_name], value, + self._subgraph_index) + + self._interpreter_wrapper.Invoke(self._subgraph_index) + result = {} + for output_name, output_index in self._outputs: + result[output_name] = self._interpreter_wrapper.GetTensor( + output_index, self._subgraph_index) + return result + + def get_input_details(self): + """Gets input tensor details. + + Returns: + A dictionary from input name to tensor details where each item is a + dictionary with details about an input tensor. Each dictionary contains + the following fields that describe the tensor: + + + `name`: The tensor name. + + `index`: The tensor index in the interpreter. + + `shape`: The shape of the tensor. + + `shape_signature`: Same as `shape` for models with known/fixed shapes. + If any dimension sizes are unknown, they are indicated with `-1`. + + `dtype`: The numpy data type (such as `np.int32` or `np.uint8`). + + `quantization`: Deprecated, use `quantization_parameters`. This field + only works for per-tensor quantization, whereas + `quantization_parameters` works in all cases. + + `quantization_parameters`: A dictionary of parameters used to quantize + the tensor: + ~ `scales`: List of scales (one if per-tensor quantization). + ~ `zero_points`: List of zero_points (one if per-tensor quantization). + ~ `quantized_dimension`: Specifies the dimension of per-axis + quantization, in the case of multiple scales/zero_points. + + `sparsity_parameters`: A dictionary of parameters used to encode a + sparse tensor. This is empty if the tensor is dense. + """ + result = {} + for input_name, tensor_index in self._inputs.items(): + result[input_name] = self._interpreter._get_tensor_details( # pylint: disable=protected-access + tensor_index, self._subgraph_index) + return result + + def get_output_details(self): + """Gets output tensor details. + + Returns: + A dictionary from input name to tensor details where each item is a + dictionary with details about an output tensor. The dictionary contains + the same fields as described for `get_input_details()`. + """ + result = {} + for output_name, tensor_index in self._outputs: + result[output_name] = self._interpreter._get_tensor_details( # pylint: disable=protected-access + tensor_index, self._subgraph_index) + return result + + +@_tf_export('lite.experimental.OpResolverType') +@enum.unique +class OpResolverType(enum.Enum): + """Different types of op resolvers for Tensorflow Lite. + + * `AUTO`: Indicates the op resolver that is chosen by default in TfLite + Python, which is the "BUILTIN" as described below. + * `BUILTIN`: Indicates the op resolver for built-in ops with optimized kernel + implementation. + * `BUILTIN_REF`: Indicates the op resolver for built-in ops with reference + kernel implementation. It's generally used for testing and debugging. + * `BUILTIN_WITHOUT_DEFAULT_DELEGATES`: Indicates the op resolver for + built-in ops with optimized kernel implementation, but it will disable + the application of default TfLite delegates (like the XNNPACK delegate) to + the model graph. Generally this should not be used unless there are issues + with the default configuration. + """ + # Corresponds to an op resolver chosen by default in TfLite Python. + AUTO = 0 + + # Corresponds to tflite::ops::builtin::BuiltinOpResolver in C++. + BUILTIN = 1 + + # Corresponds to tflite::ops::builtin::BuiltinRefOpResolver in C++. + BUILTIN_REF = 2 + + # Corresponds to + # tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates in C++. + BUILTIN_WITHOUT_DEFAULT_DELEGATES = 3 + + +def _get_op_resolver_id(op_resolver_type=OpResolverType.AUTO): + """Get a integer identifier for the op resolver.""" + + # Note: the integer identifier value needs to be same w/ op resolver ids + # defined in interpreter_wrapper/interpreter_wrapper.cc. + return { + # Note AUTO and BUILTIN currently share the same identifier. + OpResolverType.AUTO: 1, + OpResolverType.BUILTIN: 1, + OpResolverType.BUILTIN_REF: 2, + OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES: 3 + }.get(op_resolver_type, None) + + +@_tf_export('lite.Interpreter') +class Interpreter: + """Interpreter interface for running TensorFlow Lite models. + + Models obtained from `TfLiteConverter` can be run in Python with + `Interpreter`. + + As an example, lets generate a simple Keras model and convert it to TFLite + (`TfLiteConverter` also supports other input formats with `from_saved_model` + and `from_concrete_function`) + + >>> x = np.array([[1.], [2.]]) + >>> y = np.array([[2.], [4.]]) + >>> model = tf.keras.models.Sequential([ + ... tf.keras.layers.Dropout(0.2), + ... tf.keras.layers.Dense(units=1, input_shape=[1]) + ... ]) + >>> model.compile(optimizer='sgd', loss='mean_squared_error') + >>> model.fit(x, y, epochs=1) + >>> converter = tf.lite.TFLiteConverter.from_keras_model(model) + >>> tflite_model = converter.convert() + + `tflite_model` can be saved to a file and loaded later, or directly into the + `Interpreter`. Since TensorFlow Lite pre-plans tensor allocations to optimize + inference, the user needs to call `allocate_tensors()` before any inference. + + >>> interpreter = tf.lite.Interpreter(model_content=tflite_model) + >>> interpreter.allocate_tensors() # Needed before execution! + + Sample execution: + + >>> output = interpreter.get_output_details()[0] # Model has single output. + >>> input = interpreter.get_input_details()[0] # Model has single input. + >>> input_data = tf.constant(1., shape=[1, 1]) + >>> interpreter.set_tensor(input['index'], input_data) + >>> interpreter.invoke() + >>> interpreter.get_tensor(output['index']).shape + (1, 1) + + Use `get_signature_runner()` for a more user-friendly inference API. + """ + + def __init__( + self, + model_path=None, + model_content=None, + experimental_delegates=None, + num_threads=None, + experimental_op_resolver_type=OpResolverType.AUTO, + experimental_preserve_all_tensors=False, + experimental_disable_delegate_clustering=False, + ): + """Constructor. + + Args: + model_path: Path to TF-Lite Flatbuffer file. + model_content: Content of model. + experimental_delegates: Experimental. Subject to change. List of + [TfLiteDelegate](https://www.tensorflow.org/lite/performance/delegates) + objects returned by lite.load_delegate(). + num_threads: Sets the number of threads used by the interpreter and + available to CPU kernels. If not set, the interpreter will use an + implementation-dependent default number of threads. Currently, only a + subset of kernels, such as conv, support multi-threading. num_threads + should be >= -1. Setting num_threads to 0 has the effect to disable + multithreading, which is equivalent to setting num_threads to 1. If set + to the value -1, the number of threads used will be + implementation-defined and platform-dependent. + experimental_op_resolver_type: The op resolver used by the interpreter. It + must be an instance of OpResolverType. By default, we use the built-in + op resolver which corresponds to tflite::ops::builtin::BuiltinOpResolver + in C++. + experimental_preserve_all_tensors: If true, then intermediate tensors used + during computation are preserved for inspection, and if the passed op + resolver type is AUTO or BUILTIN, the type will be changed to + BUILTIN_WITHOUT_DEFAULT_DELEGATES so that no Tensorflow Lite default + delegates are applied. If false, getting intermediate tensors could + result in undefined values or None, especially when the graph is + successfully modified by the Tensorflow Lite default delegate. + experimental_disable_delegate_clustering: If true, don't perform delegate + clustering during delegate graph partitioning phase. Disabling delegate + clustering will make the execution order of ops respect the + explicitly-inserted control dependencies in the graph (inserted via + `with tf.control_dependencies()`) since the TF Lite converter will drop + control dependencies by default. Most users shouldn't turn this flag to + True if they don't insert explicit control dependencies or the graph + execution order is expected. For automatically inserted control + dependencies (with `tf.Variable`, `tf.Print` etc), the user doesn't need + to turn this flag to True since they are respected by default. Note that + this flag is currently experimental, and it might be removed/updated if + the TF Lite converter doesn't drop such control dependencies in the + model. Default is False. + + Raises: + ValueError: If the interpreter was unable to create. + """ + if not hasattr(self, '_custom_op_registerers'): + self._custom_op_registerers = [] + + actual_resolver_type = experimental_op_resolver_type + if experimental_preserve_all_tensors and ( + experimental_op_resolver_type == OpResolverType.AUTO or + experimental_op_resolver_type == OpResolverType.BUILTIN): + actual_resolver_type = OpResolverType.BUILTIN_WITHOUT_DEFAULT_DELEGATES + op_resolver_id = _get_op_resolver_id(actual_resolver_type) + if op_resolver_id is None: + raise ValueError('Unrecognized passed in op resolver type: {}'.format( + experimental_op_resolver_type)) + + if model_path and not model_content: + custom_op_registerers_by_name = [ + x for x in self._custom_op_registerers if isinstance(x, str) + ] + custom_op_registerers_by_func = [ + x for x in self._custom_op_registerers if not isinstance(x, str) + ] + self._interpreter = _interpreter_wrapper.CreateWrapperFromFile( + model_path, + op_resolver_id, + custom_op_registerers_by_name, + custom_op_registerers_by_func, + experimental_preserve_all_tensors, + experimental_disable_delegate_clustering, + ) + if not self._interpreter: + raise ValueError('Failed to open {}'.format(model_path)) + elif model_content and not model_path: + custom_op_registerers_by_name = [ + x for x in self._custom_op_registerers if isinstance(x, str) + ] + custom_op_registerers_by_func = [ + x for x in self._custom_op_registerers if not isinstance(x, str) + ] + # Take a reference, so the pointer remains valid. + # Since python strings are immutable then PyString_XX functions + # will always return the same pointer. + self._model_content = model_content + self._interpreter = _interpreter_wrapper.CreateWrapperFromBuffer( + model_content, + op_resolver_id, + custom_op_registerers_by_name, + custom_op_registerers_by_func, + experimental_preserve_all_tensors, + experimental_disable_delegate_clustering, + ) + elif not model_content and not model_path: + raise ValueError('`model_path` or `model_content` must be specified.') + else: + raise ValueError('Can\'t both provide `model_path` and `model_content`') + + if num_threads is not None: + if not isinstance(num_threads, int): + raise ValueError('type of num_threads should be int') + if num_threads < 1: + raise ValueError('num_threads should >= 1') + self._interpreter.SetNumThreads(num_threads) + + # Each delegate is a wrapper that owns the delegates that have been loaded + # as plugins. The interpreter wrapper will be using them, but we need to + # hold them in a list so that the lifetime is preserved at least as long as + # the interpreter wrapper. + self._delegates = [] + if experimental_delegates: + self._delegates = experimental_delegates + for delegate in self._delegates: + self._interpreter.ModifyGraphWithDelegate( + delegate._get_native_delegate_pointer()) # pylint: disable=protected-access + self._signature_defs = self.get_signature_list() + + self._metrics = metrics.TFLiteMetrics() + self._metrics.increase_counter_interpreter_creation() + + def __del__(self): + # Must make sure the interpreter is destroyed before things that + # are used by it like the delegates. NOTE this only works on CPython + # probably. + # TODO(b/136468453): Remove need for __del__ ordering needs of CPython + # by using explicit closes(). See implementation of Interpreter __del__. + self._interpreter = None + self._delegates = None + + def allocate_tensors(self): + self._ensure_safe() + return self._interpreter.AllocateTensors() + + def _safe_to_run(self): + """Returns true if there exist no numpy array buffers. + + This means it is safe to run tflite calls that may destroy internally + allocated memory. This works, because in the wrapper.cc we have made + the numpy base be the self._interpreter. + """ + # NOTE, our tensor() call in cpp will use _interpreter as a base pointer. + # If this environment is the only _interpreter, then the ref count should be + # 2 (1 in self and 1 in temporary of sys.getrefcount). + return sys.getrefcount(self._interpreter) == 2 + + def _ensure_safe(self): + """Makes sure no numpy arrays pointing to internal buffers are active. + + This should be called from any function that will call a function on + _interpreter that may reallocate memory e.g. invoke(), ... + + Raises: + RuntimeError: If there exist numpy objects pointing to internal memory + then we throw. + """ + if not self._safe_to_run(): + raise RuntimeError("""There is at least 1 reference to internal data + in the interpreter in the form of a numpy array or slice. Be sure to + only hold the function returned from tensor() if you are using raw + data access.""") + + # Experimental and subject to change + def _get_op_details(self, op_index): + """Gets a dictionary with arrays of ids for tensors involved with an op. + + Args: + op_index: Operation/node index of node to query. + + Returns: + a dictionary containing the index, op name, and arrays with lists of the + indices for the inputs and outputs of the op/node. + """ + op_index = int(op_index) + op_name = self._interpreter.NodeName(op_index) + op_inputs = self._interpreter.NodeInputs(op_index) + op_outputs = self._interpreter.NodeOutputs(op_index) + + details = { + 'index': op_index, + 'op_name': op_name, + 'inputs': op_inputs, + 'outputs': op_outputs, + } + + return details + + def _get_tensor_details(self, tensor_index, subgraph_index): + """Gets tensor details. + + Args: + tensor_index: Tensor index of tensor to query. + subgraph_index: Index of the subgraph. + + Returns: + A dictionary containing the following fields of the tensor: + 'name': The tensor name. + 'index': The tensor index in the interpreter. + 'shape': The shape of the tensor. + 'quantization': Deprecated, use 'quantization_parameters'. This field + only works for per-tensor quantization, whereas + 'quantization_parameters' works in all cases. + 'quantization_parameters': The parameters used to quantize the tensor: + 'scales': List of scales (one if per-tensor quantization) + 'zero_points': List of zero_points (one if per-tensor quantization) + 'quantized_dimension': Specifies the dimension of per-axis + quantization, in the case of multiple scales/zero_points. + + Raises: + ValueError: If tensor_index is invalid. + """ + tensor_index = int(tensor_index) + subgraph_index = int(subgraph_index) + tensor_name = self._interpreter.TensorName(tensor_index, subgraph_index) + tensor_size = self._interpreter.TensorSize(tensor_index, subgraph_index) + tensor_size_signature = self._interpreter.TensorSizeSignature( + tensor_index, subgraph_index) + tensor_type = self._interpreter.TensorType(tensor_index, subgraph_index) + tensor_quantization = self._interpreter.TensorQuantization( + tensor_index, subgraph_index) + tensor_quantization_params = self._interpreter.TensorQuantizationParameters( + tensor_index, subgraph_index) + tensor_sparsity_params = self._interpreter.TensorSparsityParameters( + tensor_index, subgraph_index) + + if not tensor_type: + raise ValueError('Could not get tensor details') + + details = { + 'name': tensor_name, + 'index': tensor_index, + 'shape': tensor_size, + 'shape_signature': tensor_size_signature, + 'dtype': tensor_type, + 'quantization': tensor_quantization, + 'quantization_parameters': { + 'scales': tensor_quantization_params[0], + 'zero_points': tensor_quantization_params[1], + 'quantized_dimension': tensor_quantization_params[2], + }, + 'sparsity_parameters': tensor_sparsity_params + } + + return details + + # Experimental and subject to change + def _get_ops_details(self): + """Gets op details for every node. + + Returns: + A list of dictionaries containing arrays with lists of tensor ids for + tensors involved in the op. + """ + return [ + self._get_op_details(idx) for idx in range(self._interpreter.NumNodes()) + ] + + def get_tensor_details(self): + """Gets tensor details for every tensor with valid tensor details. + + Tensors where required information about the tensor is not found are not + added to the list. This includes temporary tensors without a name. + + Returns: + A list of dictionaries containing tensor information. + """ + tensor_details = [] + for idx in range(self._interpreter.NumTensors(0)): + try: + tensor_details.append(self._get_tensor_details(idx, subgraph_index=0)) + except ValueError: + pass + return tensor_details + + def get_input_details(self): + """Gets model input tensor details. + + Returns: + A list in which each item is a dictionary with details about + an input tensor. Each dictionary contains the following fields + that describe the tensor: + + + `name`: The tensor name. + + `index`: The tensor index in the interpreter. + + `shape`: The shape of the tensor. + + `shape_signature`: Same as `shape` for models with known/fixed shapes. + If any dimension sizes are unknown, they are indicated with `-1`. + + `dtype`: The numpy data type (such as `np.int32` or `np.uint8`). + + `quantization`: Deprecated, use `quantization_parameters`. This field + only works for per-tensor quantization, whereas + `quantization_parameters` works in all cases. + + `quantization_parameters`: A dictionary of parameters used to quantize + the tensor: + ~ `scales`: List of scales (one if per-tensor quantization). + ~ `zero_points`: List of zero_points (one if per-tensor quantization). + ~ `quantized_dimension`: Specifies the dimension of per-axis + quantization, in the case of multiple scales/zero_points. + + `sparsity_parameters`: A dictionary of parameters used to encode a + sparse tensor. This is empty if the tensor is dense. + """ + return [ + self._get_tensor_details(i, subgraph_index=0) + for i in self._interpreter.InputIndices() + ] + + def set_tensor(self, tensor_index, value): + """Sets the value of the input tensor. + + Note this copies data in `value`. + + If you want to avoid copying, you can use the `tensor()` function to get a + numpy buffer pointing to the input buffer in the tflite interpreter. + + Args: + tensor_index: Tensor index of tensor to set. This value can be gotten from + the 'index' field in get_input_details. + value: Value of tensor to set. + + Raises: + ValueError: If the interpreter could not set the tensor. + """ + self._interpreter.SetTensor(tensor_index, value) + + def resize_tensor_input(self, input_index, tensor_size, strict=False): + """Resizes an input tensor. + + Args: + input_index: Tensor index of input to set. This value can be gotten from + the 'index' field in get_input_details. + tensor_size: The tensor_shape to resize the input to. + strict: Only unknown dimensions can be resized when `strict` is True. + Unknown dimensions are indicated as `-1` in the `shape_signature` + attribute of a given tensor. (default False) + + Raises: + ValueError: If the interpreter could not resize the input tensor. + + Usage: + ``` + interpreter = Interpreter(model_content=tflite_model) + interpreter.resize_tensor_input(0, [num_test_images, 224, 224, 3]) + interpreter.allocate_tensors() + interpreter.set_tensor(0, test_images) + interpreter.invoke() + ``` + """ + self._ensure_safe() + # `ResizeInputTensor` now only accepts int32 numpy array as `tensor_size + # parameter. + tensor_size = np.array(tensor_size, dtype=np.int32) + self._interpreter.ResizeInputTensor(input_index, tensor_size, strict) + + def get_output_details(self): + """Gets model output tensor details. + + Returns: + A list in which each item is a dictionary with details about + an output tensor. The dictionary contains the same fields as + described for `get_input_details()`. + """ + return [ + self._get_tensor_details(i, subgraph_index=0) + for i in self._interpreter.OutputIndices() + ] + + def get_signature_list(self): + """Gets list of SignatureDefs in the model. + + Example, + ``` + signatures = interpreter.get_signature_list() + print(signatures) + + # { + # 'add': {'inputs': ['x', 'y'], 'outputs': ['output_0']} + # } + + Then using the names in the signature list you can get a callable from + get_signature_runner(). + ``` + + Returns: + A list of SignatureDef details in a dictionary structure. + It is keyed on the SignatureDef method name, and the value holds + dictionary of inputs and outputs. + """ + full_signature_defs = self._interpreter.GetSignatureDefs() + for _, signature_def in full_signature_defs.items(): + signature_def['inputs'] = list(signature_def['inputs'].keys()) + signature_def['outputs'] = list(signature_def['outputs'].keys()) + return full_signature_defs + + def _get_full_signature_list(self): + """Gets list of SignatureDefs in the model. + + Example, + ``` + signatures = interpreter._get_full_signature_list() + print(signatures) + + # { + # 'add': {'inputs': {'x': 1, 'y': 0}, 'outputs': {'output_0': 4}} + # } + + Then using the names in the signature list you can get a callable from + get_signature_runner(). + ``` + + Returns: + A list of SignatureDef details in a dictionary structure. + It is keyed on the SignatureDef method name, and the value holds + dictionary of inputs and outputs. + """ + return self._interpreter.GetSignatureDefs() + + def get_signature_runner(self, signature_key=None): + """Gets callable for inference of specific SignatureDef. + + Example usage, + ``` + interpreter = tf.lite.Interpreter(model_content=tflite_model) + interpreter.allocate_tensors() + fn = interpreter.get_signature_runner('div_with_remainder') + output = fn(x=np.array([3]), y=np.array([2])) + print(output) + # { + # 'quotient': array([1.], dtype=float32) + # 'remainder': array([1.], dtype=float32) + # } + ``` + + None can be passed for signature_key if the model has a single Signature + only. + + All names used are this specific SignatureDef names. + + + Args: + signature_key: Signature key for the SignatureDef, it can be None if and + only if the model has a single SignatureDef. Default value is None. + + Returns: + This returns a callable that can run inference for SignatureDef defined + by argument 'signature_key'. + The callable will take key arguments corresponding to the arguments of the + SignatureDef, that should have numpy values. + The callable will returns dictionary that maps from output names to numpy + values of the computed results. + + Raises: + ValueError: If passed signature_key is invalid. + """ + if signature_key is None: + if len(self._signature_defs) != 1: + raise ValueError( + 'SignatureDef signature_key is None and model has {0} Signatures. ' + 'None is only allowed when the model has 1 SignatureDef'.format( + len(self._signature_defs))) + else: + signature_key = next(iter(self._signature_defs)) + return SignatureRunner(interpreter=self, signature_key=signature_key) + + def get_tensor(self, tensor_index, subgraph_index=0): + """Gets the value of the output tensor (get a copy). + + If you wish to avoid the copy, use `tensor()`. This function cannot be used + to read intermediate results. + + Args: + tensor_index: Tensor index of tensor to get. This value can be gotten from + the 'index' field in get_output_details. + subgraph_index: Index of the subgraph to fetch the tensor. Default value + is 0, which means to fetch from the primary subgraph. + + Returns: + a numpy array. + """ + return self._interpreter.GetTensor(tensor_index, subgraph_index) + + def tensor(self, tensor_index): + """Returns function that gives a numpy view of the current tensor buffer. + + This allows reading and writing to this tensors w/o copies. This more + closely mirrors the C++ Interpreter class interface's tensor() member, hence + the name. Be careful to not hold these output references through calls + to `allocate_tensors()` and `invoke()`. This function cannot be used to read + intermediate results. + + Usage: + + ``` + interpreter.allocate_tensors() + input = interpreter.tensor(interpreter.get_input_details()[0]["index"]) + output = interpreter.tensor(interpreter.get_output_details()[0]["index"]) + for i in range(10): + input().fill(3.) + interpreter.invoke() + print("inference %s" % output()) + ``` + + Notice how this function avoids making a numpy array directly. This is + because it is important to not hold actual numpy views to the data longer + than necessary. If you do, then the interpreter can no longer be invoked, + because it is possible the interpreter would resize and invalidate the + referenced tensors. The NumPy API doesn't allow any mutability of the + the underlying buffers. + + WRONG: + + ``` + input = interpreter.tensor(interpreter.get_input_details()[0]["index"])() + output = interpreter.tensor(interpreter.get_output_details()[0]["index"])() + interpreter.allocate_tensors() # This will throw RuntimeError + for i in range(10): + input.fill(3.) + interpreter.invoke() # this will throw RuntimeError since input,output + ``` + + Args: + tensor_index: Tensor index of tensor to get. This value can be gotten from + the 'index' field in get_output_details. + + Returns: + A function that can return a new numpy array pointing to the internal + TFLite tensor state at any point. It is safe to hold the function forever, + but it is not safe to hold the numpy array forever. + """ + return lambda: self._interpreter.tensor(self._interpreter, tensor_index) + + def invoke(self): + """Invoke the interpreter. + + Be sure to set the input sizes, allocate tensors and fill values before + calling this. Also, note that this function releases the GIL so heavy + computation can be done in the background while the Python interpreter + continues. No other function on this object should be called while the + invoke() call has not finished. + + Raises: + ValueError: When the underlying interpreter fails raise ValueError. + """ + self._ensure_safe() + self._interpreter.Invoke() + + def reset_all_variables(self): + return self._interpreter.ResetVariableTensors() + + # Experimental and subject to change. + def _native_handle(self): + """Returns a pointer to the underlying tflite::Interpreter instance. + + This allows extending tflite.Interpreter's functionality in a custom C++ + function. Consider how that may work in a custom pybind wrapper: + + m.def("SomeNewFeature", ([](py::object handle) { + auto* interpreter = + reinterpret_cast(handle.cast()); + ... + })) + + and corresponding Python call: + + SomeNewFeature(interpreter.native_handle()) + + Note: This approach is fragile. Users must guarantee the C++ extension build + is consistent with the tflite.Interpreter's underlying C++ build. + """ + return self._interpreter.interpreter() + + +class InterpreterWithCustomOps(Interpreter): + """Interpreter interface for TensorFlow Lite Models that accepts custom ops. + + The interface provided by this class is experimental and therefore not exposed + as part of the public API. + + Wraps the tf.lite.Interpreter class and adds the ability to load custom ops + by providing the names of functions that take a pointer to a BuiltinOpResolver + and add a custom op. + """ + + def __init__(self, custom_op_registerers=None, **kwargs): + """Constructor. + + Args: + custom_op_registerers: List of str (symbol names) or functions that take a + pointer to a MutableOpResolver and register a custom op. When passing + functions, use a pybind function that takes a uintptr_t that can be + recast as a pointer to a MutableOpResolver. + **kwargs: Additional arguments passed to Interpreter. + + Raises: + ValueError: If the interpreter was unable to create. + """ + self._custom_op_registerers = custom_op_registerers or [] + super(InterpreterWithCustomOps, self).__init__(**kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6e53124f39d9b8b635714e5f2c847a125965fe6d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/interpreter_wrapper/_pywrap_tensorflow_interpreter_wrapper.pyi @@ -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. +# ============================================================================== + +from typing import Any + +class InterpreterWrapper: + def __init__(self, *args, **kwargs) -> None: ... + def AllocateTensors(self, subgraph_index: int = ...) -> object: ... + def GetSignatureDefs(self) -> object: ... + def GetSubgraphIndexFromSignature(self, arg0: str) -> object: ... + def GetTensor(self, tensor_index: int, subgraph_index: int = ...) -> object: ... + def InputIndices(self) -> object: ... + def Invoke(self, subgraph_index: int = ...) -> object: ... + def ModifyGraphWithDelegate(self, arg0: int) -> object: ... + def NodeInputs(self, arg0: int) -> object: ... + def NodeName(self, arg0: int) -> str: ... + def NodeOutputs(self, arg0: int) -> object: ... + def NumNodes(self) -> int: ... + def NumTensors(self, arg0: int) -> int: ... + def OutputIndices(self) -> object: ... + def ResetVariableTensors(self) -> object: ... + def ResizeInputTensor(self, i: int, value: object, strict: bool, subgraph_index: int = ...) -> object: ... + def SetNumThreads(self, arg0: int) -> object: ... + def SetTensor(self, i: int, value: object, subgraph_index: int = ...) -> object: ... + def TensorName(self, arg0: int, arg1: int) -> str: ... + def TensorQuantization(self, arg0: int, arg1: int) -> object: ... + def TensorQuantizationParameters(self, arg0: int, arg1: int) -> object: ... + def TensorSize(self, arg0: int, arg1: int) -> object: ... + def TensorSizeSignature(self, arg0: int, arg1: int) -> object: ... + def TensorSparsityParameters(self, arg0: int, arg1: int) -> object: ... + def TensorType(self, arg0: int, arg1: int) -> object: ... + def interpreter(self) -> int: ... + def tensor(self, base_object: object, tensor_index: int, subgraph_index: int = ...) -> object: ... + +def CreateWrapperFromBuffer(*args, **kwargs) -> Any: ... +def CreateWrapperFromFile(*args, **kwargs) -> Any: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite.py new file mode 100644 index 0000000000000000000000000000000000000000..956825ba639b6ff2a937b55bf4823f270b989744 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite.py @@ -0,0 +1,3271 @@ +# 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. +# ============================================================================== +"""TensorFlow Lite tooling helper functionality.""" + +import enum +import functools +import pprint +import shutil +import sys +import tempfile +import time +import warnings + +from absl import logging + +from google.protobuf import text_format as _text_format +from google.protobuf.message import DecodeError +from tensorflow.core.framework import graph_pb2 as _graph_pb2 +from tensorflow.lite.experimental.microfrontend.python.ops import audio_microfrontend_op # pylint: disable=unused-import +from tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metdata_fb +from tensorflow.lite.python import lite_constants as constants +from tensorflow.lite.python.convert import convert_graphdef as _convert_graphdef +from tensorflow.lite.python.convert import convert_graphdef_with_arrays as _convert_graphdef_with_arrays +from tensorflow.lite.python.convert import convert_jax_hlo as _convert_jax_hlo +from tensorflow.lite.python.convert import convert_saved_model as _convert_saved_model +from tensorflow.lite.python.convert import ConverterError # pylint: disable=unused-import +from tensorflow.lite.python.convert import deduplicate_readonly_buffers as _deduplicate_readonly_buffers +from tensorflow.lite.python.convert import mlir_quantize as _mlir_quantize +from tensorflow.lite.python.convert import mlir_sparsify as _mlir_sparsify +from tensorflow.lite.python.convert import OpsSet +from tensorflow.lite.python.convert import toco_convert # pylint: disable=unused-import +from tensorflow.lite.python.convert_phase import Component +from tensorflow.lite.python.convert_phase import convert_phase +from tensorflow.lite.python.convert_phase import SubComponent +from tensorflow.lite.python.convert_saved_model import freeze_saved_model as _freeze_saved_model +from tensorflow.lite.python.interpreter import Interpreter # pylint: disable=unused-import +from tensorflow.lite.python.interpreter import load_delegate # pylint: disable=unused-import +from tensorflow.lite.python.interpreter import OpResolverType # pylint: disable=unused-import +from tensorflow.lite.python.metrics import metrics +from tensorflow.lite.python.op_hint import convert_op_hints_to_stubs # pylint: disable=unused-import +from tensorflow.lite.python.op_hint import is_ophint_converted as _is_ophint_converted +from tensorflow.lite.python.op_hint import OpHint # pylint: disable=unused-import +from tensorflow.lite.python.optimize import calibrator as _calibrator +from tensorflow.lite.python.util import _xla_computation +from tensorflow.lite.python.util import build_debug_info_func as _build_debug_info_func +from tensorflow.lite.python.util import convert_debug_info_func as _convert_debug_info_func +from tensorflow.lite.python.util import freeze_graph as _freeze_graph +from tensorflow.lite.python.util import get_debug_info as _get_debug_info +from tensorflow.lite.python.util import get_grappler_config as _get_grappler_config +from tensorflow.lite.python.util import get_sparsity_modes as _get_sparsity_modes +from tensorflow.lite.python.util import get_tensor_name as _get_tensor_name +from tensorflow.lite.python.util import get_tensors_from_tensor_names as _get_tensors_from_tensor_names +from tensorflow.lite.python.util import get_tf_type_name as _get_tf_type_name +from tensorflow.lite.python.util import is_frozen_graph as _is_frozen_graph +from tensorflow.lite.python.util import model_input_signature as _model_input_signature +from tensorflow.lite.python.util import modify_model_io_type as _modify_model_io_type +from tensorflow.lite.python.util import populate_conversion_metadata as _populate_conversion_metadata +from tensorflow.lite.python.util import run_graph_optimizations as _run_graph_optimizations +from tensorflow.lite.python.util import set_tensor_shapes as _set_tensor_shapes +from tensorflow.lite.python.util import trace_model_call as _trace_model_call +from tensorflow.lite.tools import flatbuffer_utils +from tensorflow.lite.tools.optimize.debugging.python.debugger import QuantizationDebugger # pylint: disable=unused-import +from tensorflow.lite.tools.optimize.debugging.python.debugger import QuantizationDebugOptions # pylint: disable=unused-import +from tensorflow.python.client import session as _session +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function as _def_function +from tensorflow.python.eager import function as _function +from tensorflow.python.framework import byte_swap_tensor as bst +from tensorflow.python.framework import convert_to_constants as _convert_to_constants +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import versions +from tensorflow.python.framework.errors_impl import NotFoundError as _NotFoundError +from tensorflow.python.framework.importer import import_graph_def as _import_graph_def +from tensorflow.python.platform import gfile +from tensorflow.python.saved_model import loader_impl as _loader_impl +from tensorflow.python.saved_model import save as _save +from tensorflow.python.saved_model import save_options as _save_options +from tensorflow.python.saved_model import signature_constants as _signature_constants +from tensorflow.python.saved_model import tag_constants as _tag_constants +from tensorflow.python.saved_model.load import load as _load +from tensorflow.python.saved_model.loader_impl import parse_saved_model_with_debug_info as _parse_saved_model_with_debug_info +from tensorflow.python.util import deprecation as _deprecation +from tensorflow.python.util import keras_deps +from tensorflow.python.util.tf_export import tf_export as _tf_export + + +@_tf_export("lite.Optimize") +class Optimize(enum.Enum): + """Enum defining the optimizations to apply when generating a tflite model. + + DEFAULT + The default optimization strategy that enables post-training quantization. + The type of post-training quantization that will be used is dependent on + the other converter options supplied. Refer to the + [documentation](/lite/performance/post_training_quantization) for further + information on the types available and how to use them. + + OPTIMIZE_FOR_SIZE + Deprecated. Does the same as DEFAULT. + + OPTIMIZE_FOR_LATENCY + Deprecated. Does the same as DEFAULT. + + EXPERIMENTAL_SPARSITY + Experimental flag, subject to change. + + Enable optimization by taking advantage of the sparse model weights + trained with pruning. + + The converter will inspect the sparsity pattern of the model weights and + do its best to improve size and latency. + The flag can be used alone to optimize float32 models with sparse weights. + It can also be used together with the DEFAULT optimization mode to + optimize quantized models with sparse weights. + """ + + # Default optimization strategy that quantizes model weights. Enhanced + # optimizations are gained by providing a representative dataset that + # quantizes biases and activations as well. + # Converter will do its best to reduce size and latency, while minimizing + # the loss in accuracy. + DEFAULT = "DEFAULT" + + # Deprecated. Does the same as DEFAULT. + OPTIMIZE_FOR_SIZE = "OPTIMIZE_FOR_SIZE" + + # Deprecated. Does the same as DEFAULT. + OPTIMIZE_FOR_LATENCY = "OPTIMIZE_FOR_LATENCY" + + # Experimental flag, subject to change. + # Enable optimization by taking advantage of the sparse model weights trained + # with pruning. + # + # The converter will inspect the sparsity pattern of the model weights and do + # its best to improve size and latency. + # The flag can be used alone to optimize float32 models with sparse weights. + # It can also be used together with the DEFAULT optimization mode to optimize + # quantized models with sparse weights. + # TODO(b/161560631): Add log message when this optimization is applied. + EXPERIMENTAL_SPARSITY = "EXPERIMENTAL_SPARSITY" + + def __str__(self): + return str(self.value) + + +# TODO(b/198099651): move converter implementation out of lite.py +@_tf_export("lite.RepresentativeDataset") +class RepresentativeDataset: + """Representative dataset used to optimize the model. + + This is a generator function that provides a small dataset to calibrate or + estimate the range, i.e, (min, max) of all floating-point arrays in the model + (such as model input, activation outputs of intermediate layers, and model + output) for quantization. Usually, this is a small subset of a few hundred + samples randomly chosen, in no particular order, from the training or + evaluation dataset. + """ + + def __init__(self, input_gen): + """Creates a representative dataset. + + Args: + input_gen: A generator function that generates input samples for the model + and has the same order, type and shape as the inputs to the model. + Usually, this is a small subset of a few hundred samples randomly + chosen, in no particular order, from the training or evaluation dataset. + """ + self.input_gen = input_gen + + +@_tf_export("lite.TargetSpec") +class TargetSpec: + """Specification of target device used to optimize the model. + + Attributes: + supported_ops: Experimental flag, subject to change. Set of `tf.lite.OpsSet` + options, where each option represents a set of operators supported by the + target device. (default {tf.lite.OpsSet.TFLITE_BUILTINS})) + supported_types: Set of `tf.dtypes.DType` data types supported on the target + device. If initialized, optimization might be driven by the smallest type + in this set. (default set()) + experimental_select_user_tf_ops: Experimental flag, subject to change. Set + of user's TensorFlow operators' names that are required in the TensorFlow + Lite runtime. These ops will be exported as select TensorFlow ops in the + model (in conjunction with the tf.lite.OpsSet.SELECT_TF_OPS flag). This is + an advanced feature that should only be used if the client is using TF ops + that may not be linked in by default with the TF ops that are provided + when using the SELECT_TF_OPS path. The client is responsible for linking + these ops into the target runtime. + experimental_supported_backends: Experimental flag, subject to change. Set + containing names of supported backends. Currently only "GPU" is supported, + more options will be available later. + """ + + def __init__( + self, + supported_ops=None, + supported_types=None, + experimental_select_user_tf_ops=None, + experimental_supported_backends=None, + ): + if supported_ops is None: + supported_ops = {OpsSet.TFLITE_BUILTINS} + self.supported_ops = supported_ops + if supported_types is None: + supported_types = set() + self.supported_types = supported_types + if experimental_select_user_tf_ops is None: + experimental_select_user_tf_ops = set() + self.experimental_select_user_tf_ops = experimental_select_user_tf_ops + self.experimental_supported_backends = experimental_supported_backends + self._experimental_custom_op_registerers = [] + # Hint for the supported accumulation type used for inference. Typically + # used for fp16 post-training quantization, where some models can use fp16 + # accumulators instead of the typical fp32 type. + # TODO(b/188185962): Provide full API and authoring support for + # reduced precision accumulation types. + self._experimental_supported_accumulation_type = None + + +class QuantizationMode: + """QuantizationMode determines the quantization type from user options.""" + + def __init__( + self, + optimizations, + target_spec, + representative_dataset, + graph_def, + disable_per_channel=False, + experimental_new_dynamic_range_quantizer=False, + experimental_low_bit_qat=False, + full_integer_quantization_bias_type=None, + experimental_mlir_variable_quantization=False, + ): + self._optimizations = optimizations + for deprecated_optimization in [ + Optimize.OPTIMIZE_FOR_SIZE, + Optimize.OPTIMIZE_FOR_LATENCY, + ]: + if deprecated_optimization in self._optimizations: + logging.warning( + ( + "Optimization option %s is deprecated, please use" + " optimizations=[Optimize.DEFAULT] instead." + ), + deprecated_optimization, + ) + + self._target_spec = target_spec + self._representative_dataset = representative_dataset + self._graph_def = graph_def + if self._is_int8_target_required(): + self._validate_int8_required() + + self.enable_mlir_variable_quantization = ( + experimental_mlir_variable_quantization + ) + if self._is_float16_target_required(): + self._validate_float16_required() + self._disable_per_channel = disable_per_channel + + self._enable_new_dynamic_range_quantizer = ( + experimental_new_dynamic_range_quantizer + ) + # Allow training with lower than 8 bit weights to be converted + # to constants with trained scale. + self._experimental_low_bit_qat = experimental_low_bit_qat + + self._full_integer_quantization_bias_type = ( + full_integer_quantization_bias_type + ) + self._validate_full_integer_quantization_bias_type() + + def is_post_training_int8_only_quantization(self): + return ( + self.is_any_optimization_enabled() + and self._representative_dataset is not None + and not self._is_int16x8_target_required() + and not self.is_allow_float() + and self._is_int8_target_required() + ) + + def is_post_training_int8_quantization_with_float_fallback(self): + return ( + self.is_any_optimization_enabled() + and self._representative_dataset is not None + and not self._is_int16x8_target_required() + and self.is_allow_float() + and self._smallest_supported_type() == _dtypes.int8 + ) + + def is_post_training_int8_quantization(self): + return ( + self.is_post_training_int8_only_quantization() + or self.is_post_training_int8_quantization_with_float_fallback() + ) + + def is_post_training_int16x8_only_quantization(self): + return ( + self.is_any_optimization_enabled() + and self._representative_dataset is not None + and self._is_int16x8_target_required() + and not self.is_allow_float() + ) + + def is_post_training_int16x8_quantization_with_float_fallback(self): + return ( + self.is_any_optimization_enabled() + and self._representative_dataset is not None + and self._is_int16x8_target_required() + and self.is_allow_float() + ) + + def is_post_training_int16x8_quantization(self): + return ( + self.is_post_training_int16x8_only_quantization() + or self.is_post_training_int16x8_quantization_with_float_fallback() + ) + + def is_post_training_integer_quantization(self): + return ( + self.is_post_training_int8_quantization() + or self.is_post_training_int16x8_quantization() + ) + + def is_low_bit_quantize_aware_training(self): + return ( + self.is_any_optimization_enabled() + and self.is_quantization_aware_trained_model() + and self._experimental_low_bit_qat + ) + + def is_quantization_aware_training(self): + return ( + self.is_any_optimization_enabled() + and self.is_quantization_aware_trained_model() + and not self.is_low_bit_quantize_aware_training() + ) + + def is_integer_quantization(self): + return ( + self.is_post_training_integer_quantization() + or self.is_quantization_aware_training() + or self.is_low_bit_quantize_aware_training() + ) + + def is_post_training_dynamic_range_quantization(self): + # Post-training dynamic range quantization is only enabled if post-training + # int8 quantization and training time quantization was not done. + return ( + self.is_any_optimization_enabled() + and self._representative_dataset is None + and not self.is_quantization_aware_trained_model() + and self._smallest_supported_type() == _dtypes.int8 + ) + + def is_post_training_float16_quantization(self): + return ( + self.is_any_optimization_enabled() + and self._smallest_supported_type().size == 2 + and _dtypes.float16 in self._target_spec.supported_types + ) + + def is_bfloat16_quantization(self): + return ( + self.is_any_optimization_enabled() + and self._smallest_supported_type().size == 2 + and _dtypes.bfloat16 in self._target_spec.supported_types + ) + + def activations_type(self): + if self.is_integer_quantization(): + if self._is_int16x8_target_required(): + return _dtypes.int16 + else: + return _dtypes.int8 + else: + return _dtypes.float32 + + def bias_type(self): + if self._full_integer_quantization_bias_type: + return self._full_integer_quantization_bias_type + + if self.activations_type() == _dtypes.int16: + return _dtypes.int64 + elif self.activations_type() == _dtypes.int8: + return _dtypes.int32 + else: + return _dtypes.float32 + + def converter_flags(self, inference_ty=None, inference_input_ty=None): + """Flags to the converter.""" + + if self.is_integer_quantization(): + is_low_bit_qat = self.is_low_bit_quantize_aware_training() + return { + "inference_type": ( + inference_ty + if inference_ty is not None + else self.activations_type() + ), + "inference_input_type": _dtypes.float32, + "post_training_quantize": False, # disable dynamic range quantization + "quantize_to_float16": False, # disable float16 quantization + "disable_infer_tensor_range": is_low_bit_qat, + "use_fake_quant_num_bits": is_low_bit_qat, + "enable_mlir_variable_quantization": ( + self.enable_mlir_variable_quantization + ), + } + elif self.is_post_training_dynamic_range_quantization(): + return { + "inference_type": _dtypes.float32, + "inference_input_type": _dtypes.float32, + "post_training_quantize": True, # enable dynamic range quantization + "quantize_to_float16": False, # disable float16 quantization + # experimental: disable per-channel (per-axis) quantization. + "disable_per_channel_quantization": self._disable_per_channel, + "enable_mlir_dynamic_range_quantizer": ( + self._enable_new_dynamic_range_quantizer + ), + "enable_mlir_variable_quantization": ( + self.enable_mlir_variable_quantization + ), + } + elif self.is_post_training_float16_quantization(): + return { + "inference_type": _dtypes.float32, + "inference_input_type": _dtypes.float32, + "post_training_quantize": True, + "quantize_to_float16": True, # enable float16 quantization + # pylint: disable=protected-access + "accumulation_type": ( + self._target_spec._experimental_supported_accumulation_type + ), + # pylint: enable=protected-access + "allow_bfloat16": self.is_bfloat16_quantization(), + "enable_mlir_dynamic_range_quantizer": ( + self._enable_new_dynamic_range_quantizer + ), + "enable_mlir_variable_quantization": ( + self.enable_mlir_variable_quantization + ), + } + else: + # Note this might still trigger (uint8) quantization to be compatible with + # the old converter. + return { + "inference_type": ( + inference_ty if inference_ty is not None else _dtypes.float32 + ), + "inference_input_type": inference_input_ty, + "post_training_quantize": False, # enable dynamic range quantization + "quantize_to_float16": False, # disable float16 quantization + "allow_bfloat16": self.is_bfloat16_quantization(), + } + + # Below are helpers for the above functions. + + def _validate_int8_required(self): + """Int8 mode requires certain parameters to exist and be compatible.""" + # Validate target_spec attibute. + if set(self._target_spec.supported_ops) == { + OpsSet.TFLITE_BUILTINS_INT8 + } and not ( + set(self._target_spec.supported_types) == set() + or set(self._target_spec.supported_types) == {_dtypes.int8} + ): + raise ValueError( + "As full integer quantization has been enabled by setting " + "`target_spec.supported_ops`={tf.lite.OpsSet.TFLITE_BUILTINS_INT8}, " + "thus `target_spec.supported_types` should be left uninitizalized " + "or set to {tf.int8}." + ) + if set(self._target_spec.supported_types) == {_dtypes.int8}: + self._target_spec.supported_ops = {OpsSet.TFLITE_BUILTINS_INT8} + + # Check if representative_dataset is specified. + if ( + not self._representative_dataset + and not self.is_quantization_aware_training() + ): + raise ValueError( + "For full integer quantization, a " + "`representative_dataset` must be specified." + ) + + # Update represenative dataset to the expected format. + if self._representative_dataset: + if not isinstance(self._representative_dataset, RepresentativeDataset): + self._representative_dataset = RepresentativeDataset( + self._representative_dataset + ) + + def _validate_float16_required(self): + """Float16 mode requires certain parameters to exist and be compatible.""" + if self.enable_mlir_variable_quantization: + raise ValueError( + "`_experimental_variable_quantization` is only supported for full" + " integer quantization." + ) + + def _validate_full_integer_quantization_bias_type(self): + """Validates bias type for full interger quantization.""" + bias_type = self._full_integer_quantization_bias_type + if not bias_type: + return + + if self.activations_type() == _dtypes.float32: + raise ValueError( + "`full_integer_quantization_bias_type` is only supported for full" + " integer quantization." + ) + + if self.activations_type() == _dtypes.int8 and bias_type != _dtypes.int32: + raise ValueError( + "Expected bias type to be `dtypes.int32` for Int8Quant. " + f"Current setting bias type: {bias_type}" + ) + + if ( + self.activations_type() == _dtypes.int16 + and bias_type != _dtypes.int32 + and bias_type != _dtypes.int64 + ): + raise ValueError( + "Expected bias type to be `dtypes.int32` or `dtypes.int64` for " + f"Int16Quant. Current setting bias type: {bias_type}" + ) + + def _is_int8_target_required(self): + return ( + OpsSet.TFLITE_BUILTINS_INT8 in set(self._target_spec.supported_ops) + ) or (set(self._target_spec.supported_types) == set([_dtypes.int8])) + + def _is_int16x8_target_required(self): + return ( + OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8 + in set(self._target_spec.supported_ops) + ) + + def is_allow_float(self): + return (OpsSet.TFLITE_BUILTINS in set(self._target_spec.supported_ops)) or ( + OpsSet.SELECT_TF_OPS in set(self._target_spec.supported_ops) + ) + + def _is_float16_target_required(self): + return _dtypes.float16 in self._target_spec.supported_types + + def is_any_optimization_enabled(self): + return bool( + set(self._optimizations).intersection([ + Optimize.OPTIMIZE_FOR_LATENCY, + Optimize.OPTIMIZE_FOR_SIZE, + Optimize.DEFAULT, + ]) + ) + + def _smallest_supported_type(self): + if self._target_spec.supported_types: + return min(self._target_spec.supported_types, key=lambda x: x.size) + else: + # The default smallest supported type is INT8. + return _dtypes.int8 + + def is_quantization_aware_trained_model(self): + """Checks if the graph contains any training-time quantization ops.""" + training_quant_ops = frozenset({ + "FakeQuantWithMinMaxVars", + "FakeQuantWithMinMaxVarsPerChannel", + "FakeQuantWithMinMaxArgs", + "QuantizeAndDequantizeV2", + "QuantizeAndDequantizeV3", + }) + + if self._graph_def: + for node_def in self._graph_def.node: + if node_def.op in training_quant_ops: + return True + for function in self._graph_def.library.function: + for node_def in function.node_def: + if node_def.op in training_quant_ops: + return True + return False + + +class TFLiteConverterBase: + """Converter superclass to share functionality between V1 and V2 converters.""" + + # Stores the original model type temporarily to transmit the information + # from the factory class methods to TFLiteConverterBase init function. + _original_model_type = conversion_metdata_fb.ModelType.NONE + + def __init__(self): + self.optimizations = set() + self.representative_dataset = None + self.target_spec = TargetSpec() + self.allow_custom_ops = False + self.experimental_new_converter = True + self.experimental_new_quantizer = True + self.experimental_enable_resource_variables = True + self._experimental_calibrate_only = False + self._experimental_sparsify_model = False + self._experimental_disable_per_channel = False + self._debug_info = None # contains the stack traces of all the original + # nodes in the `GraphDef` to the converter. + self.saved_model_dir = None + self._saved_model_tags = None + self._saved_model_version = 0 + self._saved_model_exported_names = [] + self._tflite_metrics = metrics.TFLiteConverterMetrics() + self._collected_converter_params = {} + self.unfold_batchmatmul = False + self.legalize_custom_tensor_list_ops = False + self._experimental_lower_tensor_list_ops = True + self._experimental_default_to_single_batch_in_tensor_list_ops = False + self._experimental_unfold_large_splat_constant = False + self._experimental_tf_quantization_mode = None + # If unset, bias:int32 is by default except 16x8 quant. + # For 16x8 quant, bias:int64 is used to prevent any overflow by default. + # The accumulator type will be the same as bias type set by + # full_integer_quantization_bias_type. + self._experimental_full_integer_quantization_bias_type = None + # Provides specs for quantization, whether preset or custom. + self._experimental_quantization_options = None + # Initializes conversion metadata. + self.exclude_conversion_metadata = False + self._metadata = conversion_metdata_fb.ConversionMetadataT() + self._metadata.environment = conversion_metdata_fb.EnvironmentT() + self._metadata.options = conversion_metdata_fb.ConversionOptionsT() + self._metadata.environment.tensorflowVersion = versions.__version__ + self._metadata.environment.modelType = self._get_original_model_type() + self._experimental_enable_dynamic_update_slice = False + self._experimental_preserve_assert_op = False + self._experimental_guarantee_all_funcs_one_use = False + + # When the value is true, the MLIR quantantizer triggers dynamic range + # quantization in MLIR instead of the old quantizer. Used only if + # experimental_new_quantizer is on. + self.experimental_new_dynamic_range_quantizer = True + # Experimental flag to enable low-bit QAT in 8 bit. + self._experimental_low_bit_qat = False + # Experimental flag to add all TF ops (including custom TF ops) to the + # converted model as flex ops. + self._experimental_allow_all_select_tf_ops = False + + self._experimental_variable_quantization = False + self._experimental_disable_fuse_mul_and_fc = False + self._experimental_use_buffer_offset = False + self._experimental_reduce_type_precision = False + + # Debug parameters + self.mlir_dump_dir = None + self.mlir_dump_pass_regex = None + self.mlir_dump_func_regex = None + self.mlir_enable_timing = None + self.mlir_print_ir_before = None + self.mlir_print_ir_after = None + self.mlir_print_ir_module_scope = None + self.mlir_elide_elementsattrs_if_larger = None + + def _grappler_config(self, optimizers=None): + """Creates a tf.compat.v1.ConfigProto for configuring Grappler. + + Args: + optimizers: List of strings that represents the list of optimizers. + + Returns: + tf.ConfigProto. + """ + if not optimizers: + optimizers = [] + # MLIR converter will take care of constant folding instead of grappler. + if not self.experimental_new_converter: + optimizers.append("constfold") + + is_only_flex_enabled = set([OpsSet.SELECT_TF_OPS]) == set( + self.target_spec.supported_ops + ) + if is_only_flex_enabled: + # The layout optimizer turns NHCW to NCHW. This provides performance + # optimizations when Flex mode is enabled. However, this is not compatible + # with builtin ops. + optimizers.append("layout") + return _get_grappler_config(optimizers) + + def _quantize( + self, + result, + input_type, + output_type, + activations_type, + bias_type, + allow_float, + enable_variable_quantization, + ): + """Quantize the model.""" + # pylint: disable=protected-access + custom_op_registerers_by_name = [ + x + for x in self.target_spec._experimental_custom_op_registerers + if isinstance(x, str) + ] + custom_op_registerers_by_func = [ + x + for x in self.target_spec._experimental_custom_op_registerers + if not isinstance(x, str) + ] + # pylint: enable=protected-access + if not isinstance(self.representative_dataset, RepresentativeDataset): + self.representative_dataset = RepresentativeDataset( + self.representative_dataset + ) + + # Add intermediate tensors to the model if needed. + result = _calibrator.add_intermediate_tensors(result) + calibrate_quantize = _calibrator.Calibrator( + result, custom_op_registerers_by_name, custom_op_registerers_by_func + ) + if self._experimental_calibrate_only or self.experimental_new_quantizer: + calibrated = calibrate_quantize.calibrate( + self.representative_dataset.input_gen + ) + + if self._experimental_calibrate_only: + return calibrated + elif self.experimental_new_quantizer and ( + activations_type != _dtypes.int16 + ): + # TODO(b/175659372): remove the activations_type restriction and enable + # it for all the activation types. + return _mlir_quantize( + calibrated, + self._experimental_disable_per_channel, + input_data_type=input_type, + output_data_type=output_type, + enable_variable_quantization=enable_variable_quantization, + ) + else: + return calibrate_quantize.calibrate_and_quantize( + self.representative_dataset.input_gen, + input_type, + output_type, + allow_float, + activations_type, + bias_type, + disable_per_channel=self._experimental_disable_per_channel, + ) + + def _is_unknown_shapes_allowed(self): + # Unknown dimensions are only allowed with the new converter. + return self.experimental_new_converter + + def _get_base_converter_args(self): + """Returns the base converter args. + + Returns: + {key str: val} + """ + args = { + "input_format": constants.TENSORFLOW_GRAPHDEF, + "allow_custom_ops": self.allow_custom_ops, + "debug_info": self._debug_info, + "target_ops": self.target_spec.supported_ops, + "enable_mlir_converter": self.experimental_new_converter, + "select_user_tf_ops": self.target_spec.experimental_select_user_tf_ops, + "supported_backends": self.target_spec.experimental_supported_backends, + "unfold_batchmatmul": self.unfold_batchmatmul, + "legalize_custom_tensor_list_ops": self.legalize_custom_tensor_list_ops, + "lower_tensor_list_ops": self._experimental_lower_tensor_list_ops, + "unfold_large_splat_constant": ( + self._experimental_unfold_large_splat_constant + ), + "default_to_single_batch_in_tensor_list_ops": ( + self._experimental_default_to_single_batch_in_tensor_list_ops + ), + "tf_quantization_mode": self._experimental_tf_quantization_mode, + "experimental_enable_resource_variables": ( + self.experimental_enable_resource_variables + ), + "enable_dynamic_update_slice": ( + self._experimental_enable_dynamic_update_slice + ), + "preserve_assert_op": self._experimental_preserve_assert_op, + "guarantee_all_funcs_one_use": ( + self._experimental_guarantee_all_funcs_one_use + ), + "allow_all_select_tf_ops": self._experimental_allow_all_select_tf_ops, + "disable_fuse_mul_and_fc": self._experimental_disable_fuse_mul_and_fc, + "quantization_options": self._experimental_quantization_options, + "mlir_dump_dir": self.mlir_dump_dir, + "mlir_dump_pass_regex": self.mlir_dump_pass_regex, + "mlir_dump_func_regex": self.mlir_dump_func_regex, + "mlir_enable_timing": self.mlir_enable_timing, + "mlir_print_ir_before": self.mlir_print_ir_before, + "mlir_print_ir_after": self.mlir_print_ir_after, + "mlir_print_ir_module_scope": self.mlir_print_ir_module_scope, + "mlir_elide_elementsattrs_if_larger": ( + self.mlir_elide_elementsattrs_if_larger + ), + "use_buffer_offset": self._experimental_use_buffer_offset, + "reduce_type_precision": self._experimental_reduce_type_precision, + } + + if self.saved_model_dir: + args.update({ + "saved_model_dir": self.saved_model_dir, + "saved_model_version": self._saved_model_version, + "saved_model_tags": self._saved_model_tags, + "saved_model_exported_names": self._saved_model_exported_names, + }) + + if self._experimental_quantization_options: + logging.warning( + "Configs from custom methods in experimental_quantization_options" + " may not produce a valid tflite model. Note that currently this" + " option only supports StableHLO path. Setting this option in TFLite" + " path will be a no-op." + ) + + return args + + def _contains_function_with_implements_attr(self, saved_model_proto): + meta_graph = saved_model_proto.meta_graphs[0] + for function in meta_graph.graph_def.library.function: + if function.attr.get("_implements", None) or function.attr.get( + "api_implements", None + ): + return True + return False + + def _parse_saved_model_args(self, always_enable_saved_model_import=False): + """Parses SavedModel arguments from the given Keras/RNN SavedModel. + + Args: + always_enable_saved_model_import: Bool. When the value is true, it enables + MLIR saved model import path regardless of checking the conditions. + """ + if not self.experimental_new_converter: + self.saved_model_dir = None + return + if self.saved_model_dir: + try: + saved_model_proto, _ = _parse_saved_model_with_debug_info( + self.saved_model_dir + ) + except OSError: + # If it fails to read the given saved model, it will fall back to the + # frozen graph def path. + self.saved_model_dir = None + return + if ( + not always_enable_saved_model_import + and not self._contains_function_with_implements_attr( + saved_model_proto + ) + ): + self.saved_model_dir = None + return + + if not self._saved_model_exported_names: + self._saved_model_exported_names = [] + self._saved_model_version = saved_model_proto.saved_model_schema_version + if self._saved_model_version == 0: + self.saved_model_dir = None + logging.warning("SavedModel schema version is zero.") + return + if self._saved_model_version not in [1, 2]: + raise ValueError( + "SavedModel file format({0}) is not supported".format( + self._saved_model_version + ) + ) + + def _sparsify_model(self): + return Optimize.EXPERIMENTAL_SPARSITY in self.optimizations + + def _increase_conversion_attempt_metric(self): + self._tflite_metrics.increase_counter_converter_attempt() + + def _increase_conversion_success_metric(self): + self._tflite_metrics.increase_counter_converter_success() + + @classmethod + def _set_original_model_type(cls, model_type): + """Stores the original model type.""" + if model_type == conversion_metdata_fb.ModelType.NONE: + raise ValueError("The original model type should be specified.") + cls._original_model_type = model_type + + def _get_original_model_type(self): + """One-time getter to return original model type and set it to NONE.""" + model_type = TFLiteConverterBase._original_model_type + TFLiteConverterBase._original_model_type = ( + conversion_metdata_fb.ModelType.NONE + ) + return model_type + + def _save_conversion_params_metric( + self, graph_def=None, inference_type=None, inference_input_type=None + ): + """Set conversion parameter metrics.""" + converter_kwargs = self._collected_converter_params + converter_kwargs.update(self._get_base_converter_args()) + + # Optimization parameters. + quant_mode = QuantizationMode( + self.optimizations, + self.target_spec, + self.representative_dataset, + graph_def, + self._experimental_disable_per_channel, + self.experimental_new_dynamic_range_quantizer, + self._experimental_low_bit_qat, + self._experimental_full_integer_quantization_bias_type, + self._experimental_variable_quantization, + ) + converter_kwargs.update({ + "tf_version": self._metadata.environment.tensorflowVersion, + "api_version": self._metadata.environment.apiVersion, + "original_model_format": self._metadata.environment.modelType, + "optimization_default": quant_mode.is_any_optimization_enabled(), + "optimization_post_training_dynamic_range": ( + quant_mode.is_post_training_dynamic_range_quantization() + ), + "optimization_post_training_float16": ( + quant_mode.is_post_training_float16_quantization() + ), + "optimization_post_training_integer_quantize": ( + quant_mode.is_post_training_integer_quantization() + ), + "optimization_qat": quant_mode.is_quantization_aware_training(), + "optimization_low_bit_qat": ( + quant_mode.is_low_bit_quantize_aware_training() + ), + "optimization_sparsify": self._sparsify_model(), + "activations_type": quant_mode.activations_type(), + }) + converter_kwargs.update( + quant_mode.converter_flags(inference_type, inference_input_type) + ) + + # pylint: disable=protected-access + if self.target_spec._experimental_supported_accumulation_type: + converter_kwargs.update( + { + "accumulation_type": ( + self.target_spec._experimental_supported_accumulation_type + ) + } + ) + # pylint: enable=protected-access + + def format_element(elem): + if isinstance(elem, enum.Enum): + return str(elem.value) + return pprint.pformat(elem) + + def format_param(param): + if isinstance(param, (list, tuple, set)): + if not param: + return "None" # Return None if empty. + string_list = [format_element(x) for x in param] + return ",".join(sorted(string_list)) + return format_element(param) + + for key, value in converter_kwargs.items(): + self._tflite_metrics.set_converter_param(key, format_param(value)) + self._tflite_metrics.set_export_required() + + # Set conversion option metadata. + self._metadata.options.allowCustomOps = self.allow_custom_ops + self._metadata.options.enableSelectTfOps = ( + OpsSet.SELECT_TF_OPS in self.target_spec.supported_ops + ) + self._metadata.options.forceSelectTfOps = set( + [OpsSet.SELECT_TF_OPS] + ) == set(self.target_spec.supported_ops) + self._metadata.options.modelOptimizationModes = [] + + if quant_mode.is_post_training_float16_quantization(): + self._metadata.options.modelOptimizationModes.append( + conversion_metdata_fb.ModelOptimizationMode.PTQ_FLOAT16 + ) + + if quant_mode.is_post_training_dynamic_range_quantization(): + self._metadata.options.modelOptimizationModes.append( + conversion_metdata_fb.ModelOptimizationMode.PTQ_DYNAMIC_RANGE + ) + + if quant_mode.is_post_training_int8_quantization(): + self._metadata.options.modelOptimizationModes.append( + conversion_metdata_fb.ModelOptimizationMode.PTQ_FULL_INTEGER + ) + + if quant_mode.is_post_training_int16x8_quantization(): + self._metadata.options.modelOptimizationModes.append( + conversion_metdata_fb.ModelOptimizationMode.PTQ_INT16 + ) + + if quant_mode.is_quantization_aware_training(): + self._metadata.options.modelOptimizationModes.append( + conversion_metdata_fb.ModelOptimizationMode.QUANTIZATION_AWARE_TRAINING + ) + + def _set_conversion_latency_metric(self, value): + self._tflite_metrics.set_converter_latency(value) + + @convert_phase(Component.OPTIMIZE_TFLITE_MODEL) + def _optimize_tflite_model(self, model, quant_mode, quant_io=True): + """Apply optimizations on a TFLite model.""" + + if quant_mode.is_integer_quantization(): + in_type, out_type = self.inference_input_type, self.inference_output_type + + if quant_mode.is_post_training_integer_quantization(): + q_in_type = in_type if in_type and quant_io else _dtypes.float32 + q_out_type = out_type if out_type and quant_io else _dtypes.float32 + q_activations_type = quant_mode.activations_type() + q_bias_type = quant_mode.bias_type() + q_allow_float = quant_mode.is_allow_float() + q_variable_quantization = quant_mode.enable_mlir_variable_quantization + model = self._quantize( + model, + q_in_type, + q_out_type, + q_activations_type, + q_bias_type, + q_allow_float, + q_variable_quantization, + ) + + m_in_type = in_type if in_type else _dtypes.float32 + m_out_type = out_type if out_type else _dtypes.float32 + # Skip updating model io types if MLIR quantizer already takes care of it + if not ( + quant_mode.is_post_training_integer_quantization() + and self.experimental_new_quantizer + and quant_io + and (m_in_type in [_dtypes.int8, _dtypes.uint8, _dtypes.float32]) + and (m_out_type in [_dtypes.int8, _dtypes.uint8, _dtypes.float32]) + ): + model = _modify_model_io_type(model, m_in_type, m_out_type) + + if self._sparsify_model(): + model = _mlir_sparsify(model) + + if not self._experimental_use_buffer_offset: + # TODO(b/287476027): move this logic into c++ + try: + model_object = flatbuffer_utils.convert_bytearray_to_object(model) + if _check_model_use_buffer_offset(model_object): + return model + model = _deduplicate_readonly_buffers(model) + except Exception: # pylint: disable=broad-except + # Skip buffer deduplication when flatbuffer library is not ready to be + # utilized. + logging.warning( + "Buffer deduplication procedure will be skipped when flatbuffer " + "library is not properly loaded" + ) + + return model + + def _convert_and_export_metrics(self, convert_func, *args, **kwargs): + """Wraps around convert function to export metrics. + + Args: + convert_func: The convert function to wrap. + *args: Positional arguments of the convert function. + **kwargs: The keyword arguments of the convert function. + + Returns: + The decorator to wrap the convert function. + """ + self._increase_conversion_attempt_metric() + self._save_conversion_params_metric() + start_time = time.process_time() + result = convert_func(self, *args, **kwargs) + elapsed_time_ms = (time.process_time() - start_time) * 1000 + if result: + self._increase_conversion_success_metric() + self._set_conversion_latency_metric(round(elapsed_time_ms)) + self._tflite_metrics.export_metrics() + if self.exclude_conversion_metadata or self._experimental_use_buffer_offset: + return result + # TODO(b/286886803): add support for adding user metadata with + # use_buffer_offset flags + model_object = flatbuffer_utils.convert_bytearray_to_object(result) + if _check_model_use_buffer_offset(model_object): + return result + # Populates the conversion metadata. + # TODO(b/202090541): Collects sparsity block size information. + sparsity_modes = _get_sparsity_modes(model_object) + self._metadata.options.modelOptimizationModes.extend(sparsity_modes) + model_object = _populate_conversion_metadata(model_object, self._metadata) + return flatbuffer_utils.convert_object_to_bytearray(model_object) + + +def _check_model_use_buffer_offset(model_object): + """Checks if a model object uses buffer offsets to store constant buffers. + + Args: + model_object: tflite model, a python object + + Returns: + True of the model_object has the metadata entry "buffer_location" + False otherwise + """ + if not model_object.metadata: + return False + for meta in model_object.metadata: + if meta.name.decode("utf-8") == "buffer_location": + return True + + return False + + +def _export_metrics(convert_func): + """The decorator around convert function to export metrics.""" + + @functools.wraps(convert_func) + def wrapper(self, *args, **kwargs): + # pylint: disable=protected-access + return self._convert_and_export_metrics(convert_func, *args, **kwargs) + # pylint: enable=protected-access + + return wrapper + + +class TFLiteConverterBaseV2(TFLiteConverterBase): + """Converter subclass to share functionality between V2 converters.""" + + def __init__(self): + """Constructor for TFLiteConverter.""" + super(TFLiteConverterBaseV2, self).__init__() + self.inference_input_type = _dtypes.float32 + self.inference_output_type = _dtypes.float32 + self._metadata.environment.apiVersion = 2 + + def _validate_inference_input_output_types(self, quant_mode): + """Validate inference_input_type and inference_output_type flags.""" + default_types = [_dtypes.float32] + # We support integer input/output for integer quantized models only. + if quant_mode.is_integer_quantization(): + if quant_mode.is_post_training_int16x8_quantization(): + all_types = default_types + [_dtypes.int16] + else: + all_types = default_types + [_dtypes.int8, _dtypes.uint8] + if ( + self.inference_input_type not in all_types + or self.inference_output_type not in all_types + ): + all_types_names = ["tf." + t.name for t in all_types] + raise ValueError( + "The inference_input_type and inference_output_type " + "must be in {}.".format(all_types_names) + ) + elif ( + self.inference_input_type not in default_types + or self.inference_output_type not in default_types + ): + raise ValueError( + "The inference_input_type and inference_output_type " + "must be tf.float32." + ) + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.LOAD_SAVED_MODEL) + def _load_saved_model(self, saved_model_dir, saved_model_tags): + """Load graph_def from saved model with the default serving signature key. + + Args: + saved_model_dir: Directory of the SavedModel. + saved_model_tags: Set of tags identifying the MetaGraphDef within the + SavedModel to analyze. + + Returns: + graph_def: The loaded GraphDef. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + """ + graph = _ops.Graph() + saved_model = _loader_impl.SavedModelLoader(saved_model_dir) + saved_model.load_graph(graph, tags=saved_model_tags) + meta_graph = saved_model.get_meta_graph_def_from_tags(saved_model_tags) + graph_def = meta_graph.graph_def + signature_def = meta_graph.signature_def[ + _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + ] + input_tensors = [ + graph.get_tensor_by_name(signature_def.inputs[key].name) + for key in signature_def.inputs + ] + output_tensors = [ + graph.get_tensor_by_name(signature_def.outputs[key].name) + for key in signature_def.outputs + ] + return graph_def, input_tensors, output_tensors + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.VALIDATE_INPUTS) + def _validate_inputs(self, graph_def, input_tensors): + """Validate the input parameters. + + Args: + graph_def: The TensorFlow GraphDef. + input_tensors: List of input tensors. + + Raise: + ValueError: Input shape is not specified. Invalid quantization parameters. + """ + # Update conversion params with graph_def. + self._save_conversion_params_metric(graph_def) + self._quant_mode = QuantizationMode( + self.optimizations, + self.target_spec, + self.representative_dataset, + graph_def, + self._experimental_disable_per_channel, + self.experimental_new_dynamic_range_quantizer, + self._experimental_low_bit_qat, + self._experimental_full_integer_quantization_bias_type, + self._experimental_variable_quantization, + ) + self._validate_inference_input_output_types(self._quant_mode) + + if not self._is_unknown_shapes_allowed(): + # Checks dimensions in input tensor. + for tensor in input_tensors: + # Note that shape_list might be empty for scalar shapes. + shape_list = tensor.shape.as_list() + if None in shape_list[1:]: + raise ValueError( + "None is only supported in the 1st dimension. Tensor '{0}' has " + "invalid shape '{1}'.".format( + _get_tensor_name(tensor), shape_list + ) + ) + elif shape_list and shape_list[0] is None: + # Set the batch size to 1 if undefined. + shape = tensor.shape.as_list() + shape[0] = 1 + tensor.set_shape(shape) + + if self._trackable_obj is None or not hasattr( + self._trackable_obj, "graph_debug_info" + ): + self._debug_info = _get_debug_info( + _build_debug_info_func(self._funcs[0].graph), graph_def + ) + else: + self._debug_info = _get_debug_info( + _convert_debug_info_func(self._trackable_obj.graph_debug_info), + graph_def, + ) + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.OPTIMIZE_TF_MODEL) + def _optimize_tf_model( + self, graph_def, input_tensors, output_tensors, frozen_func + ): + """Run a Grappler pass to optimize the TensorFlow graph. + + Args: + graph_def: Frozen GraphDef to be optimized. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + frozen_func: TensorFlow Graph. + + Returns: + The optimized TensorFlow graph. + """ + grappler_config = self._grappler_config() + # Skip running grappler when there are no optimizers to run. If not, + # grappler will run with the default optimizer set and it will lead to + # causing an unexpected behavior. + if grappler_config.graph_options.rewrite_options.optimizers: + graph_def = _run_graph_optimizations( + graph_def, + input_tensors, + output_tensors, + config=grappler_config, + graph=frozen_func.graph, + ) + return graph_def + + def _convert_from_saved_model(self, graph_def): + """Helper method that converts saved model. + + Args: + graph_def: GraphDef object for the model, used only for stats. + + Returns: + The converted TFLite model. + """ + # Update conversion params with graph_def. + self._save_conversion_params_metric(graph_def) + # Get quantization options and do some sanity checks. + quant_mode = QuantizationMode( + self.optimizations, + self.target_spec, + self.representative_dataset, + graph_def, + self._experimental_disable_per_channel, + self.experimental_new_dynamic_range_quantizer, + self._experimental_low_bit_qat, + self._experimental_full_integer_quantization_bias_type, + self._experimental_variable_quantization, + ) + self._validate_inference_input_output_types(quant_mode) + converter_kwargs = { + "enable_tflite_resource_variables": ( + self.experimental_enable_resource_variables + ) + } + converter_kwargs.update(self._get_base_converter_args()) + converter_kwargs.update(quant_mode.converter_flags()) + + result = _convert_saved_model(**converter_kwargs) + return self._optimize_tflite_model( + result, quant_mode, quant_io=self.experimental_new_quantizer + ) + + def convert(self, graph_def, input_tensors, output_tensors): + """Converts a TensorFlow GraphDef based on instance variables. + + Args: + graph_def: Frozen TensorFlow GraphDef. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + + Returns: + The converted data in serialized format. + + Raises: + ValueError: + No concrete functions is specified. + Multiple concrete functions are specified. + Input shape is not specified. + Invalid quantization parameters. + """ + self._validate_inputs(graph_def, input_tensors) + converter_kwargs = self._get_base_converter_args() + converter_kwargs.update(self._quant_mode.converter_flags()) + if not self.experimental_new_converter: + logging.warning( + "Please consider switching to the new converter by setting " + "experimental_new_converter=True. " + "The old converter is deprecated." + ) + else: + logging.info( + "Using new converter: If you encounter a problem " + "please file a bug. You can opt-out " + "by setting experimental_new_converter=False" + ) + + # Converts model. + result = _convert_graphdef( + input_data=graph_def, + input_tensors=input_tensors, + output_tensors=output_tensors, + **converter_kwargs, + ) + + return self._optimize_tflite_model( + result, self._quant_mode, quant_io=self.experimental_new_quantizer + ) + + +class TFLiteSavedModelConverterV2(TFLiteConverterBaseV2): + """Converts the given SavedModel into TensorFlow Lite model. + + Attributes: + saved_model_dir: Directory of the SavedModel. + """ + + def __init__( + self, + saved_model_dir, + saved_model_tags=None, + saved_model_exported_names=None, + trackable_obj=None, + ): + """Constructor for TFLiteConverter. + + Args: + saved_model_dir: Directory of the SavedModel. + saved_model_tags: Set of tags identifying the MetaGraphDef within the + SavedModel to analyze. All tags in the tag set must be present. (default + {tf.saved_model.SERVING}). + saved_model_exported_names: Names to be exported when the saved model + import path is on. + trackable_obj: tf.AutoTrackable object associated with `funcs`. A + reference to this object needs to be maintained so that Variables do not + get garbage collected since functions have a weak reference to + Variables. This is only required when the tf.AutoTrackable object is not + maintained by the user (e.g. `from_saved_model`). + """ + super(TFLiteSavedModelConverterV2, self).__init__() + self.saved_model_dir = saved_model_dir + self._saved_model_tags = saved_model_tags + self._saved_model_exported_names = saved_model_exported_names + self._trackable_obj = trackable_obj + self._parse_saved_model_args(always_enable_saved_model_import=True) + + @_export_metrics + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Returns: + The converted data in serialized format. + + Raises: + ValueError: + No concrete functions is specified. + Multiple concrete functions are specified. + Input shape is not specified. + Invalid quantization parameters. + """ + graph_def, input_tensors, output_tensors = self._load_saved_model( + self.saved_model_dir, self._saved_model_tags + ) + # If we can't use saved model importer, then fallback + # to frozen graph conversion path. + if self.saved_model_dir is None or not self.experimental_new_converter: + graph_def, _, _, _ = _freeze_saved_model( + self.saved_model_dir, + None, + None, + None, + self._saved_model_tags, + _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, + ) + # We make sure to clear the saved_model_dir as there is some + # legacy code down in the caller that checks this. + # TODO(b/162537905): Clean these indirect dependencies. + self.saved_model_dir = None + return super(TFLiteSavedModelConverterV2, self).convert( + graph_def, input_tensors, output_tensors + ) + + if self._trackable_obj is None: + self._debug_info = _get_debug_info( + _build_debug_info_func(self._funcs[0].graph), graph_def + ) + else: + self._debug_info = _get_debug_info( + _convert_debug_info_func(self._trackable_obj.graph_debug_info), + graph_def, + ) + + return self._convert_from_saved_model(graph_def) + + +class TFLiteKerasModelConverterV2(TFLiteConverterBaseV2): + """Converts the given Keras model into TensorFlow Lite model.""" + + def __init__(self, keras_model, trackable_obj=None): + """Constructor for TFLiteConverter. + + Args: + keras_model: tf.Keras.Model. + trackable_obj: tf.AutoTrackable object associated with `funcs`. A + reference to this object needs to be maintained so that Variables do not + get garbage collected since functions have a weak reference to + Variables. This is only required when the tf.AutoTrackable object is not + maintained by the user (e.g. `from_saved_model`). + """ + super(TFLiteKerasModelConverterV2, self).__init__() + self._keras_model = keras_model + self._trackable_obj = trackable_obj + self.experimental_lower_to_saved_model = True + + @convert_phase( + Component.PREPARE_TF_MODEL, SubComponent.CONVERT_KERAS_TO_SAVED_MODEL + ) + def _convert_keras_to_saved_model(self, output_dir): + """Save Keras model to the SavedModel format. + + Args: + output_dir: The output directory to save the SavedModel. + + Returns: + graph_def: The frozen GraphDef. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + """ + try: + _save.save( + self._keras_model, + output_dir, + options=_save_options.SaveOptions(save_debug_info=True), + ) + except Exception: # pylint: disable=broad-except + # When storing the given keras model to a saved model is failed, let's + # use original keras model conversion pipeline. + return None, None, None + self.saved_model_dir = output_dir + self._saved_model_tags = set([_tag_constants.SERVING]) + self._saved_model_exported_names = [ + _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + ] + self._parse_saved_model_args( + always_enable_saved_model_import=self.experimental_lower_to_saved_model + ) + if self.saved_model_dir: + graph_def, input_tensors, output_tensors = self._load_saved_model( + self.saved_model_dir, self._saved_model_tags + ) + self._trackable_obj = _load(self.saved_model_dir, self._saved_model_tags) + return graph_def, input_tensors, output_tensors + return None, None, None + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.FREEZE_KERAS_MODEL) + def _freeze_keras_model(self): + """Freeze Keras model to frozen graph. + + Returns: + graph_def: The frozen GraphDef. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + frozen_func: The frozen ConcreteFunction. + """ + input_signature = None + # If the model's call is not a `tf.function`, then we need to first get its + # input signature from `model_input_signature` method. We can't directly + # call `trace_model_call` because otherwise the batch dimension is set + # to None. + # Once we have better support for dynamic shapes, we can remove this. + if not isinstance(self._keras_model.call, _def_function.Function): + # Pass `keep_original_batch_size=True` will ensure that we get an input + # signature including the batch dimension specified by the user. + # TODO(b/169898786): Use the Keras public API when TFLite moves out of TF + input_signature = _model_input_signature( + self._keras_model, keep_original_batch_size=True + ) + + # TODO(b/169898786): Use the Keras public API when TFLite moves out of TF + func = _trace_model_call(self._keras_model, input_signature) + concrete_func = func.get_concrete_function() + self._funcs = [concrete_func] + + frozen_func, graph_def = ( + _convert_to_constants.convert_variables_to_constants_v2_as_graph( + self._funcs[0], lower_control_flow=False + ) + ) + + input_tensors = [ + tensor + for tensor in frozen_func.inputs + if tensor.dtype != _dtypes.resource + ] + output_tensors = frozen_func.outputs + return graph_def, input_tensors, output_tensors, frozen_func + + def _convert_as_saved_model(self): + """Converts a Keras model as a saved model. + + Returns: + The converted data in serialized format. + """ + temp_dir = tempfile.mkdtemp() + try: + graph_def, input_tensors, output_tensors = ( + self._convert_keras_to_saved_model(temp_dir) + ) + if self.saved_model_dir: + return super(TFLiteKerasModelConverterV2, self).convert( + graph_def, input_tensors, output_tensors + ) + finally: + shutil.rmtree(temp_dir, True) + + @_export_metrics + def convert(self): + """Converts a keras model based on instance variables. + + Returns: + The converted data in serialized format. + + Raises: + ValueError: + Multiple concrete functions are specified. + Input shape is not specified. + Invalid quantization parameters. + """ + saved_model_convert_result = self._convert_as_saved_model() + if saved_model_convert_result: + return saved_model_convert_result + + graph_def, input_tensors, output_tensors, frozen_func = ( + self._freeze_keras_model() + ) + + graph_def = self._optimize_tf_model( + graph_def, input_tensors, output_tensors, frozen_func + ) + + return super(TFLiteKerasModelConverterV2, self).convert( + graph_def, input_tensors, output_tensors + ) + + +class TFLiteFrozenGraphConverterV2(TFLiteConverterBaseV2): + """Converts the given frozen graph into TensorFlow Lite model.""" + + def __init__(self, funcs, trackable_obj=None): + """Constructor for TFLiteConverter. + + Args: + funcs: List of TensorFlow ConcreteFunctions. The list should not contain + duplicate elements. + trackable_obj: tf.AutoTrackable object associated with `funcs`. A + reference to this object needs to be maintained so that Variables do not + get garbage collected since functions have a weak reference to + Variables. This is only required when the tf.AutoTrackable object is not + maintained by the user (e.g. `from_saved_model`). + """ + super(TFLiteFrozenGraphConverterV2, self).__init__() + self._funcs = funcs + self._trackable_obj = trackable_obj + self.experimental_lower_to_saved_model = True + + @convert_phase( + Component.PREPARE_TF_MODEL, SubComponent.FREEZE_CONCRETE_FUNCTION + ) + def _freeze_concrete_function(self): + """Convert the given ConcreteFunction to frozen graph. + + Returns: + graph_def: The frozen GraphDef. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + frozen_func: The frozen ConcreteFunction. + + Raises: + ValueError: none or multiple ConcreteFunctions provided. + """ + # TODO(b/130297984): Add support for converting multiple function. + + if len(self._funcs) == 0: # pylint: disable=g-explicit-length-test + raise ValueError("No ConcreteFunction is specified.") + + if len(self._funcs) > 1: + raise ValueError( + "This converter can only convert a single " + "ConcreteFunction. Converting multiple functions is " + "under development." + ) + + frozen_func, graph_def = ( + _convert_to_constants.convert_variables_to_constants_v2_as_graph( + self._funcs[0], lower_control_flow=False + ) + ) + + input_tensors = [ + tensor + for tensor in frozen_func.inputs + if tensor.dtype != _dtypes.resource + ] + output_tensors = frozen_func.outputs + return graph_def, input_tensors, output_tensors, frozen_func + + @convert_phase( + Component.PREPARE_TF_MODEL, + SubComponent.CONVERT_CONCRETE_FUNCTIONS_TO_SAVED_MODEL, + ) + def _convert_concrete_functions_to_saved_model(self, output_dir): + """Save concrete functions to the SavedModel format. + + Args: + output_dir: The output directory to save the SavedModel. + + Returns: + graph_def: The frozen GraphDef. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + """ + if len(self._funcs) == 0: # pylint: disable=g-explicit-length-test + raise ValueError("No ConcreteFunction is specified.") + + if not self.experimental_lower_to_saved_model: + return None, None, None + + # Without the provided trackable obj, it is not able to serialize the given + # concrete functions as a saved model format. Also when trackable obj is + # a function, use the original concrete function conversion pipeline. + if not self._trackable_obj or isinstance( + self._trackable_obj, + (_function.ConcreteFunction, _def_function.Function), + ): + return None, None, None + + signatures = {} + signature_keys = [] + try: + if len(self._funcs) == 1: + signatures[_signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = ( + self._funcs[0] + ) + signature_keys = [ + _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + ] + else: + for func in self._funcs: + signatures[func.graph.name] = func + signature_keys.append(func.graph.name) + + _save.save( + self._trackable_obj, + output_dir, + signatures=signatures, + options=_save_options.SaveOptions(save_debug_info=True), + ) + except Exception: # pylint: disable=broad-except + # When storing the given concrete function to a saved model is failed, + # let's use original concrete function conversion pipeline. + return None, None, None + + self.saved_model_dir = output_dir + self._saved_model_tags = set([_tag_constants.SERVING]) + self._saved_model_exported_names = signature_keys + self._parse_saved_model_args(always_enable_saved_model_import=True) + if self.saved_model_dir: + graph_def, input_tensors, output_tensors = self._load_saved_model( + self.saved_model_dir, self._saved_model_tags + ) + self._trackable_obj = _load(self.saved_model_dir, self._saved_model_tags) + return graph_def, input_tensors, output_tensors + return None, None, None + + def _convert_as_saved_model(self): + """Converts the given concrete functions as a saved model format. + + Returns: + The converted data in serialized format. + """ + temp_dir = tempfile.mkdtemp() + try: + graph_def, input_tensors, _ = ( + self._convert_concrete_functions_to_saved_model(temp_dir) + ) + if self.saved_model_dir: + self._validate_inputs(graph_def, input_tensors) + return self._convert_from_saved_model(graph_def) + finally: + shutil.rmtree(temp_dir, True) + return None + + @_export_metrics + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Returns: + The converted data in serialized format. + + Raises: + ValueError: + No concrete functions is specified. + Multiple concrete functions are specified. + Input shape is not specified. + Invalid quantization parameters. + """ + if self.experimental_lower_to_saved_model: + saved_model_convert_result = self._convert_as_saved_model() + if saved_model_convert_result: + return saved_model_convert_result + + graph_def, input_tensors, output_tensors, frozen_func = ( + self._freeze_concrete_function() + ) + + graph_def = self._optimize_tf_model( + graph_def, input_tensors, output_tensors, frozen_func + ) + + return super(TFLiteFrozenGraphConverterV2, self).convert( + graph_def, input_tensors, output_tensors + ) + + +class TFLiteJaxConverterV2(TFLiteConverterBaseV2): + """Converts the given jax model into TensorFlow Lite model.""" + + def __init__(self, serving_funcs, inputs): + """Constructor for TFLiteConverter. + + Args: + serving_funcs: A list functions of the serving func of the jax module, the + model params should already be inlined. (e.g., `serving_func = + functools.partial(model, params=params)`) + inputs: Array of input tensor placeholders tuple,s like `jnp.zeros`. For + example, wrapped in an array like "[('input1', input1), ('input2', + input2)]]". + + Jax functions are polymorphic, for example: + + ```python + def add(a, b): + return a + b + ``` + + Will yield different computations if different input signatures are passed + in: Pass `add(10.0, 20.0)` will yield a scalar `add` while pass + `add(np.random((100, 1)), np.random(100, 100))` will yield a broadcasting + add. We will need the input information to do tracing for the converter + to properly convert the model. So it's important to pass in the desired + `input placeholders` with the correct input shape/type. + + In the converted tflite model, the function name will be default to "main", + the output names will be the traced outputs. The output ordering shall + match the serving function. + """ # fmt: skip + + super(TFLiteJaxConverterV2, self).__init__() + self._serving_funcs = serving_funcs + self._inputs = inputs + + @_export_metrics + def convert(self): + """Converts a Jax serving func based on instance variables. + + Returns: + The converted data in serialized format. + + Raises: + ImportError: + If cannot import the xla_computation from jax. + ValueError: + No serving function is specified. + Input tensors are not specified. + The truth value of an array with more than one element is ambiguous. + Failed to convert the given Jax function to hlo. + """ + if not _xla_computation: + raise ImportError("Cannot import xla_computation from jax.") + + if not self._serving_funcs: + raise ValueError("No serving func is specified.") + + if not self._inputs: + raise ValueError("Input tensors are not specified.") + + if len(self._inputs) != len(self._serving_funcs): + msg = ( + "Input tensor mapping len {} does not match serving func len {}." + .format(len(self._inputs), len(self._serving_funcs)) + ) + raise ValueError(msg) + + if not isinstance(self._inputs, (tuple, list)): + raise ValueError( + "Input tensors should be pass in a tuple list wrapped in an array." + ) + + # TODO(b/197690428): Support multiple functions. + # Currently only support one serving function. + if len(self._serving_funcs) > 1: + raise ValueError("Currently only support single serving function.") + + if not isinstance(self._inputs[0], (tuple, list)): + raise ValueError("The input placeholders are not a dictionary.") + + input_names = [] + ordered_inputs = [] + for input_name, tensor in self._inputs[0]: + input_names.append(input_name) + ordered_inputs.append(tensor) + + try: + xla_compuation = _xla_computation(self._serving_funcs[0], backend="cpu") + hlo_proto = xla_compuation( + *ordered_inputs + ).as_serialized_hlo_module_proto() + except Exception: # pylint: disable=broad-except + raise ValueError("Failed to convert the given Jax function to hlo.") + + # We need to set the hlo proto, and here we use serialized proto format + # since it's more compact. + converter_kwargs = { + "input_content": hlo_proto, + "input_names": input_names, + "is_proto_format": True, + } + converter_kwargs.update(self._get_base_converter_args()) + + # Get quantization options and do some checks. + quant_mode = QuantizationMode( + self.optimizations, self.target_spec, self.representative_dataset, None + ) + self._validate_inference_input_output_types(quant_mode) + converter_kwargs.update(quant_mode.converter_flags()) + result = _convert_jax_hlo(**converter_kwargs) + + return self._optimize_tflite_model( + result, quant_mode, quant_io=self.experimental_new_quantizer + ) + + +@_tf_export("lite.TFLiteConverter", v1=[]) +class TFLiteConverterV2(TFLiteFrozenGraphConverterV2): + """Converts a TensorFlow model into TensorFlow Lite model. + + Attributes: + optimizations: Experimental flag, subject to change. Set of optimizations to + apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a + set of values of type `tf.lite.Optimize`) + representative_dataset: A generator function used for integer quantization + where each generated sample has the same order, type and shape as the + inputs to the model. Usually, this is a small subset of a few hundred + samples randomly chosen, in no particular order, from the training or + evaluation dataset. This is an optional attribute, but required for full + integer quantization, i.e, if `tf.int8` is the only supported type in + `target_spec.supported_types`. Refer to `tf.lite.RepresentativeDataset`. + (default None) + target_spec: Experimental flag, subject to change. Specifications of target + device, including supported ops set, supported types and a set of user's + defined TensorFlow operators required in the TensorFlow Lite runtime. + Refer to `tf.lite.TargetSpec`. + inference_input_type: Data type of the input layer. Note that integer types + (tf.int8 and tf.uint8) are currently only supported for post training + integer quantization and quantization aware training. (default tf.float32, + must be in {tf.float32, tf.int8, tf.uint8}) + inference_output_type: Data type of the output layer. Note that integer + types (tf.int8 and tf.uint8) are currently only supported for post + training integer quantization and quantization aware training. (default + tf.float32, must be in {tf.float32, tf.int8, tf.uint8}) + allow_custom_ops: Boolean indicating whether to allow custom operations. + When False, any unknown operation is an error. When True, custom ops are + created for any op that is unknown. The developer needs to provide these + to the TensorFlow Lite runtime with a custom resolver. (default False) + exclude_conversion_metadata: Whether not to embed the conversion metadata + into the converted model. (default False) + experimental_new_converter: Experimental flag, subject to change. Enables + MLIR-based conversion. (default True) + experimental_new_quantizer: Experimental flag, subject to change. Enables + MLIR-based quantization conversion instead of Flatbuffer-based conversion. + (default True) + experimental_enable_resource_variables: Experimental flag, subject to + change. Enables [resource + variables](https://tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables) + to be converted by this converter. This is only allowed if the + from_saved_model interface is used. (default True) + + Example usage: + + ```python + # Converting a SavedModel to a TensorFlow Lite model. + converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) + tflite_model = converter.convert() + + # Converting a tf.Keras model to a TensorFlow Lite model. + converter = tf.lite.TFLiteConverter.from_keras_model(model) + tflite_model = converter.convert() + + # Converting ConcreteFunctions to a TensorFlow Lite model. + converter = tf.lite.TFLiteConverter.from_concrete_functions([func], model) + tflite_model = converter.convert() + + # Converting a Jax model to a TensorFlow Lite model. + converter = tf.lite.TFLiteConverter.experimental_from_jax( + [func], [[ ('input1', input1), ('input2', input2)]]) + tflite_model = converter.convert() + ``` + """ # fmt: skip + + # pylint: disable=useless-super-delegation + def __init__(self, funcs, trackable_obj=None): + """Constructor for TFLiteConverter. + + Args: + funcs: List of TensorFlow ConcreteFunctions. The list should not contain + duplicate elements. + trackable_obj: tf.AutoTrackable object associated with `funcs`. A + reference to this object needs to be maintained so that Variables do not + get garbage collected since functions have a weak reference to + Variables. This is only required when the tf.AutoTrackable object is not + maintained by the user (e.g. `from_saved_model`). + """ + super(TFLiteConverterV2, self).__init__(funcs, trackable_obj) + + @classmethod + def from_concrete_functions(cls, funcs, trackable_obj=None): + """Creates a TFLiteConverter object from ConcreteFunctions. + + Args: + funcs: List of TensorFlow ConcreteFunctions. The list should not contain + duplicate elements. Currently converter can only convert a single + ConcreteFunction. Converting multiple functions is under development. + trackable_obj: An `AutoTrackable` object (typically `tf.module`) + associated with `funcs`. A reference to this object needs to be + maintained so that Variables do not get garbage collected since + functions have a weak reference to Variables. + + Returns: + TFLiteConverter object. + + Raises: + Invalid input type. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.TF_CONCRETE_FUNCTIONS + ) + # pylint: enable=protected-access + if trackable_obj is None: + logging.warning( + "Please consider providing the trackable_obj argument in the " + "from_concrete_functions. Providing without the trackable_obj " + "argument is deprecated and it will use the deprecated conversion " + "path." + ) + for func in funcs: + if not isinstance(func, _function.ConcreteFunction): + message = "This function takes in a list of ConcreteFunction." + if isinstance(func, _def_function.Function): + message += ( + " To get the ConcreteFunction from a Function," + " call get_concrete_function." + ) + raise ValueError(message) + return cls(funcs, trackable_obj) + + @classmethod + def from_saved_model(cls, saved_model_dir, signature_keys=None, tags=None): + """Creates a TFLiteConverter object from a SavedModel directory. + + Args: + saved_model_dir: SavedModel directory to convert. + signature_keys: List of keys identifying SignatureDef containing inputs + and outputs. Elements should not be duplicated. By default the + `signatures` attribute of the MetaGraphdef is used. (default + saved_model.signatures) + tags: Set of tags identifying the MetaGraphDef within the SavedModel to + analyze. All tags in the tag set must be present. (default + {tf.saved_model.SERVING} or {'serve'}) + + Returns: + TFLiteConverter object. + + Raises: + Invalid signature keys. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.TF_SAVED_MODEL + ) + # pylint: enable=protected-access + # When run without eager enabled, this will return the legacy + # TFLiteConverter. + if not context.executing_eagerly(): + signature_key = None + if signature_keys: + if len(signature_keys) != 1: + raise ValueError("Only support a single signature key.") + else: + signature_key = signature_keys[0] + logging.warning( + "Invoking the TF1 implementation of TFLiteConverter " + "because eager is disabled. Consider enabling eager." + ) + return TFLiteConverter.from_saved_model( + saved_model_dir, signature_key=signature_key, tag_set=tags + ) + + # Ensures any graphs created in Eager mode are able to run. This is required + # in order to create a tf.estimator.Exporter that exports a TFLite model. + if tags is None: + tags = set([_tag_constants.SERVING]) + + with context.eager_mode(): + saved_model = _load(saved_model_dir, tags) + if not signature_keys: + signature_keys = saved_model.signatures + + if not signature_keys: + raise ValueError("Only support at least one signature key.") + + # Distinguishes SavedModel artifacts created by `model.export` + # from SavedModel created by `model.save`/`tf.saved_model.save`. + if ( + len(signature_keys) > 1 + and hasattr(saved_model, "serve") # `model.export` default endpoint + and not hasattr(saved_model, "_default_save_signature") + # `_default_save_signature` does not exist for `model.export` artifacts. + ): + # Default `serve` endpoint for `model.export` should be copied + # to `serving_default` to prevent issues in TF Lite serving. + saved_model.serving_default = saved_model.serve + delattr(saved_model, "serve") + signature_keys = ["serving_default"] + + funcs = [] + for key in signature_keys: + if key not in saved_model.signatures: + raise ValueError( + "Invalid signature key '{}' found. Valid keys are '{}'.".format( + key, ",".join(saved_model.signatures) + ) + ) + funcs.append(saved_model.signatures[key]) + + saved_model_converter = TFLiteSavedModelConverterV2( + saved_model_dir, tags, signature_keys, saved_model + ) + if saved_model_converter.saved_model_dir: + return saved_model_converter + + return cls(funcs, saved_model) + + @classmethod + def from_keras_model(cls, model): + """Creates a TFLiteConverter object from a Keras model. + + Args: + model: tf.Keras.Model + + Returns: + TFLiteConverter object. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.KERAS_MODEL + ) + # pylint: enable=protected-access + return TFLiteKerasModelConverterV2(model) + + @classmethod + @_deprecation.deprecated( + None, + "Use `jax2tf.convert` and (`lite.TFLiteConverter.from_saved_model`" + " or `lite.TFLiteConverter.from_concrete_functions`) instead.", + ) + def experimental_from_jax(cls, serving_funcs, inputs): + # Experimental API, subject to changes. + # TODO(b/197690428): Currently only support single function. + """Creates a TFLiteConverter object from a Jax model with its inputs. + + Args: + serving_funcs: A array of Jax functions with all the weights applied + already. + inputs: A array of Jax input placeholders tuples list, e.g., + jnp.zeros(INPUT_SHAPE). Each tuple list should correspond with the + serving function. + + Returns: + TFLiteConverter object. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.JAX + ) + # pylint: enable=protected-access + return TFLiteJaxConverterV2(serving_funcs, inputs) + + # pylint: disable=useless-super-delegation + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Returns: + The converted data in serialized format. + + Raises: + ValueError: + No concrete functions is specified. + Multiple concrete functions are specified. + Input shape is not specified. + Invalid quantization parameters. + """ + return super(TFLiteConverterV2, self).convert() + + +class TFLiteConverterBaseV1(TFLiteConverterBase): + """Converter subclass to share functionality between V1 converters.""" + + def __init__(self, experimental_debug_info_func): + """Constructor for TFLiteConverter. + + Args: + experimental_debug_info_func: An experimental function to retrieve the + graph debug info for a set of nodes from the `graph_def`. + """ + super(TFLiteConverterBaseV1, self).__init__() + self.inference_type = _dtypes.float32 + self.inference_input_type = None + self.inference_output_type = None + self.output_format = constants.TFLITE + self.quantized_input_stats = {} + self.default_ranges_stats = None + self.drop_control_dependency = True + self.reorder_across_fake_quant = False + self.change_concat_input_ranges = False + self.dump_graphviz_dir = None + self.dump_graphviz_video = False + self.conversion_summary_dir = None + self._debug_info_func = experimental_debug_info_func + self._metadata.environment.apiVersion = 1 + + def __setattr__(self, name, value): + if name == "post_training_quantize": + warnings.warn( + "Property %s is deprecated, " + "please use optimizations=[Optimize.DEFAULT]" + " instead." % name + ) + if value: + self.optimizations = [Optimize.DEFAULT] + else: + self.optimizations = [] + return + if name == "target_ops": + warnings.warn( + "Property %s is deprecated, please use " + "target_spec.supported_ops instead." % name + ) + self.target_spec.supported_ops = value + return + object.__setattr__(self, name, value) + + def __getattribute__(self, name): + if name == "post_training_quantize": + warnings.warn( + "Property %s is deprecated, " + "please use optimizations=[Optimize.DEFAULT]" + " instead." % name + ) + return Optimize.DEFAULT in set(self.optimizations) + if name == "target_ops": + warnings.warn( + "Property %s is deprecated, please use " + "target_spec.supported_ops instead." % name + ) + return self.target_spec.supported_ops + return object.__getattribute__(self, name) + + def _validate_quantized_input_stats(self, converter_kwargs, quant_mode): + """Ensure the `quantized_input_stats` flag is provided if required.""" + + quantized_types = frozenset({_dtypes.int8, _dtypes.uint8}) + + requires_quantized_input_stats = ( + converter_kwargs["inference_type"] in quantized_types + or converter_kwargs["inference_input_type"] in quantized_types + ) and not quant_mode.is_post_training_integer_quantization() + + if ( + requires_quantized_input_stats + and not converter_kwargs["quantized_input_stats"] + ): + raise ValueError( + "The `quantized_input_stats` flag must be defined when either " + "`inference_type` flag or `inference_input_type` flag is set to " + "tf.int8 or tf.uint8. Currently, `inference_type={}` and " + "`inference_input_type={}`.".format( + _get_tf_type_name(converter_kwargs["inference_type"]), + _get_tf_type_name(converter_kwargs["inference_input_type"]), + ) + ) + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.VALIDATE_INPUTS) + def _validate_inputs(self, input_tensors, quantized_input_stats): + """Validate input parameters. + + Args: + input_tensors: List of input tensors. + quantized_input_stats: Map of input tensor names to a tuple of floats + representing the mean and standard deviation of the training data. + + Raises: + ValueError: + Input shape is not specified. + Quantization input stats is required but not provided. + """ + + if not self._is_unknown_shapes_allowed() and self._has_valid_tensors(): + # Checks dimensions in input tensor. + for tensor in input_tensors: + shape = tensor.shape + if not shape: + raise ValueError( + "Provide an input shape for input array '{0}'.".format( + _get_tensor_name(tensor) + ) + ) + # Note that shape_list might be empty for scalar shapes. + shape_list = shape.as_list() + if None in shape_list[1:]: + raise ValueError( + "None is only supported in the 1st dimension. Tensor '{0}' has " + "invalid shape '{1}'.".format( + _get_tensor_name(tensor), shape_list + ) + ) + elif shape_list and shape_list[0] is None: + self._set_batch_size(batch_size=1) + + # Get quantization stats. Ensures there is one stat per name if the stats + # are specified. + if quantized_input_stats: + self._quantized_stats = [] + invalid_stats = [] + for name in self.get_input_arrays(): + if name in quantized_input_stats: + self._quantized_stats.append(quantized_input_stats[name]) + else: + invalid_stats.append(name) + + if invalid_stats: + raise ValueError( + "Quantization input stats are not available for input " + "tensors '{0}'.".format(",".join(invalid_stats)) + ) + else: + self._quantized_stats = None + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.OPTIMIZE_TF_MODEL) + def _optimize_tf_model( + self, graph_def, input_tensors, output_tensors, quant_mode + ): + """Run a Grappler pass to optimize the TensorFlow graph. + + Args: + graph_def: Frozen GraphDef to be optimized. + input_tensors: List of input tensors. + output_tensors: List of output tensors. + quant_mode: the quantization mode. + + Returns: + The optimized TensorFlow graph. + """ + # Disable grappler constant folding if there are training quant ops. + if self.saved_model_dir or quant_mode.is_quantization_aware_trained_model(): + return graph_def + + try: + # TODO(b/150163103): Merge `disabling lower using switch merge' calls. + # Grappler will also try to lower while loop into switch merge + # representation which is undesired for Ophints, so we simply remove + # those attributes to prevent Grappler from doing so. + graph = _convert_to_constants.disable_lower_using_switch_merge(graph_def) + # Run function inlining optimization to ensure any models generated + # through the from_frozen_graph path have been inlined. + optimized_graph = _run_graph_optimizations( + graph, + input_tensors, + output_tensors, + config=self._grappler_config(["function"]), + ) + return optimized_graph + except Exception: # pylint: disable=broad-except + return graph_def + + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Returns: + The converted data in serialized format. Either a TFLite Flatbuffer or a + Graphviz graph depending on value in `output_format`. + + Raises: + ValueError: + Input shape is not specified. + None value for dimension in input_tensor. + """ + self._validate_inputs(self._input_tensors, self.quantized_input_stats) + + quant_mode = QuantizationMode( + self.optimizations, + self.target_spec, + self.representative_dataset, + self._graph_def, + self._experimental_disable_per_channel, + self.experimental_new_dynamic_range_quantizer, + self._experimental_low_bit_qat, + self._experimental_full_integer_quantization_bias_type, + self._experimental_variable_quantization, + ) + + optimized_graph = self._optimize_tf_model( + self._graph_def, self._input_tensors, self._output_tensors, quant_mode + ) + + self._debug_info = _get_debug_info(self._debug_info_func, optimized_graph) + + converter_kwargs = self._get_base_converter_args() + converter_kwargs.update( + quant_mode.converter_flags( + self.inference_type, self.inference_input_type + ) + ) + converter_kwargs.update({ + "output_format": self.output_format, + "quantized_input_stats": self._quantized_stats, + "default_ranges_stats": self.default_ranges_stats, + "drop_control_dependency": self.drop_control_dependency, + "reorder_across_fake_quant": self.reorder_across_fake_quant, + "change_concat_input_ranges": self.change_concat_input_ranges, + "dump_graphviz_dir": self.dump_graphviz_dir, + "dump_graphviz_video": self.dump_graphviz_video, + "conversion_summary_dir": self.conversion_summary_dir, + }) + + self._validate_quantized_input_stats(converter_kwargs, quant_mode) + if not self.experimental_new_converter: + logging.warning( + "Please consider switching to the new converter by setting " + "experimental_new_converter=True. " + "The old converter is deprecated." + ) + else: + logging.info( + "Using experimental converter: If you encountered a problem " + "please file a bug. You can opt-out " + "by setting experimental_new_converter=False" + ) + # Converts model. + if self._has_valid_tensors(): + result = _convert_graphdef( + input_data=optimized_graph, + input_tensors=self._input_tensors, + output_tensors=self._output_tensors, + **converter_kwargs, + ) + else: + result = _convert_graphdef_with_arrays( + input_data=optimized_graph, + input_arrays_with_shape=self._input_arrays_with_shape, + output_arrays=self._output_arrays, + control_output_arrays=self._control_output_arrays, + **converter_kwargs, + ) + + return self._optimize_tflite_model( + result, quant_mode, quant_io=self.experimental_new_quantizer + ) + + def get_input_arrays(self): + """Returns a list of the names of the input tensors. + + Returns: + List of strings. + """ + if self._has_valid_tensors(): + return [_get_tensor_name(tensor) for tensor in self._input_tensors] + else: + return [name for name, _ in self._input_arrays_with_shape] + + def _has_valid_tensors(self): + """Checks if the input and output tensors have been initialized. + + Returns: + Bool. + """ + return self._input_tensors is not None and self._output_tensors + + def _set_batch_size(self, batch_size): + """Sets the first dimension of the input tensor to `batch_size`. + + Args: + batch_size: Batch size for the model. Replaces the first dimension of an + input size array if undefined. (default 1) + + Raises: + ValueError: input_tensor is not defined. + """ + if not self._has_valid_tensors(): + raise ValueError( + "The batch size cannot be set for this model. Please " + "use input_shapes parameter." + ) + + for tensor in self._input_tensors: + shape = tensor.shape.as_list() + if shape[0] is None: + shape[0] = batch_size + tensor.set_shape(shape) + + def _is_unknown_shapes_allowed(self): + # Ophint Converted nodes will need the shapes to be known. + if _is_ophint_converted(self._graph_def): + return False + + if not super(TFLiteConverterBaseV1, self)._is_unknown_shapes_allowed(): + return False + + # `conversion_summary_dir` calls the old converter. Unknown shapes are only + # supported by the MLIR converter. + if self.conversion_summary_dir: + logging.warning( + "`conversion_summary_dir` does not work with unknown shapes. " + "Graphs with unknown shapes might be different than when this flag " + "is disabled." + ) + return False + return True + + def _save_conversion_params_metric(self): + self._collected_converter_params.update({ + "output_format": self.output_format, + "default_ranges_stats": self.default_ranges_stats, + "drop_control_dependency": self.drop_control_dependency, + "reorder_across_fake_quant": self.reorder_across_fake_quant, + "change_concat_input_ranges": self.change_concat_input_ranges, + "dump_graphviz_dir": self.dump_graphviz_dir, + "dump_graphviz_video": self.dump_graphviz_video, + "conversion_summary_dir": self.conversion_summary_dir, + }) + super(TFLiteConverterBaseV1, self)._save_conversion_params_metric( + self._graph_def, self.inference_type, self.inference_input_type + ) + + +class TFLiteSavedModelConverter(TFLiteConverterBaseV1): + """Converts the given SavedModel into TensorFlow Lite model. + + Attributes: + saved_model_dir: Directory of the SavedModel. + """ + + def __init__( + self, + saved_model_dir, + saved_model_tags, + saved_model_exported_names, + experimental_debug_info_func=None, + ): + """Constructor for TFLiteConverter. + + Args: + saved_model_dir: Directory of the SavedModel. + saved_model_tags: Set of tags identifying the MetaGraphDef within the + SavedModel to analyze. All tags in the tag set must be present. (default + {tf.saved_model.SERVING}). + saved_model_exported_names: Names to be exported when the saved model + import path is on. + experimental_debug_info_func: An experimental function to retrieve the + graph debug info for a set of nodes from the `graph_def`. + + Raises: + ValueError: Invalid arguments. + """ + super(TFLiteSavedModelConverter, self).__init__( + experimental_debug_info_func + ) + self.saved_model_dir = saved_model_dir + self._saved_model_tags = saved_model_tags + self._saved_model_exported_names = saved_model_exported_names + + signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + + if len(self._saved_model_exported_names) != 1: + raise ValueError("Only support a single signature key.") + + signature_key = self._saved_model_exported_names[0] + + result = _freeze_saved_model( + self.saved_model_dir, + None, + None, + None, + self._saved_model_tags, + signature_key, + ) + self._graph_def = result[0] + self._input_tensors = result[1] + self._output_tensors = result[2] + self._parse_saved_model_args() + + @_export_metrics + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Note that in the converted TensorFlow Lite model, the input tensor's order + might be changed each time `convert` is called. To access input tensor + information, please consider using the `SignatureRunner` API + (`interpreter.get_signature_runner`). + + Returns: + The converted data in serialized format. Either a TFLite Flatbuffer or a + Graphviz graph depending on value in `output_format`. + + Raises: + ValueError: + Input shape is not specified. + None value for dimension in input_tensor. + """ + return super(TFLiteSavedModelConverter, self).convert() + + +class TFLiteKerasModelConverter(TFLiteConverterBaseV1): + """Converts the given SavedModel into TensorFlow Lite model.""" + + def __init__( + self, + model_file, + input_arrays=None, + input_shapes=None, + output_arrays=None, + custom_objects=None, + ): + """Constructor for TFLiteConverter. + + Args: + model_file: Full filepath of HDF5 file containing the tf.keras model. + input_arrays: List of input tensors to freeze graph with. Uses input + arrays from SignatureDef when none are provided. (default None) + input_shapes: Dict of strings representing input tensor names to list of + integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). + Automatically determined when input shapes is None (e.g., {"foo" : + None}). (default None) + output_arrays: List of output tensors to freeze graph with. Uses output + arrays from SignatureDef when none are provided. (default None) + custom_objects: Dict mapping names (strings) to custom classes or + functions to be considered during model deserialization. (default None) + + Raises: + ValueError: Invalid arguments. + """ + super(TFLiteKerasModelConverter, self).__init__( + experimental_debug_info_func=None + ) + # Handles Keras when Eager mode is enabled. + if context.executing_eagerly(): + if input_arrays or output_arrays: + raise ValueError( + "`input_arrays` and `output_arrays` are unsupported " + "with Eager mode. If your model requires any of these " + "parameters, please use disable_eager_execution()." + ) + + keras_model = keras_deps.get_load_model_function()( + model_file, custom_objects + ) + function = _trace_model_call(keras_model) + concrete_func = function.get_concrete_function() + + frozen_func = _convert_to_constants.convert_variables_to_constants_v2( + concrete_func, lower_control_flow=False + ) + _set_tensor_shapes(frozen_func.inputs, input_shapes) + self._keras_model = keras_model + self._graph_def = frozen_func.graph.as_graph_def() + self._input_tensors = frozen_func.inputs + self._output_tensors = frozen_func.outputs + self._debug_info_func = _build_debug_info_func(frozen_func.graph) + return + + # Handles Keras when Eager mode is disabled. + keras_deps.get_clear_session_function()() + keras_model = keras_deps.get_load_model_function()( + model_file, custom_objects + ) + sess = keras_deps.get_get_session_function()() + + # Get input and output tensors. + if input_arrays: + input_tensors = _get_tensors_from_tensor_names(sess.graph, input_arrays) + else: + input_tensors = keras_model.inputs + + if output_arrays: + output_tensors = _get_tensors_from_tensor_names(sess.graph, output_arrays) + else: + output_tensors = keras_model.outputs + _set_tensor_shapes(input_tensors, input_shapes) + + graph_def = _freeze_graph(sess, input_tensors, output_tensors) + self._keras_model = keras_model + self._graph_def = graph_def + self._input_tensors = input_tensors + self._output_tensors = output_tensors + self._debug_info_func = _build_debug_info_func(sess.graph) + + @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.FREEZE_KERAS_MODEL) + def _freeze_keras_model(self, output_dir): + """Save Keras model to Saved Model format. + + Args: + output_dir: The output directory to save the SavedModel. + """ + try: + self._keras_model.save(output_dir, save_format="tf") + except Exception: # pylint: disable=broad-except + # When storing the given keras model to a saved model is failed, let's + # use original keras model conversion pipeline. + return None + tag_set = set([_tag_constants.SERVING]) + signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + graph_def, input_tensors, output_tensors, sess_graph = _freeze_saved_model( + output_dir, None, None, None, tag_set, signature_key + ) + + self.saved_model_dir = output_dir + self._saved_model_tags = tag_set + self._saved_model_exported_names = [signature_key] + self._parse_saved_model_args() + if self.saved_model_dir: + self._graph_def = graph_def + self._input_tensors = input_tensors + self._output_tensors = output_tensors + self._debug_info_func = _build_debug_info_func(sess_graph) + + def _convert_as_saved_model(self): + """Converts a Keras model as a saved model. + + Returns: + The converted data in serialized format. + """ + temp_dir = tempfile.mkdtemp() + try: + self._freeze_keras_model(temp_dir) + if self.saved_model_dir: + return super(TFLiteKerasModelConverter, self).convert() + finally: + shutil.rmtree(temp_dir, True) + + @_export_metrics + def convert(self): + """Converts a Keras model based on instance variables. + + Returns: + The converted data in serialized format. Either a TFLite Flatbuffer or a + Graphviz graph depending on value in `output_format`. + + Raises: + ValueError: + Input shape is not specified. + None value for dimension in input_tensor. + """ + saved_model_convert_result = self._convert_as_saved_model() + if saved_model_convert_result: + return saved_model_convert_result + + return super(TFLiteKerasModelConverter, self).convert() + + +class TFLiteFrozenGraphConverter(TFLiteConverterBaseV1): + """Converts the given frozen graph def into TensorFlow Lite model.""" + + def __init__( + self, + graph_def, + input_tensors, + output_tensors, + input_arrays_with_shape=None, + output_arrays=None, + experimental_debug_info_func=None, + ): + """Constructor for TFLiteConverter. + + Args: + graph_def: Frozen TensorFlow GraphDef. + input_tensors: List of input tensors. Type and shape are computed using + `foo.shape` and `foo.dtype`. + output_tensors: List of output tensors (only .name is used from this). + input_arrays_with_shape: Tuple of strings representing input tensor names + and list of integers representing input shapes (e.g., [("foo", [1, 16, + 16, 3])]). Use only when graph cannot be loaded into TensorFlow and when + `input_tensors` and `output_tensors` are None. (default None) + output_arrays: List of output tensors to freeze graph with. Use only when + graph cannot be loaded into TensorFlow and when `input_tensors` and + `output_tensors` are None. (default None) + experimental_debug_info_func: An experimental function to retrieve the + graph debug info for a set of nodes from the `graph_def`. + + Raises: + ValueError: Invalid arguments. + """ + super(TFLiteFrozenGraphConverter, self).__init__( + experimental_debug_info_func + ) + self._graph_def = graph_def + self._input_tensors = input_tensors + self._output_tensors = output_tensors + self._control_output_arrays = None + + # Attributes are used by models that cannot be loaded into TensorFlow. + if not self._has_valid_tensors(): + self._input_arrays_with_shape = input_arrays_with_shape + self._output_arrays = output_arrays + + if input_tensors is not None and input_arrays_with_shape is not None: + logging.warning( + "input_arrays_with_shape will be ignored when both the " + "given input_tensors and input_arrays_with_shape are not " + "None." + ) + + if output_tensors is not None and output_arrays is not None: + logging.warning( + "output_arrays will be ignored when both the given " + "output_tensors and output_arrays are not None." + ) + + @_export_metrics + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Returns: + The converted data in serialized format. Either a TFLite Flatbuffer or a + Graphviz graph depending on value in `output_format`. + + Raises: + ValueError: + Input shape is not specified. + None value for dimension in input_tensor. + """ + if not self._has_valid_tensors(): + if not self._input_arrays_with_shape or not ( + self._output_arrays or self._control_output_arrays + ): + raise ValueError( + "If input_tensors and output_tensors are None, both " + "input_arrays_with_shape and output_arrays|control_output_arrays " + "must be defined." + ) + return super(TFLiteFrozenGraphConverter, self).convert() + + +@_tf_export(v1=["lite.TFLiteConverter"]) +class TFLiteConverter(TFLiteFrozenGraphConverter): + """Convert a TensorFlow model into `output_format`. + + This is used to convert from a TensorFlow GraphDef, SavedModel or tf.keras + model into either a TFLite FlatBuffer or graph visualization. + + Attributes: + optimizations: Experimental flag, subject to change. Set of optimizations to + apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a + set of values of type `tf.lite.Optimize`) + representative_dataset: A generator function used for integer quantization + where each generated sample has the same order, type and shape as the + inputs to the model. Usually, this is a small subset of a few hundred + samples randomly chosen, in no particular order, from the training or + evaluation dataset. This is an optional attribute, but required for full + integer quantization, i.e, if `tf.int8` is the only supported type in + `target_spec.supported_types`. Refer to `tf.lite.RepresentativeDataset`. + (default None) + target_spec: Experimental flag, subject to change. Specifications of target + device, including supported ops set, supported types and a set of user's + defined TensorFlow operators required in the TensorFlow Lite runtime. + Refer to `tf.lite.TargetSpec`. + inference_type: Data type of numeric arrays, excluding the input layer. + (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8}) + inference_input_type: Data type of the numeric arrays in the input layer. If + `inference_input_type` is in {tf.int8, tf.uint8}, then + `quantized_input_stats` must be provided. (default is the value assigned + to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8}) + inference_output_type: Data type of the numeric arrays in the output layer. + (default is the value assigned to `inference_type`, must be in + {tf.float32, tf.int8, tf.uint8}) + quantized_input_stats: Map of input tensor names to a tuple of floats + representing the mean and standard deviation of the training data. (e.g., + {"foo" : (0., 1.)}). Required if `inference_input_type` is tf.int8 or + tf.uint8. (default None) + default_ranges_stats: Tuple of integers (min, max) representing range values + for all numeric arrays without a specified range. Intended for + experimenting with quantization via "dummy quantization". (default None) + allow_custom_ops: Boolean indicating whether to allow custom operations. + When False any unknown operation is an error. When True, custom ops are + created for any op that is unknown. The developer will need to provide + these to the TensorFlow Lite runtime with a custom resolver. (default + False) + drop_control_dependency: Boolean indicating whether to drop control + dependencies silently. This is due to TFLite not supporting control + dependencies. (default True) + reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant + nodes in unexpected locations. Used when the location of the FakeQuant + nodes is preventing graph transformations necessary to convert the graph. + Results in a graph that differs from the quantized training graph, + potentially causing differing arithmetic behavior. (default False) + change_concat_input_ranges: Boolean to change behavior of min/max ranges for + inputs and outputs of the concat operator for quantized models. Changes + the ranges of concat operator overlap when true. (default False) + output_format: Output file format. (default + tf.compat.v1.lite.constants.TFLITE, must be in + {tf.compat.v1.lite.constants.TFLITE, + tf.compat.v1.lite.constants.GRAPHVIZ_DOT}) + dump_graphviz_dir: Full filepath of folder to dump the graphs at various + stages of processing GraphViz .dot files. Preferred over + `output_format=tf.compat.v1.lite.constants.GRAPHVIZ_DOT` in order to keep + the requirements of the output file. (default None) + dump_graphviz_video: Boolean indicating whether to dump the GraphViz .dot + files after every graph transformation. Requires the `dump_graphviz_dir` + flag to be specified. (default False) + conversion_summary_dir: Full path of the directory to store conversion logs. + (default None) + exclude_conversion_metadata: Whether not to embed the conversion metadata + into the converted model. (default False) + target_ops: Deprecated. Please use `target_spec.supported_ops` instead. + post_training_quantize: Deprecated. Please use `optimizations` instead and + set it to `{tf.lite.Optimize.DEFAULT}`. (default False) + experimental_new_converter: Experimental flag, subject to change. Enables + MLIR-based conversion. (default True) + experimental_new_quantizer: Experimental flag, subject to change. Enables + MLIR-based quantization conversion instead of Flatbuffer-based conversion. + (default True) Example usage: ```python # Converting a GraphDef from + session. converter = tf.compat.v1.lite.TFLiteConverter.from_session( sess, + in_tensors, out_tensors) tflite_model = converter.convert() + open("converted_model.tflite", "wb").write(tflite_model) # Converting a + GraphDef from file. converter = + tf.compat.v1.lite.TFLiteConverter.from_frozen_graph( graph_def_file, + input_arrays, output_arrays) tflite_model = converter.convert() + open("converted_model.tflite", "wb").write(tflite_model) # Converting a + SavedModel. converter = + tf.compat.v1.lite.TFLiteConverter.from_saved_model( saved_model_dir) + tflite_model = converter.convert() open("converted_model.tflite", + "wb").write(tflite_model) # Converting a tf.keras model. converter = + tf.compat.v1.lite.TFLiteConverter.from_keras_model_file( keras_model) + tflite_model = converter.convert() open("converted_model.tflite", + "wb").write(tflite_model) ``` + """ + + # pylint: disable=useless-super-delegation + def __init__( + self, + graph_def, + input_tensors, + output_tensors, + input_arrays_with_shape=None, + output_arrays=None, + experimental_debug_info_func=None, + ): + """Constructor for TFLiteConverter. + + Args: + graph_def: Frozen TensorFlow GraphDef. + input_tensors: List of input tensors. Type and shape are computed using + `foo.shape` and `foo.dtype`. + output_tensors: List of output tensors (only .name is used from this). + input_arrays_with_shape: Tuple of strings representing input tensor names + and list of integers representing input shapes (e.g., [("foo" : [1, 16, + 16, 3])]). Use only when graph cannot be loaded into TensorFlow and when + `input_tensors` and `output_tensors` are None. (default None) + output_arrays: List of output tensors to freeze graph with. Use only when + graph cannot be loaded into TensorFlow and when `input_tensors` and + `output_tensors` are None. (default None) + experimental_debug_info_func: An experimental function to retrieve the + graph debug info for a set of nodes from the `graph_def`. + + Raises: + ValueError: Invalid arguments. + """ + super(TFLiteConverter, self).__init__( + graph_def, + input_tensors, + output_tensors, + input_arrays_with_shape, + output_arrays, + experimental_debug_info_func, + ) + + @classmethod + def from_session(cls, sess, input_tensors, output_tensors): + """Creates a TFLiteConverter class from a TensorFlow Session. + + Args: + sess: TensorFlow Session. + input_tensors: List of input tensors. Type and shape are computed using + `foo.shape` and `foo.dtype`. + output_tensors: List of output tensors (only .name is used from this). + + Returns: + TFLiteConverter class. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.TF_SESSION + ) + # pylint: enable=protected-access + graph_def = _freeze_graph(sess, input_tensors, output_tensors) + return cls( + graph_def, + input_tensors, + output_tensors, + experimental_debug_info_func=_build_debug_info_func(sess.graph), + ) + + @classmethod + def from_frozen_graph( + cls, graph_def_file, input_arrays, output_arrays, input_shapes=None + ): + """Creates a TFLiteConverter class from a file containing a frozen GraphDef. + + Args: + graph_def_file: Full filepath of file containing frozen GraphDef. + input_arrays: List of input tensors to freeze graph with. + output_arrays: List of output tensors to freeze graph with. + input_shapes: Dict of strings representing input tensor names to list of + integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). + Automatically determined when input shapes is None (e.g., {"foo" : + None}). (default None) + + Returns: + TFLiteConverter class. + + Raises: + IOError: + File not found. + Unable to parse input file. + ValueError: + The graph is not frozen. + input_arrays or output_arrays contains an invalid tensor name. + input_shapes is not correctly defined when required + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.TF_GRAPH_DEF + ) + # pylint: enable=protected-access + with _ops.Graph().as_default(): + with _session.Session() as sess: + # Read GraphDef from file. + if not gfile.Exists(graph_def_file): + raise IOError("File '{0}' does not exist.".format(graph_def_file)) + with gfile.GFile(graph_def_file, "rb") as f: + file_content = f.read() + + try: + graph_def = _graph_pb2.GraphDef() + graph_def.ParseFromString(file_content) + except (_text_format.ParseError, DecodeError): + try: + print("Ignore 'tcmalloc: large alloc' warnings.") + + if not isinstance(file_content, str): + file_content = file_content.decode("utf-8") + graph_def = _graph_pb2.GraphDef() + _text_format.Merge(file_content, graph_def) + except (_text_format.ParseError, DecodeError): + raise IOError( + "Unable to parse input file '{}'.".format(graph_def_file) + ) + + if sys.byteorder == "big": + bst.swap_tensor_content_in_graph_node(graph_def, "little", "big") + + # Handles models with custom TFLite ops that cannot be resolved in + # TensorFlow. + load_model_in_session = True + try: + _import_graph_def(graph_def, name="") + except _NotFoundError: + load_model_in_session = False + + if load_model_in_session: + # Check if graph is frozen. + if not _is_frozen_graph(sess): + raise ValueError("Please freeze the graph using freeze_graph.py.") + + # Get input and output tensors. + input_tensors = _get_tensors_from_tensor_names( + sess.graph, input_arrays + ) + output_tensors = _get_tensors_from_tensor_names( + sess.graph, output_arrays + ) + _set_tensor_shapes(input_tensors, input_shapes) + + return cls(sess.graph_def, input_tensors, output_tensors) + else: + if not input_shapes: + raise ValueError("input_shapes must be defined for this model.") + if set(input_arrays) != set(input_shapes.keys()): + raise ValueError( + "input_shapes must contain a value for each item " + "in input_array." + ) + + input_arrays_with_shape = [ + (name, input_shapes[name]) for name in input_arrays + ] + return cls( + graph_def, + input_tensors=None, + output_tensors=None, + input_arrays_with_shape=input_arrays_with_shape, + output_arrays=output_arrays, + ) + + @classmethod + def from_saved_model( + cls, + saved_model_dir, + input_arrays=None, + input_shapes=None, + output_arrays=None, + tag_set=None, + signature_key=None, + ): + """Creates a TFLiteConverter class from a SavedModel. + + Args: + saved_model_dir: SavedModel directory to convert. + input_arrays: List of input tensors to freeze graph with. Uses input + arrays from SignatureDef when none are provided. (default None) + input_shapes: Dict of strings representing input tensor names to list of + integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). + Automatically determined when input shapes is None (e.g., {"foo" : + None}). (default None) + output_arrays: List of output tensors to freeze graph with. Uses output + arrays from SignatureDef when none are provided. (default None) + tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to + analyze. All tags in the tag set must be present. (default + {tf.saved_model.SERVING}) + signature_key: Key identifying SignatureDef containing inputs and outputs. + (default tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY) + + Returns: + TFLiteConverter class. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.TF_SAVED_MODEL + ) + # pylint: enable=protected-access + if tag_set is None: + tag_set = set([_tag_constants.SERVING]) + if signature_key is None: + signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + + saved_model_converter = TFLiteSavedModelConverter( + saved_model_dir, tag_set, [signature_key] + ) + if saved_model_converter.saved_model_dir: + return saved_model_converter + + result = _freeze_saved_model( + saved_model_dir, + input_arrays, + input_shapes, + output_arrays, + tag_set, + signature_key, + ) + + return cls( + graph_def=result[0], + input_tensors=result[1], + output_tensors=result[2], + experimental_debug_info_func=_build_debug_info_func(result[3]), + ) + + @classmethod + def from_keras_model_file( + cls, + model_file, + input_arrays=None, + input_shapes=None, + output_arrays=None, + custom_objects=None, + ): + """Creates a TFLiteConverter class from a tf.keras model file. + + Args: + model_file: Full filepath of HDF5 file containing the tf.keras model. + input_arrays: List of input tensors to freeze graph with. Uses input + arrays from SignatureDef when none are provided. (default None) + input_shapes: Dict of strings representing input tensor names to list of + integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). + Automatically determined when input shapes is None (e.g., {"foo" : + None}). (default None) + output_arrays: List of output tensors to freeze graph with. Uses output + arrays from SignatureDef when none are provided. (default None) + custom_objects: Dict mapping names (strings) to custom classes or + functions to be considered during model deserialization. (default None) + + Returns: + TFLiteConverter class. + """ + # pylint: disable=protected-access + TFLiteConverterBase._set_original_model_type( + conversion_metdata_fb.ModelType.KERAS_MODEL + ) + # pylint: enable=protected-access + return TFLiteKerasModelConverter( + model_file, input_arrays, input_shapes, output_arrays, custom_objects + ) + + # pylint: disable=useless-super-delegation + def convert(self): + """Converts a TensorFlow GraphDef based on instance variables. + + Returns: + The converted data in serialized format. Either a TFLite Flatbuffer or a + Graphviz graph depending on value in `output_format`. + + Raises: + ValueError: + Input shape is not specified. + None value for dimension in input_tensor. + """ + return super(TFLiteConverter, self).convert() + + +@_tf_export(v1=["lite.TocoConverter"]) +class TocoConverter: + """Convert a TensorFlow model into `output_format`. + + This class has been deprecated. Please use `lite.TFLiteConverter` instead. + """ + + @classmethod + @_deprecation.deprecated( + None, "Use `lite.TFLiteConverter.from_session` instead." + ) + def from_session(cls, sess, input_tensors, output_tensors): + """Creates a TocoConverter class from a TensorFlow Session.""" + return TFLiteConverter.from_session(sess, input_tensors, output_tensors) + + @classmethod + @_deprecation.deprecated( + None, "Use `lite.TFLiteConverter.from_frozen_graph` instead." + ) + def from_frozen_graph( + cls, graph_def_file, input_arrays, output_arrays, input_shapes=None + ): + """Creates a TocoConverter class from a file containing a frozen graph.""" + return TFLiteConverter.from_frozen_graph( + graph_def_file, input_arrays, output_arrays, input_shapes + ) + + @classmethod + @_deprecation.deprecated( + None, "Use `lite.TFLiteConverter.from_saved_model` instead." + ) + def from_saved_model( + cls, + saved_model_dir, + input_arrays=None, + input_shapes=None, + output_arrays=None, + tag_set=None, + signature_key=None, + ): + """Creates a TocoConverter class from a SavedModel.""" + return TFLiteConverter.from_saved_model( + saved_model_dir, + input_arrays, + input_shapes, + output_arrays, + tag_set, + signature_key, + ) + + @classmethod + @_deprecation.deprecated( + None, "Use `lite.TFLiteConverter.from_keras_model_file` instead." + ) + def from_keras_model_file( + cls, model_file, input_arrays=None, input_shapes=None, output_arrays=None + ): + """Creates a TocoConverter class from a tf.keras model file.""" + return TFLiteConverter.from_keras_model_file( + model_file, input_arrays, input_shapes, output_arrays + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite_constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..4700a5920b57c04157dead55ae998e7c695a20cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/lite_constants.py @@ -0,0 +1,70 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Constants for TFLite.""" + +from tensorflow.lite.toco import toco_flags_pb2 as _toco_flags_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.util.all_util import remove_undocumented +from tensorflow.python.util.tf_export import tf_export as _tf_export + +FLOAT = dtypes.float32 +FLOAT16 = dtypes.float16 +INT32 = dtypes.int32 +INT64 = dtypes.int64 +STRING = dtypes.string +QUANTIZED_UINT8 = dtypes.uint8 +INT8 = dtypes.int8 +INT16 = dtypes.int16 +COMPLEX64 = dtypes.complex64 +TENSORFLOW_GRAPHDEF = _toco_flags_pb2.TENSORFLOW_GRAPHDEF +TFLITE = _toco_flags_pb2.TFLITE +GRAPHVIZ_DOT = _toco_flags_pb2.GRAPHVIZ_DOT + +_tf_export(v1=["lite.constants.FLOAT"]).export_constant(__name__, "FLOAT") +_tf_export(v1=["lite.constants.FLOAT16"]).export_constant(__name__, "FLOAT16") +_tf_export(v1=["lite.constants.INT32"]).export_constant(__name__, "INT32") +_tf_export(v1=["lite.constants.INT64"]).export_constant(__name__, "INT64") +_tf_export(v1=["lite.constants.STRING"]).export_constant(__name__, "STRING") +_tf_export(v1=["lite.constants.QUANTIZED_UINT8"]).export_constant( + __name__, "QUANTIZED_UINT8") +_tf_export(v1=["lite.constants.INT8"]).export_constant(__name__, "INT8") +_tf_export(v1=["lite.constants.INT16"]).export_constant(__name__, "INT16") +_tf_export(v1=["lite.constants.TFLITE"]).export_constant(__name__, "TFLITE") +_tf_export(v1=["lite.constants.GRAPHVIZ_DOT"]).export_constant( + __name__, "GRAPHVIZ_DOT") + +# Currently the default mode of operation is to shell to another python process +# to protect against crashes. However, it breaks some dependent targets because +# it forces us to depend on an external py_binary. The experimental API doesn't +# have that drawback. +EXPERIMENTAL_USE_TOCO_API_DIRECTLY = False + + +_allowed_symbols = [ + "FLOAT", + "FLOAT16", + "INT32", + "INT64", + "STRING", + "QUANTIZED_UINT8", + "INT8", + "INT16", + "COMPLEX64", + "TENSORFLOW_GRAPHDEF", + "TFLITE", + "GRAPHVIZ_DOT", + "EXPERIMENTAL_USE_TOCO_API_DIRECTLY", +] +remove_undocumented(__name__, _allowed_symbols) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..79b8ac2ac6314c6d18b56335efa4c728748b6815 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.pyi @@ -0,0 +1,18 @@ +# 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. +# ============================================================================== + +class MetricsWrapper: + def __init__(self, arg0: str) -> None: ... + def ExportMetrics(self) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/converter_error_data_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/converter_error_data_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..2500b003cd87b92b6021df2cadf88a5616be2c93 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/converter_error_data_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/lite/python/metrics/converter_error_data.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n9tensorflow/lite/python/metrics/converter_error_data.proto\x12\x0etflite.metrics\"\xdc\x06\n\x12\x43onverterErrorData\x12\x11\n\tcomponent\x18\x01 \x01(\t\x12\x14\n\x0csubcomponent\x18\x02 \x01(\t\x12@\n\nerror_code\x18\x03 \x01(\x0e\x32,.tflite.metrics.ConverterErrorData.ErrorCode\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12=\n\x08operator\x18\x05 \x01(\x0b\x32+.tflite.metrics.ConverterErrorData.Operator\x12=\n\x08location\x18\x06 \x01(\x0b\x32+.tflite.metrics.ConverterErrorData.Location\x1a\x18\n\x08Operator\x12\x0c\n\x04name\x18\x01 \x01(\t\x1a\x39\n\x07\x46ileLoc\x12\x10\n\x08\x66ilename\x18\x01 \x01(\t\x12\x0c\n\x04line\x18\x02 \x01(\r\x12\x0e\n\x06\x63olumn\x18\x03 \x01(\r\x1aU\n\tSourceLoc\x12\x0c\n\x04name\x18\x01 \x01(\t\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.tflite.metrics.ConverterErrorData.FileLoc\x1a\x85\x01\n\x08Location\x12=\n\x04type\x18\x01 \x01(\x0e\x32/.tflite.metrics.ConverterErrorData.LocationType\x12:\n\x04\x63\x61ll\x18\x02 \x03(\x0b\x32,.tflite.metrics.ConverterErrorData.SourceLoc\"\xc5\x01\n\tErrorCode\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x18\n\x14\x45RROR_NEEDS_FLEX_OPS\x10\x01\x12\x1a\n\x16\x45RROR_NEEDS_CUSTOM_OPS\x10\x02\x12%\n!ERROR_UNSUPPORTED_CONTROL_FLOW_V1\x10\x03\x12/\n+ERROR_STATEFUL_PARTITIONED_CALL_IN_FINAL_IR\x10\x04\x12\x1d\n\x18\x45RROR_GPU_NOT_COMPATIBLE\x10\xc8\x01\"J\n\x0cLocationType\x12\x0e\n\nUNKNOWNLOC\x10\x00\x12\x0b\n\x07NAMELOC\x10\x01\x12\x0f\n\x0b\x43\x41LLSITELOC\x10\x02\x12\x0c\n\x08\x46USEDLOC\x10\x03') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.python.metrics.converter_error_data_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _CONVERTERERRORDATA._serialized_start=78 + _CONVERTERERRORDATA._serialized_end=938 + _CONVERTERERRORDATA_OPERATOR._serialized_start=356 + _CONVERTERERRORDATA_OPERATOR._serialized_end=380 + _CONVERTERERRORDATA_FILELOC._serialized_start=382 + _CONVERTERERRORDATA_FILELOC._serialized_end=439 + _CONVERTERERRORDATA_SOURCELOC._serialized_start=441 + _CONVERTERERRORDATA_SOURCELOC._serialized_end=526 + _CONVERTERERRORDATA_LOCATION._serialized_start=529 + _CONVERTERERRORDATA_LOCATION._serialized_end=662 + _CONVERTERERRORDATA_ERRORCODE._serialized_start=665 + _CONVERTERERRORDATA_ERRORCODE._serialized_end=862 + _CONVERTERERRORDATA_LOCATIONTYPE._serialized_start=864 + _CONVERTERERRORDATA_LOCATIONTYPE._serialized_end=938 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f21859b610696b5f0c263ffdb8d81a7e7ddd7734 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics.py @@ -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. +# ============================================================================== +"""Python TFLite metrics helper.""" +import os +from typing import Optional, Text + +# pylint: disable=g-import-not-at-top +if not os.path.splitext(__file__)[0].endswith( + os.path.join('tflite_runtime', 'metrics_portable')): + # This file is part of tensorflow package. + from tensorflow.lite.python.metrics import metrics_interface # type: ignore +else: + # This file is part of tflite_runtime package. + from tflite_runtime import metrics_interface # type: ignore +# pylint: enable=g-import-not-at-top + + +class TFLiteMetrics(metrics_interface.TFLiteMetricsInterface): + """TFLite metrics helper.""" + + def __init__(self, + model_hash: Optional[Text] = None, + model_path: Optional[Text] = None) -> None: + pass + + def increase_counter_debugger_creation(self): + pass + + def increase_counter_interpreter_creation(self): + pass + + def increase_counter_converter_attempt(self): + pass + + def increase_counter_converter_success(self): + pass + + def set_converter_param(self, name, value): + pass + + def set_converter_error(self, error_data): + pass + + def set_converter_latency(self, value): + pass + + +class TFLiteConverterMetrics(TFLiteMetrics): + """Similar to TFLiteMetrics but specialized for converter.""" + + def __del__(self): + pass + + def set_export_required(self): + pass + + def export_metrics(self): + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics_interface.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f38f3d40d400d52c315a2a7db129807e099161 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/metrics_interface.py @@ -0,0 +1,48 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Python TFLite metrics helper interface.""" +import abc + + +class TFLiteMetricsInterface(metaclass=abc.ABCMeta): + """Abstract class for TFLiteMetrics.""" + + @abc.abstractmethod + def increase_counter_debugger_creation(self): + raise NotImplementedError + + @abc.abstractmethod + def increase_counter_interpreter_creation(self): + raise NotImplementedError + + @abc.abstractmethod + def increase_counter_converter_attempt(self): + raise NotImplementedError + + @abc.abstractmethod + def increase_counter_converter_success(self): + raise NotImplementedError + + @abc.abstractmethod + def set_converter_param(self, name, value): + raise NotImplementedError + + @abc.abstractmethod + def set_converter_error(self, error_data): + raise NotImplementedError + + @abc.abstractmethod + def set_converter_latency(self, value): + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/metrics_wrapper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/metrics_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..fa05f7d62644ce9d166852e50e2c95f867d76ddf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/metrics/wrapper/metrics_wrapper.py @@ -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. +# ============================================================================== +"""Stub to make pywrap metrics wrapper accessible.""" + +from tensorflow.lite.python import wrap_toco +from tensorflow.lite.python.metrics import converter_error_data_pb2 +from tensorflow.lite.python.metrics._pywrap_tensorflow_lite_metrics_wrapper import MetricsWrapper # pylint: disable=unused-import + + +def retrieve_collected_errors(): + """Returns and clears the list of collected errors in ErrorCollector. + + The RetrieveCollectedErrors function in C++ returns a list of serialized proto + messages. This function will convert them to ConverterErrorData instances. + + Returns: + A list of ConverterErrorData. + """ + serialized_message_list = wrap_toco.wrapped_retrieve_collected_errors() + return list( + map(converter_error_data_pb2.ConverterErrorData.FromString, + serialized_message_list)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/op_hint.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/op_hint.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0201bc219ec2b93144cd42db55b9848e4995c6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/op_hint.py @@ -0,0 +1,1338 @@ +# 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. +# ============================================================================== +"""Define tflite op hints (intrinsic operations). + +This essentially allows defining a TensorFlow API for tflite operations in +Python with hints on how they are represented in TensorFlow Lite. This basically +is a form of tflite intrinsic. It wraps a subpart of a TensorFlow execution +graph and is useful for LSTMs and other complicated TensorFlow constructions +that are difficult to pattern match in TOCO, but are represented by a single +accelerated tflite op. + +Example: + def tflite_cool_activation(input): + # A cool activation function. + custom = tf.lite.OpHint("cool_activation") + input, = custom.add_inputs(input) + output = tf.sigmoid(input) * input + output, = custom.add_outputs(output) + return output + + image = tf.compat.v1.placeholder(tf.float32, (1, 16, 16, 1)) + output = tf.identity(tflite_cool_activation(image)) + + session = tf.compat.v1.Session() + + graphdef_to_convert = tf.lite.experimental.convert_op_hints_to_stubs(session) + tflite_graph = tf.compat.v1.lite.toco_convert( + graphdef_to_convert, [image], [output], allow_custom_ops=True) + with open("/tmp/graph.fb", "wb") as fp: + fp.write(tflite_graph) + +How does it work?: + +OpHint is a helper that you use when defining a vanilla python function. +It allows you to wrap arguments with tf.identities with some custom attributes. +These attributes allow you to find the original block of ops that was created. +For example, if you use cool_activation above you essentially get: + +a_input = tf.identity() +result = tf.multiply(tf.sigmoid(a_input), a_input) +output = tf.identity() + +a_input, output are identities that have parameters representing +what argument they are, what the name of the function they should turn into +in tf lite as well as a guid that uniquely identifies a particular invocation. + +Once you have built your whole tensorflow graph, you can run it and train it +as usual, but after you have done that, you need to convert the graph into +a form that replaces these subgraphs wrapped in identities to stub ops. These +ops don't actually exist in the normal TensorFlow runtime, but will be +understood by toco later. The generated TensorFlow Lite flatbuffer file will +contain a custom operator called "cool_activation". Developer needs to implement +and register this operator in TensorFlow Lite in order to do inference. +""" + +import collections as _collections +import copy as _copy +import json as _json +import uuid as _uuid + +from tensorflow.core.framework import attr_value_pb2 as _attr_value_pb2 +from tensorflow.core.framework import graph_pb2 as _graph_pb2 +from tensorflow.core.framework import node_def_pb2 as _node_def_pb2 +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import tensor_util as _tensor_util +from tensorflow.python.framework.graph_util_impl import _bfs_for_reachable_nodes +from tensorflow.python.framework.graph_util_impl import _extract_graph_summary +from tensorflow.python.ops import array_ops as _array_ops +from tensorflow.python.util import compat as _compat +from tensorflow.python.util import deprecation as _deprecation +from tensorflow.python.util.all_util import remove_undocumented +from tensorflow.python.util.tf_export import tf_export as _tf_export + + +@_tf_export(v1=["lite.OpHint"]) +@_deprecation.deprecated( + None, + "Please follow instructions under " + "https://www.tensorflow.org/lite/convert/operation_fusion for operation" + "fusion in tflite." +) +class OpHint: + """A class that helps build tflite function invocations. + + It allows you to take a bunch of TensorFlow ops and annotate the construction + such that toco knows how to convert it to tflite. This embeds a pseudo + function in a TensorFlow graph. This allows embedding high-level API usage + information in a lower level TensorFlow implementation so that an alternative + implementation can be substituted later. + + Essentially, any "input" into this pseudo op is fed into an identity, and + attributes are added to that input before being used by the constituent ops + that make up the pseudo op. A similar process is done to any output that + is to be exported from the current op. + + """ + # Attr constants that are used for representation in the GraphDef. These + # will be used on every Identity op that is involved in a total OpHint. + + # Name of the OpHint function (cosmetic). + FUNCTION_NAME_ATTR = "_tflite_function_name" + # UUID of the function (each OpHint gets a new uuid). + FUNCTION_UUID_ATTR = "_tflite_function_uuid" + # The input index of the input (or nothing if it is an output). + FUNCTION_INPUT_INDEX_ATTR = "_tflite_function_input_index" + # The output index of the output (or nothing if it is an input). + FUNCTION_OUTPUT_INDEX_ATTR = "_tflite_function_output_index" + # An index that orders aggregate arguments. Aggregate arguments are ones + # that are separate but will be fused horizontally. For example a static LSTM + # has a lstm cell for each time step. Each one has a separate opHint, but a + # fused SequentialLSTM will treat this as a single tensor. + FUNCTION_SORT_INDEX_ATTR = "_tflite_function_sort_index" + # The way in which multiple parts of the aggregate argument will be joined + # into a fused operand. Valid options are OpHint.AGGREGATE_FIRST, + # OpHint.AGGREGATE_LAST, OpHint.AGGREGATE_STACK. + FUNCTION_AGGREGATE_ATTR = "_tflite_function_aggregate" + # On fused OpHint stub, the order of inputs that the final LSTM call will + # have. What this means is that the TensorFlow order might be + # "foo", "bar", "stuff" and you might want the TF lite op order to be + # "stuff", "foo", "bar", -1 (where -1 is unused). So you would set this + # attribute to [2, 0, 1, -1]. + TFLITE_INPUT_INDICES = "_tflite_input_indices" + # OpHint level. + FUNCTION_LEVEL_ATTR = "_tflite_ophint_level" + # Ophint internal mapping, this is for high level Ophint only. + # This basically contains three kinds of mapping: + # 1) How parental ophinted inputs map to the first child ophinted inputs; + # 2) How internal children nodes are connected; + # 3) How parental ophinted outputs map to the last child ophinted outputs. + CHILDREN_INPUTS_MAPPINGS = "_tflite_children_ophint_inputs_mapping" + + # Types of aggregations + # stack: stacks all ophints with matching tags. i.e. for a static rnn. + # specifically, this is good for an input or output to a static rnn cell. + AGGREGATE_STACK = "stack" + # first: only takes the first output (one with lowest sort index) + # of matching tags. This is good for the input state to an RNN. + AGGREGATE_FIRST = "first" + # aggregation last takes only the last tag (one with highest sort index). + # This is good for an output value on the last stack item of a + # static rnn. + AGGREGATE_LAST = "last" + + class OpHintArgumentTracker: + """Conceptually tracks indices of arguments of "OpHint functions". + + The inputs and arguments of these functions both use an instance + of the class so they can have independent numbering. + """ + + def __init__(self, + function_name, + unique_function_id, + node_name_prefix, + attr_name, + level=1, + children_inputs_mappings=None): + """Initialize ophint argument. + + Args: + function_name: Name of the function that this tracks arguments for. + unique_function_id: UUID of function that this tracks arguments for. + node_name_prefix: How identities that are created are named. + attr_name: Name of attribute to use to store the index for this hint. + i.e. FUNCTION_INPUT_INDEX or FUNCTION_OUTPUT_INDEX + level: Hierarchical level of the Ophint node, a number. + children_inputs_mappings: Inputs/Outputs mapping for children hints. + """ + + # The global index is the argument index of the op. This is in contrast + # to the sort index which is the sequence number of a particular instance + # of a given global index. For example, you may have called add hint + # twice with the tag "foo". Then the global index will be 0 for both + # and the sort index will be 0 for the first added and 1 for the second. + self._function_name = function_name + self._unique_function_id = unique_function_id + self._next_global_index = 0 # The absolute global index + self._used_global_indices = set() + self._tag_to_global_index = {} # The argument index a given tag maps to + self._tag_to_next_sort_index = {} # The current index for each tag + self._node_name_prefix = node_name_prefix + self._attr_name = attr_name + self._level = level + self._children_inputs_mappings = children_inputs_mappings + + def _get_new_global_index(self, index_override): + """Return the next unused argument index in order or use an override. + + Args: + index_override: An index to use instead of the next available or None + to use the next available. + + Returns: + A valid global_index to use for the next hint argument. + + Raises: + ValueError: If the index_override is already used by another hint. + """ + if index_override is None: + global_index = self._next_global_index + else: + if index_override in self._used_global_indices: + raise ValueError("Index %d was already used by another call to add") + global_index = index_override + # Make next_global_index valid + self._used_global_indices.add(global_index) + while self._next_global_index in self._used_global_indices: + self._next_global_index += 1 + return global_index + + def add(self, arg, tag=None, name=None, aggregate=None, + index_override=None): + """Return a wrapped tensor of an input tensor as an argument. + + Args: + arg: A TensorFlow tensor that should be considered an argument. + tag: String tag to identify arguments that should be packed. + name: Name of argument. This is included in the Identity hint op names. + aggregate: Strategy to aggregate. + Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST, + and OpHint.AGGREGATE_STACK. + Note, aggregate is only valid if tag is specified. + index_override: Specify what input/output index should this be in the + final stub. i.e. add(arg0, index=1); add(arg1, index=0) will make the + final stub be as stub_func(inputs[arg1, arg0], outputs=[]) rather than + the default call order based ordering. + + Returns: + A tensor representing the wrapped argument. + + Raises: + ValueError: When indices are not consistent. + """ + + # Find the appropriate index + if tag is None: + if aggregate is not None: + raise ValueError("You must specify `tag` if using aggregate.") + global_index = self._get_new_global_index(index_override) + sort_index = None + else: + if aggregate is None: + raise ValueError("You must specify `aggregate` if using tag.") + if tag not in self._tag_to_global_index: + self._tag_to_global_index[tag] = ( + self._get_new_global_index(index_override)) + self._tag_to_next_sort_index[tag] = 0 + elif (index_override and + index_override != self._tag_to_global_index[tag]): + raise ValueError( + "Tag %r was called with two indices %r and %r" % + (tag, index_override, self._tag_to_global_index[tag])) + global_index = self._tag_to_global_index[tag] + sort_index = self._tag_to_next_sort_index[tag] + self._tag_to_next_sort_index[tag] += 1 + + uuid = self._unique_function_id + name = "%s-%s-%s-%r-%r-%s" % (self._node_name_prefix, self._function_name, + uuid, global_index, sort_index, name) + + identity_op = _array_ops.identity(arg, name=name) + + # pylint: disable=protected-access + identity_op.op._set_attr( + OpHint.FUNCTION_NAME_ATTR, + _attr_value_pb2.AttrValue( + s=_compat.as_bytes(self._function_name))) + identity_op.op._set_attr( + OpHint.FUNCTION_UUID_ATTR, + _attr_value_pb2.AttrValue( + s=_compat.as_bytes(self._unique_function_id))) + identity_op.op._set_attr( + self._attr_name, _attr_value_pb2.AttrValue(i=global_index)) + identity_op.op._set_attr(OpHint.FUNCTION_LEVEL_ATTR, + _attr_value_pb2.AttrValue(i=self._level)) + if self._children_inputs_mappings: + identity_op.op._set_attr( + OpHint.CHILDREN_INPUTS_MAPPINGS, + _attr_value_pb2.AttrValue( + s=_compat.as_bytes(_json.dumps( + self._children_inputs_mappings)))) + + if sort_index is not None: + identity_op.op._set_attr( + OpHint.FUNCTION_SORT_INDEX_ATTR, + _attr_value_pb2.AttrValue(i=sort_index)) + if aggregate is not None: + identity_op.op._set_attr( + OpHint.FUNCTION_AGGREGATE_ATTR, + _attr_value_pb2.AttrValue(s=_compat.as_bytes((aggregate)))) + # pylint: enable=protected-access + return identity_op + + def __init__(self, + function_name, + level=1, + children_inputs_mappings=None, + **kwargs): + """Create a OpHint. + + Args: + function_name: Name of the function (the custom op name in tflite) + level: OpHint level. + children_inputs_mappings: Children OpHint inputs/outputs mapping. + children_inputs_mappings should like below: + "parent_first_child_input": + [{"parent_input_index": num, "child_input_index": num}, ...] + "parent_last_child_output": + [{"parent_output_index": num, "child_output_index": num}, ...] + "internal_children_input_output": + [{"child_input_index": num, "child_output_index": num}, ...] + **kwargs: Keyword arguments of any constant attributes for the function. + """ + self._function_name = function_name + self._level = level + if self._level == 1: + assert children_inputs_mappings is None + else: + assert isinstance(children_inputs_mappings, dict) + self._children_inputs_mappings = children_inputs_mappings + if self._children_inputs_mappings is not None: + self._validate_children_inputs_mappings(self._children_inputs_mappings) + self._unique_function_id = _uuid.uuid1().hex + self._attrs_to_store_later = kwargs + self._stored_attrs = False + self._inputs = OpHint.OpHintArgumentTracker( + self._function_name, self._unique_function_id, "InputHint", + OpHint.FUNCTION_INPUT_INDEX_ATTR, level, self._children_inputs_mappings) + self._outputs = OpHint.OpHintArgumentTracker( + self._function_name, self._unique_function_id, "OutputHint", + OpHint.FUNCTION_OUTPUT_INDEX_ATTR, level, + self._children_inputs_mappings) + + def _validate_children_inputs_mappings(self, children_inputs_mappings): + """Validate children inputs mappings is in the right format. + + Args: + children_inputs_mappings: the Children ophint inputs/outputs mapping. + """ + assert isinstance(children_inputs_mappings, dict) + assert "parent_first_child_input" in children_inputs_mappings + assert "parent_last_child_output" in children_inputs_mappings + assert "internal_children_input_output" in children_inputs_mappings + + # validate parent_first_child_input. + + def assert_dictlist_has_keys(dictlist, keys): + for dikt in dictlist: + assert isinstance(dikt, dict) + for key in keys: + assert key in dikt + + assert_dictlist_has_keys( + children_inputs_mappings["parent_first_child_input"], + ["parent_ophint_input_index", "first_child_ophint_input_index"]) + assert_dictlist_has_keys( + children_inputs_mappings["parent_last_child_output"], + ["parent_output_index", "child_output_index"]) + assert_dictlist_has_keys( + children_inputs_mappings["internal_children_input_output"], + ["child_input_index", "child_output_index"]) + + def _setattr(self, dest_op, name, value): + tensor_value = _ops.convert_to_tensor(value) + # pylint: disable=protected-access + dest_op.op._set_attr(name, _attr_value_pb2.AttrValue( + tensor=tensor_value.op.node_def.attr["value"].tensor)) + # pylint: enable=protected-access + + def add_input(self, *args, **kwargs): + """Add a wrapped input argument to the hint. + + Args: + *args: The input tensor. + **kwargs: + "name" label + "tag" a tag to group multiple arguments that will be aggregated. I.e. + a string like 'cool_input'. Basically multiple inputs can be added + to the same hint for parallel operations that will eventually be + combined. An example would be static_rnn which creates multiple copies + of state or inputs. + "aggregate" aggregation strategy that is valid only for tag non None. + Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST, + and OpHint.AGGREGATE_STACK. + "index_override" The global index to use. This corresponds to the + argument order in the final stub that will be generated. + Returns: + The wrapped input tensor. + """ + return self._inputs.add(*args, **kwargs) + + def add_output(self, *args, **kwargs): + """Add a wrapped output argument to the hint. + + Args: + *args: The output tensor. + **kwargs: + "name" label + "tag" a tag to group multiple arguments that will be aggregated. I.e. + a string like 'cool_input'. Basically multiple inputs can be added + to the same hint for parallel operations that will eventually be + combined. An example would be static_rnn which creates multiple copies + of state or inputs. + "aggregate" aggregation strategy that is valid only for tag non None. + Acceptable values are OpHint.AGGREGATE_FIRST, OpHint.AGGREGATE_LAST, + and OpHint.AGGREGATE_STACK. + "index_override" The global index to use. This corresponds to the + argument order in the final stub that will be generated. + Returns: + The wrapped output tensor. + """ + return self._outputs.add(*args, **kwargs) + + def add_inputs(self, *args, **kwargs): + """Add a sequence of inputs to the function invocation. + + Args: + *args: List of inputs to be converted (should be Tf.Tensor). + **kwargs: This allows 'names' which should be a list of names. + + Returns: + Wrapped inputs (identity standins that have additional metadata). These + are also are also tf.Tensor's. + """ + if "names" in kwargs: + return [ + self._inputs.add(arg, name=name) + for arg, name in zip(args, kwargs["names"]) + ] + else: + return [self._inputs.add(arg) for arg in args] + + def add_outputs(self, *args, **kwargs): + """Add a sequence of outputs to the function invocation. + + Args: + *args: List of outputs to be converted (should be tf.Tensor). + **kwargs: See + + Returns: + Wrapped outputs (identity standins that have additional metadata). These + are also tf.Tensor's. + """ + if "names" in kwargs: + return [ + self._outputs.add(arg, name=name) + for arg, name in zip(args, kwargs["names"]) + ] + else: + return [self._outputs.add(arg) for arg in args] + + +class _LiteOperand: + """Abstract operand for a tflite hint function._dynamic_rnn_loop. + + This is a base class that handles representing arguments to an OpHint. + It also is able to serialize operands to the stubbed graph_def. + Child classes are responsible for being able to + store information about the hint identity operators. They are also responsible + for knowing how to serialize to output graphdefs. + + Typically this will be implemented by holding one or more identity nodes + that were previously discovered as hints. + """ + + def aggregate_and_return_name_for_input(self, out_graphdef): + """This adds the node(s) to out_graphdef and returns the input node name. + + Args: + out_graphdef: A graphdef that is ready to have this input added. + + Returns: + The output that the stub should use as an input for this operand. + + Raises: + RuntimeError: if the method is not implemented. + """ + del out_graphdef + raise RuntimeError("Unimplemented abstract method.") + + def aggregate_and_return_name_for_output(self, fused_op_name, output_index, + out_graphdef): + """Add node(s) to graph representing output operands and returns type. + + Args: + fused_op_name: name of the fused op stub name. + output_index: Output index that we are currently processing from stub. + out_graphdef: The destination graphdef we are currently building up. + + Returns: + The datatype of this identity. + + Raises: + RuntimeError: if the method is not implemented. + """ + del fused_op_name, output_index, out_graphdef + raise RuntimeError("Unimplemented abstract method.") + + +class _LiteSingleOperand(_LiteOperand): + """A simple operand that is non-aggregated (i.e. most hints).""" + + def __init__(self, node): + _LiteOperand.__init__(self) + self.node = node + self.name = _tensor_name_base(node.name) + + def flatten(self): + return [self.name] + + def aggregate_and_return_name_for_input(self, out_graphdef): + return self.name + + def aggregate_and_return_name_for_output(self, fused_op_name, index, + out_graphdef): + output_node = _copy.deepcopy(self.node) + del output_node.input[:] + output_node.input.append(_tensorflow_output_name(fused_op_name, index)) + out_graphdef.node.extend([output_node]) + return self.node.attr["type"].i + + def __str__(self): + return str(self.name) + + +class _LiteAggregateOperand(_LiteOperand): + """An operand for a tflite hint function that is aggregated from many. + + For example, an LSTM is a grid of operators that are all related. Inputs + going into them may need to be fused, so they should all be tracked as + related arguments. + """ + + def __init__(self, aggregation): + _LiteOperand.__init__(self) + self.aggregation = aggregation + self.names = {} + self.nodes = {} + self.flattened = None + + def add(self, sort, node): + self.names[sort] = _tensor_name_base(node.name) + self.nodes[sort] = node + + def flatten_nodes(self): + """Return a list of all the node protos in aggregation sorted order.""" + if not self.flattened: + self.flattened = [None] * len(self.nodes) + for idx, node in self.nodes.items(): + self.flattened[idx] = node + for n in self.nodes: + if n is None: + raise RuntimeError("Aggregate was missing argument.") + if self.aggregation == OpHint.AGGREGATE_FIRST: + self.flattened = self.flattened[:1] + elif self.aggregation == OpHint.AGGREGATE_LAST: + self.flattened = self.flattened[-1:] + elif self.aggregation == OpHint.AGGREGATE_STACK: + pass + else: + raise ValueError("Invalid aggregation type %r specified" % + self.aggregation) + return self.flattened + + def flatten(self): + """Return a list of all node names in aggregation sorted sorter.""" + return [_tensor_name_base(x.name) for x in self.flatten_nodes()] + + def aggregate_and_return_name_for_input(self, out_graphdef): + """This adds the nodes to out_graphdef and returns an aggregated output. + + In particular, if you have 4 inputs to a hint stub, this will be the + node that you can use as an output. I.e. you have 4 timesteps from a + static rnn, then a fused UnidirectionalLSTM will expect 1 input with + all 4 time steps. So here we make a pack and return the output name of + that pack. + + Args: + out_graphdef: A graphdef that is ready to have this input added. + + Returns: + The name of a pack that aggregates this node. + """ + flattened = self.flatten_nodes() + if (self.aggregation == OpHint.AGGREGATE_FIRST) or ( + self.aggregation == OpHint.AGGREGATE_LAST): + assert len(flattened) == 1 + if len(flattened) == 1 and self.aggregation != OpHint.AGGREGATE_STACK: + return _tensor_name_base(flattened[0].name) + else: + new_node = _node_def_pb2.NodeDef() + new_node.op = "Pack" + new_node.name = "OpHintStack-%s" % flattened[0].name + new_node.attr["N"].i = len(flattened) + new_node.attr["T"].type = flattened[0].attr["T"].type + for discrete in flattened: + new_node.input.append(_tensor_name_base(discrete.name)) + out_graphdef.node.extend([new_node]) + return new_node.name + + def aggregate_and_return_name_for_output(self, fused_op_name, output_index, + out_graphdef): + """This adds to `out_graphdef` all the unaggregated outputs. + + I.e. we are outputting from a fused stub, but we need to make it compatible + with the unfused original graph so we insert an unpack. Ideally in a later + stage the unpack -> pack sequences will be removed. + + Args: + fused_op_name: The name of the stub we are in the process of fusing. + output_index: The output output_index this object represents. + out_graphdef: The graphdef we are in the process of buildings + + Returns: + The type of the aggregated output (so we can finish building the stub + op). + """ + flattened = self.flatten_nodes() + if (self.aggregation == OpHint.AGGREGATE_FIRST) or ( + self.aggregation == OpHint.AGGREGATE_LAST): + assert len(flattened) == 1 + if len(flattened) == 1 and self.aggregation != OpHint.AGGREGATE_STACK: + temp_op = _LiteSingleOperand(flattened[0]) + return temp_op.aggregate_and_return_name_for_output( + fused_op_name, output_index, out_graphdef) + else: + stack_node = _node_def_pb2.NodeDef() + stack_node.op = "Unpack" + stack_node.name = "OpHintUnstack-%s" % flattened[0].name + stack_node.attr["num"].i = len(flattened) + output_type = flattened[0].attr["T"].type + stack_node.attr["T"].type = output_type + stack_node.input.append( + _tensorflow_output_name(fused_op_name, output_index)) + out_graphdef.node.extend([stack_node]) + + for idx, discrete in enumerate(flattened): + output_node = _copy.deepcopy(discrete) + del output_node.input[:] + output_node.input.append(_tensorflow_output_name(stack_node.name, idx)) + out_graphdef.node.extend([output_node]) + + return output_type + + def __str__(self): + s = "\t\t\tAGGREGATE %s\n" % self.aggregation + for sort, val in self.names.iteritems(): + s += "\t\t\t%d: %s\n" % (sort, val) + return s + + +class _LiteFuncCall: + """Represent a TensorFlow Lite custom function. + + This is uses to accumulate found hints in the graphdef into a single + conceptual unit. + + Attributes: + inputs: inputs to the op (hash from index # to argument) + outputs: outputs to the op (hash from index # to argument) + function_name: the tflite custom op name to use + uuid: a unique call id for this particular call (i.e. multiple function + calls would have the same function_name but different uuids. + params: A param name to key value for op constant data. I.e. for axis on a + reduction, strides on a convolution, etc. + level: Level of the OpHint. + children_inputs_mappings: If the Ophint has children, children inputs + mappings indicate how their inputs & outputs are mapped. + """ + + def __init__(self): + self.inputs = {} + self.outputs = {} + self.function_name = None + self.uuid = None + self.params = {} + self.level = -1 + self.children_inputs_mappings = {} + + def flattened_inputs_and_outputs(self): + """Return a list of inputs and outputs in a flattened format. + + Returns: + Tuple of (inputs, outputs). where input and output i a list of names. + """ + + def _flatten(input_or_output_dict): + flattened_items = [] + for item in input_or_output_dict.values(): + flattened_items.extend(item.flatten()) + return flattened_items + + return _flatten(self.inputs), _flatten(self.outputs) + + def __str__(self): + + def format_args(items): + s = "" + for idx, item in items.iteritems(): + s += ("\t\t%d:\n" % idx) + str(item) + return s + + inputs_str = "\tInputs\n" + format_args(self.inputs) + outputs_str = "\tOutputs\n" + format_args(self.outputs) + + return ( + "tflite function %s call %s level %d " + "\n\tinputs:\n\t\t%s\n\toutputs:\n\t\t%s" % + (self.function_name, self.uuid, self.level, inputs_str, outputs_str)) + + +def _find_all_hints_in_nodes(nodes): + """Look at the all the input nodes and return a list of LiteFuncCall objs. + + Args: + nodes: A TensorFlow graph_def to look for LiteFuncCalls. + + Returns: + a list of `LifeFuncCall` objects in the form + + """ + func_calls = _collections.defaultdict(_LiteFuncCall) + + for node in nodes: + attr = node.attr + # This is an op hint if it has a FUNCTION_UUID_ATTR, otherwise skip + if (OpHint.FUNCTION_UUID_ATTR not in attr or + not attr[OpHint.FUNCTION_UUID_ATTR].s): + continue + uuid = attr[OpHint.FUNCTION_UUID_ATTR].s + + # Start building function + call_def = func_calls[uuid] + call_def.uuid = uuid + call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s + call_def.level = attr[OpHint.FUNCTION_LEVEL_ATTR].i + # Get sorting and aggregation information + + sort = ( + attr[OpHint.FUNCTION_SORT_INDEX_ATTR].i + if OpHint.FUNCTION_SORT_INDEX_ATTR in attr else None) + if sort == -1: + sort = None + aggregation = None + if OpHint.FUNCTION_AGGREGATE_ATTR in attr: + aggregation = _compat.as_text(attr[OpHint.FUNCTION_AGGREGATE_ATTR].s) + + if OpHint.CHILDREN_INPUTS_MAPPINGS in attr: + call_def.children_inputs_mappings = _json.loads( + _compat.as_text(attr[OpHint.CHILDREN_INPUTS_MAPPINGS].s)) + + # Add the input or output + def put_operand(stuff, index, sort, operand, aggregation): + """Add a given index into the function structure.""" + if sort is None: + stuff[index] = _LiteSingleOperand(operand) + else: + if index not in stuff: + stuff[index] = _LiteAggregateOperand(aggregation) + stuff[index].add(sort, operand) + + if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr: + put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i, + sort, node, aggregation) + if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr: + put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i, + sort, node, aggregation) + + # Remember attributes + for a in attr: + if a.startswith("_tflite_attr_"): + call_def.params[a.replace("_tflite_attr_,", "")] = attr[a].tensor + + return func_calls + + +def _extract_topology_sequence_mapping(nodes): + return dict( + (_tensor_name_base(node.name), idx) for idx, node in enumerate(nodes)) + + +def _find_children_hints_in_while_loop(function_def, nodes_mapping): + """Find children hints and all nodes inside the while loop. + + Args: + function_def: Function def of the while loop. + nodes_mapping: While loop input_arg : real node name. + + Returns: + Ordered children hints and all re-mapped nodes inside the while loop. + """ + new_nodes = [] + + # Make nodes inside function def inputs point to the real nodes. + for node in function_def.node_def: + for i, _ in enumerate(node.input): + if node.input[i] in nodes_mapping: + node.input[i] = nodes_mapping[node.input[i]] + new_nodes.append(_copy.deepcopy(node)) + name_to_seq_num = _extract_topology_sequence_mapping(function_def.node_def) + children_hints = _find_all_hints_in_nodes(new_nodes) + children_hints_q = [] + # Ordered by the outputs. + for hint in children_hints.values(): + _, output_names = hint.flattened_inputs_and_outputs() + seq = name_to_seq_num[output_names[0]] + for output_name in output_names: + seq = min(seq, name_to_seq_num[output_name]) + children_hints_q.append((seq, hint)) + children_hints_q.sort(key=lambda tup: tup[0]) + ordered_children_hints = [x[1] for x in children_hints_q] + return ordered_children_hints, new_nodes + + +def _find_children_hints(call, graph_def): + """Find all children hints. + + For a given OpHint, we find all children hints inside it, we also copy all the + nodes inside function defs (if applicable) to the original graph_def, they are + returned in a list as well. + + Args: + call: Parent OpHint that contains children ophints. + graph_def: Original graph def. + + Returns: + Ordered children hints inside the parent ophint; new graph def that contains + nodes inside function defs (if applicable); nodes inside function defs. + """ + name_to_input_name, _, _ = _extract_graph_summary(graph_def) + input_names, output_names = call.flattened_inputs_and_outputs() + + reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name) + reachable_by_output = _bfs_for_reachable_nodes(output_names, + name_to_input_name) + output_nodes_set = set(output_names) + children_hints = [] + out = _graph_pb2.GraphDef() + out.library.CopyFrom(graph_def.library) + out.versions.CopyFrom(graph_def.versions) + function_def_nodes = set() + for node in graph_def.node: + out.node.extend([_copy.deepcopy(node)]) + n = _tensor_name_base(node.name) + if n in reachable_by_output: + if n not in reachable_by_input and n not in output_nodes_set: + # special handle for while loop function def. + if node.op == "While" or node.op == "StatelessWhile": + body_name = node.attr["body"].func.name + inputs_outside_loop = node.input + for function_def in graph_def.library.function: + if function_def.signature.name == body_name: + function_inputs = function_def.signature.input_arg + assert len(inputs_outside_loop) == len(function_inputs) + nodes_mapping = {} + for i, function_input in enumerate(function_inputs): + nodes_mapping[function_input.name] = inputs_outside_loop[i] + (children_hints_in_loop, + new_nodes) = _find_children_hints_in_while_loop( + function_def, nodes_mapping) + function_def_nodes.update([x.name for x in new_nodes]) + children_hints.extend(children_hints_in_loop) + out.node.extend(new_nodes) + + return children_hints, out, function_def_nodes + + +def _tensor_name_base(full_tensor_name): + """Removes the device assignment code from a tensor. + + e.g. _tensor_name_base("foo:3") => "foo" + + Args: + full_tensor_name: A tensor name that is annotated with a device placement + (this is what tensor flow introspection gives). + + Returns: + A name without any device assignment. + """ + if full_tensor_name.startswith("^"): + return full_tensor_name[1:] + return full_tensor_name.split(":")[0] + + +def _tensorflow_output_name(tensor_name, output_index): + return tensor_name if output_index == 0 else "%s:%d" % (tensor_name, + output_index) + + +def _check_subgraph_closed(n, reachable_by_input, input_nodes_set, + name_to_input_name): + """Checks to make sure node only connects to predecessor graph through inputs. + + Args: + n: Node to check + reachable_by_input: Nodes that are reachable by all inputs of subgraph + input_nodes_set: The set of nodes that are "inputs". + name_to_input_name: Maps from name to the list of inputs. + + Raises: + TypeError: If the given node uses items past inputs directly. + """ + next_to_visit = [n] + visited = set() + while next_to_visit: + current_node = next_to_visit.pop() + visited.add(current_node) + if (current_node in reachable_by_input and + current_node not in input_nodes_set): + raise TypeError("Node %s uses input %s not in input_nodes." % + (n, current_node)) + if current_node not in input_nodes_set: + next_to_visit += [ + input_node for input_node in name_to_input_name[current_node] + if input_node not in visited + ] + + +def _convert_single_op_hint_to_stub(call, + graph_def, + function_def_nodes=None, + is_last_run=True): + """Given a graph_def, converts `call` into a stub and returns a new graph_def. + + Args: + call: A single function call to be converted. + graph_def: A graph_def to use as input (that has call obviously). + function_def_nodes: Nodes inside the function def those are not connected to + the graph. + is_last_run: Whether it is the last run for a given pass (for OpHint has + children). + + Returns: + A new transformed graph-def that has call as a stub (single op). + + Note: after this process, the graph_def can no longer be loaded into + the tensorflow runtime, so all future manipulations are done in graph_def + level. + """ + if function_def_nodes is None: + function_def_nodes = set() + name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary( + graph_def) + input_names, output_names = call.flattened_inputs_and_outputs() + + reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name) + reachable_by_output = _bfs_for_reachable_nodes(output_names, + name_to_input_name) + output_nodes_set = set(output_names) + nodes_after_fuse = [] + nodes_deleted_by_fuse = set() + # Classify each node. We want to keep everything reachable by input, but + # we don't know if things that are not reachable by output or input (things + # after fusing). + for node in graph_def.node: + n = _tensor_name_base(node.name) + if n in reachable_by_output: + if n not in reachable_by_input and n not in output_nodes_set: + nodes_deleted_by_fuse.add(n) + elif n not in reachable_by_input and n not in function_def_nodes: + # n is a node that after all the fusings, so keep it. + nodes_after_fuse.append(n) + else: + # In the last run, n is a node that is randomly in the graph but not + # connected to the chain of dependencies, we will delete n, otherwise + # we keep them. + if not is_last_run: + nodes_after_fuse.append(n) + + # Make a new graphdef with all the pre-input and input nodes + out = _graph_pb2.GraphDef() + reachable_by_input_sorted = sorted( + list(reachable_by_input), key=lambda n: name_to_seq_num[n]) + for node in reachable_by_input_sorted: + out.node.extend([_copy.deepcopy(name_to_node[node])]) + + # Create any stacks to aggregate arguments into to a single input + # i.e. for static_rnn's. + sorted_input_indices = list(call.inputs.keys()) + sorted_input_indices.sort() + sorted_output_indices = list(call.outputs.keys()) + sorted_output_indices.sort() + new_node = _node_def_pb2.NodeDef() + # Delegate to each operand to produce the proper new input for this stub node. + # In particular, an aggregate input will now be a Pack of some previously + # non-fused things. + + optional_input_node = _node_def_pb2.NodeDef() + optional_input_node.name = "Const" + str(_uuid.uuid1().hex) + optional_input_node.op = "Const" + optional_input_node.attr["dtype"].CopyFrom( + _attr_value_pb2.AttrValue(type=_dtypes.float32.as_datatype_enum)) + optional_input_node.attr["value"].CopyFrom( + _attr_value_pb2.AttrValue( + tensor=_tensor_util.make_tensor_proto([-1], _dtypes.float32, [1]))) + out.node.extend([optional_input_node]) + + max_index = max(sorted_input_indices) + 1 + for cur_index in range(max_index): + if cur_index in sorted_input_indices: + inputs = call.inputs[cur_index] + input_name = inputs.aggregate_and_return_name_for_input(out) + new_node.input.append(input_name) + else: + new_node.input.append(optional_input_node.name) + + new_node.attr[OpHint.TFLITE_INPUT_INDICES].list.i.extend(sorted_input_indices) + + # Create the function + new_node.op = call.function_name + new_node.name = call.uuid + out.node.extend([new_node]) + + # Now call each output argument to give them a chance to make the proper + # output type and add it to our new_node. + output_dtypes = [] + max_output_index = max(sorted_output_indices) + 1 + for cur_index in range(max_output_index): + if cur_index in sorted_output_indices: + output = call.outputs[cur_index] + output_dtype = ( + output.aggregate_and_return_name_for_output(new_node.name, cur_index, + out)) + else: + output_dtype = optional_input_node.attr["type"].i + output_dtypes.append(output_dtype) + new_node.attr["_output_types"].list.type[:] = output_dtypes + new_node.attr["_output_quantized"].b = False + + # Add post output nodes that do not depend on the outputs + for n in nodes_after_fuse: + should_keep = True + for input_name in name_to_input_name[n]: + if input_name in nodes_deleted_by_fuse: + should_keep = False + if should_keep: + out.node.extend([_copy.deepcopy(name_to_node[n])]) + + # Misc. graph_def data that needs copying. + out.library.CopyFrom(graph_def.library) + out.versions.CopyFrom(graph_def.versions) + + return out + + +def _remove_one_redundant_stack_unstack(in_graph_def): + """Removes a stack->unstack pattern from in_graph_def in a returned graph. + + Args: + in_graph_def: Graph def to use as input. + + Returns: + Simplified tuple (graph_def, changed_something) where changed_something + is true if anything was done. + """ + name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary( + in_graph_def) + del name_to_seq_num + + do_generic_pack_unpack = True + + out = _graph_pb2.GraphDef() + out.library.CopyFrom(in_graph_def.library) + out.versions.CopyFrom(in_graph_def.versions) + for n in in_graph_def.node: + node_name = _tensor_name_base(n.name) + if not node_name.startswith("OpHintStack") and not n.op.startswith("Pack"): + continue + next_to_visit = [node_name] + visited = set() + + unpack_nodes = set() + pack_node = node_name + + # Find a pattern of unstack connected to a stack (with identities + # in between. + matches_pattern = True + is_hint_created_stack = False + while next_to_visit: + current_node_name = next_to_visit[0] + visited.add(current_node_name) + del next_to_visit[0] + node = name_to_node[current_node_name] + is_op_hint_stack = node.name.startswith("OpHintStack") + is_op_hint_unstack = node.name.startswith("OpHintUnstack") + if (node.op == "Identity" or is_op_hint_stack or + (do_generic_pack_unpack and node.op == "Pack")): + is_hint_created_stack |= is_op_hint_stack + next_to_visit += [ + input_node for input_node in name_to_input_name[current_node_name] + if input_node not in visited + ] + elif (is_op_hint_unstack or + (do_generic_pack_unpack and node.op == "Unpack")): + unpack_nodes.add(node.name) + is_hint_created_stack &= is_op_hint_unstack + else: + matches_pattern = False + break + visited.add(node.name) + + if matches_pattern and len(unpack_nodes) == 1: + pack_node = node_name + + # Check to see if anyone depends on the intermediate identity or the + # Unstacked form + no_external_dependency = True + for other_n in in_graph_def.node: + if other_n.name in visited: + continue + for input_tensor in name_to_input_name[other_n.name]: + input_op = _tensor_name_base(input_tensor) + if input_op in visited and input_op != pack_node: + no_external_dependency = False + # Proceed with the substitution if the stack/unstack pair was created + # through hints, or that it was not, but nobody is consuming things + # between the stack and unstack. + if is_hint_created_stack or no_external_dependency: + end = unpack_nodes.pop() + end_input = name_to_node[end].input[0] + # All nodes that depend on the final stack need to be redone to use + for other_n in in_graph_def.node: + node_name = _tensor_name_base(other_n.name) + if node_name not in visited: + new_node = _copy.deepcopy(other_n) + new_node.input[:] = [ + (end_input if stripped == pack_node else non_stripped) + for stripped, non_stripped in zip(name_to_input_name[node_name], + new_node.input[:]) + ] + out.node.extend([new_node]) + return out, True + return in_graph_def, False + + +def _remove_redundant_stack_unstack(graph_def): + curr = graph_def + del graph_def + changed_stuff = True + while changed_stuff: + curr, changed_stuff = _remove_one_redundant_stack_unstack(curr) + return curr + + +def _get_correct_mapping(original_index, nodes): + # Special handle for the index is -1 case. + # If it is -1, return the last index. + if original_index == -1: + node_indices = nodes.keys() + node_indices = sorted(node_indices) + return node_indices[-1] + return original_index + + +def _convert_op_hints_to_stubs_helper( + graph_def, write_callback=lambda sess, graph_def: None): + """Converts a graph_def to a new graph_def where all op hints are stubbed. + + Args: + graph_def: A graph def that we should convert. + write_callback: A function pointer that can be used to write intermediate + steps of graph transformation (optional). + + Returns: + A new stubbed graph_def. + """ + hints = _find_all_hints_in_nodes(graph_def.node) + + hints_q = [] + for hint in hints.values(): + hints_q.append((hint.level, hint.uuid)) + + hints_q.sort(key=lambda tup: tup[0]) + for i in range(len(hints_q) - 1, -1, -1): + level, hint_uuid = hints_q[i] + + curr_graph_def = graph_def + del graph_def # prevent using graph_def again (common source of error) + for i in range(len(hints_q) - 1, -1, -1): + level, hint_uuid = hints_q[i] + if level >= 2: + children_hints, curr_graph_def, function_def_nodes = _find_children_hints( + hints[hint_uuid], curr_graph_def) + # pylint: disable=superfluous-parens + assert (len(children_hints) > 0) # pylint: disable=g-explicit-length-test + # pylint: enable=superfluous-parens + + # Re-wire the children hints inputs/outputs, so latter child's inputs + # connect to previous child node's outputs. + children_inputs_mappings = hints[hint_uuid].children_inputs_mappings + for j, child_hint in enumerate(children_hints): + if j == 0: + for mapping in children_inputs_mappings["parent_first_child_input"]: + parent_input_index = _get_correct_mapping( + mapping["parent_ophint_input_index"], hints[hint_uuid].inputs) + child_input_index = _get_correct_mapping( + mapping["first_child_ophint_input_index"], child_hint.inputs) + child_hint.inputs[child_input_index] = hints[hint_uuid].inputs[ + parent_input_index] + else: + for mapping in children_inputs_mappings[ + "internal_children_input_output"]: + input_index = _get_correct_mapping(mapping["child_input_index"], + child_hint.inputs) + output_index = _get_correct_mapping(mapping["child_output_index"], + children_hints[j - 1].outputs) + child_hint.inputs[input_index] = children_hints[ + j - 1].outputs[output_index] + if j == len(children_hints) - 1: + for mapping in children_inputs_mappings["parent_last_child_output"]: + parent_output_index = _get_correct_mapping( + mapping["parent_output_index"], hints[hint_uuid].outputs) + child_output_index = _get_correct_mapping( + mapping["child_output_index"], child_hint.outputs) + child_hint.outputs[child_output_index] = hints[hint_uuid].outputs[ + parent_output_index] + + for j, child_hint in enumerate(children_hints): + curr_graph_def = _convert_single_op_hint_to_stub( + child_hint, curr_graph_def, function_def_nodes, + j == len(children_hints) - 1) + else: + curr_graph_def = _convert_single_op_hint_to_stub(hints[hint_uuid], + curr_graph_def) + write_callback(curr_graph_def, "initial") + # The stubbing process can create stacks/unstacks in the case of LSTMs + # remove them. + curr_graph_def = _remove_redundant_stack_unstack(curr_graph_def) + return curr_graph_def + + +def find_all_hinted_output_nodes(session=None, graph_def=None): + """Find all Ophints output nodes in the graph. + + This is used to get all the output nodes those are ophinted, it is important + for operation like convert_variables_to_constants keep all ophints structure. + Note: only one of session or graph_def should be used, not both. + Why this can be useful? Some TensorFlow ops (e.g. bidirectional rnn), can + generate multiple outputs for unfused subgraph. If not all output nodes are + consumed, graph optimization can potentially drop the unused nodes and cause + ophints in an invalid states (due to missing ophinted output nodes). So it's + important for us to find all those hinted output nodes and make sure they're + not discarded away. + + Args: + session: A TensorFlow session that contains the graph to convert. + graph_def: A graph def that we should convert. + + Returns: + A list of OpHints output nodes. + Raises: + ValueError: If both session and graph_def are provided. + """ + if session is not None and graph_def is not None: + raise ValueError("Provide only one of session and graph_def.") + hinted_outputs_nodes = [] + if session is not None: + hints = _find_all_hints_in_nodes(session.graph_def.node) + elif graph_def is not None: + hints = _find_all_hints_in_nodes(graph_def.node) + for hint in hints.values(): + _, output_nodes = hint.flattened_inputs_and_outputs() + hinted_outputs_nodes.extend(output_nodes) + return hinted_outputs_nodes + + +def is_ophint_converted(graph_def): + if graph_def is None: + raise ValueError("Must provide the graph_def.") + ophint_converted = False + for node in graph_def.node: + attr = node.attr + if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr: + ophint_converted = True + break + return ophint_converted + + +@_tf_export(v1=["lite.experimental.convert_op_hints_to_stubs"]) +@_deprecation.deprecated( + None, + "Please follow instructions under " + "https://www.tensorflow.org/lite/convert/operation_fusion for operation" + "fusion in tflite." +) +def convert_op_hints_to_stubs(session=None, + graph_def=None, + write_callback=lambda graph_def, comments: None): + """Converts a graphdef with LiteOp hints into stub operations. + + This is used to prepare for toco conversion of complex intrinsic usages. + Note: only one of session or graph_def should be used, not both. + + Args: + session: A TensorFlow session that contains the graph to convert. + graph_def: A graph def that we should convert. + write_callback: A function pointer that can be used to write intermediate + steps of graph transformation (optional). + + Returns: + A new graphdef with all ops contained in OpHints being replaced by + a single op call with the right parameters. + Raises: + ValueError: If both session and graph_def are provided. + """ + + if session is not None and graph_def is not None: + raise ValueError("Provide only one of session and graph_def.") + + if session is not None: + return _convert_op_hints_to_stubs_helper(session.graph_def, write_callback) + elif graph_def is not None: + return _convert_op_hints_to_stubs_helper(graph_def, write_callback) + else: + raise ValueError("Must specify session or graph_def as input.") + + +_allowed_symbols = [ + "OpHint", + "convert_op_hints_to_stubs", + "convert_op_hints_to_stubs_new", + "find_all_hinted_output_nodes", + "is_ophint_converted", +] +remove_undocumented(__name__, _allowed_symbols) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b020337da48ed95f2eea3c956e82abbf30f51087 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/_pywrap_tensorflow_lite_calibration_wrapper.pyi @@ -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. +# ============================================================================== + +from typing import Callable + +from typing import overload + +class CalibrationWrapper: + def __init__(self, arg0: object, arg1: list[str], arg2: list[Callable[[int],None]]) -> None: ... + def Calibrate(self) -> object: ... + @overload + def FeedTensor(self, arg0: object, arg1: str) -> object: ... + @overload + def FeedTensor(self, arg0: object) -> object: ... + @overload + def Prepare(self, arg0: object, arg1: str) -> object: ... + @overload + def Prepare(self, arg0: object) -> object: ... + @overload + def Prepare(self, arg0: str) -> object: ... + @overload + def Prepare(self) -> object: ... + @overload + def QuantizeModel(self, arg0: int, arg1: int, arg2: bool, arg3: int, arg4: int, arg5: bool) -> object: ... + @overload + def QuantizeModel(self, arg0: int, arg1: int, arg2: bool, arg3: str) -> object: ... + +def AddIntermediateTensors(arg0: object) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/calibrator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/calibrator.py new file mode 100644 index 0000000000000000000000000000000000000000..136890589a09fcb6c9a38d7cce232df7df864700 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/optimize/calibrator.py @@ -0,0 +1,255 @@ +# 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. +# ============================================================================== +"""Python wrapper for post training quantization with calibration.""" +import numpy as np + +from tensorflow.lite.python.convert_phase import Component +from tensorflow.lite.python.convert_phase import convert_phase +from tensorflow.lite.python.convert_phase import SubComponent +from tensorflow.lite.python.interpreter import Interpreter +from tensorflow.python.framework import dtypes +from tensorflow.python.util.lazy_loader import LazyLoader + +# Lazy load since some of the performance benchmark skylark rules +# break dependencies. Must use double quotes to match code internal rewrite +# rule. +_calibration_wrapper = LazyLoader( + "_calibration_wrapper", + globals(), + ( + "tensorflow.lite.python.optimize." + "_pywrap_tensorflow_lite_calibration_wrapper" + ), +) + + +def add_intermediate_tensors(model_content): + """Adds intermediate tensors to fused op if needed.""" + return _calibration_wrapper.AddIntermediateTensors(model_content) + + +class Calibrator: + """Calibrates a floating point model and then quantizes it. + + This is an internal class, not a public interface. + """ + + def __init__( + self, + model_content, + custom_op_registerers_by_name=None, + custom_op_registerers_by_func=None, + ): + """Constructor. + + Args: + model_content: Content of a TF-Lite Flatbuffer file. + custom_op_registerers_by_name: List of str (symbol names) that take a + pointer to a MutableOpResolver and register custom ops. + custom_op_registerers_by_func: List of functions that take a pointer to a + MutableOpResolver and register custom ops. + + Raises: + ValueError: If the calibrator was unable to open the model. + """ + if not model_content: + raise ValueError("`model_content` must be specified.") + if custom_op_registerers_by_name is None: + custom_op_registerers_by_name = [] + if custom_op_registerers_by_func is None: + custom_op_registerers_by_func = [] + try: + self._calibrator = _calibration_wrapper.CalibrationWrapper( + model_content, + custom_op_registerers_by_name, + custom_op_registerers_by_func, + ) + self._model_content = model_content + except Exception as e: + raise ValueError("Failed to parse the model: %s." % e) + if not self._calibrator: + raise ValueError("Failed to parse the model.") + self._interpreter = None + + def _create_input_array_from_dict(self, signature_key, inputs): + input_array = [] + signature_runner = self._interpreter.get_signature_runner(signature_key) + input_details = sorted( + signature_runner.get_input_details().items(), + key=lambda item: item[1]["index"], + ) + for input_name, _ in input_details: + input_array.append(inputs[input_name]) + return input_array + + def _feed_tensors(self, dataset_gen, resize_input): + """Feed tensors to the calibrator.""" + initialized = {} + + for sample in dataset_gen(): + if isinstance(sample, tuple): + if not isinstance(sample[1], dict): + raise ValueError( + "You need to provide either a dictionary with input " + "names and values in the second argument in the " + "tuple" + ) + # Convert signature based inputs to the tensor index based data. + if self._interpreter is None: + self._interpreter = Interpreter(model_content=self._model_content) + signature_key = sample[0] + input_array = self._create_input_array_from_dict( + signature_key, sample[1] + ) + elif isinstance(sample, dict): + # Convert signature based inputs to the tensor index based data. + if self._interpreter is None: + self._interpreter = Interpreter(model_content=self._model_content) + signature_key = None + input_array = self._create_input_array_from_dict(None, sample) + elif isinstance(sample, list): + signature_key = None + input_array = sample + else: + raise ValueError( + "You need to provide either a dictionary with input " + "names and values, a tuple with signature key and a " + "dictionary with input names and values, or an array " + "with input values in the order of input tensors of " + "the graph in the representative_dataset function. " + "Unsupported value from dataset: {}.".format(sample) + ) + + if signature_key not in initialized: + initialized[signature_key] = True + if resize_input: + if signature_key is not None: + self._calibrator.Prepare( + [list(s.shape) for s in input_array], signature_key + ) + else: + self._calibrator.Prepare([list(s.shape) for s in input_array]) + else: + if signature_key is not None: + self._calibrator.Prepare(signature_key) + else: + self._calibrator.Prepare() + if signature_key is not None: + self._calibrator.FeedTensor(input_array, signature_key) + else: + self._calibrator.FeedTensor(input_array) + + @convert_phase( + Component.OPTIMIZE_TFLITE_MODEL, + SubComponent.QUANTIZE_USING_DEPRECATED_QUANTIZER, + ) + def calibrate_and_quantize( + self, + dataset_gen, + input_type, + output_type, + allow_float, + activations_type=dtypes.int8, + bias_type=dtypes.int32, + resize_input=True, + disable_per_channel=False, + ): + """Calibrates the model with specified generator and then quantizes it. + + The input shapes of the calibrator are resized with the calibration data if + `resize_input` is set. + + Returns: + A quantized model. + + Args: + dataset_gen: A generator that generates calibration samples. + input_type: A tf.dtype representing the desired real-value input type. + output_type: A tf.dtype representing the desired real-value output type. + allow_float: A boolean. False if the resulting model cannot perform float + computation, useful when targeting an integer-only backend. If False, an + error will be thrown if an operation cannot be quantized, otherwise the + model will fallback to float ops. + activations_type: A tf.dtype representing the desired type for + activations. + bias_type: A tf.dtype representing the desired type for bias. + resize_input: A boolean. True if the shape of the sample data is different + from the input. + disable_per_channel: A boolean. True if disabling per-channel + quantization. + """ + self._feed_tensors(dataset_gen, resize_input) + return self._calibrator.QuantizeModel( + np.dtype(input_type.as_numpy_dtype()).num, + np.dtype(output_type.as_numpy_dtype()).num, + allow_float, + np.dtype(activations_type.as_numpy_dtype()).num, + np.dtype(bias_type.as_numpy_dtype()).num, + disable_per_channel, + ) + + @convert_phase( + Component.OPTIMIZE_TFLITE_MODEL, + SubComponent.QUANTIZE_USING_DEPRECATED_QUANTIZER, + ) + def calibrate_and_quantize_single( + self, + dataset_gen, + input_type, + output_type, + allow_float, + op_output_name, + resize_input=True, + ): + """Calibrates the model with specified generator and then quantizes it. + + Only the single op with output op_output_name will be quantized. + The input shapes of the calibrator are resized with the calibration data. + + Returns: + A quantized model. + + Args: + dataset_gen: A generator that generates calibration samples. + input_type: A tf.dtype representing the desired real-value input type. + output_type: A tf.dtype representing the desired real-value output type. + allow_float: A boolean. False if the resulting model cannot perform float + computation, useful when targeting an integer-only backend. If False, an + error will be thrown if an operation cannot be quantized, otherwise the + model will fallback to float ops. + op_output_name: A string, only this op will be quantized. + resize_input: A boolean. True if the shape of the sample data is different + from the input. + """ + self._feed_tensors(dataset_gen, resize_input) + return self._calibrator.QuantizeModel( + np.dtype(input_type.as_numpy_dtype()).num, + np.dtype(output_type.as_numpy_dtype()).num, + allow_float, + op_output_name, + ) + + @convert_phase(Component.OPTIMIZE_TFLITE_MODEL, SubComponent.CALIBRATE) + def calibrate(self, dataset_gen): + """Calibrates the model with specified generator. + + Returns: + A model with min and max calibration stats. + + Args: + dataset_gen: A generator that generates calibration samples. + """ + self._feed_tensors(dataset_gen, resize_input=True) + return self._calibrator.Calibrate() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_py_generated.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_py_generated.py new file mode 100644 index 0000000000000000000000000000000000000000..994ab39d7ab64391704c36387721c3616837c998 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_py_generated.py @@ -0,0 +1,18163 @@ +import flatbuffers + +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: tflite + +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TensorType(object): + FLOAT32 = 0 + FLOAT16 = 1 + INT32 = 2 + UINT8 = 3 + INT64 = 4 + STRING = 5 + BOOL = 6 + INT16 = 7 + COMPLEX64 = 8 + INT8 = 9 + FLOAT64 = 10 + COMPLEX128 = 11 + UINT64 = 12 + RESOURCE = 13 + VARIANT = 14 + UINT32 = 15 + UINT16 = 16 + INT4 = 17 + + +class QuantizationDetails(object): + NONE = 0 + CustomQuantization = 1 + +def QuantizationDetailsCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == QuantizationDetails().CustomQuantization: + return CustomQuantizationT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class DimensionType(object): + DENSE = 0 + SPARSE_CSR = 1 + + +class SparseIndexVector(object): + NONE = 0 + Int32Vector = 1 + Uint16Vector = 2 + Uint8Vector = 3 + +def SparseIndexVectorCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == SparseIndexVector().Int32Vector: + return Int32VectorT.InitFromBuf(table.Bytes, table.Pos) + if unionType == SparseIndexVector().Uint16Vector: + return Uint16VectorT.InitFromBuf(table.Bytes, table.Pos) + if unionType == SparseIndexVector().Uint8Vector: + return Uint8VectorT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class BuiltinOperator(object): + ADD = 0 + AVERAGE_POOL_2D = 1 + CONCATENATION = 2 + CONV_2D = 3 + DEPTHWISE_CONV_2D = 4 + DEPTH_TO_SPACE = 5 + DEQUANTIZE = 6 + EMBEDDING_LOOKUP = 7 + FLOOR = 8 + FULLY_CONNECTED = 9 + HASHTABLE_LOOKUP = 10 + L2_NORMALIZATION = 11 + L2_POOL_2D = 12 + LOCAL_RESPONSE_NORMALIZATION = 13 + LOGISTIC = 14 + LSH_PROJECTION = 15 + LSTM = 16 + MAX_POOL_2D = 17 + MUL = 18 + RELU = 19 + RELU_N1_TO_1 = 20 + RELU6 = 21 + RESHAPE = 22 + RESIZE_BILINEAR = 23 + RNN = 24 + SOFTMAX = 25 + SPACE_TO_DEPTH = 26 + SVDF = 27 + TANH = 28 + CONCAT_EMBEDDINGS = 29 + SKIP_GRAM = 30 + CALL = 31 + CUSTOM = 32 + EMBEDDING_LOOKUP_SPARSE = 33 + PAD = 34 + UNIDIRECTIONAL_SEQUENCE_RNN = 35 + GATHER = 36 + BATCH_TO_SPACE_ND = 37 + SPACE_TO_BATCH_ND = 38 + TRANSPOSE = 39 + MEAN = 40 + SUB = 41 + DIV = 42 + SQUEEZE = 43 + UNIDIRECTIONAL_SEQUENCE_LSTM = 44 + STRIDED_SLICE = 45 + BIDIRECTIONAL_SEQUENCE_RNN = 46 + EXP = 47 + TOPK_V2 = 48 + SPLIT = 49 + LOG_SOFTMAX = 50 + DELEGATE = 51 + BIDIRECTIONAL_SEQUENCE_LSTM = 52 + CAST = 53 + PRELU = 54 + MAXIMUM = 55 + ARG_MAX = 56 + MINIMUM = 57 + LESS = 58 + NEG = 59 + PADV2 = 60 + GREATER = 61 + GREATER_EQUAL = 62 + LESS_EQUAL = 63 + SELECT = 64 + SLICE = 65 + SIN = 66 + TRANSPOSE_CONV = 67 + SPARSE_TO_DENSE = 68 + TILE = 69 + EXPAND_DIMS = 70 + EQUAL = 71 + NOT_EQUAL = 72 + LOG = 73 + SUM = 74 + SQRT = 75 + RSQRT = 76 + SHAPE = 77 + POW = 78 + ARG_MIN = 79 + FAKE_QUANT = 80 + REDUCE_PROD = 81 + REDUCE_MAX = 82 + PACK = 83 + LOGICAL_OR = 84 + ONE_HOT = 85 + LOGICAL_AND = 86 + LOGICAL_NOT = 87 + UNPACK = 88 + REDUCE_MIN = 89 + FLOOR_DIV = 90 + REDUCE_ANY = 91 + SQUARE = 92 + ZEROS_LIKE = 93 + FILL = 94 + FLOOR_MOD = 95 + RANGE = 96 + RESIZE_NEAREST_NEIGHBOR = 97 + LEAKY_RELU = 98 + SQUARED_DIFFERENCE = 99 + MIRROR_PAD = 100 + ABS = 101 + SPLIT_V = 102 + UNIQUE = 103 + CEIL = 104 + REVERSE_V2 = 105 + ADD_N = 106 + GATHER_ND = 107 + COS = 108 + WHERE = 109 + RANK = 110 + ELU = 111 + REVERSE_SEQUENCE = 112 + MATRIX_DIAG = 113 + QUANTIZE = 114 + MATRIX_SET_DIAG = 115 + ROUND = 116 + HARD_SWISH = 117 + IF = 118 + WHILE = 119 + NON_MAX_SUPPRESSION_V4 = 120 + NON_MAX_SUPPRESSION_V5 = 121 + SCATTER_ND = 122 + SELECT_V2 = 123 + DENSIFY = 124 + SEGMENT_SUM = 125 + BATCH_MATMUL = 126 + PLACEHOLDER_FOR_GREATER_OP_CODES = 127 + CUMSUM = 128 + CALL_ONCE = 129 + BROADCAST_TO = 130 + RFFT2D = 131 + CONV_3D = 132 + IMAG = 133 + REAL = 134 + COMPLEX_ABS = 135 + HASHTABLE = 136 + HASHTABLE_FIND = 137 + HASHTABLE_IMPORT = 138 + HASHTABLE_SIZE = 139 + REDUCE_ALL = 140 + CONV_3D_TRANSPOSE = 141 + VAR_HANDLE = 142 + READ_VARIABLE = 143 + ASSIGN_VARIABLE = 144 + BROADCAST_ARGS = 145 + RANDOM_STANDARD_NORMAL = 146 + BUCKETIZE = 147 + RANDOM_UNIFORM = 148 + MULTINOMIAL = 149 + GELU = 150 + DYNAMIC_UPDATE_SLICE = 151 + RELU_0_TO_1 = 152 + UNSORTED_SEGMENT_PROD = 153 + UNSORTED_SEGMENT_MAX = 154 + UNSORTED_SEGMENT_SUM = 155 + ATAN2 = 156 + UNSORTED_SEGMENT_MIN = 157 + SIGN = 158 + BITCAST = 159 + BITWISE_XOR = 160 + RIGHT_SHIFT = 161 + STABLEHLO_LOGISTIC = 162 + STABLEHLO_ADD = 163 + STABLEHLO_DIVIDE = 164 + STABLEHLO_MULTIPLY = 165 + STABLEHLO_MAXIMUM = 166 + STABLEHLO_RESHAPE = 167 + STABLEHLO_CLAMP = 168 + STABLEHLO_CONCATENATE = 169 + STABLEHLO_BROADCAST_IN_DIM = 170 + STABLEHLO_CONVOLUTION = 171 + STABLEHLO_SLICE = 172 + STABLEHLO_CUSTOM_CALL = 173 + STABLEHLO_REDUCE = 174 + STABLEHLO_ABS = 175 + STABLEHLO_AND = 176 + STABLEHLO_COSINE = 177 + STABLEHLO_EXPONENTIAL = 178 + STABLEHLO_FLOOR = 179 + STABLEHLO_LOG = 180 + STABLEHLO_MINIMUM = 181 + STABLEHLO_NEGATE = 182 + STABLEHLO_OR = 183 + STABLEHLO_POWER = 184 + STABLEHLO_REMAINDER = 185 + STABLEHLO_RSQRT = 186 + STABLEHLO_SELECT = 187 + STABLEHLO_SUBTRACT = 188 + STABLEHLO_TANH = 189 + STABLEHLO_SCATTER = 190 + STABLEHLO_COMPARE = 191 + STABLEHLO_CONVERT = 192 + STABLEHLO_DYNAMIC_SLICE = 193 + STABLEHLO_DYNAMIC_UPDATE_SLICE = 194 + STABLEHLO_PAD = 195 + STABLEHLO_IOTA = 196 + STABLEHLO_DOT_GENERAL = 197 + STABLEHLO_REDUCE_WINDOW = 198 + STABLEHLO_SORT = 199 + STABLEHLO_WHILE = 200 + STABLEHLO_GATHER = 201 + STABLEHLO_TRANSPOSE = 202 + DILATE = 203 + STABLEHLO_RNG_BIT_GENERATOR = 204 + REDUCE_WINDOW = 205 + + +class BuiltinOptions(object): + NONE = 0 + Conv2DOptions = 1 + DepthwiseConv2DOptions = 2 + ConcatEmbeddingsOptions = 3 + LSHProjectionOptions = 4 + Pool2DOptions = 5 + SVDFOptions = 6 + RNNOptions = 7 + FullyConnectedOptions = 8 + SoftmaxOptions = 9 + ConcatenationOptions = 10 + AddOptions = 11 + L2NormOptions = 12 + LocalResponseNormalizationOptions = 13 + LSTMOptions = 14 + ResizeBilinearOptions = 15 + CallOptions = 16 + ReshapeOptions = 17 + SkipGramOptions = 18 + SpaceToDepthOptions = 19 + EmbeddingLookupSparseOptions = 20 + MulOptions = 21 + PadOptions = 22 + GatherOptions = 23 + BatchToSpaceNDOptions = 24 + SpaceToBatchNDOptions = 25 + TransposeOptions = 26 + ReducerOptions = 27 + SubOptions = 28 + DivOptions = 29 + SqueezeOptions = 30 + SequenceRNNOptions = 31 + StridedSliceOptions = 32 + ExpOptions = 33 + TopKV2Options = 34 + SplitOptions = 35 + LogSoftmaxOptions = 36 + CastOptions = 37 + DequantizeOptions = 38 + MaximumMinimumOptions = 39 + ArgMaxOptions = 40 + LessOptions = 41 + NegOptions = 42 + PadV2Options = 43 + GreaterOptions = 44 + GreaterEqualOptions = 45 + LessEqualOptions = 46 + SelectOptions = 47 + SliceOptions = 48 + TransposeConvOptions = 49 + SparseToDenseOptions = 50 + TileOptions = 51 + ExpandDimsOptions = 52 + EqualOptions = 53 + NotEqualOptions = 54 + ShapeOptions = 55 + PowOptions = 56 + ArgMinOptions = 57 + FakeQuantOptions = 58 + PackOptions = 59 + LogicalOrOptions = 60 + OneHotOptions = 61 + LogicalAndOptions = 62 + LogicalNotOptions = 63 + UnpackOptions = 64 + FloorDivOptions = 65 + SquareOptions = 66 + ZerosLikeOptions = 67 + FillOptions = 68 + BidirectionalSequenceLSTMOptions = 69 + BidirectionalSequenceRNNOptions = 70 + UnidirectionalSequenceLSTMOptions = 71 + FloorModOptions = 72 + RangeOptions = 73 + ResizeNearestNeighborOptions = 74 + LeakyReluOptions = 75 + SquaredDifferenceOptions = 76 + MirrorPadOptions = 77 + AbsOptions = 78 + SplitVOptions = 79 + UniqueOptions = 80 + ReverseV2Options = 81 + AddNOptions = 82 + GatherNdOptions = 83 + CosOptions = 84 + WhereOptions = 85 + RankOptions = 86 + ReverseSequenceOptions = 87 + MatrixDiagOptions = 88 + QuantizeOptions = 89 + MatrixSetDiagOptions = 90 + HardSwishOptions = 91 + IfOptions = 92 + WhileOptions = 93 + DepthToSpaceOptions = 94 + NonMaxSuppressionV4Options = 95 + NonMaxSuppressionV5Options = 96 + ScatterNdOptions = 97 + SelectV2Options = 98 + DensifyOptions = 99 + SegmentSumOptions = 100 + BatchMatMulOptions = 101 + CumsumOptions = 102 + CallOnceOptions = 103 + BroadcastToOptions = 104 + Rfft2dOptions = 105 + Conv3DOptions = 106 + HashtableOptions = 107 + HashtableFindOptions = 108 + HashtableImportOptions = 109 + HashtableSizeOptions = 110 + VarHandleOptions = 111 + ReadVariableOptions = 112 + AssignVariableOptions = 113 + RandomOptions = 114 + BucketizeOptions = 115 + GeluOptions = 116 + DynamicUpdateSliceOptions = 117 + UnsortedSegmentProdOptions = 118 + UnsortedSegmentMaxOptions = 119 + UnsortedSegmentMinOptions = 120 + UnsortedSegmentSumOptions = 121 + ATan2Options = 122 + SignOptions = 123 + BitcastOptions = 124 + BitwiseXorOptions = 125 + RightShiftOptions = 126 + +def BuiltinOptionsCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == BuiltinOptions().Conv2DOptions: + return Conv2DOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().DepthwiseConv2DOptions: + return DepthwiseConv2DOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ConcatEmbeddingsOptions: + return ConcatEmbeddingsOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LSHProjectionOptions: + return LSHProjectionOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().Pool2DOptions: + return Pool2DOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SVDFOptions: + return SVDFOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().RNNOptions: + return RNNOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().FullyConnectedOptions: + return FullyConnectedOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SoftmaxOptions: + return SoftmaxOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ConcatenationOptions: + return ConcatenationOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().AddOptions: + return AddOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().L2NormOptions: + return L2NormOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LocalResponseNormalizationOptions: + return LocalResponseNormalizationOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LSTMOptions: + return LSTMOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ResizeBilinearOptions: + return ResizeBilinearOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().CallOptions: + return CallOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ReshapeOptions: + return ReshapeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SkipGramOptions: + return SkipGramOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SpaceToDepthOptions: + return SpaceToDepthOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().EmbeddingLookupSparseOptions: + return EmbeddingLookupSparseOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().MulOptions: + return MulOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().PadOptions: + return PadOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().GatherOptions: + return GatherOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BatchToSpaceNDOptions: + return BatchToSpaceNDOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SpaceToBatchNDOptions: + return SpaceToBatchNDOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().TransposeOptions: + return TransposeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ReducerOptions: + return ReducerOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SubOptions: + return SubOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().DivOptions: + return DivOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SqueezeOptions: + return SqueezeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SequenceRNNOptions: + return SequenceRNNOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().StridedSliceOptions: + return StridedSliceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ExpOptions: + return ExpOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().TopKV2Options: + return TopKV2OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SplitOptions: + return SplitOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LogSoftmaxOptions: + return LogSoftmaxOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().CastOptions: + return CastOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().DequantizeOptions: + return DequantizeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().MaximumMinimumOptions: + return MaximumMinimumOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ArgMaxOptions: + return ArgMaxOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LessOptions: + return LessOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().NegOptions: + return NegOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().PadV2Options: + return PadV2OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().GreaterOptions: + return GreaterOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().GreaterEqualOptions: + return GreaterEqualOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LessEqualOptions: + return LessEqualOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SelectOptions: + return SelectOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SliceOptions: + return SliceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().TransposeConvOptions: + return TransposeConvOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SparseToDenseOptions: + return SparseToDenseOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().TileOptions: + return TileOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ExpandDimsOptions: + return ExpandDimsOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().EqualOptions: + return EqualOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().NotEqualOptions: + return NotEqualOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ShapeOptions: + return ShapeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().PowOptions: + return PowOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ArgMinOptions: + return ArgMinOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().FakeQuantOptions: + return FakeQuantOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().PackOptions: + return PackOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LogicalOrOptions: + return LogicalOrOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().OneHotOptions: + return OneHotOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LogicalAndOptions: + return LogicalAndOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LogicalNotOptions: + return LogicalNotOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UnpackOptions: + return UnpackOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().FloorDivOptions: + return FloorDivOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SquareOptions: + return SquareOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ZerosLikeOptions: + return ZerosLikeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().FillOptions: + return FillOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BidirectionalSequenceLSTMOptions: + return BidirectionalSequenceLSTMOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BidirectionalSequenceRNNOptions: + return BidirectionalSequenceRNNOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UnidirectionalSequenceLSTMOptions: + return UnidirectionalSequenceLSTMOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().FloorModOptions: + return FloorModOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().RangeOptions: + return RangeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ResizeNearestNeighborOptions: + return ResizeNearestNeighborOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().LeakyReluOptions: + return LeakyReluOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SquaredDifferenceOptions: + return SquaredDifferenceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().MirrorPadOptions: + return MirrorPadOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().AbsOptions: + return AbsOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SplitVOptions: + return SplitVOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UniqueOptions: + return UniqueOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ReverseV2Options: + return ReverseV2OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().AddNOptions: + return AddNOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().GatherNdOptions: + return GatherNdOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().CosOptions: + return CosOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().WhereOptions: + return WhereOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().RankOptions: + return RankOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ReverseSequenceOptions: + return ReverseSequenceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().MatrixDiagOptions: + return MatrixDiagOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().QuantizeOptions: + return QuantizeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().MatrixSetDiagOptions: + return MatrixSetDiagOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().HardSwishOptions: + return HardSwishOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().IfOptions: + return IfOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().WhileOptions: + return WhileOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().DepthToSpaceOptions: + return DepthToSpaceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().NonMaxSuppressionV4Options: + return NonMaxSuppressionV4OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().NonMaxSuppressionV5Options: + return NonMaxSuppressionV5OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ScatterNdOptions: + return ScatterNdOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SelectV2Options: + return SelectV2OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().DensifyOptions: + return DensifyOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SegmentSumOptions: + return SegmentSumOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BatchMatMulOptions: + return BatchMatMulOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().CumsumOptions: + return CumsumOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().CallOnceOptions: + return CallOnceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BroadcastToOptions: + return BroadcastToOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().Rfft2dOptions: + return Rfft2dOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().Conv3DOptions: + return Conv3DOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().HashtableOptions: + return HashtableOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().HashtableFindOptions: + return HashtableFindOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().HashtableImportOptions: + return HashtableImportOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().HashtableSizeOptions: + return HashtableSizeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().VarHandleOptions: + return VarHandleOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ReadVariableOptions: + return ReadVariableOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().AssignVariableOptions: + return AssignVariableOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().RandomOptions: + return RandomOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BucketizeOptions: + return BucketizeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().GeluOptions: + return GeluOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().DynamicUpdateSliceOptions: + return DynamicUpdateSliceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UnsortedSegmentProdOptions: + return UnsortedSegmentProdOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UnsortedSegmentMaxOptions: + return UnsortedSegmentMaxOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UnsortedSegmentMinOptions: + return UnsortedSegmentMinOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().UnsortedSegmentSumOptions: + return UnsortedSegmentSumOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().ATan2Options: + return ATan2OptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().SignOptions: + return SignOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BitcastOptions: + return BitcastOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().BitwiseXorOptions: + return BitwiseXorOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions().RightShiftOptions: + return RightShiftOptionsT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class BuiltinOptions2(object): + NONE = 0 + StablehloConcatenateOptions = 1 + StablehloBroadcastInDimOptions = 2 + StablehloSliceOptions = 3 + StablehloConvolutionOptions = 4 + StablehloCustomCallOptions = 5 + StablehloReduceOptions = 6 + StablehloScatterOptions = 7 + StablehloCompareOptions = 8 + StablehloDynamicSliceOptions = 9 + StablehloPadOptions = 10 + StablehloIotaOptions = 11 + StablehloDotGeneralOptions = 12 + StablehloReduceWindowOptions = 13 + StablehloSortOptions = 14 + StablehloWhileOptions = 15 + StablehloGatherOptions = 16 + StablehloTransposeOptions = 17 + DilateOptions = 18 + StablehloRngBitGeneratorOptions = 19 + ReduceWindowOptions = 20 + +def BuiltinOptions2Creator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == BuiltinOptions2().StablehloConcatenateOptions: + return StablehloConcatenateOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloBroadcastInDimOptions: + return StablehloBroadcastInDimOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloSliceOptions: + return StablehloSliceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloConvolutionOptions: + return StablehloConvolutionOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloCustomCallOptions: + return StablehloCustomCallOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloReduceOptions: + return StablehloReduceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloScatterOptions: + return StablehloScatterOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloCompareOptions: + return StablehloCompareOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloDynamicSliceOptions: + return StablehloDynamicSliceOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloPadOptions: + return StablehloPadOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloIotaOptions: + return StablehloIotaOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloDotGeneralOptions: + return StablehloDotGeneralOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloReduceWindowOptions: + return StablehloReduceWindowOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloSortOptions: + return StablehloSortOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloWhileOptions: + return StablehloWhileOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloGatherOptions: + return StablehloGatherOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloTransposeOptions: + return StablehloTransposeOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().DilateOptions: + return DilateOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().StablehloRngBitGeneratorOptions: + return StablehloRngBitGeneratorOptionsT.InitFromBuf(table.Bytes, table.Pos) + if unionType == BuiltinOptions2().ReduceWindowOptions: + return ReduceWindowOptionsT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class StablehloPrecisionConfig(object): + DEFAULT = 0 + HIGH = 1 + HIGHEST = 2 + + +class StablehloComparisonDirection(object): + STABLEHLO_COMPARISON_DIRECTION_EQ = 0 + STABLEHLO_COMPARISON_DIRECTION_NE = 1 + STABLEHLO_COMPARISON_DIRECTION_GE = 2 + STABLEHLO_COMPARISON_DIRECTION_GT = 3 + STABLEHLO_COMPARISON_DIRECTION_LE = 4 + STABLEHLO_COMPARISON_DIRECTION_LT = 5 + + +class StablehloComparisonType(object): + STABLEHLO_COMPARISON_TYPE_NOTYPE = 0 + STABLEHLO_COMPARISON_TYPE_FLOAT = 1 + STABLEHLO_COMPARISON_TYPE_FLOAT_TOTAL_ORDER = 2 + STABLEHLO_COMPARISON_TYPE_SIGNED = 3 + STABLEHLO_COMPARISON_TYPE_UNSIGNED = 4 + + +class RngAlgorithm(object): + DEFAULT = 0 + PHILOX = 1 + THREEFRY = 2 + + +class Padding(object): + SAME = 0 + VALID = 1 + + +class ActivationFunctionType(object): + NONE = 0 + RELU = 1 + RELU_N1_TO_1 = 2 + RELU6 = 3 + TANH = 4 + SIGN_BIT = 5 + + +class LSHProjectionType(object): + UNKNOWN = 0 + SPARSE = 1 + DENSE = 2 + + +class FullyConnectedOptionsWeightsFormat(object): + DEFAULT = 0 + SHUFFLED4x16INT8 = 1 + + +class LSTMKernelType(object): + FULL = 0 + BASIC = 1 + + +class CombinerType(object): + SUM = 0 + MEAN = 1 + SQRTN = 2 + + +class MirrorPadMode(object): + REFLECT = 0 + SYMMETRIC = 1 + + +class ReduceWindowFunction(object): + UNSUPPORTED = 0 + ADD = 1 + MUL = 2 + MINIMUM = 3 + MAXIMUM = 4 + ALL = 5 + ANY = 6 + + +class CustomOptionsFormat(object): + FLEXBUFFERS = 0 + + +class CustomQuantization(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = CustomQuantization() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCustomQuantization(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CustomQuantizationBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # CustomQuantization + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # CustomQuantization + def Custom(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # CustomQuantization + def CustomAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # CustomQuantization + def CustomLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # CustomQuantization + def CustomIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def CustomQuantizationStart(builder): + builder.StartObject(1) + +def CustomQuantizationAddCustom(builder, custom): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(custom), 0) + +def CustomQuantizationStartCustomVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def CustomQuantizationEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class CustomQuantizationT(object): + + # CustomQuantizationT + def __init__(self): + self.custom = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + customQuantization = CustomQuantization() + customQuantization.Init(buf, pos) + return cls.InitFromObj(customQuantization) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, customQuantization): + x = CustomQuantizationT() + x._UnPack(customQuantization) + return x + + # CustomQuantizationT + def _UnPack(self, customQuantization): + if customQuantization is None: + return + if not customQuantization.CustomIsNone(): + if np is None: + self.custom = [] + for i in range(customQuantization.CustomLength()): + self.custom.append(customQuantization.Custom(i)) + else: + self.custom = customQuantization.CustomAsNumpy() + + # CustomQuantizationT + def Pack(self, builder): + if self.custom is not None: + if np is not None and type(self.custom) is np.ndarray: + custom = builder.CreateNumpyVector(self.custom) + else: + CustomQuantizationStartCustomVector(builder, len(self.custom)) + for i in reversed(range(len(self.custom))): + builder.PrependUint8(self.custom[i]) + custom = builder.EndVector() + CustomQuantizationStart(builder) + if self.custom is not None: + CustomQuantizationAddCustom(builder, custom) + customQuantization = CustomQuantizationEnd(builder) + return customQuantization + + +class QuantizationParameters(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = QuantizationParameters() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsQuantizationParameters(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def QuantizationParametersBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # QuantizationParameters + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # QuantizationParameters + def Min(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # QuantizationParameters + def MinAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float32Flags, o) + return 0 + + # QuantizationParameters + def MinLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # QuantizationParameters + def MinIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # QuantizationParameters + def Max(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # QuantizationParameters + def MaxAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float32Flags, o) + return 0 + + # QuantizationParameters + def MaxLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # QuantizationParameters + def MaxIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # QuantizationParameters + def Scale(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # QuantizationParameters + def ScaleAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float32Flags, o) + return 0 + + # QuantizationParameters + def ScaleLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # QuantizationParameters + def ScaleIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # QuantizationParameters + def ZeroPoint(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # QuantizationParameters + def ZeroPointAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # QuantizationParameters + def ZeroPointLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # QuantizationParameters + def ZeroPointIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + + # QuantizationParameters + def DetailsType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # QuantizationParameters + def Details(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # QuantizationParameters + def QuantizedDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def QuantizationParametersStart(builder): + builder.StartObject(7) + +def QuantizationParametersAddMin(builder, min): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(min), 0) + +def QuantizationParametersStartMinVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def QuantizationParametersAddMax(builder, max): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(max), 0) + +def QuantizationParametersStartMaxVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def QuantizationParametersAddScale(builder, scale): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(scale), 0) + +def QuantizationParametersStartScaleVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def QuantizationParametersAddZeroPoint(builder, zeroPoint): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(zeroPoint), 0) + +def QuantizationParametersStartZeroPointVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def QuantizationParametersAddDetailsType(builder, detailsType): + builder.PrependUint8Slot(4, detailsType, 0) + +def QuantizationParametersAddDetails(builder, details): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(details), 0) + +def QuantizationParametersAddQuantizedDimension(builder, quantizedDimension): + builder.PrependInt32Slot(6, quantizedDimension, 0) + +def QuantizationParametersEnd(builder): + return builder.EndObject() + + +try: + from typing import List, Union +except: + pass + +class QuantizationParametersT(object): + + # QuantizationParametersT + def __init__(self): + self.min = None # type: List[float] + self.max = None # type: List[float] + self.scale = None # type: List[float] + self.zeroPoint = None # type: List[int] + self.detailsType = 0 # type: int + self.details = None # type: Union[None, CustomQuantizationT] + self.quantizedDimension = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + quantizationParameters = QuantizationParameters() + quantizationParameters.Init(buf, pos) + return cls.InitFromObj(quantizationParameters) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, quantizationParameters): + x = QuantizationParametersT() + x._UnPack(quantizationParameters) + return x + + # QuantizationParametersT + def _UnPack(self, quantizationParameters): + if quantizationParameters is None: + return + if not quantizationParameters.MinIsNone(): + if np is None: + self.min = [] + for i in range(quantizationParameters.MinLength()): + self.min.append(quantizationParameters.Min(i)) + else: + self.min = quantizationParameters.MinAsNumpy() + if not quantizationParameters.MaxIsNone(): + if np is None: + self.max = [] + for i in range(quantizationParameters.MaxLength()): + self.max.append(quantizationParameters.Max(i)) + else: + self.max = quantizationParameters.MaxAsNumpy() + if not quantizationParameters.ScaleIsNone(): + if np is None: + self.scale = [] + for i in range(quantizationParameters.ScaleLength()): + self.scale.append(quantizationParameters.Scale(i)) + else: + self.scale = quantizationParameters.ScaleAsNumpy() + if not quantizationParameters.ZeroPointIsNone(): + if np is None: + self.zeroPoint = [] + for i in range(quantizationParameters.ZeroPointLength()): + self.zeroPoint.append(quantizationParameters.ZeroPoint(i)) + else: + self.zeroPoint = quantizationParameters.ZeroPointAsNumpy() + self.detailsType = quantizationParameters.DetailsType() + self.details = QuantizationDetailsCreator(self.detailsType, quantizationParameters.Details()) + self.quantizedDimension = quantizationParameters.QuantizedDimension() + + # QuantizationParametersT + def Pack(self, builder): + if self.min is not None: + if np is not None and type(self.min) is np.ndarray: + min = builder.CreateNumpyVector(self.min) + else: + QuantizationParametersStartMinVector(builder, len(self.min)) + for i in reversed(range(len(self.min))): + builder.PrependFloat32(self.min[i]) + min = builder.EndVector() + if self.max is not None: + if np is not None and type(self.max) is np.ndarray: + max = builder.CreateNumpyVector(self.max) + else: + QuantizationParametersStartMaxVector(builder, len(self.max)) + for i in reversed(range(len(self.max))): + builder.PrependFloat32(self.max[i]) + max = builder.EndVector() + if self.scale is not None: + if np is not None and type(self.scale) is np.ndarray: + scale = builder.CreateNumpyVector(self.scale) + else: + QuantizationParametersStartScaleVector(builder, len(self.scale)) + for i in reversed(range(len(self.scale))): + builder.PrependFloat32(self.scale[i]) + scale = builder.EndVector() + if self.zeroPoint is not None: + if np is not None and type(self.zeroPoint) is np.ndarray: + zeroPoint = builder.CreateNumpyVector(self.zeroPoint) + else: + QuantizationParametersStartZeroPointVector(builder, len(self.zeroPoint)) + for i in reversed(range(len(self.zeroPoint))): + builder.PrependInt64(self.zeroPoint[i]) + zeroPoint = builder.EndVector() + if self.details is not None: + details = self.details.Pack(builder) + QuantizationParametersStart(builder) + if self.min is not None: + QuantizationParametersAddMin(builder, min) + if self.max is not None: + QuantizationParametersAddMax(builder, max) + if self.scale is not None: + QuantizationParametersAddScale(builder, scale) + if self.zeroPoint is not None: + QuantizationParametersAddZeroPoint(builder, zeroPoint) + QuantizationParametersAddDetailsType(builder, self.detailsType) + if self.details is not None: + QuantizationParametersAddDetails(builder, details) + QuantizationParametersAddQuantizedDimension(builder, self.quantizedDimension) + quantizationParameters = QuantizationParametersEnd(builder) + return quantizationParameters + + +class Int32Vector(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Int32Vector() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsInt32Vector(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Int32VectorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Int32Vector + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Int32Vector + def Values(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Int32Vector + def ValuesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Int32Vector + def ValuesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Int32Vector + def ValuesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def Int32VectorStart(builder): + builder.StartObject(1) + +def Int32VectorAddValues(builder, values): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0) + +def Int32VectorStartValuesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def Int32VectorEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class Int32VectorT(object): + + # Int32VectorT + def __init__(self): + self.values = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + int32Vector = Int32Vector() + int32Vector.Init(buf, pos) + return cls.InitFromObj(int32Vector) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, int32Vector): + x = Int32VectorT() + x._UnPack(int32Vector) + return x + + # Int32VectorT + def _UnPack(self, int32Vector): + if int32Vector is None: + return + if not int32Vector.ValuesIsNone(): + if np is None: + self.values = [] + for i in range(int32Vector.ValuesLength()): + self.values.append(int32Vector.Values(i)) + else: + self.values = int32Vector.ValuesAsNumpy() + + # Int32VectorT + def Pack(self, builder): + if self.values is not None: + if np is not None and type(self.values) is np.ndarray: + values = builder.CreateNumpyVector(self.values) + else: + Int32VectorStartValuesVector(builder, len(self.values)) + for i in reversed(range(len(self.values))): + builder.PrependInt32(self.values[i]) + values = builder.EndVector() + Int32VectorStart(builder) + if self.values is not None: + Int32VectorAddValues(builder, values) + int32Vector = Int32VectorEnd(builder) + return int32Vector + + +class Uint16Vector(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Uint16Vector() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUint16Vector(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Uint16VectorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Uint16Vector + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Uint16Vector + def Values(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint16Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 2)) + return 0 + + # Uint16Vector + def ValuesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint16Flags, o) + return 0 + + # Uint16Vector + def ValuesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Uint16Vector + def ValuesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def Uint16VectorStart(builder): + builder.StartObject(1) + +def Uint16VectorAddValues(builder, values): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0) + +def Uint16VectorStartValuesVector(builder, numElems): + return builder.StartVector(2, numElems, 2) + +def Uint16VectorEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class Uint16VectorT(object): + + # Uint16VectorT + def __init__(self): + self.values = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + uint16Vector = Uint16Vector() + uint16Vector.Init(buf, pos) + return cls.InitFromObj(uint16Vector) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, uint16Vector): + x = Uint16VectorT() + x._UnPack(uint16Vector) + return x + + # Uint16VectorT + def _UnPack(self, uint16Vector): + if uint16Vector is None: + return + if not uint16Vector.ValuesIsNone(): + if np is None: + self.values = [] + for i in range(uint16Vector.ValuesLength()): + self.values.append(uint16Vector.Values(i)) + else: + self.values = uint16Vector.ValuesAsNumpy() + + # Uint16VectorT + def Pack(self, builder): + if self.values is not None: + if np is not None and type(self.values) is np.ndarray: + values = builder.CreateNumpyVector(self.values) + else: + Uint16VectorStartValuesVector(builder, len(self.values)) + for i in reversed(range(len(self.values))): + builder.PrependUint16(self.values[i]) + values = builder.EndVector() + Uint16VectorStart(builder) + if self.values is not None: + Uint16VectorAddValues(builder, values) + uint16Vector = Uint16VectorEnd(builder) + return uint16Vector + + +class Uint8Vector(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Uint8Vector() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUint8Vector(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Uint8VectorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Uint8Vector + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Uint8Vector + def Values(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Uint8Vector + def ValuesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Uint8Vector + def ValuesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Uint8Vector + def ValuesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def Uint8VectorStart(builder): + builder.StartObject(1) + +def Uint8VectorAddValues(builder, values): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(values), 0) + +def Uint8VectorStartValuesVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def Uint8VectorEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class Uint8VectorT(object): + + # Uint8VectorT + def __init__(self): + self.values = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + uint8Vector = Uint8Vector() + uint8Vector.Init(buf, pos) + return cls.InitFromObj(uint8Vector) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, uint8Vector): + x = Uint8VectorT() + x._UnPack(uint8Vector) + return x + + # Uint8VectorT + def _UnPack(self, uint8Vector): + if uint8Vector is None: + return + if not uint8Vector.ValuesIsNone(): + if np is None: + self.values = [] + for i in range(uint8Vector.ValuesLength()): + self.values.append(uint8Vector.Values(i)) + else: + self.values = uint8Vector.ValuesAsNumpy() + + # Uint8VectorT + def Pack(self, builder): + if self.values is not None: + if np is not None and type(self.values) is np.ndarray: + values = builder.CreateNumpyVector(self.values) + else: + Uint8VectorStartValuesVector(builder, len(self.values)) + for i in reversed(range(len(self.values))): + builder.PrependUint8(self.values[i]) + values = builder.EndVector() + Uint8VectorStart(builder) + if self.values is not None: + Uint8VectorAddValues(builder, values) + uint8Vector = Uint8VectorEnd(builder) + return uint8Vector + + +class DimensionMetadata(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DimensionMetadata() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDimensionMetadata(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DimensionMetadataBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DimensionMetadata + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DimensionMetadata + def Format(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # DimensionMetadata + def DenseSize(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # DimensionMetadata + def ArraySegmentsType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # DimensionMetadata + def ArraySegments(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # DimensionMetadata + def ArrayIndicesType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # DimensionMetadata + def ArrayIndices(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + +def DimensionMetadataStart(builder): + builder.StartObject(6) + +def DimensionMetadataAddFormat(builder, format): + builder.PrependInt8Slot(0, format, 0) + +def DimensionMetadataAddDenseSize(builder, denseSize): + builder.PrependInt32Slot(1, denseSize, 0) + +def DimensionMetadataAddArraySegmentsType(builder, arraySegmentsType): + builder.PrependUint8Slot(2, arraySegmentsType, 0) + +def DimensionMetadataAddArraySegments(builder, arraySegments): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(arraySegments), 0) + +def DimensionMetadataAddArrayIndicesType(builder, arrayIndicesType): + builder.PrependUint8Slot(4, arrayIndicesType, 0) + +def DimensionMetadataAddArrayIndices(builder, arrayIndices): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(arrayIndices), 0) + +def DimensionMetadataEnd(builder): + return builder.EndObject() + + +try: + from typing import Union +except: + pass + +class DimensionMetadataT(object): + + # DimensionMetadataT + def __init__(self): + self.format = 0 # type: int + self.denseSize = 0 # type: int + self.arraySegmentsType = 0 # type: int + self.arraySegments = None # type: Union[None, Int32VectorT, Uint16VectorT, Uint8VectorT] + self.arrayIndicesType = 0 # type: int + self.arrayIndices = None # type: Union[None, Int32VectorT, Uint16VectorT, Uint8VectorT] + + @classmethod + def InitFromBuf(cls, buf, pos): + dimensionMetadata = DimensionMetadata() + dimensionMetadata.Init(buf, pos) + return cls.InitFromObj(dimensionMetadata) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, dimensionMetadata): + x = DimensionMetadataT() + x._UnPack(dimensionMetadata) + return x + + # DimensionMetadataT + def _UnPack(self, dimensionMetadata): + if dimensionMetadata is None: + return + self.format = dimensionMetadata.Format() + self.denseSize = dimensionMetadata.DenseSize() + self.arraySegmentsType = dimensionMetadata.ArraySegmentsType() + self.arraySegments = SparseIndexVectorCreator(self.arraySegmentsType, dimensionMetadata.ArraySegments()) + self.arrayIndicesType = dimensionMetadata.ArrayIndicesType() + self.arrayIndices = SparseIndexVectorCreator(self.arrayIndicesType, dimensionMetadata.ArrayIndices()) + + # DimensionMetadataT + def Pack(self, builder): + if self.arraySegments is not None: + arraySegments = self.arraySegments.Pack(builder) + if self.arrayIndices is not None: + arrayIndices = self.arrayIndices.Pack(builder) + DimensionMetadataStart(builder) + DimensionMetadataAddFormat(builder, self.format) + DimensionMetadataAddDenseSize(builder, self.denseSize) + DimensionMetadataAddArraySegmentsType(builder, self.arraySegmentsType) + if self.arraySegments is not None: + DimensionMetadataAddArraySegments(builder, arraySegments) + DimensionMetadataAddArrayIndicesType(builder, self.arrayIndicesType) + if self.arrayIndices is not None: + DimensionMetadataAddArrayIndices(builder, arrayIndices) + dimensionMetadata = DimensionMetadataEnd(builder) + return dimensionMetadata + + +class SparsityParameters(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SparsityParameters() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSparsityParameters(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SparsityParametersBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SparsityParameters + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SparsityParameters + def TraversalOrder(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # SparsityParameters + def TraversalOrderAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # SparsityParameters + def TraversalOrderLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SparsityParameters + def TraversalOrderIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # SparsityParameters + def BlockMap(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # SparsityParameters + def BlockMapAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # SparsityParameters + def BlockMapLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SparsityParameters + def BlockMapIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # SparsityParameters + def DimMetadata(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = DimensionMetadata() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SparsityParameters + def DimMetadataLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SparsityParameters + def DimMetadataIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def SparsityParametersStart(builder): + builder.StartObject(3) + +def SparsityParametersAddTraversalOrder(builder, traversalOrder): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(traversalOrder), 0) + +def SparsityParametersStartTraversalOrderVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SparsityParametersAddBlockMap(builder, blockMap): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(blockMap), 0) + +def SparsityParametersStartBlockMapVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SparsityParametersAddDimMetadata(builder, dimMetadata): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(dimMetadata), 0) + +def SparsityParametersStartDimMetadataVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SparsityParametersEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class SparsityParametersT(object): + + # SparsityParametersT + def __init__(self): + self.traversalOrder = None # type: List[int] + self.blockMap = None # type: List[int] + self.dimMetadata = None # type: List[DimensionMetadataT] + + @classmethod + def InitFromBuf(cls, buf, pos): + sparsityParameters = SparsityParameters() + sparsityParameters.Init(buf, pos) + return cls.InitFromObj(sparsityParameters) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, sparsityParameters): + x = SparsityParametersT() + x._UnPack(sparsityParameters) + return x + + # SparsityParametersT + def _UnPack(self, sparsityParameters): + if sparsityParameters is None: + return + if not sparsityParameters.TraversalOrderIsNone(): + if np is None: + self.traversalOrder = [] + for i in range(sparsityParameters.TraversalOrderLength()): + self.traversalOrder.append(sparsityParameters.TraversalOrder(i)) + else: + self.traversalOrder = sparsityParameters.TraversalOrderAsNumpy() + if not sparsityParameters.BlockMapIsNone(): + if np is None: + self.blockMap = [] + for i in range(sparsityParameters.BlockMapLength()): + self.blockMap.append(sparsityParameters.BlockMap(i)) + else: + self.blockMap = sparsityParameters.BlockMapAsNumpy() + if not sparsityParameters.DimMetadataIsNone(): + self.dimMetadata = [] + for i in range(sparsityParameters.DimMetadataLength()): + if sparsityParameters.DimMetadata(i) is None: + self.dimMetadata.append(None) + else: + dimensionMetadata_ = DimensionMetadataT.InitFromObj(sparsityParameters.DimMetadata(i)) + self.dimMetadata.append(dimensionMetadata_) + + # SparsityParametersT + def Pack(self, builder): + if self.traversalOrder is not None: + if np is not None and type(self.traversalOrder) is np.ndarray: + traversalOrder = builder.CreateNumpyVector(self.traversalOrder) + else: + SparsityParametersStartTraversalOrderVector(builder, len(self.traversalOrder)) + for i in reversed(range(len(self.traversalOrder))): + builder.PrependInt32(self.traversalOrder[i]) + traversalOrder = builder.EndVector() + if self.blockMap is not None: + if np is not None and type(self.blockMap) is np.ndarray: + blockMap = builder.CreateNumpyVector(self.blockMap) + else: + SparsityParametersStartBlockMapVector(builder, len(self.blockMap)) + for i in reversed(range(len(self.blockMap))): + builder.PrependInt32(self.blockMap[i]) + blockMap = builder.EndVector() + if self.dimMetadata is not None: + dimMetadatalist = [] + for i in range(len(self.dimMetadata)): + dimMetadatalist.append(self.dimMetadata[i].Pack(builder)) + SparsityParametersStartDimMetadataVector(builder, len(self.dimMetadata)) + for i in reversed(range(len(self.dimMetadata))): + builder.PrependUOffsetTRelative(dimMetadatalist[i]) + dimMetadata = builder.EndVector() + SparsityParametersStart(builder) + if self.traversalOrder is not None: + SparsityParametersAddTraversalOrder(builder, traversalOrder) + if self.blockMap is not None: + SparsityParametersAddBlockMap(builder, blockMap) + if self.dimMetadata is not None: + SparsityParametersAddDimMetadata(builder, dimMetadata) + sparsityParameters = SparsityParametersEnd(builder) + return sparsityParameters + + +class VariantSubType(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = VariantSubType() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsVariantSubType(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def VariantSubTypeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # VariantSubType + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # VariantSubType + def Shape(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # VariantSubType + def ShapeAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # VariantSubType + def ShapeLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # VariantSubType + def ShapeIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # VariantSubType + def Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # VariantSubType + def HasRank(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def VariantSubTypeStart(builder): + builder.StartObject(3) + +def VariantSubTypeAddShape(builder, shape): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(shape), 0) + +def VariantSubTypeStartShapeVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def VariantSubTypeAddType(builder, type): + builder.PrependInt8Slot(1, type, 0) + +def VariantSubTypeAddHasRank(builder, hasRank): + builder.PrependBoolSlot(2, hasRank, 0) + +def VariantSubTypeEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class VariantSubTypeT(object): + + # VariantSubTypeT + def __init__(self): + self.shape = None # type: List[int] + self.type = 0 # type: int + self.hasRank = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + variantSubType = VariantSubType() + variantSubType.Init(buf, pos) + return cls.InitFromObj(variantSubType) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, variantSubType): + x = VariantSubTypeT() + x._UnPack(variantSubType) + return x + + # VariantSubTypeT + def _UnPack(self, variantSubType): + if variantSubType is None: + return + if not variantSubType.ShapeIsNone(): + if np is None: + self.shape = [] + for i in range(variantSubType.ShapeLength()): + self.shape.append(variantSubType.Shape(i)) + else: + self.shape = variantSubType.ShapeAsNumpy() + self.type = variantSubType.Type() + self.hasRank = variantSubType.HasRank() + + # VariantSubTypeT + def Pack(self, builder): + if self.shape is not None: + if np is not None and type(self.shape) is np.ndarray: + shape = builder.CreateNumpyVector(self.shape) + else: + VariantSubTypeStartShapeVector(builder, len(self.shape)) + for i in reversed(range(len(self.shape))): + builder.PrependInt32(self.shape[i]) + shape = builder.EndVector() + VariantSubTypeStart(builder) + if self.shape is not None: + VariantSubTypeAddShape(builder, shape) + VariantSubTypeAddType(builder, self.type) + VariantSubTypeAddHasRank(builder, self.hasRank) + variantSubType = VariantSubTypeEnd(builder) + return variantSubType + + +class Tensor(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Tensor() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTensor(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TensorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Tensor + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Tensor + def Shape(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Tensor + def ShapeAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Tensor + def ShapeLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Tensor + def ShapeIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # Tensor + def Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Tensor + def Buffer(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Tensor + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Tensor + def Quantization(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = QuantizationParameters() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Tensor + def IsVariable(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # Tensor + def Sparsity(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = SparsityParameters() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Tensor + def ShapeSignature(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Tensor + def ShapeSignatureAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Tensor + def ShapeSignatureLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Tensor + def ShapeSignatureIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + return o == 0 + + # Tensor + def HasRank(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # Tensor + def VariantTensors(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = VariantSubType() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Tensor + def VariantTensorsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Tensor + def VariantTensorsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + +def TensorStart(builder): + builder.StartObject(10) + +def TensorAddShape(builder, shape): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(shape), 0) + +def TensorStartShapeVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def TensorAddType(builder, type): + builder.PrependInt8Slot(1, type, 0) + +def TensorAddBuffer(builder, buffer): + builder.PrependUint32Slot(2, buffer, 0) + +def TensorAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def TensorAddQuantization(builder, quantization): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(quantization), 0) + +def TensorAddIsVariable(builder, isVariable): + builder.PrependBoolSlot(5, isVariable, 0) + +def TensorAddSparsity(builder, sparsity): + builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(sparsity), 0) + +def TensorAddShapeSignature(builder, shapeSignature): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(shapeSignature), 0) + +def TensorStartShapeSignatureVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def TensorAddHasRank(builder, hasRank): + builder.PrependBoolSlot(8, hasRank, 0) + +def TensorAddVariantTensors(builder, variantTensors): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(variantTensors), 0) + +def TensorStartVariantTensorsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def TensorEnd(builder): + return builder.EndObject() + + +try: + from typing import List, Optional +except: + pass + +class TensorT(object): + + # TensorT + def __init__(self): + self.shape = None # type: List[int] + self.type = 0 # type: int + self.buffer = 0 # type: int + self.name = None # type: str + self.quantization = None # type: Optional[QuantizationParametersT] + self.isVariable = False # type: bool + self.sparsity = None # type: Optional[SparsityParametersT] + self.shapeSignature = None # type: List[int] + self.hasRank = False # type: bool + self.variantTensors = None # type: List[VariantSubTypeT] + + @classmethod + def InitFromBuf(cls, buf, pos): + tensor = Tensor() + tensor.Init(buf, pos) + return cls.InitFromObj(tensor) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, tensor): + x = TensorT() + x._UnPack(tensor) + return x + + # TensorT + def _UnPack(self, tensor): + if tensor is None: + return + if not tensor.ShapeIsNone(): + if np is None: + self.shape = [] + for i in range(tensor.ShapeLength()): + self.shape.append(tensor.Shape(i)) + else: + self.shape = tensor.ShapeAsNumpy() + self.type = tensor.Type() + self.buffer = tensor.Buffer() + self.name = tensor.Name() + if tensor.Quantization() is not None: + self.quantization = QuantizationParametersT.InitFromObj(tensor.Quantization()) + self.isVariable = tensor.IsVariable() + if tensor.Sparsity() is not None: + self.sparsity = SparsityParametersT.InitFromObj(tensor.Sparsity()) + if not tensor.ShapeSignatureIsNone(): + if np is None: + self.shapeSignature = [] + for i in range(tensor.ShapeSignatureLength()): + self.shapeSignature.append(tensor.ShapeSignature(i)) + else: + self.shapeSignature = tensor.ShapeSignatureAsNumpy() + self.hasRank = tensor.HasRank() + if not tensor.VariantTensorsIsNone(): + self.variantTensors = [] + for i in range(tensor.VariantTensorsLength()): + if tensor.VariantTensors(i) is None: + self.variantTensors.append(None) + else: + variantSubType_ = VariantSubTypeT.InitFromObj(tensor.VariantTensors(i)) + self.variantTensors.append(variantSubType_) + + # TensorT + def Pack(self, builder): + if self.shape is not None: + if np is not None and type(self.shape) is np.ndarray: + shape = builder.CreateNumpyVector(self.shape) + else: + TensorStartShapeVector(builder, len(self.shape)) + for i in reversed(range(len(self.shape))): + builder.PrependInt32(self.shape[i]) + shape = builder.EndVector() + if self.name is not None: + name = builder.CreateString(self.name) + if self.quantization is not None: + quantization = self.quantization.Pack(builder) + if self.sparsity is not None: + sparsity = self.sparsity.Pack(builder) + if self.shapeSignature is not None: + if np is not None and type(self.shapeSignature) is np.ndarray: + shapeSignature = builder.CreateNumpyVector(self.shapeSignature) + else: + TensorStartShapeSignatureVector(builder, len(self.shapeSignature)) + for i in reversed(range(len(self.shapeSignature))): + builder.PrependInt32(self.shapeSignature[i]) + shapeSignature = builder.EndVector() + if self.variantTensors is not None: + variantTensorslist = [] + for i in range(len(self.variantTensors)): + variantTensorslist.append(self.variantTensors[i].Pack(builder)) + TensorStartVariantTensorsVector(builder, len(self.variantTensors)) + for i in reversed(range(len(self.variantTensors))): + builder.PrependUOffsetTRelative(variantTensorslist[i]) + variantTensors = builder.EndVector() + TensorStart(builder) + if self.shape is not None: + TensorAddShape(builder, shape) + TensorAddType(builder, self.type) + TensorAddBuffer(builder, self.buffer) + if self.name is not None: + TensorAddName(builder, name) + if self.quantization is not None: + TensorAddQuantization(builder, quantization) + TensorAddIsVariable(builder, self.isVariable) + if self.sparsity is not None: + TensorAddSparsity(builder, sparsity) + if self.shapeSignature is not None: + TensorAddShapeSignature(builder, shapeSignature) + TensorAddHasRank(builder, self.hasRank) + if self.variantTensors is not None: + TensorAddVariantTensors(builder, variantTensors) + tensor = TensorEnd(builder) + return tensor + + +class StablehloGatherOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloGatherOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloGatherOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloGatherOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloGatherOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloGatherOptions + def OffsetDims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloGatherOptions + def OffsetDimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloGatherOptions + def OffsetDimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloGatherOptions + def OffsetDimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloGatherOptions + def CollapsedSliceDims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloGatherOptions + def CollapsedSliceDimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloGatherOptions + def CollapsedSliceDimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloGatherOptions + def CollapsedSliceDimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloGatherOptions + def StartIndexMap(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloGatherOptions + def StartIndexMapAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloGatherOptions + def StartIndexMapLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloGatherOptions + def StartIndexMapIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # StablehloGatherOptions + def IndexVectorDim(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloGatherOptions + def SliceSizes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloGatherOptions + def SliceSizesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloGatherOptions + def SliceSizesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloGatherOptions + def SliceSizesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # StablehloGatherOptions + def IndicesAreSorted(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def StablehloGatherOptionsStart(builder): + builder.StartObject(6) + +def StablehloGatherOptionsAddOffsetDims(builder, offsetDims): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(offsetDims), 0) + +def StablehloGatherOptionsStartOffsetDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloGatherOptionsAddCollapsedSliceDims(builder, collapsedSliceDims): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(collapsedSliceDims), 0) + +def StablehloGatherOptionsStartCollapsedSliceDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloGatherOptionsAddStartIndexMap(builder, startIndexMap): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(startIndexMap), 0) + +def StablehloGatherOptionsStartStartIndexMapVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloGatherOptionsAddIndexVectorDim(builder, indexVectorDim): + builder.PrependInt64Slot(3, indexVectorDim, 0) + +def StablehloGatherOptionsAddSliceSizes(builder, sliceSizes): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(sliceSizes), 0) + +def StablehloGatherOptionsStartSliceSizesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloGatherOptionsAddIndicesAreSorted(builder, indicesAreSorted): + builder.PrependBoolSlot(5, indicesAreSorted, 0) + +def StablehloGatherOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloGatherOptionsT(object): + + # StablehloGatherOptionsT + def __init__(self): + self.offsetDims = None # type: List[int] + self.collapsedSliceDims = None # type: List[int] + self.startIndexMap = None # type: List[int] + self.indexVectorDim = 0 # type: int + self.sliceSizes = None # type: List[int] + self.indicesAreSorted = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloGatherOptions = StablehloGatherOptions() + stablehloGatherOptions.Init(buf, pos) + return cls.InitFromObj(stablehloGatherOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloGatherOptions): + x = StablehloGatherOptionsT() + x._UnPack(stablehloGatherOptions) + return x + + # StablehloGatherOptionsT + def _UnPack(self, stablehloGatherOptions): + if stablehloGatherOptions is None: + return + if not stablehloGatherOptions.OffsetDimsIsNone(): + if np is None: + self.offsetDims = [] + for i in range(stablehloGatherOptions.OffsetDimsLength()): + self.offsetDims.append(stablehloGatherOptions.OffsetDims(i)) + else: + self.offsetDims = stablehloGatherOptions.OffsetDimsAsNumpy() + if not stablehloGatherOptions.CollapsedSliceDimsIsNone(): + if np is None: + self.collapsedSliceDims = [] + for i in range(stablehloGatherOptions.CollapsedSliceDimsLength()): + self.collapsedSliceDims.append(stablehloGatherOptions.CollapsedSliceDims(i)) + else: + self.collapsedSliceDims = stablehloGatherOptions.CollapsedSliceDimsAsNumpy() + if not stablehloGatherOptions.StartIndexMapIsNone(): + if np is None: + self.startIndexMap = [] + for i in range(stablehloGatherOptions.StartIndexMapLength()): + self.startIndexMap.append(stablehloGatherOptions.StartIndexMap(i)) + else: + self.startIndexMap = stablehloGatherOptions.StartIndexMapAsNumpy() + self.indexVectorDim = stablehloGatherOptions.IndexVectorDim() + if not stablehloGatherOptions.SliceSizesIsNone(): + if np is None: + self.sliceSizes = [] + for i in range(stablehloGatherOptions.SliceSizesLength()): + self.sliceSizes.append(stablehloGatherOptions.SliceSizes(i)) + else: + self.sliceSizes = stablehloGatherOptions.SliceSizesAsNumpy() + self.indicesAreSorted = stablehloGatherOptions.IndicesAreSorted() + + # StablehloGatherOptionsT + def Pack(self, builder): + if self.offsetDims is not None: + if np is not None and type(self.offsetDims) is np.ndarray: + offsetDims = builder.CreateNumpyVector(self.offsetDims) + else: + StablehloGatherOptionsStartOffsetDimsVector(builder, len(self.offsetDims)) + for i in reversed(range(len(self.offsetDims))): + builder.PrependInt64(self.offsetDims[i]) + offsetDims = builder.EndVector() + if self.collapsedSliceDims is not None: + if np is not None and type(self.collapsedSliceDims) is np.ndarray: + collapsedSliceDims = builder.CreateNumpyVector(self.collapsedSliceDims) + else: + StablehloGatherOptionsStartCollapsedSliceDimsVector(builder, len(self.collapsedSliceDims)) + for i in reversed(range(len(self.collapsedSliceDims))): + builder.PrependInt64(self.collapsedSliceDims[i]) + collapsedSliceDims = builder.EndVector() + if self.startIndexMap is not None: + if np is not None and type(self.startIndexMap) is np.ndarray: + startIndexMap = builder.CreateNumpyVector(self.startIndexMap) + else: + StablehloGatherOptionsStartStartIndexMapVector(builder, len(self.startIndexMap)) + for i in reversed(range(len(self.startIndexMap))): + builder.PrependInt64(self.startIndexMap[i]) + startIndexMap = builder.EndVector() + if self.sliceSizes is not None: + if np is not None and type(self.sliceSizes) is np.ndarray: + sliceSizes = builder.CreateNumpyVector(self.sliceSizes) + else: + StablehloGatherOptionsStartSliceSizesVector(builder, len(self.sliceSizes)) + for i in reversed(range(len(self.sliceSizes))): + builder.PrependInt64(self.sliceSizes[i]) + sliceSizes = builder.EndVector() + StablehloGatherOptionsStart(builder) + if self.offsetDims is not None: + StablehloGatherOptionsAddOffsetDims(builder, offsetDims) + if self.collapsedSliceDims is not None: + StablehloGatherOptionsAddCollapsedSliceDims(builder, collapsedSliceDims) + if self.startIndexMap is not None: + StablehloGatherOptionsAddStartIndexMap(builder, startIndexMap) + StablehloGatherOptionsAddIndexVectorDim(builder, self.indexVectorDim) + if self.sliceSizes is not None: + StablehloGatherOptionsAddSliceSizes(builder, sliceSizes) + StablehloGatherOptionsAddIndicesAreSorted(builder, self.indicesAreSorted) + stablehloGatherOptions = StablehloGatherOptionsEnd(builder) + return stablehloGatherOptions + + +class StablehloTransposeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloTransposeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloTransposeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloTransposeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloTransposeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloTransposeOptions + def Permutation(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloTransposeOptions + def PermutationAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloTransposeOptions + def PermutationLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloTransposeOptions + def PermutationIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def StablehloTransposeOptionsStart(builder): + builder.StartObject(1) + +def StablehloTransposeOptionsAddPermutation(builder, permutation): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(permutation), 0) + +def StablehloTransposeOptionsStartPermutationVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloTransposeOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloTransposeOptionsT(object): + + # StablehloTransposeOptionsT + def __init__(self): + self.permutation = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloTransposeOptions = StablehloTransposeOptions() + stablehloTransposeOptions.Init(buf, pos) + return cls.InitFromObj(stablehloTransposeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloTransposeOptions): + x = StablehloTransposeOptionsT() + x._UnPack(stablehloTransposeOptions) + return x + + # StablehloTransposeOptionsT + def _UnPack(self, stablehloTransposeOptions): + if stablehloTransposeOptions is None: + return + if not stablehloTransposeOptions.PermutationIsNone(): + if np is None: + self.permutation = [] + for i in range(stablehloTransposeOptions.PermutationLength()): + self.permutation.append(stablehloTransposeOptions.Permutation(i)) + else: + self.permutation = stablehloTransposeOptions.PermutationAsNumpy() + + # StablehloTransposeOptionsT + def Pack(self, builder): + if self.permutation is not None: + if np is not None and type(self.permutation) is np.ndarray: + permutation = builder.CreateNumpyVector(self.permutation) + else: + StablehloTransposeOptionsStartPermutationVector(builder, len(self.permutation)) + for i in reversed(range(len(self.permutation))): + builder.PrependInt64(self.permutation[i]) + permutation = builder.EndVector() + StablehloTransposeOptionsStart(builder) + if self.permutation is not None: + StablehloTransposeOptionsAddPermutation(builder, permutation) + stablehloTransposeOptions = StablehloTransposeOptionsEnd(builder) + return stablehloTransposeOptions + + +class StablehloDotGeneralOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloDotGeneralOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloDotGeneralOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloDotGeneralOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloDotGeneralOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloDotGeneralOptions + def LhsBatchingDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloDotGeneralOptions + def LhsBatchingDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloDotGeneralOptions + def LhsBatchingDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloDotGeneralOptions + def LhsBatchingDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloDotGeneralOptions + def RhsBatchingDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloDotGeneralOptions + def RhsBatchingDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloDotGeneralOptions + def RhsBatchingDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloDotGeneralOptions + def RhsBatchingDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloDotGeneralOptions + def LhsContractingDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloDotGeneralOptions + def LhsContractingDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloDotGeneralOptions + def LhsContractingDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloDotGeneralOptions + def LhsContractingDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # StablehloDotGeneralOptions + def RhsContractingDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloDotGeneralOptions + def RhsContractingDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloDotGeneralOptions + def RhsContractingDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloDotGeneralOptions + def RhsContractingDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + + # StablehloDotGeneralOptions + def PrecisionConfig(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # StablehloDotGeneralOptions + def PrecisionConfigAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint32Flags, o) + return 0 + + # StablehloDotGeneralOptions + def PrecisionConfigLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloDotGeneralOptions + def PrecisionConfigIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + +def StablehloDotGeneralOptionsStart(builder): + builder.StartObject(5) + +def StablehloDotGeneralOptionsAddLhsBatchingDimensions(builder, lhsBatchingDimensions): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(lhsBatchingDimensions), 0) + +def StablehloDotGeneralOptionsStartLhsBatchingDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloDotGeneralOptionsAddRhsBatchingDimensions(builder, rhsBatchingDimensions): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(rhsBatchingDimensions), 0) + +def StablehloDotGeneralOptionsStartRhsBatchingDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloDotGeneralOptionsAddLhsContractingDimensions(builder, lhsContractingDimensions): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(lhsContractingDimensions), 0) + +def StablehloDotGeneralOptionsStartLhsContractingDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloDotGeneralOptionsAddRhsContractingDimensions(builder, rhsContractingDimensions): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(rhsContractingDimensions), 0) + +def StablehloDotGeneralOptionsStartRhsContractingDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloDotGeneralOptionsAddPrecisionConfig(builder, precisionConfig): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(precisionConfig), 0) + +def StablehloDotGeneralOptionsStartPrecisionConfigVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StablehloDotGeneralOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloDotGeneralOptionsT(object): + + # StablehloDotGeneralOptionsT + def __init__(self): + self.lhsBatchingDimensions = None # type: List[int] + self.rhsBatchingDimensions = None # type: List[int] + self.lhsContractingDimensions = None # type: List[int] + self.rhsContractingDimensions = None # type: List[int] + self.precisionConfig = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloDotGeneralOptions = StablehloDotGeneralOptions() + stablehloDotGeneralOptions.Init(buf, pos) + return cls.InitFromObj(stablehloDotGeneralOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloDotGeneralOptions): + x = StablehloDotGeneralOptionsT() + x._UnPack(stablehloDotGeneralOptions) + return x + + # StablehloDotGeneralOptionsT + def _UnPack(self, stablehloDotGeneralOptions): + if stablehloDotGeneralOptions is None: + return + if not stablehloDotGeneralOptions.LhsBatchingDimensionsIsNone(): + if np is None: + self.lhsBatchingDimensions = [] + for i in range(stablehloDotGeneralOptions.LhsBatchingDimensionsLength()): + self.lhsBatchingDimensions.append(stablehloDotGeneralOptions.LhsBatchingDimensions(i)) + else: + self.lhsBatchingDimensions = stablehloDotGeneralOptions.LhsBatchingDimensionsAsNumpy() + if not stablehloDotGeneralOptions.RhsBatchingDimensionsIsNone(): + if np is None: + self.rhsBatchingDimensions = [] + for i in range(stablehloDotGeneralOptions.RhsBatchingDimensionsLength()): + self.rhsBatchingDimensions.append(stablehloDotGeneralOptions.RhsBatchingDimensions(i)) + else: + self.rhsBatchingDimensions = stablehloDotGeneralOptions.RhsBatchingDimensionsAsNumpy() + if not stablehloDotGeneralOptions.LhsContractingDimensionsIsNone(): + if np is None: + self.lhsContractingDimensions = [] + for i in range(stablehloDotGeneralOptions.LhsContractingDimensionsLength()): + self.lhsContractingDimensions.append(stablehloDotGeneralOptions.LhsContractingDimensions(i)) + else: + self.lhsContractingDimensions = stablehloDotGeneralOptions.LhsContractingDimensionsAsNumpy() + if not stablehloDotGeneralOptions.RhsContractingDimensionsIsNone(): + if np is None: + self.rhsContractingDimensions = [] + for i in range(stablehloDotGeneralOptions.RhsContractingDimensionsLength()): + self.rhsContractingDimensions.append(stablehloDotGeneralOptions.RhsContractingDimensions(i)) + else: + self.rhsContractingDimensions = stablehloDotGeneralOptions.RhsContractingDimensionsAsNumpy() + if not stablehloDotGeneralOptions.PrecisionConfigIsNone(): + if np is None: + self.precisionConfig = [] + for i in range(stablehloDotGeneralOptions.PrecisionConfigLength()): + self.precisionConfig.append(stablehloDotGeneralOptions.PrecisionConfig(i)) + else: + self.precisionConfig = stablehloDotGeneralOptions.PrecisionConfigAsNumpy() + + # StablehloDotGeneralOptionsT + def Pack(self, builder): + if self.lhsBatchingDimensions is not None: + if np is not None and type(self.lhsBatchingDimensions) is np.ndarray: + lhsBatchingDimensions = builder.CreateNumpyVector(self.lhsBatchingDimensions) + else: + StablehloDotGeneralOptionsStartLhsBatchingDimensionsVector(builder, len(self.lhsBatchingDimensions)) + for i in reversed(range(len(self.lhsBatchingDimensions))): + builder.PrependInt64(self.lhsBatchingDimensions[i]) + lhsBatchingDimensions = builder.EndVector() + if self.rhsBatchingDimensions is not None: + if np is not None and type(self.rhsBatchingDimensions) is np.ndarray: + rhsBatchingDimensions = builder.CreateNumpyVector(self.rhsBatchingDimensions) + else: + StablehloDotGeneralOptionsStartRhsBatchingDimensionsVector(builder, len(self.rhsBatchingDimensions)) + for i in reversed(range(len(self.rhsBatchingDimensions))): + builder.PrependInt64(self.rhsBatchingDimensions[i]) + rhsBatchingDimensions = builder.EndVector() + if self.lhsContractingDimensions is not None: + if np is not None and type(self.lhsContractingDimensions) is np.ndarray: + lhsContractingDimensions = builder.CreateNumpyVector(self.lhsContractingDimensions) + else: + StablehloDotGeneralOptionsStartLhsContractingDimensionsVector(builder, len(self.lhsContractingDimensions)) + for i in reversed(range(len(self.lhsContractingDimensions))): + builder.PrependInt64(self.lhsContractingDimensions[i]) + lhsContractingDimensions = builder.EndVector() + if self.rhsContractingDimensions is not None: + if np is not None and type(self.rhsContractingDimensions) is np.ndarray: + rhsContractingDimensions = builder.CreateNumpyVector(self.rhsContractingDimensions) + else: + StablehloDotGeneralOptionsStartRhsContractingDimensionsVector(builder, len(self.rhsContractingDimensions)) + for i in reversed(range(len(self.rhsContractingDimensions))): + builder.PrependInt64(self.rhsContractingDimensions[i]) + rhsContractingDimensions = builder.EndVector() + if self.precisionConfig is not None: + if np is not None and type(self.precisionConfig) is np.ndarray: + precisionConfig = builder.CreateNumpyVector(self.precisionConfig) + else: + StablehloDotGeneralOptionsStartPrecisionConfigVector(builder, len(self.precisionConfig)) + for i in reversed(range(len(self.precisionConfig))): + builder.PrependUint32(self.precisionConfig[i]) + precisionConfig = builder.EndVector() + StablehloDotGeneralOptionsStart(builder) + if self.lhsBatchingDimensions is not None: + StablehloDotGeneralOptionsAddLhsBatchingDimensions(builder, lhsBatchingDimensions) + if self.rhsBatchingDimensions is not None: + StablehloDotGeneralOptionsAddRhsBatchingDimensions(builder, rhsBatchingDimensions) + if self.lhsContractingDimensions is not None: + StablehloDotGeneralOptionsAddLhsContractingDimensions(builder, lhsContractingDimensions) + if self.rhsContractingDimensions is not None: + StablehloDotGeneralOptionsAddRhsContractingDimensions(builder, rhsContractingDimensions) + if self.precisionConfig is not None: + StablehloDotGeneralOptionsAddPrecisionConfig(builder, precisionConfig) + stablehloDotGeneralOptions = StablehloDotGeneralOptionsEnd(builder) + return stablehloDotGeneralOptions + + +class StablehloReduceWindowOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloReduceWindowOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloReduceWindowOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloReduceWindowOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloReduceWindowOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloReduceWindowOptions + def WindowDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloReduceWindowOptions + def WindowDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloReduceWindowOptions + def WindowDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloReduceWindowOptions + def WindowDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloReduceWindowOptions + def WindowStrides(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloReduceWindowOptions + def WindowStridesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloReduceWindowOptions + def WindowStridesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloReduceWindowOptions + def WindowStridesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloReduceWindowOptions + def BaseDilations(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloReduceWindowOptions + def BaseDilationsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloReduceWindowOptions + def BaseDilationsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloReduceWindowOptions + def BaseDilationsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # StablehloReduceWindowOptions + def WindowDilations(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloReduceWindowOptions + def WindowDilationsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloReduceWindowOptions + def WindowDilationsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloReduceWindowOptions + def WindowDilationsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + + # StablehloReduceWindowOptions + def Padding(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloReduceWindowOptions + def PaddingAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloReduceWindowOptions + def PaddingLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloReduceWindowOptions + def PaddingIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # StablehloReduceWindowOptions + def BodySubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def StablehloReduceWindowOptionsStart(builder): + builder.StartObject(6) + +def StablehloReduceWindowOptionsAddWindowDimensions(builder, windowDimensions): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(windowDimensions), 0) + +def StablehloReduceWindowOptionsStartWindowDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloReduceWindowOptionsAddWindowStrides(builder, windowStrides): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(windowStrides), 0) + +def StablehloReduceWindowOptionsStartWindowStridesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloReduceWindowOptionsAddBaseDilations(builder, baseDilations): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(baseDilations), 0) + +def StablehloReduceWindowOptionsStartBaseDilationsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloReduceWindowOptionsAddWindowDilations(builder, windowDilations): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(windowDilations), 0) + +def StablehloReduceWindowOptionsStartWindowDilationsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloReduceWindowOptionsAddPadding(builder, padding): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(padding), 0) + +def StablehloReduceWindowOptionsStartPaddingVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloReduceWindowOptionsAddBodySubgraphIndex(builder, bodySubgraphIndex): + builder.PrependInt32Slot(5, bodySubgraphIndex, 0) + +def StablehloReduceWindowOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloReduceWindowOptionsT(object): + + # StablehloReduceWindowOptionsT + def __init__(self): + self.windowDimensions = None # type: List[int] + self.windowStrides = None # type: List[int] + self.baseDilations = None # type: List[int] + self.windowDilations = None # type: List[int] + self.padding = None # type: List[int] + self.bodySubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloReduceWindowOptions = StablehloReduceWindowOptions() + stablehloReduceWindowOptions.Init(buf, pos) + return cls.InitFromObj(stablehloReduceWindowOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloReduceWindowOptions): + x = StablehloReduceWindowOptionsT() + x._UnPack(stablehloReduceWindowOptions) + return x + + # StablehloReduceWindowOptionsT + def _UnPack(self, stablehloReduceWindowOptions): + if stablehloReduceWindowOptions is None: + return + if not stablehloReduceWindowOptions.WindowDimensionsIsNone(): + if np is None: + self.windowDimensions = [] + for i in range(stablehloReduceWindowOptions.WindowDimensionsLength()): + self.windowDimensions.append(stablehloReduceWindowOptions.WindowDimensions(i)) + else: + self.windowDimensions = stablehloReduceWindowOptions.WindowDimensionsAsNumpy() + if not stablehloReduceWindowOptions.WindowStridesIsNone(): + if np is None: + self.windowStrides = [] + for i in range(stablehloReduceWindowOptions.WindowStridesLength()): + self.windowStrides.append(stablehloReduceWindowOptions.WindowStrides(i)) + else: + self.windowStrides = stablehloReduceWindowOptions.WindowStridesAsNumpy() + if not stablehloReduceWindowOptions.BaseDilationsIsNone(): + if np is None: + self.baseDilations = [] + for i in range(stablehloReduceWindowOptions.BaseDilationsLength()): + self.baseDilations.append(stablehloReduceWindowOptions.BaseDilations(i)) + else: + self.baseDilations = stablehloReduceWindowOptions.BaseDilationsAsNumpy() + if not stablehloReduceWindowOptions.WindowDilationsIsNone(): + if np is None: + self.windowDilations = [] + for i in range(stablehloReduceWindowOptions.WindowDilationsLength()): + self.windowDilations.append(stablehloReduceWindowOptions.WindowDilations(i)) + else: + self.windowDilations = stablehloReduceWindowOptions.WindowDilationsAsNumpy() + if not stablehloReduceWindowOptions.PaddingIsNone(): + if np is None: + self.padding = [] + for i in range(stablehloReduceWindowOptions.PaddingLength()): + self.padding.append(stablehloReduceWindowOptions.Padding(i)) + else: + self.padding = stablehloReduceWindowOptions.PaddingAsNumpy() + self.bodySubgraphIndex = stablehloReduceWindowOptions.BodySubgraphIndex() + + # StablehloReduceWindowOptionsT + def Pack(self, builder): + if self.windowDimensions is not None: + if np is not None and type(self.windowDimensions) is np.ndarray: + windowDimensions = builder.CreateNumpyVector(self.windowDimensions) + else: + StablehloReduceWindowOptionsStartWindowDimensionsVector(builder, len(self.windowDimensions)) + for i in reversed(range(len(self.windowDimensions))): + builder.PrependInt64(self.windowDimensions[i]) + windowDimensions = builder.EndVector() + if self.windowStrides is not None: + if np is not None and type(self.windowStrides) is np.ndarray: + windowStrides = builder.CreateNumpyVector(self.windowStrides) + else: + StablehloReduceWindowOptionsStartWindowStridesVector(builder, len(self.windowStrides)) + for i in reversed(range(len(self.windowStrides))): + builder.PrependInt64(self.windowStrides[i]) + windowStrides = builder.EndVector() + if self.baseDilations is not None: + if np is not None and type(self.baseDilations) is np.ndarray: + baseDilations = builder.CreateNumpyVector(self.baseDilations) + else: + StablehloReduceWindowOptionsStartBaseDilationsVector(builder, len(self.baseDilations)) + for i in reversed(range(len(self.baseDilations))): + builder.PrependInt64(self.baseDilations[i]) + baseDilations = builder.EndVector() + if self.windowDilations is not None: + if np is not None and type(self.windowDilations) is np.ndarray: + windowDilations = builder.CreateNumpyVector(self.windowDilations) + else: + StablehloReduceWindowOptionsStartWindowDilationsVector(builder, len(self.windowDilations)) + for i in reversed(range(len(self.windowDilations))): + builder.PrependInt64(self.windowDilations[i]) + windowDilations = builder.EndVector() + if self.padding is not None: + if np is not None and type(self.padding) is np.ndarray: + padding = builder.CreateNumpyVector(self.padding) + else: + StablehloReduceWindowOptionsStartPaddingVector(builder, len(self.padding)) + for i in reversed(range(len(self.padding))): + builder.PrependInt64(self.padding[i]) + padding = builder.EndVector() + StablehloReduceWindowOptionsStart(builder) + if self.windowDimensions is not None: + StablehloReduceWindowOptionsAddWindowDimensions(builder, windowDimensions) + if self.windowStrides is not None: + StablehloReduceWindowOptionsAddWindowStrides(builder, windowStrides) + if self.baseDilations is not None: + StablehloReduceWindowOptionsAddBaseDilations(builder, baseDilations) + if self.windowDilations is not None: + StablehloReduceWindowOptionsAddWindowDilations(builder, windowDilations) + if self.padding is not None: + StablehloReduceWindowOptionsAddPadding(builder, padding) + StablehloReduceWindowOptionsAddBodySubgraphIndex(builder, self.bodySubgraphIndex) + stablehloReduceWindowOptions = StablehloReduceWindowOptionsEnd(builder) + return stablehloReduceWindowOptions + + +class StablehloWhileOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloWhileOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloWhileOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloWhileOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloWhileOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloWhileOptions + def CondSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StablehloWhileOptions + def BodySubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def StablehloWhileOptionsStart(builder): + builder.StartObject(2) + +def StablehloWhileOptionsAddCondSubgraphIndex(builder, condSubgraphIndex): + builder.PrependInt32Slot(0, condSubgraphIndex, 0) + +def StablehloWhileOptionsAddBodySubgraphIndex(builder, bodySubgraphIndex): + builder.PrependInt32Slot(1, bodySubgraphIndex, 0) + +def StablehloWhileOptionsEnd(builder): + return builder.EndObject() + + + +class StablehloWhileOptionsT(object): + + # StablehloWhileOptionsT + def __init__(self): + self.condSubgraphIndex = 0 # type: int + self.bodySubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloWhileOptions = StablehloWhileOptions() + stablehloWhileOptions.Init(buf, pos) + return cls.InitFromObj(stablehloWhileOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloWhileOptions): + x = StablehloWhileOptionsT() + x._UnPack(stablehloWhileOptions) + return x + + # StablehloWhileOptionsT + def _UnPack(self, stablehloWhileOptions): + if stablehloWhileOptions is None: + return + self.condSubgraphIndex = stablehloWhileOptions.CondSubgraphIndex() + self.bodySubgraphIndex = stablehloWhileOptions.BodySubgraphIndex() + + # StablehloWhileOptionsT + def Pack(self, builder): + StablehloWhileOptionsStart(builder) + StablehloWhileOptionsAddCondSubgraphIndex(builder, self.condSubgraphIndex) + StablehloWhileOptionsAddBodySubgraphIndex(builder, self.bodySubgraphIndex) + stablehloWhileOptions = StablehloWhileOptionsEnd(builder) + return stablehloWhileOptions + + +class StablehloSortOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloSortOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloSortOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloSortOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloSortOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloSortOptions + def Dimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloSortOptions + def IsStable(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # StablehloSortOptions + def ComparatorSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def StablehloSortOptionsStart(builder): + builder.StartObject(3) + +def StablehloSortOptionsAddDimension(builder, dimension): + builder.PrependInt64Slot(0, dimension, 0) + +def StablehloSortOptionsAddIsStable(builder, isStable): + builder.PrependBoolSlot(1, isStable, 0) + +def StablehloSortOptionsAddComparatorSubgraphIndex(builder, comparatorSubgraphIndex): + builder.PrependInt32Slot(2, comparatorSubgraphIndex, 0) + +def StablehloSortOptionsEnd(builder): + return builder.EndObject() + + + +class StablehloSortOptionsT(object): + + # StablehloSortOptionsT + def __init__(self): + self.dimension = 0 # type: int + self.isStable = False # type: bool + self.comparatorSubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloSortOptions = StablehloSortOptions() + stablehloSortOptions.Init(buf, pos) + return cls.InitFromObj(stablehloSortOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloSortOptions): + x = StablehloSortOptionsT() + x._UnPack(stablehloSortOptions) + return x + + # StablehloSortOptionsT + def _UnPack(self, stablehloSortOptions): + if stablehloSortOptions is None: + return + self.dimension = stablehloSortOptions.Dimension() + self.isStable = stablehloSortOptions.IsStable() + self.comparatorSubgraphIndex = stablehloSortOptions.ComparatorSubgraphIndex() + + # StablehloSortOptionsT + def Pack(self, builder): + StablehloSortOptionsStart(builder) + StablehloSortOptionsAddDimension(builder, self.dimension) + StablehloSortOptionsAddIsStable(builder, self.isStable) + StablehloSortOptionsAddComparatorSubgraphIndex(builder, self.comparatorSubgraphIndex) + stablehloSortOptions = StablehloSortOptionsEnd(builder) + return stablehloSortOptions + + +class StablehloConcatenateOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloConcatenateOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloConcatenateOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloConcatenateOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloConcatenateOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloConcatenateOptions + def Dimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + +def StablehloConcatenateOptionsStart(builder): + builder.StartObject(1) + +def StablehloConcatenateOptionsAddDimension(builder, dimension): + builder.PrependInt64Slot(0, dimension, 0) + +def StablehloConcatenateOptionsEnd(builder): + return builder.EndObject() + + + +class StablehloConcatenateOptionsT(object): + + # StablehloConcatenateOptionsT + def __init__(self): + self.dimension = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloConcatenateOptions = StablehloConcatenateOptions() + stablehloConcatenateOptions.Init(buf, pos) + return cls.InitFromObj(stablehloConcatenateOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloConcatenateOptions): + x = StablehloConcatenateOptionsT() + x._UnPack(stablehloConcatenateOptions) + return x + + # StablehloConcatenateOptionsT + def _UnPack(self, stablehloConcatenateOptions): + if stablehloConcatenateOptions is None: + return + self.dimension = stablehloConcatenateOptions.Dimension() + + # StablehloConcatenateOptionsT + def Pack(self, builder): + StablehloConcatenateOptionsStart(builder) + StablehloConcatenateOptionsAddDimension(builder, self.dimension) + stablehloConcatenateOptions = StablehloConcatenateOptionsEnd(builder) + return stablehloConcatenateOptions + + +class StablehloBroadcastInDimOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloBroadcastInDimOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloBroadcastInDimOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloBroadcastInDimOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloBroadcastInDimOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloBroadcastInDimOptions + def BroadcastDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloBroadcastInDimOptions + def BroadcastDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloBroadcastInDimOptions + def BroadcastDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloBroadcastInDimOptions + def BroadcastDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def StablehloBroadcastInDimOptionsStart(builder): + builder.StartObject(1) + +def StablehloBroadcastInDimOptionsAddBroadcastDimensions(builder, broadcastDimensions): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(broadcastDimensions), 0) + +def StablehloBroadcastInDimOptionsStartBroadcastDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloBroadcastInDimOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloBroadcastInDimOptionsT(object): + + # StablehloBroadcastInDimOptionsT + def __init__(self): + self.broadcastDimensions = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloBroadcastInDimOptions = StablehloBroadcastInDimOptions() + stablehloBroadcastInDimOptions.Init(buf, pos) + return cls.InitFromObj(stablehloBroadcastInDimOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloBroadcastInDimOptions): + x = StablehloBroadcastInDimOptionsT() + x._UnPack(stablehloBroadcastInDimOptions) + return x + + # StablehloBroadcastInDimOptionsT + def _UnPack(self, stablehloBroadcastInDimOptions): + if stablehloBroadcastInDimOptions is None: + return + if not stablehloBroadcastInDimOptions.BroadcastDimensionsIsNone(): + if np is None: + self.broadcastDimensions = [] + for i in range(stablehloBroadcastInDimOptions.BroadcastDimensionsLength()): + self.broadcastDimensions.append(stablehloBroadcastInDimOptions.BroadcastDimensions(i)) + else: + self.broadcastDimensions = stablehloBroadcastInDimOptions.BroadcastDimensionsAsNumpy() + + # StablehloBroadcastInDimOptionsT + def Pack(self, builder): + if self.broadcastDimensions is not None: + if np is not None and type(self.broadcastDimensions) is np.ndarray: + broadcastDimensions = builder.CreateNumpyVector(self.broadcastDimensions) + else: + StablehloBroadcastInDimOptionsStartBroadcastDimensionsVector(builder, len(self.broadcastDimensions)) + for i in reversed(range(len(self.broadcastDimensions))): + builder.PrependInt64(self.broadcastDimensions[i]) + broadcastDimensions = builder.EndVector() + StablehloBroadcastInDimOptionsStart(builder) + if self.broadcastDimensions is not None: + StablehloBroadcastInDimOptionsAddBroadcastDimensions(builder, broadcastDimensions) + stablehloBroadcastInDimOptions = StablehloBroadcastInDimOptionsEnd(builder) + return stablehloBroadcastInDimOptions + + +class StablehloCompareOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloCompareOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloCompareOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloCompareOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloCompareOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloCompareOptions + def ComparisonDirection(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # StablehloCompareOptions + def CompareType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def StablehloCompareOptionsStart(builder): + builder.StartObject(2) + +def StablehloCompareOptionsAddComparisonDirection(builder, comparisonDirection): + builder.PrependUint32Slot(0, comparisonDirection, 0) + +def StablehloCompareOptionsAddCompareType(builder, compareType): + builder.PrependUint32Slot(1, compareType, 0) + +def StablehloCompareOptionsEnd(builder): + return builder.EndObject() + + + +class StablehloCompareOptionsT(object): + + # StablehloCompareOptionsT + def __init__(self): + self.comparisonDirection = 0 # type: int + self.compareType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloCompareOptions = StablehloCompareOptions() + stablehloCompareOptions.Init(buf, pos) + return cls.InitFromObj(stablehloCompareOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloCompareOptions): + x = StablehloCompareOptionsT() + x._UnPack(stablehloCompareOptions) + return x + + # StablehloCompareOptionsT + def _UnPack(self, stablehloCompareOptions): + if stablehloCompareOptions is None: + return + self.comparisonDirection = stablehloCompareOptions.ComparisonDirection() + self.compareType = stablehloCompareOptions.CompareType() + + # StablehloCompareOptionsT + def Pack(self, builder): + StablehloCompareOptionsStart(builder) + StablehloCompareOptionsAddComparisonDirection(builder, self.comparisonDirection) + StablehloCompareOptionsAddCompareType(builder, self.compareType) + stablehloCompareOptions = StablehloCompareOptionsEnd(builder) + return stablehloCompareOptions + + +class StablehloDynamicSliceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloDynamicSliceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloDynamicSliceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloDynamicSliceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloDynamicSliceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloDynamicSliceOptions + def SliceSizes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloDynamicSliceOptions + def SliceSizesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloDynamicSliceOptions + def SliceSizesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloDynamicSliceOptions + def SliceSizesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def StablehloDynamicSliceOptionsStart(builder): + builder.StartObject(1) + +def StablehloDynamicSliceOptionsAddSliceSizes(builder, sliceSizes): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(sliceSizes), 0) + +def StablehloDynamicSliceOptionsStartSliceSizesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloDynamicSliceOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloDynamicSliceOptionsT(object): + + # StablehloDynamicSliceOptionsT + def __init__(self): + self.sliceSizes = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloDynamicSliceOptions = StablehloDynamicSliceOptions() + stablehloDynamicSliceOptions.Init(buf, pos) + return cls.InitFromObj(stablehloDynamicSliceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloDynamicSliceOptions): + x = StablehloDynamicSliceOptionsT() + x._UnPack(stablehloDynamicSliceOptions) + return x + + # StablehloDynamicSliceOptionsT + def _UnPack(self, stablehloDynamicSliceOptions): + if stablehloDynamicSliceOptions is None: + return + if not stablehloDynamicSliceOptions.SliceSizesIsNone(): + if np is None: + self.sliceSizes = [] + for i in range(stablehloDynamicSliceOptions.SliceSizesLength()): + self.sliceSizes.append(stablehloDynamicSliceOptions.SliceSizes(i)) + else: + self.sliceSizes = stablehloDynamicSliceOptions.SliceSizesAsNumpy() + + # StablehloDynamicSliceOptionsT + def Pack(self, builder): + if self.sliceSizes is not None: + if np is not None and type(self.sliceSizes) is np.ndarray: + sliceSizes = builder.CreateNumpyVector(self.sliceSizes) + else: + StablehloDynamicSliceOptionsStartSliceSizesVector(builder, len(self.sliceSizes)) + for i in reversed(range(len(self.sliceSizes))): + builder.PrependInt64(self.sliceSizes[i]) + sliceSizes = builder.EndVector() + StablehloDynamicSliceOptionsStart(builder) + if self.sliceSizes is not None: + StablehloDynamicSliceOptionsAddSliceSizes(builder, sliceSizes) + stablehloDynamicSliceOptions = StablehloDynamicSliceOptionsEnd(builder) + return stablehloDynamicSliceOptions + + +class StablehloPadOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloPadOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloPadOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloPadOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloPadOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloPadOptions + def EdgePaddingLow(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloPadOptions + def EdgePaddingLowAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloPadOptions + def EdgePaddingLowLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloPadOptions + def EdgePaddingLowIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloPadOptions + def EdgePaddingHigh(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloPadOptions + def EdgePaddingHighAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloPadOptions + def EdgePaddingHighLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloPadOptions + def EdgePaddingHighIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloPadOptions + def InteriorPadding(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloPadOptions + def InteriorPaddingAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloPadOptions + def InteriorPaddingLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloPadOptions + def InteriorPaddingIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def StablehloPadOptionsStart(builder): + builder.StartObject(3) + +def StablehloPadOptionsAddEdgePaddingLow(builder, edgePaddingLow): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(edgePaddingLow), 0) + +def StablehloPadOptionsStartEdgePaddingLowVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloPadOptionsAddEdgePaddingHigh(builder, edgePaddingHigh): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(edgePaddingHigh), 0) + +def StablehloPadOptionsStartEdgePaddingHighVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloPadOptionsAddInteriorPadding(builder, interiorPadding): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(interiorPadding), 0) + +def StablehloPadOptionsStartInteriorPaddingVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloPadOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloPadOptionsT(object): + + # StablehloPadOptionsT + def __init__(self): + self.edgePaddingLow = None # type: List[int] + self.edgePaddingHigh = None # type: List[int] + self.interiorPadding = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloPadOptions = StablehloPadOptions() + stablehloPadOptions.Init(buf, pos) + return cls.InitFromObj(stablehloPadOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloPadOptions): + x = StablehloPadOptionsT() + x._UnPack(stablehloPadOptions) + return x + + # StablehloPadOptionsT + def _UnPack(self, stablehloPadOptions): + if stablehloPadOptions is None: + return + if not stablehloPadOptions.EdgePaddingLowIsNone(): + if np is None: + self.edgePaddingLow = [] + for i in range(stablehloPadOptions.EdgePaddingLowLength()): + self.edgePaddingLow.append(stablehloPadOptions.EdgePaddingLow(i)) + else: + self.edgePaddingLow = stablehloPadOptions.EdgePaddingLowAsNumpy() + if not stablehloPadOptions.EdgePaddingHighIsNone(): + if np is None: + self.edgePaddingHigh = [] + for i in range(stablehloPadOptions.EdgePaddingHighLength()): + self.edgePaddingHigh.append(stablehloPadOptions.EdgePaddingHigh(i)) + else: + self.edgePaddingHigh = stablehloPadOptions.EdgePaddingHighAsNumpy() + if not stablehloPadOptions.InteriorPaddingIsNone(): + if np is None: + self.interiorPadding = [] + for i in range(stablehloPadOptions.InteriorPaddingLength()): + self.interiorPadding.append(stablehloPadOptions.InteriorPadding(i)) + else: + self.interiorPadding = stablehloPadOptions.InteriorPaddingAsNumpy() + + # StablehloPadOptionsT + def Pack(self, builder): + if self.edgePaddingLow is not None: + if np is not None and type(self.edgePaddingLow) is np.ndarray: + edgePaddingLow = builder.CreateNumpyVector(self.edgePaddingLow) + else: + StablehloPadOptionsStartEdgePaddingLowVector(builder, len(self.edgePaddingLow)) + for i in reversed(range(len(self.edgePaddingLow))): + builder.PrependInt64(self.edgePaddingLow[i]) + edgePaddingLow = builder.EndVector() + if self.edgePaddingHigh is not None: + if np is not None and type(self.edgePaddingHigh) is np.ndarray: + edgePaddingHigh = builder.CreateNumpyVector(self.edgePaddingHigh) + else: + StablehloPadOptionsStartEdgePaddingHighVector(builder, len(self.edgePaddingHigh)) + for i in reversed(range(len(self.edgePaddingHigh))): + builder.PrependInt64(self.edgePaddingHigh[i]) + edgePaddingHigh = builder.EndVector() + if self.interiorPadding is not None: + if np is not None and type(self.interiorPadding) is np.ndarray: + interiorPadding = builder.CreateNumpyVector(self.interiorPadding) + else: + StablehloPadOptionsStartInteriorPaddingVector(builder, len(self.interiorPadding)) + for i in reversed(range(len(self.interiorPadding))): + builder.PrependInt64(self.interiorPadding[i]) + interiorPadding = builder.EndVector() + StablehloPadOptionsStart(builder) + if self.edgePaddingLow is not None: + StablehloPadOptionsAddEdgePaddingLow(builder, edgePaddingLow) + if self.edgePaddingHigh is not None: + StablehloPadOptionsAddEdgePaddingHigh(builder, edgePaddingHigh) + if self.interiorPadding is not None: + StablehloPadOptionsAddInteriorPadding(builder, interiorPadding) + stablehloPadOptions = StablehloPadOptionsEnd(builder) + return stablehloPadOptions + + +class StablehloIotaOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloIotaOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloIotaOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloIotaOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloIotaOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloIotaOptions + def IotaDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + +def StablehloIotaOptionsStart(builder): + builder.StartObject(1) + +def StablehloIotaOptionsAddIotaDimension(builder, iotaDimension): + builder.PrependInt64Slot(0, iotaDimension, 0) + +def StablehloIotaOptionsEnd(builder): + return builder.EndObject() + + + +class StablehloIotaOptionsT(object): + + # StablehloIotaOptionsT + def __init__(self): + self.iotaDimension = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloIotaOptions = StablehloIotaOptions() + stablehloIotaOptions.Init(buf, pos) + return cls.InitFromObj(stablehloIotaOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloIotaOptions): + x = StablehloIotaOptionsT() + x._UnPack(stablehloIotaOptions) + return x + + # StablehloIotaOptionsT + def _UnPack(self, stablehloIotaOptions): + if stablehloIotaOptions is None: + return + self.iotaDimension = stablehloIotaOptions.IotaDimension() + + # StablehloIotaOptionsT + def Pack(self, builder): + StablehloIotaOptionsStart(builder) + StablehloIotaOptionsAddIotaDimension(builder, self.iotaDimension) + stablehloIotaOptions = StablehloIotaOptionsEnd(builder) + return stablehloIotaOptions + + +class StablehloCustomCallOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloCustomCallOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloCustomCallOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloCustomCallOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloCustomCallOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloCustomCallOptions + def CallTargetName(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # StablehloCustomCallOptions + def HasSideEffect(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # StablehloCustomCallOptions + def BackendConfig(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # StablehloCustomCallOptions + def ApiVersion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StablehloCustomCallOptions + def CalledComputations(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # StablehloCustomCallOptions + def CalledComputationsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # StablehloCustomCallOptions + def CalledComputationsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloCustomCallOptions + def CalledComputationsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # StablehloCustomCallOptions + def CustomAttributes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # StablehloCustomCallOptions + def CustomAttributesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # StablehloCustomCallOptions + def CustomAttributesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloCustomCallOptions + def CustomAttributesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + +def StablehloCustomCallOptionsStart(builder): + builder.StartObject(6) + +def StablehloCustomCallOptionsAddCallTargetName(builder, callTargetName): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(callTargetName), 0) + +def StablehloCustomCallOptionsAddHasSideEffect(builder, hasSideEffect): + builder.PrependBoolSlot(1, hasSideEffect, 0) + +def StablehloCustomCallOptionsAddBackendConfig(builder, backendConfig): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(backendConfig), 0) + +def StablehloCustomCallOptionsAddApiVersion(builder, apiVersion): + builder.PrependInt32Slot(3, apiVersion, 0) + +def StablehloCustomCallOptionsAddCalledComputations(builder, calledComputations): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(calledComputations), 0) + +def StablehloCustomCallOptionsStartCalledComputationsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StablehloCustomCallOptionsAddCustomAttributes(builder, customAttributes): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(customAttributes), 0) + +def StablehloCustomCallOptionsStartCustomAttributesVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StablehloCustomCallOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloCustomCallOptionsT(object): + + # StablehloCustomCallOptionsT + def __init__(self): + self.callTargetName = None # type: str + self.hasSideEffect = False # type: bool + self.backendConfig = None # type: str + self.apiVersion = 0 # type: int + self.calledComputations = None # type: List[int] + self.customAttributes = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloCustomCallOptions = StablehloCustomCallOptions() + stablehloCustomCallOptions.Init(buf, pos) + return cls.InitFromObj(stablehloCustomCallOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloCustomCallOptions): + x = StablehloCustomCallOptionsT() + x._UnPack(stablehloCustomCallOptions) + return x + + # StablehloCustomCallOptionsT + def _UnPack(self, stablehloCustomCallOptions): + if stablehloCustomCallOptions is None: + return + self.callTargetName = stablehloCustomCallOptions.CallTargetName() + self.hasSideEffect = stablehloCustomCallOptions.HasSideEffect() + self.backendConfig = stablehloCustomCallOptions.BackendConfig() + self.apiVersion = stablehloCustomCallOptions.ApiVersion() + if not stablehloCustomCallOptions.CalledComputationsIsNone(): + if np is None: + self.calledComputations = [] + for i in range(stablehloCustomCallOptions.CalledComputationsLength()): + self.calledComputations.append(stablehloCustomCallOptions.CalledComputations(i)) + else: + self.calledComputations = stablehloCustomCallOptions.CalledComputationsAsNumpy() + if not stablehloCustomCallOptions.CustomAttributesIsNone(): + if np is None: + self.customAttributes = [] + for i in range(stablehloCustomCallOptions.CustomAttributesLength()): + self.customAttributes.append(stablehloCustomCallOptions.CustomAttributes(i)) + else: + self.customAttributes = stablehloCustomCallOptions.CustomAttributesAsNumpy() + + # StablehloCustomCallOptionsT + def Pack(self, builder): + if self.callTargetName is not None: + callTargetName = builder.CreateString(self.callTargetName) + if self.backendConfig is not None: + backendConfig = builder.CreateString(self.backendConfig) + if self.calledComputations is not None: + if np is not None and type(self.calledComputations) is np.ndarray: + calledComputations = builder.CreateNumpyVector(self.calledComputations) + else: + StablehloCustomCallOptionsStartCalledComputationsVector(builder, len(self.calledComputations)) + for i in reversed(range(len(self.calledComputations))): + builder.PrependInt32(self.calledComputations[i]) + calledComputations = builder.EndVector() + if self.customAttributes is not None: + if np is not None and type(self.customAttributes) is np.ndarray: + customAttributes = builder.CreateNumpyVector(self.customAttributes) + else: + StablehloCustomCallOptionsStartCustomAttributesVector(builder, len(self.customAttributes)) + for i in reversed(range(len(self.customAttributes))): + builder.PrependUint8(self.customAttributes[i]) + customAttributes = builder.EndVector() + StablehloCustomCallOptionsStart(builder) + if self.callTargetName is not None: + StablehloCustomCallOptionsAddCallTargetName(builder, callTargetName) + StablehloCustomCallOptionsAddHasSideEffect(builder, self.hasSideEffect) + if self.backendConfig is not None: + StablehloCustomCallOptionsAddBackendConfig(builder, backendConfig) + StablehloCustomCallOptionsAddApiVersion(builder, self.apiVersion) + if self.calledComputations is not None: + StablehloCustomCallOptionsAddCalledComputations(builder, calledComputations) + if self.customAttributes is not None: + StablehloCustomCallOptionsAddCustomAttributes(builder, customAttributes) + stablehloCustomCallOptions = StablehloCustomCallOptionsEnd(builder) + return stablehloCustomCallOptions + + +class StablehloReduceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloReduceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloReduceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloReduceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloReduceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloReduceOptions + def Dimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloReduceOptions + def DimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloReduceOptions + def DimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloReduceOptions + def DimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloReduceOptions + def BodySubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def StablehloReduceOptionsStart(builder): + builder.StartObject(2) + +def StablehloReduceOptionsAddDimensions(builder, dimensions): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(dimensions), 0) + +def StablehloReduceOptionsStartDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloReduceOptionsAddBodySubgraphIndex(builder, bodySubgraphIndex): + builder.PrependInt32Slot(1, bodySubgraphIndex, 0) + +def StablehloReduceOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloReduceOptionsT(object): + + # StablehloReduceOptionsT + def __init__(self): + self.dimensions = None # type: List[int] + self.bodySubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloReduceOptions = StablehloReduceOptions() + stablehloReduceOptions.Init(buf, pos) + return cls.InitFromObj(stablehloReduceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloReduceOptions): + x = StablehloReduceOptionsT() + x._UnPack(stablehloReduceOptions) + return x + + # StablehloReduceOptionsT + def _UnPack(self, stablehloReduceOptions): + if stablehloReduceOptions is None: + return + if not stablehloReduceOptions.DimensionsIsNone(): + if np is None: + self.dimensions = [] + for i in range(stablehloReduceOptions.DimensionsLength()): + self.dimensions.append(stablehloReduceOptions.Dimensions(i)) + else: + self.dimensions = stablehloReduceOptions.DimensionsAsNumpy() + self.bodySubgraphIndex = stablehloReduceOptions.BodySubgraphIndex() + + # StablehloReduceOptionsT + def Pack(self, builder): + if self.dimensions is not None: + if np is not None and type(self.dimensions) is np.ndarray: + dimensions = builder.CreateNumpyVector(self.dimensions) + else: + StablehloReduceOptionsStartDimensionsVector(builder, len(self.dimensions)) + for i in reversed(range(len(self.dimensions))): + builder.PrependInt64(self.dimensions[i]) + dimensions = builder.EndVector() + StablehloReduceOptionsStart(builder) + if self.dimensions is not None: + StablehloReduceOptionsAddDimensions(builder, dimensions) + StablehloReduceOptionsAddBodySubgraphIndex(builder, self.bodySubgraphIndex) + stablehloReduceOptions = StablehloReduceOptionsEnd(builder) + return stablehloReduceOptions + + +class StablehloSliceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloSliceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloSliceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloSliceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloSliceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloSliceOptions + def StartIndices(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloSliceOptions + def StartIndicesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloSliceOptions + def StartIndicesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloSliceOptions + def StartIndicesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloSliceOptions + def LimitIndices(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloSliceOptions + def LimitIndicesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloSliceOptions + def LimitIndicesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloSliceOptions + def LimitIndicesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloSliceOptions + def Strides(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloSliceOptions + def StridesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloSliceOptions + def StridesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloSliceOptions + def StridesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def StablehloSliceOptionsStart(builder): + builder.StartObject(3) + +def StablehloSliceOptionsAddStartIndices(builder, startIndices): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(startIndices), 0) + +def StablehloSliceOptionsStartStartIndicesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloSliceOptionsAddLimitIndices(builder, limitIndices): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(limitIndices), 0) + +def StablehloSliceOptionsStartLimitIndicesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloSliceOptionsAddStrides(builder, strides): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(strides), 0) + +def StablehloSliceOptionsStartStridesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloSliceOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloSliceOptionsT(object): + + # StablehloSliceOptionsT + def __init__(self): + self.startIndices = None # type: List[int] + self.limitIndices = None # type: List[int] + self.strides = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloSliceOptions = StablehloSliceOptions() + stablehloSliceOptions.Init(buf, pos) + return cls.InitFromObj(stablehloSliceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloSliceOptions): + x = StablehloSliceOptionsT() + x._UnPack(stablehloSliceOptions) + return x + + # StablehloSliceOptionsT + def _UnPack(self, stablehloSliceOptions): + if stablehloSliceOptions is None: + return + if not stablehloSliceOptions.StartIndicesIsNone(): + if np is None: + self.startIndices = [] + for i in range(stablehloSliceOptions.StartIndicesLength()): + self.startIndices.append(stablehloSliceOptions.StartIndices(i)) + else: + self.startIndices = stablehloSliceOptions.StartIndicesAsNumpy() + if not stablehloSliceOptions.LimitIndicesIsNone(): + if np is None: + self.limitIndices = [] + for i in range(stablehloSliceOptions.LimitIndicesLength()): + self.limitIndices.append(stablehloSliceOptions.LimitIndices(i)) + else: + self.limitIndices = stablehloSliceOptions.LimitIndicesAsNumpy() + if not stablehloSliceOptions.StridesIsNone(): + if np is None: + self.strides = [] + for i in range(stablehloSliceOptions.StridesLength()): + self.strides.append(stablehloSliceOptions.Strides(i)) + else: + self.strides = stablehloSliceOptions.StridesAsNumpy() + + # StablehloSliceOptionsT + def Pack(self, builder): + if self.startIndices is not None: + if np is not None and type(self.startIndices) is np.ndarray: + startIndices = builder.CreateNumpyVector(self.startIndices) + else: + StablehloSliceOptionsStartStartIndicesVector(builder, len(self.startIndices)) + for i in reversed(range(len(self.startIndices))): + builder.PrependInt64(self.startIndices[i]) + startIndices = builder.EndVector() + if self.limitIndices is not None: + if np is not None and type(self.limitIndices) is np.ndarray: + limitIndices = builder.CreateNumpyVector(self.limitIndices) + else: + StablehloSliceOptionsStartLimitIndicesVector(builder, len(self.limitIndices)) + for i in reversed(range(len(self.limitIndices))): + builder.PrependInt64(self.limitIndices[i]) + limitIndices = builder.EndVector() + if self.strides is not None: + if np is not None and type(self.strides) is np.ndarray: + strides = builder.CreateNumpyVector(self.strides) + else: + StablehloSliceOptionsStartStridesVector(builder, len(self.strides)) + for i in reversed(range(len(self.strides))): + builder.PrependInt64(self.strides[i]) + strides = builder.EndVector() + StablehloSliceOptionsStart(builder) + if self.startIndices is not None: + StablehloSliceOptionsAddStartIndices(builder, startIndices) + if self.limitIndices is not None: + StablehloSliceOptionsAddLimitIndices(builder, limitIndices) + if self.strides is not None: + StablehloSliceOptionsAddStrides(builder, strides) + stablehloSliceOptions = StablehloSliceOptionsEnd(builder) + return stablehloSliceOptions + + +class StablehloConvolutionOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloConvolutionOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloConvolutionOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloConvolutionOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloConvolutionOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloConvolutionOptions + def WindowStrides(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def WindowStridesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def WindowStridesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def WindowStridesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # StablehloConvolutionOptions + def Padding(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def PaddingAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def PaddingLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def PaddingIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloConvolutionOptions + def LhsDilation(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def LhsDilationAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def LhsDilationLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def LhsDilationIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # StablehloConvolutionOptions + def RhsDilation(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def RhsDilationAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def RhsDilationLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def RhsDilationIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + + # StablehloConvolutionOptions + def WindowReversal(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.BoolFlags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # StablehloConvolutionOptions + def WindowReversalAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.BoolFlags, o) + return 0 + + # StablehloConvolutionOptions + def WindowReversalLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def WindowReversalIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # StablehloConvolutionOptions + def InputBatchDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def InputFeatureDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def InputSpatialDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def InputSpatialDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def InputSpatialDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def InputSpatialDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + return o == 0 + + # StablehloConvolutionOptions + def KernelInputFeatureDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def KernelOutputFeatureDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def KernelSpatialDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def KernelSpatialDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def KernelSpatialDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def KernelSpatialDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # StablehloConvolutionOptions + def OutputBatchDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def OutputFeatureDimension(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def OutputSpatialDimensions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloConvolutionOptions + def OutputSpatialDimensionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloConvolutionOptions + def OutputSpatialDimensionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def OutputSpatialDimensionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + return o == 0 + + # StablehloConvolutionOptions + def FeatureGroupCount(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(32)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def BatchGroupCount(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(34)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloConvolutionOptions + def PrecisionConfig(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # StablehloConvolutionOptions + def PrecisionConfigAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint32Flags, o) + return 0 + + # StablehloConvolutionOptions + def PrecisionConfigLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloConvolutionOptions + def PrecisionConfigIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + return o == 0 + +def StablehloConvolutionOptionsStart(builder): + builder.StartObject(17) + +def StablehloConvolutionOptionsAddWindowStrides(builder, windowStrides): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(windowStrides), 0) + +def StablehloConvolutionOptionsStartWindowStridesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddPadding(builder, padding): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(padding), 0) + +def StablehloConvolutionOptionsStartPaddingVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddLhsDilation(builder, lhsDilation): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(lhsDilation), 0) + +def StablehloConvolutionOptionsStartLhsDilationVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddRhsDilation(builder, rhsDilation): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(rhsDilation), 0) + +def StablehloConvolutionOptionsStartRhsDilationVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddWindowReversal(builder, windowReversal): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(windowReversal), 0) + +def StablehloConvolutionOptionsStartWindowReversalVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StablehloConvolutionOptionsAddInputBatchDimension(builder, inputBatchDimension): + builder.PrependInt64Slot(5, inputBatchDimension, 0) + +def StablehloConvolutionOptionsAddInputFeatureDimension(builder, inputFeatureDimension): + builder.PrependInt64Slot(6, inputFeatureDimension, 0) + +def StablehloConvolutionOptionsAddInputSpatialDimensions(builder, inputSpatialDimensions): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(inputSpatialDimensions), 0) + +def StablehloConvolutionOptionsStartInputSpatialDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddKernelInputFeatureDimension(builder, kernelInputFeatureDimension): + builder.PrependInt64Slot(8, kernelInputFeatureDimension, 0) + +def StablehloConvolutionOptionsAddKernelOutputFeatureDimension(builder, kernelOutputFeatureDimension): + builder.PrependInt64Slot(9, kernelOutputFeatureDimension, 0) + +def StablehloConvolutionOptionsAddKernelSpatialDimensions(builder, kernelSpatialDimensions): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(kernelSpatialDimensions), 0) + +def StablehloConvolutionOptionsStartKernelSpatialDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddOutputBatchDimension(builder, outputBatchDimension): + builder.PrependInt64Slot(11, outputBatchDimension, 0) + +def StablehloConvolutionOptionsAddOutputFeatureDimension(builder, outputFeatureDimension): + builder.PrependInt64Slot(12, outputFeatureDimension, 0) + +def StablehloConvolutionOptionsAddOutputSpatialDimensions(builder, outputSpatialDimensions): + builder.PrependUOffsetTRelativeSlot(13, flatbuffers.number_types.UOffsetTFlags.py_type(outputSpatialDimensions), 0) + +def StablehloConvolutionOptionsStartOutputSpatialDimensionsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloConvolutionOptionsAddFeatureGroupCount(builder, featureGroupCount): + builder.PrependInt64Slot(14, featureGroupCount, 0) + +def StablehloConvolutionOptionsAddBatchGroupCount(builder, batchGroupCount): + builder.PrependInt64Slot(15, batchGroupCount, 0) + +def StablehloConvolutionOptionsAddPrecisionConfig(builder, precisionConfig): + builder.PrependUOffsetTRelativeSlot(16, flatbuffers.number_types.UOffsetTFlags.py_type(precisionConfig), 0) + +def StablehloConvolutionOptionsStartPrecisionConfigVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StablehloConvolutionOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloConvolutionOptionsT(object): + + # StablehloConvolutionOptionsT + def __init__(self): + self.windowStrides = None # type: List[int] + self.padding = None # type: List[int] + self.lhsDilation = None # type: List[int] + self.rhsDilation = None # type: List[int] + self.windowReversal = None # type: List[bool] + self.inputBatchDimension = 0 # type: int + self.inputFeatureDimension = 0 # type: int + self.inputSpatialDimensions = None # type: List[int] + self.kernelInputFeatureDimension = 0 # type: int + self.kernelOutputFeatureDimension = 0 # type: int + self.kernelSpatialDimensions = None # type: List[int] + self.outputBatchDimension = 0 # type: int + self.outputFeatureDimension = 0 # type: int + self.outputSpatialDimensions = None # type: List[int] + self.featureGroupCount = 0 # type: int + self.batchGroupCount = 0 # type: int + self.precisionConfig = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloConvolutionOptions = StablehloConvolutionOptions() + stablehloConvolutionOptions.Init(buf, pos) + return cls.InitFromObj(stablehloConvolutionOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloConvolutionOptions): + x = StablehloConvolutionOptionsT() + x._UnPack(stablehloConvolutionOptions) + return x + + # StablehloConvolutionOptionsT + def _UnPack(self, stablehloConvolutionOptions): + if stablehloConvolutionOptions is None: + return + if not stablehloConvolutionOptions.WindowStridesIsNone(): + if np is None: + self.windowStrides = [] + for i in range(stablehloConvolutionOptions.WindowStridesLength()): + self.windowStrides.append(stablehloConvolutionOptions.WindowStrides(i)) + else: + self.windowStrides = stablehloConvolutionOptions.WindowStridesAsNumpy() + if not stablehloConvolutionOptions.PaddingIsNone(): + if np is None: + self.padding = [] + for i in range(stablehloConvolutionOptions.PaddingLength()): + self.padding.append(stablehloConvolutionOptions.Padding(i)) + else: + self.padding = stablehloConvolutionOptions.PaddingAsNumpy() + if not stablehloConvolutionOptions.LhsDilationIsNone(): + if np is None: + self.lhsDilation = [] + for i in range(stablehloConvolutionOptions.LhsDilationLength()): + self.lhsDilation.append(stablehloConvolutionOptions.LhsDilation(i)) + else: + self.lhsDilation = stablehloConvolutionOptions.LhsDilationAsNumpy() + if not stablehloConvolutionOptions.RhsDilationIsNone(): + if np is None: + self.rhsDilation = [] + for i in range(stablehloConvolutionOptions.RhsDilationLength()): + self.rhsDilation.append(stablehloConvolutionOptions.RhsDilation(i)) + else: + self.rhsDilation = stablehloConvolutionOptions.RhsDilationAsNumpy() + if not stablehloConvolutionOptions.WindowReversalIsNone(): + if np is None: + self.windowReversal = [] + for i in range(stablehloConvolutionOptions.WindowReversalLength()): + self.windowReversal.append(stablehloConvolutionOptions.WindowReversal(i)) + else: + self.windowReversal = stablehloConvolutionOptions.WindowReversalAsNumpy() + self.inputBatchDimension = stablehloConvolutionOptions.InputBatchDimension() + self.inputFeatureDimension = stablehloConvolutionOptions.InputFeatureDimension() + if not stablehloConvolutionOptions.InputSpatialDimensionsIsNone(): + if np is None: + self.inputSpatialDimensions = [] + for i in range(stablehloConvolutionOptions.InputSpatialDimensionsLength()): + self.inputSpatialDimensions.append(stablehloConvolutionOptions.InputSpatialDimensions(i)) + else: + self.inputSpatialDimensions = stablehloConvolutionOptions.InputSpatialDimensionsAsNumpy() + self.kernelInputFeatureDimension = stablehloConvolutionOptions.KernelInputFeatureDimension() + self.kernelOutputFeatureDimension = stablehloConvolutionOptions.KernelOutputFeatureDimension() + if not stablehloConvolutionOptions.KernelSpatialDimensionsIsNone(): + if np is None: + self.kernelSpatialDimensions = [] + for i in range(stablehloConvolutionOptions.KernelSpatialDimensionsLength()): + self.kernelSpatialDimensions.append(stablehloConvolutionOptions.KernelSpatialDimensions(i)) + else: + self.kernelSpatialDimensions = stablehloConvolutionOptions.KernelSpatialDimensionsAsNumpy() + self.outputBatchDimension = stablehloConvolutionOptions.OutputBatchDimension() + self.outputFeatureDimension = stablehloConvolutionOptions.OutputFeatureDimension() + if not stablehloConvolutionOptions.OutputSpatialDimensionsIsNone(): + if np is None: + self.outputSpatialDimensions = [] + for i in range(stablehloConvolutionOptions.OutputSpatialDimensionsLength()): + self.outputSpatialDimensions.append(stablehloConvolutionOptions.OutputSpatialDimensions(i)) + else: + self.outputSpatialDimensions = stablehloConvolutionOptions.OutputSpatialDimensionsAsNumpy() + self.featureGroupCount = stablehloConvolutionOptions.FeatureGroupCount() + self.batchGroupCount = stablehloConvolutionOptions.BatchGroupCount() + if not stablehloConvolutionOptions.PrecisionConfigIsNone(): + if np is None: + self.precisionConfig = [] + for i in range(stablehloConvolutionOptions.PrecisionConfigLength()): + self.precisionConfig.append(stablehloConvolutionOptions.PrecisionConfig(i)) + else: + self.precisionConfig = stablehloConvolutionOptions.PrecisionConfigAsNumpy() + + # StablehloConvolutionOptionsT + def Pack(self, builder): + if self.windowStrides is not None: + if np is not None and type(self.windowStrides) is np.ndarray: + windowStrides = builder.CreateNumpyVector(self.windowStrides) + else: + StablehloConvolutionOptionsStartWindowStridesVector(builder, len(self.windowStrides)) + for i in reversed(range(len(self.windowStrides))): + builder.PrependInt64(self.windowStrides[i]) + windowStrides = builder.EndVector() + if self.padding is not None: + if np is not None and type(self.padding) is np.ndarray: + padding = builder.CreateNumpyVector(self.padding) + else: + StablehloConvolutionOptionsStartPaddingVector(builder, len(self.padding)) + for i in reversed(range(len(self.padding))): + builder.PrependInt64(self.padding[i]) + padding = builder.EndVector() + if self.lhsDilation is not None: + if np is not None and type(self.lhsDilation) is np.ndarray: + lhsDilation = builder.CreateNumpyVector(self.lhsDilation) + else: + StablehloConvolutionOptionsStartLhsDilationVector(builder, len(self.lhsDilation)) + for i in reversed(range(len(self.lhsDilation))): + builder.PrependInt64(self.lhsDilation[i]) + lhsDilation = builder.EndVector() + if self.rhsDilation is not None: + if np is not None and type(self.rhsDilation) is np.ndarray: + rhsDilation = builder.CreateNumpyVector(self.rhsDilation) + else: + StablehloConvolutionOptionsStartRhsDilationVector(builder, len(self.rhsDilation)) + for i in reversed(range(len(self.rhsDilation))): + builder.PrependInt64(self.rhsDilation[i]) + rhsDilation = builder.EndVector() + if self.windowReversal is not None: + if np is not None and type(self.windowReversal) is np.ndarray: + windowReversal = builder.CreateNumpyVector(self.windowReversal) + else: + StablehloConvolutionOptionsStartWindowReversalVector(builder, len(self.windowReversal)) + for i in reversed(range(len(self.windowReversal))): + builder.PrependBool(self.windowReversal[i]) + windowReversal = builder.EndVector() + if self.inputSpatialDimensions is not None: + if np is not None and type(self.inputSpatialDimensions) is np.ndarray: + inputSpatialDimensions = builder.CreateNumpyVector(self.inputSpatialDimensions) + else: + StablehloConvolutionOptionsStartInputSpatialDimensionsVector(builder, len(self.inputSpatialDimensions)) + for i in reversed(range(len(self.inputSpatialDimensions))): + builder.PrependInt64(self.inputSpatialDimensions[i]) + inputSpatialDimensions = builder.EndVector() + if self.kernelSpatialDimensions is not None: + if np is not None and type(self.kernelSpatialDimensions) is np.ndarray: + kernelSpatialDimensions = builder.CreateNumpyVector(self.kernelSpatialDimensions) + else: + StablehloConvolutionOptionsStartKernelSpatialDimensionsVector(builder, len(self.kernelSpatialDimensions)) + for i in reversed(range(len(self.kernelSpatialDimensions))): + builder.PrependInt64(self.kernelSpatialDimensions[i]) + kernelSpatialDimensions = builder.EndVector() + if self.outputSpatialDimensions is not None: + if np is not None and type(self.outputSpatialDimensions) is np.ndarray: + outputSpatialDimensions = builder.CreateNumpyVector(self.outputSpatialDimensions) + else: + StablehloConvolutionOptionsStartOutputSpatialDimensionsVector(builder, len(self.outputSpatialDimensions)) + for i in reversed(range(len(self.outputSpatialDimensions))): + builder.PrependInt64(self.outputSpatialDimensions[i]) + outputSpatialDimensions = builder.EndVector() + if self.precisionConfig is not None: + if np is not None and type(self.precisionConfig) is np.ndarray: + precisionConfig = builder.CreateNumpyVector(self.precisionConfig) + else: + StablehloConvolutionOptionsStartPrecisionConfigVector(builder, len(self.precisionConfig)) + for i in reversed(range(len(self.precisionConfig))): + builder.PrependUint32(self.precisionConfig[i]) + precisionConfig = builder.EndVector() + StablehloConvolutionOptionsStart(builder) + if self.windowStrides is not None: + StablehloConvolutionOptionsAddWindowStrides(builder, windowStrides) + if self.padding is not None: + StablehloConvolutionOptionsAddPadding(builder, padding) + if self.lhsDilation is not None: + StablehloConvolutionOptionsAddLhsDilation(builder, lhsDilation) + if self.rhsDilation is not None: + StablehloConvolutionOptionsAddRhsDilation(builder, rhsDilation) + if self.windowReversal is not None: + StablehloConvolutionOptionsAddWindowReversal(builder, windowReversal) + StablehloConvolutionOptionsAddInputBatchDimension(builder, self.inputBatchDimension) + StablehloConvolutionOptionsAddInputFeatureDimension(builder, self.inputFeatureDimension) + if self.inputSpatialDimensions is not None: + StablehloConvolutionOptionsAddInputSpatialDimensions(builder, inputSpatialDimensions) + StablehloConvolutionOptionsAddKernelInputFeatureDimension(builder, self.kernelInputFeatureDimension) + StablehloConvolutionOptionsAddKernelOutputFeatureDimension(builder, self.kernelOutputFeatureDimension) + if self.kernelSpatialDimensions is not None: + StablehloConvolutionOptionsAddKernelSpatialDimensions(builder, kernelSpatialDimensions) + StablehloConvolutionOptionsAddOutputBatchDimension(builder, self.outputBatchDimension) + StablehloConvolutionOptionsAddOutputFeatureDimension(builder, self.outputFeatureDimension) + if self.outputSpatialDimensions is not None: + StablehloConvolutionOptionsAddOutputSpatialDimensions(builder, outputSpatialDimensions) + StablehloConvolutionOptionsAddFeatureGroupCount(builder, self.featureGroupCount) + StablehloConvolutionOptionsAddBatchGroupCount(builder, self.batchGroupCount) + if self.precisionConfig is not None: + StablehloConvolutionOptionsAddPrecisionConfig(builder, precisionConfig) + stablehloConvolutionOptions = StablehloConvolutionOptionsEnd(builder) + return stablehloConvolutionOptions + + +class StablehloScatterOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloScatterOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloScatterOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloScatterOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloScatterOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloScatterOptions + def IndicesAreSorted(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # StablehloScatterOptions + def UpdateWindowDims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloScatterOptions + def UpdateWindowDimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloScatterOptions + def UpdateWindowDimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloScatterOptions + def UpdateWindowDimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # StablehloScatterOptions + def InsertedWindowDims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloScatterOptions + def InsertedWindowDimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloScatterOptions + def InsertedWindowDimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloScatterOptions + def InsertedWindowDimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # StablehloScatterOptions + def ScatterDimsToOperandDims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # StablehloScatterOptions + def ScatterDimsToOperandDimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # StablehloScatterOptions + def ScatterDimsToOperandDimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # StablehloScatterOptions + def ScatterDimsToOperandDimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + + # StablehloScatterOptions + def IndexVectorDim(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # StablehloScatterOptions + def UniqueIndices(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # StablehloScatterOptions + def UpdateComputationSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def StablehloScatterOptionsStart(builder): + builder.StartObject(7) + +def StablehloScatterOptionsAddIndicesAreSorted(builder, indicesAreSorted): + builder.PrependBoolSlot(0, indicesAreSorted, 0) + +def StablehloScatterOptionsAddUpdateWindowDims(builder, updateWindowDims): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(updateWindowDims), 0) + +def StablehloScatterOptionsStartUpdateWindowDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloScatterOptionsAddInsertedWindowDims(builder, insertedWindowDims): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(insertedWindowDims), 0) + +def StablehloScatterOptionsStartInsertedWindowDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloScatterOptionsAddScatterDimsToOperandDims(builder, scatterDimsToOperandDims): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(scatterDimsToOperandDims), 0) + +def StablehloScatterOptionsStartScatterDimsToOperandDimsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StablehloScatterOptionsAddIndexVectorDim(builder, indexVectorDim): + builder.PrependInt64Slot(4, indexVectorDim, 0) + +def StablehloScatterOptionsAddUniqueIndices(builder, uniqueIndices): + builder.PrependBoolSlot(5, uniqueIndices, 0) + +def StablehloScatterOptionsAddUpdateComputationSubgraphIndex(builder, updateComputationSubgraphIndex): + builder.PrependInt32Slot(6, updateComputationSubgraphIndex, 0) + +def StablehloScatterOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class StablehloScatterOptionsT(object): + + # StablehloScatterOptionsT + def __init__(self): + self.indicesAreSorted = False # type: bool + self.updateWindowDims = None # type: List[int] + self.insertedWindowDims = None # type: List[int] + self.scatterDimsToOperandDims = None # type: List[int] + self.indexVectorDim = 0 # type: int + self.uniqueIndices = False # type: bool + self.updateComputationSubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloScatterOptions = StablehloScatterOptions() + stablehloScatterOptions.Init(buf, pos) + return cls.InitFromObj(stablehloScatterOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloScatterOptions): + x = StablehloScatterOptionsT() + x._UnPack(stablehloScatterOptions) + return x + + # StablehloScatterOptionsT + def _UnPack(self, stablehloScatterOptions): + if stablehloScatterOptions is None: + return + self.indicesAreSorted = stablehloScatterOptions.IndicesAreSorted() + if not stablehloScatterOptions.UpdateWindowDimsIsNone(): + if np is None: + self.updateWindowDims = [] + for i in range(stablehloScatterOptions.UpdateWindowDimsLength()): + self.updateWindowDims.append(stablehloScatterOptions.UpdateWindowDims(i)) + else: + self.updateWindowDims = stablehloScatterOptions.UpdateWindowDimsAsNumpy() + if not stablehloScatterOptions.InsertedWindowDimsIsNone(): + if np is None: + self.insertedWindowDims = [] + for i in range(stablehloScatterOptions.InsertedWindowDimsLength()): + self.insertedWindowDims.append(stablehloScatterOptions.InsertedWindowDims(i)) + else: + self.insertedWindowDims = stablehloScatterOptions.InsertedWindowDimsAsNumpy() + if not stablehloScatterOptions.ScatterDimsToOperandDimsIsNone(): + if np is None: + self.scatterDimsToOperandDims = [] + for i in range(stablehloScatterOptions.ScatterDimsToOperandDimsLength()): + self.scatterDimsToOperandDims.append(stablehloScatterOptions.ScatterDimsToOperandDims(i)) + else: + self.scatterDimsToOperandDims = stablehloScatterOptions.ScatterDimsToOperandDimsAsNumpy() + self.indexVectorDim = stablehloScatterOptions.IndexVectorDim() + self.uniqueIndices = stablehloScatterOptions.UniqueIndices() + self.updateComputationSubgraphIndex = stablehloScatterOptions.UpdateComputationSubgraphIndex() + + # StablehloScatterOptionsT + def Pack(self, builder): + if self.updateWindowDims is not None: + if np is not None and type(self.updateWindowDims) is np.ndarray: + updateWindowDims = builder.CreateNumpyVector(self.updateWindowDims) + else: + StablehloScatterOptionsStartUpdateWindowDimsVector(builder, len(self.updateWindowDims)) + for i in reversed(range(len(self.updateWindowDims))): + builder.PrependInt64(self.updateWindowDims[i]) + updateWindowDims = builder.EndVector() + if self.insertedWindowDims is not None: + if np is not None and type(self.insertedWindowDims) is np.ndarray: + insertedWindowDims = builder.CreateNumpyVector(self.insertedWindowDims) + else: + StablehloScatterOptionsStartInsertedWindowDimsVector(builder, len(self.insertedWindowDims)) + for i in reversed(range(len(self.insertedWindowDims))): + builder.PrependInt64(self.insertedWindowDims[i]) + insertedWindowDims = builder.EndVector() + if self.scatterDimsToOperandDims is not None: + if np is not None and type(self.scatterDimsToOperandDims) is np.ndarray: + scatterDimsToOperandDims = builder.CreateNumpyVector(self.scatterDimsToOperandDims) + else: + StablehloScatterOptionsStartScatterDimsToOperandDimsVector(builder, len(self.scatterDimsToOperandDims)) + for i in reversed(range(len(self.scatterDimsToOperandDims))): + builder.PrependInt64(self.scatterDimsToOperandDims[i]) + scatterDimsToOperandDims = builder.EndVector() + StablehloScatterOptionsStart(builder) + StablehloScatterOptionsAddIndicesAreSorted(builder, self.indicesAreSorted) + if self.updateWindowDims is not None: + StablehloScatterOptionsAddUpdateWindowDims(builder, updateWindowDims) + if self.insertedWindowDims is not None: + StablehloScatterOptionsAddInsertedWindowDims(builder, insertedWindowDims) + if self.scatterDimsToOperandDims is not None: + StablehloScatterOptionsAddScatterDimsToOperandDims(builder, scatterDimsToOperandDims) + StablehloScatterOptionsAddIndexVectorDim(builder, self.indexVectorDim) + StablehloScatterOptionsAddUniqueIndices(builder, self.uniqueIndices) + StablehloScatterOptionsAddUpdateComputationSubgraphIndex(builder, self.updateComputationSubgraphIndex) + stablehloScatterOptions = StablehloScatterOptionsEnd(builder) + return stablehloScatterOptions + + +class StablehloRngBitGeneratorOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StablehloRngBitGeneratorOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStablehloRngBitGeneratorOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StablehloRngBitGeneratorOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StablehloRngBitGeneratorOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StablehloRngBitGeneratorOptions + def Algorithm(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def StablehloRngBitGeneratorOptionsStart(builder): + builder.StartObject(1) + +def StablehloRngBitGeneratorOptionsAddAlgorithm(builder, algorithm): + builder.PrependInt8Slot(0, algorithm, 0) + +def StablehloRngBitGeneratorOptionsEnd(builder): + return builder.EndObject() + + + +class StablehloRngBitGeneratorOptionsT(object): + + # StablehloRngBitGeneratorOptionsT + def __init__(self): + self.algorithm = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stablehloRngBitGeneratorOptions = StablehloRngBitGeneratorOptions() + stablehloRngBitGeneratorOptions.Init(buf, pos) + return cls.InitFromObj(stablehloRngBitGeneratorOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stablehloRngBitGeneratorOptions): + x = StablehloRngBitGeneratorOptionsT() + x._UnPack(stablehloRngBitGeneratorOptions) + return x + + # StablehloRngBitGeneratorOptionsT + def _UnPack(self, stablehloRngBitGeneratorOptions): + if stablehloRngBitGeneratorOptions is None: + return + self.algorithm = stablehloRngBitGeneratorOptions.Algorithm() + + # StablehloRngBitGeneratorOptionsT + def Pack(self, builder): + StablehloRngBitGeneratorOptionsStart(builder) + StablehloRngBitGeneratorOptionsAddAlgorithm(builder, self.algorithm) + stablehloRngBitGeneratorOptions = StablehloRngBitGeneratorOptionsEnd(builder) + return stablehloRngBitGeneratorOptions + + +class Conv2DOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Conv2DOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsConv2DOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Conv2DOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Conv2DOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Conv2DOptions + def Padding(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Conv2DOptions + def StrideW(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Conv2DOptions + def StrideH(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Conv2DOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Conv2DOptions + def DilationWFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + + # Conv2DOptions + def DilationHFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + + # Conv2DOptions + def QuantizedBiasType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def Conv2DOptionsStart(builder): + builder.StartObject(7) + +def Conv2DOptionsAddPadding(builder, padding): + builder.PrependInt8Slot(0, padding, 0) + +def Conv2DOptionsAddStrideW(builder, strideW): + builder.PrependInt32Slot(1, strideW, 0) + +def Conv2DOptionsAddStrideH(builder, strideH): + builder.PrependInt32Slot(2, strideH, 0) + +def Conv2DOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(3, fusedActivationFunction, 0) + +def Conv2DOptionsAddDilationWFactor(builder, dilationWFactor): + builder.PrependInt32Slot(4, dilationWFactor, 1) + +def Conv2DOptionsAddDilationHFactor(builder, dilationHFactor): + builder.PrependInt32Slot(5, dilationHFactor, 1) + +def Conv2DOptionsAddQuantizedBiasType(builder, quantizedBiasType): + builder.PrependInt8Slot(6, quantizedBiasType, 0) + +def Conv2DOptionsEnd(builder): + return builder.EndObject() + + + +class Conv2DOptionsT(object): + + # Conv2DOptionsT + def __init__(self): + self.padding = 0 # type: int + self.strideW = 0 # type: int + self.strideH = 0 # type: int + self.fusedActivationFunction = 0 # type: int + self.dilationWFactor = 1 # type: int + self.dilationHFactor = 1 # type: int + self.quantizedBiasType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + conv2Doptions = Conv2DOptions() + conv2Doptions.Init(buf, pos) + return cls.InitFromObj(conv2Doptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, conv2Doptions): + x = Conv2DOptionsT() + x._UnPack(conv2Doptions) + return x + + # Conv2DOptionsT + def _UnPack(self, conv2Doptions): + if conv2Doptions is None: + return + self.padding = conv2Doptions.Padding() + self.strideW = conv2Doptions.StrideW() + self.strideH = conv2Doptions.StrideH() + self.fusedActivationFunction = conv2Doptions.FusedActivationFunction() + self.dilationWFactor = conv2Doptions.DilationWFactor() + self.dilationHFactor = conv2Doptions.DilationHFactor() + self.quantizedBiasType = conv2Doptions.QuantizedBiasType() + + # Conv2DOptionsT + def Pack(self, builder): + Conv2DOptionsStart(builder) + Conv2DOptionsAddPadding(builder, self.padding) + Conv2DOptionsAddStrideW(builder, self.strideW) + Conv2DOptionsAddStrideH(builder, self.strideH) + Conv2DOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + Conv2DOptionsAddDilationWFactor(builder, self.dilationWFactor) + Conv2DOptionsAddDilationHFactor(builder, self.dilationHFactor) + Conv2DOptionsAddQuantizedBiasType(builder, self.quantizedBiasType) + conv2Doptions = Conv2DOptionsEnd(builder) + return conv2Doptions + + +class Conv3DOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Conv3DOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsConv3DOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Conv3DOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Conv3DOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Conv3DOptions + def Padding(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Conv3DOptions + def StrideD(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Conv3DOptions + def StrideW(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Conv3DOptions + def StrideH(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Conv3DOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Conv3DOptions + def DilationDFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + + # Conv3DOptions + def DilationWFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + + # Conv3DOptions + def DilationHFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + +def Conv3DOptionsStart(builder): + builder.StartObject(8) + +def Conv3DOptionsAddPadding(builder, padding): + builder.PrependInt8Slot(0, padding, 0) + +def Conv3DOptionsAddStrideD(builder, strideD): + builder.PrependInt32Slot(1, strideD, 0) + +def Conv3DOptionsAddStrideW(builder, strideW): + builder.PrependInt32Slot(2, strideW, 0) + +def Conv3DOptionsAddStrideH(builder, strideH): + builder.PrependInt32Slot(3, strideH, 0) + +def Conv3DOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(4, fusedActivationFunction, 0) + +def Conv3DOptionsAddDilationDFactor(builder, dilationDFactor): + builder.PrependInt32Slot(5, dilationDFactor, 1) + +def Conv3DOptionsAddDilationWFactor(builder, dilationWFactor): + builder.PrependInt32Slot(6, dilationWFactor, 1) + +def Conv3DOptionsAddDilationHFactor(builder, dilationHFactor): + builder.PrependInt32Slot(7, dilationHFactor, 1) + +def Conv3DOptionsEnd(builder): + return builder.EndObject() + + + +class Conv3DOptionsT(object): + + # Conv3DOptionsT + def __init__(self): + self.padding = 0 # type: int + self.strideD = 0 # type: int + self.strideW = 0 # type: int + self.strideH = 0 # type: int + self.fusedActivationFunction = 0 # type: int + self.dilationDFactor = 1 # type: int + self.dilationWFactor = 1 # type: int + self.dilationHFactor = 1 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + conv3Doptions = Conv3DOptions() + conv3Doptions.Init(buf, pos) + return cls.InitFromObj(conv3Doptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, conv3Doptions): + x = Conv3DOptionsT() + x._UnPack(conv3Doptions) + return x + + # Conv3DOptionsT + def _UnPack(self, conv3Doptions): + if conv3Doptions is None: + return + self.padding = conv3Doptions.Padding() + self.strideD = conv3Doptions.StrideD() + self.strideW = conv3Doptions.StrideW() + self.strideH = conv3Doptions.StrideH() + self.fusedActivationFunction = conv3Doptions.FusedActivationFunction() + self.dilationDFactor = conv3Doptions.DilationDFactor() + self.dilationWFactor = conv3Doptions.DilationWFactor() + self.dilationHFactor = conv3Doptions.DilationHFactor() + + # Conv3DOptionsT + def Pack(self, builder): + Conv3DOptionsStart(builder) + Conv3DOptionsAddPadding(builder, self.padding) + Conv3DOptionsAddStrideD(builder, self.strideD) + Conv3DOptionsAddStrideW(builder, self.strideW) + Conv3DOptionsAddStrideH(builder, self.strideH) + Conv3DOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + Conv3DOptionsAddDilationDFactor(builder, self.dilationDFactor) + Conv3DOptionsAddDilationWFactor(builder, self.dilationWFactor) + Conv3DOptionsAddDilationHFactor(builder, self.dilationHFactor) + conv3Doptions = Conv3DOptionsEnd(builder) + return conv3Doptions + + +class Pool2DOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Pool2DOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsPool2DOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Pool2DOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Pool2DOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Pool2DOptions + def Padding(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Pool2DOptions + def StrideW(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Pool2DOptions + def StrideH(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Pool2DOptions + def FilterWidth(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Pool2DOptions + def FilterHeight(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Pool2DOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def Pool2DOptionsStart(builder): + builder.StartObject(6) + +def Pool2DOptionsAddPadding(builder, padding): + builder.PrependInt8Slot(0, padding, 0) + +def Pool2DOptionsAddStrideW(builder, strideW): + builder.PrependInt32Slot(1, strideW, 0) + +def Pool2DOptionsAddStrideH(builder, strideH): + builder.PrependInt32Slot(2, strideH, 0) + +def Pool2DOptionsAddFilterWidth(builder, filterWidth): + builder.PrependInt32Slot(3, filterWidth, 0) + +def Pool2DOptionsAddFilterHeight(builder, filterHeight): + builder.PrependInt32Slot(4, filterHeight, 0) + +def Pool2DOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(5, fusedActivationFunction, 0) + +def Pool2DOptionsEnd(builder): + return builder.EndObject() + + + +class Pool2DOptionsT(object): + + # Pool2DOptionsT + def __init__(self): + self.padding = 0 # type: int + self.strideW = 0 # type: int + self.strideH = 0 # type: int + self.filterWidth = 0 # type: int + self.filterHeight = 0 # type: int + self.fusedActivationFunction = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + pool2Doptions = Pool2DOptions() + pool2Doptions.Init(buf, pos) + return cls.InitFromObj(pool2Doptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, pool2Doptions): + x = Pool2DOptionsT() + x._UnPack(pool2Doptions) + return x + + # Pool2DOptionsT + def _UnPack(self, pool2Doptions): + if pool2Doptions is None: + return + self.padding = pool2Doptions.Padding() + self.strideW = pool2Doptions.StrideW() + self.strideH = pool2Doptions.StrideH() + self.filterWidth = pool2Doptions.FilterWidth() + self.filterHeight = pool2Doptions.FilterHeight() + self.fusedActivationFunction = pool2Doptions.FusedActivationFunction() + + # Pool2DOptionsT + def Pack(self, builder): + Pool2DOptionsStart(builder) + Pool2DOptionsAddPadding(builder, self.padding) + Pool2DOptionsAddStrideW(builder, self.strideW) + Pool2DOptionsAddStrideH(builder, self.strideH) + Pool2DOptionsAddFilterWidth(builder, self.filterWidth) + Pool2DOptionsAddFilterHeight(builder, self.filterHeight) + Pool2DOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + pool2Doptions = Pool2DOptionsEnd(builder) + return pool2Doptions + + +class DepthwiseConv2DOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DepthwiseConv2DOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDepthwiseConv2DOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DepthwiseConv2DOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DepthwiseConv2DOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DepthwiseConv2DOptions + def Padding(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # DepthwiseConv2DOptions + def StrideW(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # DepthwiseConv2DOptions + def StrideH(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # DepthwiseConv2DOptions + def DepthMultiplier(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # DepthwiseConv2DOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # DepthwiseConv2DOptions + def DilationWFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + + # DepthwiseConv2DOptions + def DilationHFactor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + +def DepthwiseConv2DOptionsStart(builder): + builder.StartObject(7) + +def DepthwiseConv2DOptionsAddPadding(builder, padding): + builder.PrependInt8Slot(0, padding, 0) + +def DepthwiseConv2DOptionsAddStrideW(builder, strideW): + builder.PrependInt32Slot(1, strideW, 0) + +def DepthwiseConv2DOptionsAddStrideH(builder, strideH): + builder.PrependInt32Slot(2, strideH, 0) + +def DepthwiseConv2DOptionsAddDepthMultiplier(builder, depthMultiplier): + builder.PrependInt32Slot(3, depthMultiplier, 0) + +def DepthwiseConv2DOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(4, fusedActivationFunction, 0) + +def DepthwiseConv2DOptionsAddDilationWFactor(builder, dilationWFactor): + builder.PrependInt32Slot(5, dilationWFactor, 1) + +def DepthwiseConv2DOptionsAddDilationHFactor(builder, dilationHFactor): + builder.PrependInt32Slot(6, dilationHFactor, 1) + +def DepthwiseConv2DOptionsEnd(builder): + return builder.EndObject() + + + +class DepthwiseConv2DOptionsT(object): + + # DepthwiseConv2DOptionsT + def __init__(self): + self.padding = 0 # type: int + self.strideW = 0 # type: int + self.strideH = 0 # type: int + self.depthMultiplier = 0 # type: int + self.fusedActivationFunction = 0 # type: int + self.dilationWFactor = 1 # type: int + self.dilationHFactor = 1 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + depthwiseConv2Doptions = DepthwiseConv2DOptions() + depthwiseConv2Doptions.Init(buf, pos) + return cls.InitFromObj(depthwiseConv2Doptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, depthwiseConv2Doptions): + x = DepthwiseConv2DOptionsT() + x._UnPack(depthwiseConv2Doptions) + return x + + # DepthwiseConv2DOptionsT + def _UnPack(self, depthwiseConv2Doptions): + if depthwiseConv2Doptions is None: + return + self.padding = depthwiseConv2Doptions.Padding() + self.strideW = depthwiseConv2Doptions.StrideW() + self.strideH = depthwiseConv2Doptions.StrideH() + self.depthMultiplier = depthwiseConv2Doptions.DepthMultiplier() + self.fusedActivationFunction = depthwiseConv2Doptions.FusedActivationFunction() + self.dilationWFactor = depthwiseConv2Doptions.DilationWFactor() + self.dilationHFactor = depthwiseConv2Doptions.DilationHFactor() + + # DepthwiseConv2DOptionsT + def Pack(self, builder): + DepthwiseConv2DOptionsStart(builder) + DepthwiseConv2DOptionsAddPadding(builder, self.padding) + DepthwiseConv2DOptionsAddStrideW(builder, self.strideW) + DepthwiseConv2DOptionsAddStrideH(builder, self.strideH) + DepthwiseConv2DOptionsAddDepthMultiplier(builder, self.depthMultiplier) + DepthwiseConv2DOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + DepthwiseConv2DOptionsAddDilationWFactor(builder, self.dilationWFactor) + DepthwiseConv2DOptionsAddDilationHFactor(builder, self.dilationHFactor) + depthwiseConv2Doptions = DepthwiseConv2DOptionsEnd(builder) + return depthwiseConv2Doptions + + +class ConcatEmbeddingsOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ConcatEmbeddingsOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsConcatEmbeddingsOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ConcatEmbeddingsOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ConcatEmbeddingsOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ConcatEmbeddingsOptions + def NumChannels(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # ConcatEmbeddingsOptions + def NumColumnsPerChannel(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # ConcatEmbeddingsOptions + def NumColumnsPerChannelAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # ConcatEmbeddingsOptions + def NumColumnsPerChannelLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ConcatEmbeddingsOptions + def NumColumnsPerChannelIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # ConcatEmbeddingsOptions + def EmbeddingDimPerChannel(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # ConcatEmbeddingsOptions + def EmbeddingDimPerChannelAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # ConcatEmbeddingsOptions + def EmbeddingDimPerChannelLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ConcatEmbeddingsOptions + def EmbeddingDimPerChannelIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + +def ConcatEmbeddingsOptionsStart(builder): + builder.StartObject(3) + +def ConcatEmbeddingsOptionsAddNumChannels(builder, numChannels): + builder.PrependInt32Slot(0, numChannels, 0) + +def ConcatEmbeddingsOptionsAddNumColumnsPerChannel(builder, numColumnsPerChannel): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(numColumnsPerChannel), 0) + +def ConcatEmbeddingsOptionsStartNumColumnsPerChannelVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ConcatEmbeddingsOptionsAddEmbeddingDimPerChannel(builder, embeddingDimPerChannel): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(embeddingDimPerChannel), 0) + +def ConcatEmbeddingsOptionsStartEmbeddingDimPerChannelVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ConcatEmbeddingsOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class ConcatEmbeddingsOptionsT(object): + + # ConcatEmbeddingsOptionsT + def __init__(self): + self.numChannels = 0 # type: int + self.numColumnsPerChannel = None # type: List[int] + self.embeddingDimPerChannel = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + concatEmbeddingsOptions = ConcatEmbeddingsOptions() + concatEmbeddingsOptions.Init(buf, pos) + return cls.InitFromObj(concatEmbeddingsOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, concatEmbeddingsOptions): + x = ConcatEmbeddingsOptionsT() + x._UnPack(concatEmbeddingsOptions) + return x + + # ConcatEmbeddingsOptionsT + def _UnPack(self, concatEmbeddingsOptions): + if concatEmbeddingsOptions is None: + return + self.numChannels = concatEmbeddingsOptions.NumChannels() + if not concatEmbeddingsOptions.NumColumnsPerChannelIsNone(): + if np is None: + self.numColumnsPerChannel = [] + for i in range(concatEmbeddingsOptions.NumColumnsPerChannelLength()): + self.numColumnsPerChannel.append(concatEmbeddingsOptions.NumColumnsPerChannel(i)) + else: + self.numColumnsPerChannel = concatEmbeddingsOptions.NumColumnsPerChannelAsNumpy() + if not concatEmbeddingsOptions.EmbeddingDimPerChannelIsNone(): + if np is None: + self.embeddingDimPerChannel = [] + for i in range(concatEmbeddingsOptions.EmbeddingDimPerChannelLength()): + self.embeddingDimPerChannel.append(concatEmbeddingsOptions.EmbeddingDimPerChannel(i)) + else: + self.embeddingDimPerChannel = concatEmbeddingsOptions.EmbeddingDimPerChannelAsNumpy() + + # ConcatEmbeddingsOptionsT + def Pack(self, builder): + if self.numColumnsPerChannel is not None: + if np is not None and type(self.numColumnsPerChannel) is np.ndarray: + numColumnsPerChannel = builder.CreateNumpyVector(self.numColumnsPerChannel) + else: + ConcatEmbeddingsOptionsStartNumColumnsPerChannelVector(builder, len(self.numColumnsPerChannel)) + for i in reversed(range(len(self.numColumnsPerChannel))): + builder.PrependInt32(self.numColumnsPerChannel[i]) + numColumnsPerChannel = builder.EndVector() + if self.embeddingDimPerChannel is not None: + if np is not None and type(self.embeddingDimPerChannel) is np.ndarray: + embeddingDimPerChannel = builder.CreateNumpyVector(self.embeddingDimPerChannel) + else: + ConcatEmbeddingsOptionsStartEmbeddingDimPerChannelVector(builder, len(self.embeddingDimPerChannel)) + for i in reversed(range(len(self.embeddingDimPerChannel))): + builder.PrependInt32(self.embeddingDimPerChannel[i]) + embeddingDimPerChannel = builder.EndVector() + ConcatEmbeddingsOptionsStart(builder) + ConcatEmbeddingsOptionsAddNumChannels(builder, self.numChannels) + if self.numColumnsPerChannel is not None: + ConcatEmbeddingsOptionsAddNumColumnsPerChannel(builder, numColumnsPerChannel) + if self.embeddingDimPerChannel is not None: + ConcatEmbeddingsOptionsAddEmbeddingDimPerChannel(builder, embeddingDimPerChannel) + concatEmbeddingsOptions = ConcatEmbeddingsOptionsEnd(builder) + return concatEmbeddingsOptions + + +class LSHProjectionOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LSHProjectionOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLSHProjectionOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LSHProjectionOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LSHProjectionOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # LSHProjectionOptions + def Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def LSHProjectionOptionsStart(builder): + builder.StartObject(1) + +def LSHProjectionOptionsAddType(builder, type): + builder.PrependInt8Slot(0, type, 0) + +def LSHProjectionOptionsEnd(builder): + return builder.EndObject() + + + +class LSHProjectionOptionsT(object): + + # LSHProjectionOptionsT + def __init__(self): + self.type = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + lshprojectionOptions = LSHProjectionOptions() + lshprojectionOptions.Init(buf, pos) + return cls.InitFromObj(lshprojectionOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, lshprojectionOptions): + x = LSHProjectionOptionsT() + x._UnPack(lshprojectionOptions) + return x + + # LSHProjectionOptionsT + def _UnPack(self, lshprojectionOptions): + if lshprojectionOptions is None: + return + self.type = lshprojectionOptions.Type() + + # LSHProjectionOptionsT + def Pack(self, builder): + LSHProjectionOptionsStart(builder) + LSHProjectionOptionsAddType(builder, self.type) + lshprojectionOptions = LSHProjectionOptionsEnd(builder) + return lshprojectionOptions + + +class SVDFOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SVDFOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSVDFOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SVDFOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SVDFOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SVDFOptions + def Rank(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # SVDFOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # SVDFOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def SVDFOptionsStart(builder): + builder.StartObject(3) + +def SVDFOptionsAddRank(builder, rank): + builder.PrependInt32Slot(0, rank, 0) + +def SVDFOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(1, fusedActivationFunction, 0) + +def SVDFOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(2, asymmetricQuantizeInputs, 0) + +def SVDFOptionsEnd(builder): + return builder.EndObject() + + + +class SVDFOptionsT(object): + + # SVDFOptionsT + def __init__(self): + self.rank = 0 # type: int + self.fusedActivationFunction = 0 # type: int + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + svdfoptions = SVDFOptions() + svdfoptions.Init(buf, pos) + return cls.InitFromObj(svdfoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, svdfoptions): + x = SVDFOptionsT() + x._UnPack(svdfoptions) + return x + + # SVDFOptionsT + def _UnPack(self, svdfoptions): + if svdfoptions is None: + return + self.rank = svdfoptions.Rank() + self.fusedActivationFunction = svdfoptions.FusedActivationFunction() + self.asymmetricQuantizeInputs = svdfoptions.AsymmetricQuantizeInputs() + + # SVDFOptionsT + def Pack(self, builder): + SVDFOptionsStart(builder) + SVDFOptionsAddRank(builder, self.rank) + SVDFOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + SVDFOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + svdfoptions = SVDFOptionsEnd(builder) + return svdfoptions + + +class RNNOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RNNOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRNNOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RNNOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # RNNOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # RNNOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # RNNOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def RNNOptionsStart(builder): + builder.StartObject(2) + +def RNNOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def RNNOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(1, asymmetricQuantizeInputs, 0) + +def RNNOptionsEnd(builder): + return builder.EndObject() + + + +class RNNOptionsT(object): + + # RNNOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + rnnoptions = RNNOptions() + rnnoptions.Init(buf, pos) + return cls.InitFromObj(rnnoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, rnnoptions): + x = RNNOptionsT() + x._UnPack(rnnoptions) + return x + + # RNNOptionsT + def _UnPack(self, rnnoptions): + if rnnoptions is None: + return + self.fusedActivationFunction = rnnoptions.FusedActivationFunction() + self.asymmetricQuantizeInputs = rnnoptions.AsymmetricQuantizeInputs() + + # RNNOptionsT + def Pack(self, builder): + RNNOptionsStart(builder) + RNNOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + RNNOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + rnnoptions = RNNOptionsEnd(builder) + return rnnoptions + + +class SequenceRNNOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SequenceRNNOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSequenceRNNOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SequenceRNNOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SequenceRNNOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SequenceRNNOptions + def TimeMajor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # SequenceRNNOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # SequenceRNNOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def SequenceRNNOptionsStart(builder): + builder.StartObject(3) + +def SequenceRNNOptionsAddTimeMajor(builder, timeMajor): + builder.PrependBoolSlot(0, timeMajor, 0) + +def SequenceRNNOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(1, fusedActivationFunction, 0) + +def SequenceRNNOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(2, asymmetricQuantizeInputs, 0) + +def SequenceRNNOptionsEnd(builder): + return builder.EndObject() + + + +class SequenceRNNOptionsT(object): + + # SequenceRNNOptionsT + def __init__(self): + self.timeMajor = False # type: bool + self.fusedActivationFunction = 0 # type: int + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + sequenceRnnoptions = SequenceRNNOptions() + sequenceRnnoptions.Init(buf, pos) + return cls.InitFromObj(sequenceRnnoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, sequenceRnnoptions): + x = SequenceRNNOptionsT() + x._UnPack(sequenceRnnoptions) + return x + + # SequenceRNNOptionsT + def _UnPack(self, sequenceRnnoptions): + if sequenceRnnoptions is None: + return + self.timeMajor = sequenceRnnoptions.TimeMajor() + self.fusedActivationFunction = sequenceRnnoptions.FusedActivationFunction() + self.asymmetricQuantizeInputs = sequenceRnnoptions.AsymmetricQuantizeInputs() + + # SequenceRNNOptionsT + def Pack(self, builder): + SequenceRNNOptionsStart(builder) + SequenceRNNOptionsAddTimeMajor(builder, self.timeMajor) + SequenceRNNOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + SequenceRNNOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + sequenceRnnoptions = SequenceRNNOptionsEnd(builder) + return sequenceRnnoptions + + +class BidirectionalSequenceRNNOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BidirectionalSequenceRNNOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBidirectionalSequenceRNNOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BidirectionalSequenceRNNOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BidirectionalSequenceRNNOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # BidirectionalSequenceRNNOptions + def TimeMajor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # BidirectionalSequenceRNNOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # BidirectionalSequenceRNNOptions + def MergeOutputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # BidirectionalSequenceRNNOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def BidirectionalSequenceRNNOptionsStart(builder): + builder.StartObject(4) + +def BidirectionalSequenceRNNOptionsAddTimeMajor(builder, timeMajor): + builder.PrependBoolSlot(0, timeMajor, 0) + +def BidirectionalSequenceRNNOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(1, fusedActivationFunction, 0) + +def BidirectionalSequenceRNNOptionsAddMergeOutputs(builder, mergeOutputs): + builder.PrependBoolSlot(2, mergeOutputs, 0) + +def BidirectionalSequenceRNNOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(3, asymmetricQuantizeInputs, 0) + +def BidirectionalSequenceRNNOptionsEnd(builder): + return builder.EndObject() + + + +class BidirectionalSequenceRNNOptionsT(object): + + # BidirectionalSequenceRNNOptionsT + def __init__(self): + self.timeMajor = False # type: bool + self.fusedActivationFunction = 0 # type: int + self.mergeOutputs = False # type: bool + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + bidirectionalSequenceRnnoptions = BidirectionalSequenceRNNOptions() + bidirectionalSequenceRnnoptions.Init(buf, pos) + return cls.InitFromObj(bidirectionalSequenceRnnoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, bidirectionalSequenceRnnoptions): + x = BidirectionalSequenceRNNOptionsT() + x._UnPack(bidirectionalSequenceRnnoptions) + return x + + # BidirectionalSequenceRNNOptionsT + def _UnPack(self, bidirectionalSequenceRnnoptions): + if bidirectionalSequenceRnnoptions is None: + return + self.timeMajor = bidirectionalSequenceRnnoptions.TimeMajor() + self.fusedActivationFunction = bidirectionalSequenceRnnoptions.FusedActivationFunction() + self.mergeOutputs = bidirectionalSequenceRnnoptions.MergeOutputs() + self.asymmetricQuantizeInputs = bidirectionalSequenceRnnoptions.AsymmetricQuantizeInputs() + + # BidirectionalSequenceRNNOptionsT + def Pack(self, builder): + BidirectionalSequenceRNNOptionsStart(builder) + BidirectionalSequenceRNNOptionsAddTimeMajor(builder, self.timeMajor) + BidirectionalSequenceRNNOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + BidirectionalSequenceRNNOptionsAddMergeOutputs(builder, self.mergeOutputs) + BidirectionalSequenceRNNOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + bidirectionalSequenceRnnoptions = BidirectionalSequenceRNNOptionsEnd(builder) + return bidirectionalSequenceRnnoptions + + +class FullyConnectedOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = FullyConnectedOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsFullyConnectedOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def FullyConnectedOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # FullyConnectedOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # FullyConnectedOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # FullyConnectedOptions + def WeightsFormat(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # FullyConnectedOptions + def KeepNumDims(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # FullyConnectedOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # FullyConnectedOptions + def QuantizedBiasType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def FullyConnectedOptionsStart(builder): + builder.StartObject(5) + +def FullyConnectedOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def FullyConnectedOptionsAddWeightsFormat(builder, weightsFormat): + builder.PrependInt8Slot(1, weightsFormat, 0) + +def FullyConnectedOptionsAddKeepNumDims(builder, keepNumDims): + builder.PrependBoolSlot(2, keepNumDims, 0) + +def FullyConnectedOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(3, asymmetricQuantizeInputs, 0) + +def FullyConnectedOptionsAddQuantizedBiasType(builder, quantizedBiasType): + builder.PrependInt8Slot(4, quantizedBiasType, 0) + +def FullyConnectedOptionsEnd(builder): + return builder.EndObject() + + + +class FullyConnectedOptionsT(object): + + # FullyConnectedOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.weightsFormat = 0 # type: int + self.keepNumDims = False # type: bool + self.asymmetricQuantizeInputs = False # type: bool + self.quantizedBiasType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + fullyConnectedOptions = FullyConnectedOptions() + fullyConnectedOptions.Init(buf, pos) + return cls.InitFromObj(fullyConnectedOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, fullyConnectedOptions): + x = FullyConnectedOptionsT() + x._UnPack(fullyConnectedOptions) + return x + + # FullyConnectedOptionsT + def _UnPack(self, fullyConnectedOptions): + if fullyConnectedOptions is None: + return + self.fusedActivationFunction = fullyConnectedOptions.FusedActivationFunction() + self.weightsFormat = fullyConnectedOptions.WeightsFormat() + self.keepNumDims = fullyConnectedOptions.KeepNumDims() + self.asymmetricQuantizeInputs = fullyConnectedOptions.AsymmetricQuantizeInputs() + self.quantizedBiasType = fullyConnectedOptions.QuantizedBiasType() + + # FullyConnectedOptionsT + def Pack(self, builder): + FullyConnectedOptionsStart(builder) + FullyConnectedOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + FullyConnectedOptionsAddWeightsFormat(builder, self.weightsFormat) + FullyConnectedOptionsAddKeepNumDims(builder, self.keepNumDims) + FullyConnectedOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + FullyConnectedOptionsAddQuantizedBiasType(builder, self.quantizedBiasType) + fullyConnectedOptions = FullyConnectedOptionsEnd(builder) + return fullyConnectedOptions + + +class SoftmaxOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SoftmaxOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSoftmaxOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SoftmaxOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SoftmaxOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SoftmaxOptions + def Beta(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + +def SoftmaxOptionsStart(builder): + builder.StartObject(1) + +def SoftmaxOptionsAddBeta(builder, beta): + builder.PrependFloat32Slot(0, beta, 0.0) + +def SoftmaxOptionsEnd(builder): + return builder.EndObject() + + + +class SoftmaxOptionsT(object): + + # SoftmaxOptionsT + def __init__(self): + self.beta = 0.0 # type: float + + @classmethod + def InitFromBuf(cls, buf, pos): + softmaxOptions = SoftmaxOptions() + softmaxOptions.Init(buf, pos) + return cls.InitFromObj(softmaxOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, softmaxOptions): + x = SoftmaxOptionsT() + x._UnPack(softmaxOptions) + return x + + # SoftmaxOptionsT + def _UnPack(self, softmaxOptions): + if softmaxOptions is None: + return + self.beta = softmaxOptions.Beta() + + # SoftmaxOptionsT + def Pack(self, builder): + SoftmaxOptionsStart(builder) + SoftmaxOptionsAddBeta(builder, self.beta) + softmaxOptions = SoftmaxOptionsEnd(builder) + return softmaxOptions + + +class ConcatenationOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ConcatenationOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsConcatenationOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ConcatenationOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ConcatenationOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ConcatenationOptions + def Axis(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # ConcatenationOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def ConcatenationOptionsStart(builder): + builder.StartObject(2) + +def ConcatenationOptionsAddAxis(builder, axis): + builder.PrependInt32Slot(0, axis, 0) + +def ConcatenationOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(1, fusedActivationFunction, 0) + +def ConcatenationOptionsEnd(builder): + return builder.EndObject() + + + +class ConcatenationOptionsT(object): + + # ConcatenationOptionsT + def __init__(self): + self.axis = 0 # type: int + self.fusedActivationFunction = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + concatenationOptions = ConcatenationOptions() + concatenationOptions.Init(buf, pos) + return cls.InitFromObj(concatenationOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, concatenationOptions): + x = ConcatenationOptionsT() + x._UnPack(concatenationOptions) + return x + + # ConcatenationOptionsT + def _UnPack(self, concatenationOptions): + if concatenationOptions is None: + return + self.axis = concatenationOptions.Axis() + self.fusedActivationFunction = concatenationOptions.FusedActivationFunction() + + # ConcatenationOptionsT + def Pack(self, builder): + ConcatenationOptionsStart(builder) + ConcatenationOptionsAddAxis(builder, self.axis) + ConcatenationOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + concatenationOptions = ConcatenationOptionsEnd(builder) + return concatenationOptions + + +class AddOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = AddOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsAddOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def AddOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # AddOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # AddOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # AddOptions + def PotScaleInt16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return True + +def AddOptionsStart(builder): + builder.StartObject(2) + +def AddOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def AddOptionsAddPotScaleInt16(builder, potScaleInt16): + builder.PrependBoolSlot(1, potScaleInt16, 1) + +def AddOptionsEnd(builder): + return builder.EndObject() + + + +class AddOptionsT(object): + + # AddOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.potScaleInt16 = True # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + addOptions = AddOptions() + addOptions.Init(buf, pos) + return cls.InitFromObj(addOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, addOptions): + x = AddOptionsT() + x._UnPack(addOptions) + return x + + # AddOptionsT + def _UnPack(self, addOptions): + if addOptions is None: + return + self.fusedActivationFunction = addOptions.FusedActivationFunction() + self.potScaleInt16 = addOptions.PotScaleInt16() + + # AddOptionsT + def Pack(self, builder): + AddOptionsStart(builder) + AddOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + AddOptionsAddPotScaleInt16(builder, self.potScaleInt16) + addOptions = AddOptionsEnd(builder) + return addOptions + + +class MulOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MulOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMulOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MulOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # MulOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # MulOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def MulOptionsStart(builder): + builder.StartObject(1) + +def MulOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def MulOptionsEnd(builder): + return builder.EndObject() + + + +class MulOptionsT(object): + + # MulOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + mulOptions = MulOptions() + mulOptions.Init(buf, pos) + return cls.InitFromObj(mulOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, mulOptions): + x = MulOptionsT() + x._UnPack(mulOptions) + return x + + # MulOptionsT + def _UnPack(self, mulOptions): + if mulOptions is None: + return + self.fusedActivationFunction = mulOptions.FusedActivationFunction() + + # MulOptionsT + def Pack(self, builder): + MulOptionsStart(builder) + MulOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + mulOptions = MulOptionsEnd(builder) + return mulOptions + + +class L2NormOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = L2NormOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsL2NormOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def L2NormOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # L2NormOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # L2NormOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def L2NormOptionsStart(builder): + builder.StartObject(1) + +def L2NormOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def L2NormOptionsEnd(builder): + return builder.EndObject() + + + +class L2NormOptionsT(object): + + # L2NormOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + l2NormOptions = L2NormOptions() + l2NormOptions.Init(buf, pos) + return cls.InitFromObj(l2NormOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, l2NormOptions): + x = L2NormOptionsT() + x._UnPack(l2NormOptions) + return x + + # L2NormOptionsT + def _UnPack(self, l2NormOptions): + if l2NormOptions is None: + return + self.fusedActivationFunction = l2NormOptions.FusedActivationFunction() + + # L2NormOptionsT + def Pack(self, builder): + L2NormOptionsStart(builder) + L2NormOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + l2NormOptions = L2NormOptionsEnd(builder) + return l2NormOptions + + +class LocalResponseNormalizationOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LocalResponseNormalizationOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLocalResponseNormalizationOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LocalResponseNormalizationOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LocalResponseNormalizationOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # LocalResponseNormalizationOptions + def Radius(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # LocalResponseNormalizationOptions + def Bias(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # LocalResponseNormalizationOptions + def Alpha(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # LocalResponseNormalizationOptions + def Beta(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + +def LocalResponseNormalizationOptionsStart(builder): + builder.StartObject(4) + +def LocalResponseNormalizationOptionsAddRadius(builder, radius): + builder.PrependInt32Slot(0, radius, 0) + +def LocalResponseNormalizationOptionsAddBias(builder, bias): + builder.PrependFloat32Slot(1, bias, 0.0) + +def LocalResponseNormalizationOptionsAddAlpha(builder, alpha): + builder.PrependFloat32Slot(2, alpha, 0.0) + +def LocalResponseNormalizationOptionsAddBeta(builder, beta): + builder.PrependFloat32Slot(3, beta, 0.0) + +def LocalResponseNormalizationOptionsEnd(builder): + return builder.EndObject() + + + +class LocalResponseNormalizationOptionsT(object): + + # LocalResponseNormalizationOptionsT + def __init__(self): + self.radius = 0 # type: int + self.bias = 0.0 # type: float + self.alpha = 0.0 # type: float + self.beta = 0.0 # type: float + + @classmethod + def InitFromBuf(cls, buf, pos): + localResponseNormalizationOptions = LocalResponseNormalizationOptions() + localResponseNormalizationOptions.Init(buf, pos) + return cls.InitFromObj(localResponseNormalizationOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, localResponseNormalizationOptions): + x = LocalResponseNormalizationOptionsT() + x._UnPack(localResponseNormalizationOptions) + return x + + # LocalResponseNormalizationOptionsT + def _UnPack(self, localResponseNormalizationOptions): + if localResponseNormalizationOptions is None: + return + self.radius = localResponseNormalizationOptions.Radius() + self.bias = localResponseNormalizationOptions.Bias() + self.alpha = localResponseNormalizationOptions.Alpha() + self.beta = localResponseNormalizationOptions.Beta() + + # LocalResponseNormalizationOptionsT + def Pack(self, builder): + LocalResponseNormalizationOptionsStart(builder) + LocalResponseNormalizationOptionsAddRadius(builder, self.radius) + LocalResponseNormalizationOptionsAddBias(builder, self.bias) + LocalResponseNormalizationOptionsAddAlpha(builder, self.alpha) + LocalResponseNormalizationOptionsAddBeta(builder, self.beta) + localResponseNormalizationOptions = LocalResponseNormalizationOptionsEnd(builder) + return localResponseNormalizationOptions + + +class LSTMOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LSTMOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLSTMOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LSTMOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LSTMOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # LSTMOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # LSTMOptions + def CellClip(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # LSTMOptions + def ProjClip(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # LSTMOptions + def KernelType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # LSTMOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def LSTMOptionsStart(builder): + builder.StartObject(5) + +def LSTMOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def LSTMOptionsAddCellClip(builder, cellClip): + builder.PrependFloat32Slot(1, cellClip, 0.0) + +def LSTMOptionsAddProjClip(builder, projClip): + builder.PrependFloat32Slot(2, projClip, 0.0) + +def LSTMOptionsAddKernelType(builder, kernelType): + builder.PrependInt8Slot(3, kernelType, 0) + +def LSTMOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(4, asymmetricQuantizeInputs, 0) + +def LSTMOptionsEnd(builder): + return builder.EndObject() + + + +class LSTMOptionsT(object): + + # LSTMOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.cellClip = 0.0 # type: float + self.projClip = 0.0 # type: float + self.kernelType = 0 # type: int + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + lstmoptions = LSTMOptions() + lstmoptions.Init(buf, pos) + return cls.InitFromObj(lstmoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, lstmoptions): + x = LSTMOptionsT() + x._UnPack(lstmoptions) + return x + + # LSTMOptionsT + def _UnPack(self, lstmoptions): + if lstmoptions is None: + return + self.fusedActivationFunction = lstmoptions.FusedActivationFunction() + self.cellClip = lstmoptions.CellClip() + self.projClip = lstmoptions.ProjClip() + self.kernelType = lstmoptions.KernelType() + self.asymmetricQuantizeInputs = lstmoptions.AsymmetricQuantizeInputs() + + # LSTMOptionsT + def Pack(self, builder): + LSTMOptionsStart(builder) + LSTMOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + LSTMOptionsAddCellClip(builder, self.cellClip) + LSTMOptionsAddProjClip(builder, self.projClip) + LSTMOptionsAddKernelType(builder, self.kernelType) + LSTMOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + lstmoptions = LSTMOptionsEnd(builder) + return lstmoptions + + +class UnidirectionalSequenceLSTMOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UnidirectionalSequenceLSTMOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUnidirectionalSequenceLSTMOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UnidirectionalSequenceLSTMOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UnidirectionalSequenceLSTMOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # UnidirectionalSequenceLSTMOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # UnidirectionalSequenceLSTMOptions + def CellClip(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # UnidirectionalSequenceLSTMOptions + def ProjClip(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # UnidirectionalSequenceLSTMOptions + def TimeMajor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # UnidirectionalSequenceLSTMOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # UnidirectionalSequenceLSTMOptions + def DiagonalRecurrentTensors(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def UnidirectionalSequenceLSTMOptionsStart(builder): + builder.StartObject(6) + +def UnidirectionalSequenceLSTMOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def UnidirectionalSequenceLSTMOptionsAddCellClip(builder, cellClip): + builder.PrependFloat32Slot(1, cellClip, 0.0) + +def UnidirectionalSequenceLSTMOptionsAddProjClip(builder, projClip): + builder.PrependFloat32Slot(2, projClip, 0.0) + +def UnidirectionalSequenceLSTMOptionsAddTimeMajor(builder, timeMajor): + builder.PrependBoolSlot(3, timeMajor, 0) + +def UnidirectionalSequenceLSTMOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(4, asymmetricQuantizeInputs, 0) + +def UnidirectionalSequenceLSTMOptionsAddDiagonalRecurrentTensors(builder, diagonalRecurrentTensors): + builder.PrependBoolSlot(5, diagonalRecurrentTensors, 0) + +def UnidirectionalSequenceLSTMOptionsEnd(builder): + return builder.EndObject() + + + +class UnidirectionalSequenceLSTMOptionsT(object): + + # UnidirectionalSequenceLSTMOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.cellClip = 0.0 # type: float + self.projClip = 0.0 # type: float + self.timeMajor = False # type: bool + self.asymmetricQuantizeInputs = False # type: bool + self.diagonalRecurrentTensors = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + unidirectionalSequenceLstmoptions = UnidirectionalSequenceLSTMOptions() + unidirectionalSequenceLstmoptions.Init(buf, pos) + return cls.InitFromObj(unidirectionalSequenceLstmoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, unidirectionalSequenceLstmoptions): + x = UnidirectionalSequenceLSTMOptionsT() + x._UnPack(unidirectionalSequenceLstmoptions) + return x + + # UnidirectionalSequenceLSTMOptionsT + def _UnPack(self, unidirectionalSequenceLstmoptions): + if unidirectionalSequenceLstmoptions is None: + return + self.fusedActivationFunction = unidirectionalSequenceLstmoptions.FusedActivationFunction() + self.cellClip = unidirectionalSequenceLstmoptions.CellClip() + self.projClip = unidirectionalSequenceLstmoptions.ProjClip() + self.timeMajor = unidirectionalSequenceLstmoptions.TimeMajor() + self.asymmetricQuantizeInputs = unidirectionalSequenceLstmoptions.AsymmetricQuantizeInputs() + self.diagonalRecurrentTensors = unidirectionalSequenceLstmoptions.DiagonalRecurrentTensors() + + # UnidirectionalSequenceLSTMOptionsT + def Pack(self, builder): + UnidirectionalSequenceLSTMOptionsStart(builder) + UnidirectionalSequenceLSTMOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + UnidirectionalSequenceLSTMOptionsAddCellClip(builder, self.cellClip) + UnidirectionalSequenceLSTMOptionsAddProjClip(builder, self.projClip) + UnidirectionalSequenceLSTMOptionsAddTimeMajor(builder, self.timeMajor) + UnidirectionalSequenceLSTMOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + UnidirectionalSequenceLSTMOptionsAddDiagonalRecurrentTensors(builder, self.diagonalRecurrentTensors) + unidirectionalSequenceLstmoptions = UnidirectionalSequenceLSTMOptionsEnd(builder) + return unidirectionalSequenceLstmoptions + + +class BidirectionalSequenceLSTMOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BidirectionalSequenceLSTMOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBidirectionalSequenceLSTMOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BidirectionalSequenceLSTMOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BidirectionalSequenceLSTMOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # BidirectionalSequenceLSTMOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # BidirectionalSequenceLSTMOptions + def CellClip(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # BidirectionalSequenceLSTMOptions + def ProjClip(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # BidirectionalSequenceLSTMOptions + def MergeOutputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # BidirectionalSequenceLSTMOptions + def TimeMajor(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return True + + # BidirectionalSequenceLSTMOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def BidirectionalSequenceLSTMOptionsStart(builder): + builder.StartObject(6) + +def BidirectionalSequenceLSTMOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def BidirectionalSequenceLSTMOptionsAddCellClip(builder, cellClip): + builder.PrependFloat32Slot(1, cellClip, 0.0) + +def BidirectionalSequenceLSTMOptionsAddProjClip(builder, projClip): + builder.PrependFloat32Slot(2, projClip, 0.0) + +def BidirectionalSequenceLSTMOptionsAddMergeOutputs(builder, mergeOutputs): + builder.PrependBoolSlot(3, mergeOutputs, 0) + +def BidirectionalSequenceLSTMOptionsAddTimeMajor(builder, timeMajor): + builder.PrependBoolSlot(4, timeMajor, 1) + +def BidirectionalSequenceLSTMOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(5, asymmetricQuantizeInputs, 0) + +def BidirectionalSequenceLSTMOptionsEnd(builder): + return builder.EndObject() + + + +class BidirectionalSequenceLSTMOptionsT(object): + + # BidirectionalSequenceLSTMOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.cellClip = 0.0 # type: float + self.projClip = 0.0 # type: float + self.mergeOutputs = False # type: bool + self.timeMajor = True # type: bool + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + bidirectionalSequenceLstmoptions = BidirectionalSequenceLSTMOptions() + bidirectionalSequenceLstmoptions.Init(buf, pos) + return cls.InitFromObj(bidirectionalSequenceLstmoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, bidirectionalSequenceLstmoptions): + x = BidirectionalSequenceLSTMOptionsT() + x._UnPack(bidirectionalSequenceLstmoptions) + return x + + # BidirectionalSequenceLSTMOptionsT + def _UnPack(self, bidirectionalSequenceLstmoptions): + if bidirectionalSequenceLstmoptions is None: + return + self.fusedActivationFunction = bidirectionalSequenceLstmoptions.FusedActivationFunction() + self.cellClip = bidirectionalSequenceLstmoptions.CellClip() + self.projClip = bidirectionalSequenceLstmoptions.ProjClip() + self.mergeOutputs = bidirectionalSequenceLstmoptions.MergeOutputs() + self.timeMajor = bidirectionalSequenceLstmoptions.TimeMajor() + self.asymmetricQuantizeInputs = bidirectionalSequenceLstmoptions.AsymmetricQuantizeInputs() + + # BidirectionalSequenceLSTMOptionsT + def Pack(self, builder): + BidirectionalSequenceLSTMOptionsStart(builder) + BidirectionalSequenceLSTMOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + BidirectionalSequenceLSTMOptionsAddCellClip(builder, self.cellClip) + BidirectionalSequenceLSTMOptionsAddProjClip(builder, self.projClip) + BidirectionalSequenceLSTMOptionsAddMergeOutputs(builder, self.mergeOutputs) + BidirectionalSequenceLSTMOptionsAddTimeMajor(builder, self.timeMajor) + BidirectionalSequenceLSTMOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + bidirectionalSequenceLstmoptions = BidirectionalSequenceLSTMOptionsEnd(builder) + return bidirectionalSequenceLstmoptions + + +class ResizeBilinearOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ResizeBilinearOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsResizeBilinearOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ResizeBilinearOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ResizeBilinearOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ResizeBilinearOptions + def AlignCorners(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ResizeBilinearOptions + def HalfPixelCenters(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def ResizeBilinearOptionsStart(builder): + builder.StartObject(4) + +def ResizeBilinearOptionsAddAlignCorners(builder, alignCorners): + builder.PrependBoolSlot(2, alignCorners, 0) + +def ResizeBilinearOptionsAddHalfPixelCenters(builder, halfPixelCenters): + builder.PrependBoolSlot(3, halfPixelCenters, 0) + +def ResizeBilinearOptionsEnd(builder): + return builder.EndObject() + + + +class ResizeBilinearOptionsT(object): + + # ResizeBilinearOptionsT + def __init__(self): + self.alignCorners = False # type: bool + self.halfPixelCenters = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + resizeBilinearOptions = ResizeBilinearOptions() + resizeBilinearOptions.Init(buf, pos) + return cls.InitFromObj(resizeBilinearOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, resizeBilinearOptions): + x = ResizeBilinearOptionsT() + x._UnPack(resizeBilinearOptions) + return x + + # ResizeBilinearOptionsT + def _UnPack(self, resizeBilinearOptions): + if resizeBilinearOptions is None: + return + self.alignCorners = resizeBilinearOptions.AlignCorners() + self.halfPixelCenters = resizeBilinearOptions.HalfPixelCenters() + + # ResizeBilinearOptionsT + def Pack(self, builder): + ResizeBilinearOptionsStart(builder) + ResizeBilinearOptionsAddAlignCorners(builder, self.alignCorners) + ResizeBilinearOptionsAddHalfPixelCenters(builder, self.halfPixelCenters) + resizeBilinearOptions = ResizeBilinearOptionsEnd(builder) + return resizeBilinearOptions + + +class ResizeNearestNeighborOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ResizeNearestNeighborOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsResizeNearestNeighborOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ResizeNearestNeighborOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ResizeNearestNeighborOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ResizeNearestNeighborOptions + def AlignCorners(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ResizeNearestNeighborOptions + def HalfPixelCenters(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def ResizeNearestNeighborOptionsStart(builder): + builder.StartObject(2) + +def ResizeNearestNeighborOptionsAddAlignCorners(builder, alignCorners): + builder.PrependBoolSlot(0, alignCorners, 0) + +def ResizeNearestNeighborOptionsAddHalfPixelCenters(builder, halfPixelCenters): + builder.PrependBoolSlot(1, halfPixelCenters, 0) + +def ResizeNearestNeighborOptionsEnd(builder): + return builder.EndObject() + + + +class ResizeNearestNeighborOptionsT(object): + + # ResizeNearestNeighborOptionsT + def __init__(self): + self.alignCorners = False # type: bool + self.halfPixelCenters = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + resizeNearestNeighborOptions = ResizeNearestNeighborOptions() + resizeNearestNeighborOptions.Init(buf, pos) + return cls.InitFromObj(resizeNearestNeighborOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, resizeNearestNeighborOptions): + x = ResizeNearestNeighborOptionsT() + x._UnPack(resizeNearestNeighborOptions) + return x + + # ResizeNearestNeighborOptionsT + def _UnPack(self, resizeNearestNeighborOptions): + if resizeNearestNeighborOptions is None: + return + self.alignCorners = resizeNearestNeighborOptions.AlignCorners() + self.halfPixelCenters = resizeNearestNeighborOptions.HalfPixelCenters() + + # ResizeNearestNeighborOptionsT + def Pack(self, builder): + ResizeNearestNeighborOptionsStart(builder) + ResizeNearestNeighborOptionsAddAlignCorners(builder, self.alignCorners) + ResizeNearestNeighborOptionsAddHalfPixelCenters(builder, self.halfPixelCenters) + resizeNearestNeighborOptions = ResizeNearestNeighborOptionsEnd(builder) + return resizeNearestNeighborOptions + + +class CallOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = CallOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCallOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CallOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # CallOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # CallOptions + def Subgraph(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def CallOptionsStart(builder): + builder.StartObject(1) + +def CallOptionsAddSubgraph(builder, subgraph): + builder.PrependUint32Slot(0, subgraph, 0) + +def CallOptionsEnd(builder): + return builder.EndObject() + + + +class CallOptionsT(object): + + # CallOptionsT + def __init__(self): + self.subgraph = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + callOptions = CallOptions() + callOptions.Init(buf, pos) + return cls.InitFromObj(callOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, callOptions): + x = CallOptionsT() + x._UnPack(callOptions) + return x + + # CallOptionsT + def _UnPack(self, callOptions): + if callOptions is None: + return + self.subgraph = callOptions.Subgraph() + + # CallOptionsT + def Pack(self, builder): + CallOptionsStart(builder) + CallOptionsAddSubgraph(builder, self.subgraph) + callOptions = CallOptionsEnd(builder) + return callOptions + + +class PadOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = PadOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsPadOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def PadOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # PadOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def PadOptionsStart(builder): + builder.StartObject(0) + +def PadOptionsEnd(builder): + return builder.EndObject() + + + +class PadOptionsT(object): + + # PadOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + padOptions = PadOptions() + padOptions.Init(buf, pos) + return cls.InitFromObj(padOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, padOptions): + x = PadOptionsT() + x._UnPack(padOptions) + return x + + # PadOptionsT + def _UnPack(self, padOptions): + if padOptions is None: + return + + # PadOptionsT + def Pack(self, builder): + PadOptionsStart(builder) + padOptions = PadOptionsEnd(builder) + return padOptions + + +class PadV2Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = PadV2Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsPadV2Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def PadV2OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # PadV2Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def PadV2OptionsStart(builder): + builder.StartObject(0) + +def PadV2OptionsEnd(builder): + return builder.EndObject() + + + +class PadV2OptionsT(object): + + # PadV2OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + padV2Options = PadV2Options() + padV2Options.Init(buf, pos) + return cls.InitFromObj(padV2Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, padV2Options): + x = PadV2OptionsT() + x._UnPack(padV2Options) + return x + + # PadV2OptionsT + def _UnPack(self, padV2Options): + if padV2Options is None: + return + + # PadV2OptionsT + def Pack(self, builder): + PadV2OptionsStart(builder) + padV2Options = PadV2OptionsEnd(builder) + return padV2Options + + +class ReshapeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ReshapeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReshapeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReshapeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ReshapeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ReshapeOptions + def NewShape(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # ReshapeOptions + def NewShapeAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # ReshapeOptions + def NewShapeLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # ReshapeOptions + def NewShapeIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def ReshapeOptionsStart(builder): + builder.StartObject(1) + +def ReshapeOptionsAddNewShape(builder, newShape): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(newShape), 0) + +def ReshapeOptionsStartNewShapeVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ReshapeOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class ReshapeOptionsT(object): + + # ReshapeOptionsT + def __init__(self): + self.newShape = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + reshapeOptions = ReshapeOptions() + reshapeOptions.Init(buf, pos) + return cls.InitFromObj(reshapeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, reshapeOptions): + x = ReshapeOptionsT() + x._UnPack(reshapeOptions) + return x + + # ReshapeOptionsT + def _UnPack(self, reshapeOptions): + if reshapeOptions is None: + return + if not reshapeOptions.NewShapeIsNone(): + if np is None: + self.newShape = [] + for i in range(reshapeOptions.NewShapeLength()): + self.newShape.append(reshapeOptions.NewShape(i)) + else: + self.newShape = reshapeOptions.NewShapeAsNumpy() + + # ReshapeOptionsT + def Pack(self, builder): + if self.newShape is not None: + if np is not None and type(self.newShape) is np.ndarray: + newShape = builder.CreateNumpyVector(self.newShape) + else: + ReshapeOptionsStartNewShapeVector(builder, len(self.newShape)) + for i in reversed(range(len(self.newShape))): + builder.PrependInt32(self.newShape[i]) + newShape = builder.EndVector() + ReshapeOptionsStart(builder) + if self.newShape is not None: + ReshapeOptionsAddNewShape(builder, newShape) + reshapeOptions = ReshapeOptionsEnd(builder) + return reshapeOptions + + +class SpaceToBatchNDOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SpaceToBatchNDOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSpaceToBatchNDOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SpaceToBatchNDOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SpaceToBatchNDOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SpaceToBatchNDOptionsStart(builder): + builder.StartObject(0) + +def SpaceToBatchNDOptionsEnd(builder): + return builder.EndObject() + + + +class SpaceToBatchNDOptionsT(object): + + # SpaceToBatchNDOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + spaceToBatchNdoptions = SpaceToBatchNDOptions() + spaceToBatchNdoptions.Init(buf, pos) + return cls.InitFromObj(spaceToBatchNdoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, spaceToBatchNdoptions): + x = SpaceToBatchNDOptionsT() + x._UnPack(spaceToBatchNdoptions) + return x + + # SpaceToBatchNDOptionsT + def _UnPack(self, spaceToBatchNdoptions): + if spaceToBatchNdoptions is None: + return + + # SpaceToBatchNDOptionsT + def Pack(self, builder): + SpaceToBatchNDOptionsStart(builder) + spaceToBatchNdoptions = SpaceToBatchNDOptionsEnd(builder) + return spaceToBatchNdoptions + + +class BatchToSpaceNDOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BatchToSpaceNDOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBatchToSpaceNDOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BatchToSpaceNDOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BatchToSpaceNDOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def BatchToSpaceNDOptionsStart(builder): + builder.StartObject(0) + +def BatchToSpaceNDOptionsEnd(builder): + return builder.EndObject() + + + +class BatchToSpaceNDOptionsT(object): + + # BatchToSpaceNDOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + batchToSpaceNdoptions = BatchToSpaceNDOptions() + batchToSpaceNdoptions.Init(buf, pos) + return cls.InitFromObj(batchToSpaceNdoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, batchToSpaceNdoptions): + x = BatchToSpaceNDOptionsT() + x._UnPack(batchToSpaceNdoptions) + return x + + # BatchToSpaceNDOptionsT + def _UnPack(self, batchToSpaceNdoptions): + if batchToSpaceNdoptions is None: + return + + # BatchToSpaceNDOptionsT + def Pack(self, builder): + BatchToSpaceNDOptionsStart(builder) + batchToSpaceNdoptions = BatchToSpaceNDOptionsEnd(builder) + return batchToSpaceNdoptions + + +class SkipGramOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SkipGramOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSkipGramOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SkipGramOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SkipGramOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SkipGramOptions + def NgramSize(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # SkipGramOptions + def MaxSkipSize(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # SkipGramOptions + def IncludeAllNgrams(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def SkipGramOptionsStart(builder): + builder.StartObject(3) + +def SkipGramOptionsAddNgramSize(builder, ngramSize): + builder.PrependInt32Slot(0, ngramSize, 0) + +def SkipGramOptionsAddMaxSkipSize(builder, maxSkipSize): + builder.PrependInt32Slot(1, maxSkipSize, 0) + +def SkipGramOptionsAddIncludeAllNgrams(builder, includeAllNgrams): + builder.PrependBoolSlot(2, includeAllNgrams, 0) + +def SkipGramOptionsEnd(builder): + return builder.EndObject() + + + +class SkipGramOptionsT(object): + + # SkipGramOptionsT + def __init__(self): + self.ngramSize = 0 # type: int + self.maxSkipSize = 0 # type: int + self.includeAllNgrams = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + skipGramOptions = SkipGramOptions() + skipGramOptions.Init(buf, pos) + return cls.InitFromObj(skipGramOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, skipGramOptions): + x = SkipGramOptionsT() + x._UnPack(skipGramOptions) + return x + + # SkipGramOptionsT + def _UnPack(self, skipGramOptions): + if skipGramOptions is None: + return + self.ngramSize = skipGramOptions.NgramSize() + self.maxSkipSize = skipGramOptions.MaxSkipSize() + self.includeAllNgrams = skipGramOptions.IncludeAllNgrams() + + # SkipGramOptionsT + def Pack(self, builder): + SkipGramOptionsStart(builder) + SkipGramOptionsAddNgramSize(builder, self.ngramSize) + SkipGramOptionsAddMaxSkipSize(builder, self.maxSkipSize) + SkipGramOptionsAddIncludeAllNgrams(builder, self.includeAllNgrams) + skipGramOptions = SkipGramOptionsEnd(builder) + return skipGramOptions + + +class SpaceToDepthOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SpaceToDepthOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSpaceToDepthOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SpaceToDepthOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SpaceToDepthOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SpaceToDepthOptions + def BlockSize(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def SpaceToDepthOptionsStart(builder): + builder.StartObject(1) + +def SpaceToDepthOptionsAddBlockSize(builder, blockSize): + builder.PrependInt32Slot(0, blockSize, 0) + +def SpaceToDepthOptionsEnd(builder): + return builder.EndObject() + + + +class SpaceToDepthOptionsT(object): + + # SpaceToDepthOptionsT + def __init__(self): + self.blockSize = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + spaceToDepthOptions = SpaceToDepthOptions() + spaceToDepthOptions.Init(buf, pos) + return cls.InitFromObj(spaceToDepthOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, spaceToDepthOptions): + x = SpaceToDepthOptionsT() + x._UnPack(spaceToDepthOptions) + return x + + # SpaceToDepthOptionsT + def _UnPack(self, spaceToDepthOptions): + if spaceToDepthOptions is None: + return + self.blockSize = spaceToDepthOptions.BlockSize() + + # SpaceToDepthOptionsT + def Pack(self, builder): + SpaceToDepthOptionsStart(builder) + SpaceToDepthOptionsAddBlockSize(builder, self.blockSize) + spaceToDepthOptions = SpaceToDepthOptionsEnd(builder) + return spaceToDepthOptions + + +class DepthToSpaceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DepthToSpaceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDepthToSpaceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DepthToSpaceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DepthToSpaceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DepthToSpaceOptions + def BlockSize(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def DepthToSpaceOptionsStart(builder): + builder.StartObject(1) + +def DepthToSpaceOptionsAddBlockSize(builder, blockSize): + builder.PrependInt32Slot(0, blockSize, 0) + +def DepthToSpaceOptionsEnd(builder): + return builder.EndObject() + + + +class DepthToSpaceOptionsT(object): + + # DepthToSpaceOptionsT + def __init__(self): + self.blockSize = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + depthToSpaceOptions = DepthToSpaceOptions() + depthToSpaceOptions.Init(buf, pos) + return cls.InitFromObj(depthToSpaceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, depthToSpaceOptions): + x = DepthToSpaceOptionsT() + x._UnPack(depthToSpaceOptions) + return x + + # DepthToSpaceOptionsT + def _UnPack(self, depthToSpaceOptions): + if depthToSpaceOptions is None: + return + self.blockSize = depthToSpaceOptions.BlockSize() + + # DepthToSpaceOptionsT + def Pack(self, builder): + DepthToSpaceOptionsStart(builder) + DepthToSpaceOptionsAddBlockSize(builder, self.blockSize) + depthToSpaceOptions = DepthToSpaceOptionsEnd(builder) + return depthToSpaceOptions + + +class SubOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SubOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSubOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SubOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SubOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SubOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # SubOptions + def PotScaleInt16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return True + +def SubOptionsStart(builder): + builder.StartObject(2) + +def SubOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def SubOptionsAddPotScaleInt16(builder, potScaleInt16): + builder.PrependBoolSlot(1, potScaleInt16, 1) + +def SubOptionsEnd(builder): + return builder.EndObject() + + + +class SubOptionsT(object): + + # SubOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + self.potScaleInt16 = True # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + subOptions = SubOptions() + subOptions.Init(buf, pos) + return cls.InitFromObj(subOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, subOptions): + x = SubOptionsT() + x._UnPack(subOptions) + return x + + # SubOptionsT + def _UnPack(self, subOptions): + if subOptions is None: + return + self.fusedActivationFunction = subOptions.FusedActivationFunction() + self.potScaleInt16 = subOptions.PotScaleInt16() + + # SubOptionsT + def Pack(self, builder): + SubOptionsStart(builder) + SubOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + SubOptionsAddPotScaleInt16(builder, self.potScaleInt16) + subOptions = SubOptionsEnd(builder) + return subOptions + + +class DivOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DivOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDivOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DivOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DivOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # DivOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def DivOptionsStart(builder): + builder.StartObject(1) + +def DivOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(0, fusedActivationFunction, 0) + +def DivOptionsEnd(builder): + return builder.EndObject() + + + +class DivOptionsT(object): + + # DivOptionsT + def __init__(self): + self.fusedActivationFunction = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + divOptions = DivOptions() + divOptions.Init(buf, pos) + return cls.InitFromObj(divOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, divOptions): + x = DivOptionsT() + x._UnPack(divOptions) + return x + + # DivOptionsT + def _UnPack(self, divOptions): + if divOptions is None: + return + self.fusedActivationFunction = divOptions.FusedActivationFunction() + + # DivOptionsT + def Pack(self, builder): + DivOptionsStart(builder) + DivOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + divOptions = DivOptionsEnd(builder) + return divOptions + + +class TopKV2Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TopKV2Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTopKV2Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TopKV2OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # TopKV2Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def TopKV2OptionsStart(builder): + builder.StartObject(0) + +def TopKV2OptionsEnd(builder): + return builder.EndObject() + + + +class TopKV2OptionsT(object): + + # TopKV2OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + topKv2Options = TopKV2Options() + topKv2Options.Init(buf, pos) + return cls.InitFromObj(topKv2Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, topKv2Options): + x = TopKV2OptionsT() + x._UnPack(topKv2Options) + return x + + # TopKV2OptionsT + def _UnPack(self, topKv2Options): + if topKv2Options is None: + return + + # TopKV2OptionsT + def Pack(self, builder): + TopKV2OptionsStart(builder) + topKv2Options = TopKV2OptionsEnd(builder) + return topKv2Options + + +class EmbeddingLookupSparseOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = EmbeddingLookupSparseOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsEmbeddingLookupSparseOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def EmbeddingLookupSparseOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # EmbeddingLookupSparseOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # EmbeddingLookupSparseOptions + def Combiner(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def EmbeddingLookupSparseOptionsStart(builder): + builder.StartObject(1) + +def EmbeddingLookupSparseOptionsAddCombiner(builder, combiner): + builder.PrependInt8Slot(0, combiner, 0) + +def EmbeddingLookupSparseOptionsEnd(builder): + return builder.EndObject() + + + +class EmbeddingLookupSparseOptionsT(object): + + # EmbeddingLookupSparseOptionsT + def __init__(self): + self.combiner = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + embeddingLookupSparseOptions = EmbeddingLookupSparseOptions() + embeddingLookupSparseOptions.Init(buf, pos) + return cls.InitFromObj(embeddingLookupSparseOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, embeddingLookupSparseOptions): + x = EmbeddingLookupSparseOptionsT() + x._UnPack(embeddingLookupSparseOptions) + return x + + # EmbeddingLookupSparseOptionsT + def _UnPack(self, embeddingLookupSparseOptions): + if embeddingLookupSparseOptions is None: + return + self.combiner = embeddingLookupSparseOptions.Combiner() + + # EmbeddingLookupSparseOptionsT + def Pack(self, builder): + EmbeddingLookupSparseOptionsStart(builder) + EmbeddingLookupSparseOptionsAddCombiner(builder, self.combiner) + embeddingLookupSparseOptions = EmbeddingLookupSparseOptionsEnd(builder) + return embeddingLookupSparseOptions + + +class GatherOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = GatherOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGatherOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def GatherOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # GatherOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # GatherOptions + def Axis(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # GatherOptions + def BatchDims(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def GatherOptionsStart(builder): + builder.StartObject(2) + +def GatherOptionsAddAxis(builder, axis): + builder.PrependInt32Slot(0, axis, 0) + +def GatherOptionsAddBatchDims(builder, batchDims): + builder.PrependInt32Slot(1, batchDims, 0) + +def GatherOptionsEnd(builder): + return builder.EndObject() + + + +class GatherOptionsT(object): + + # GatherOptionsT + def __init__(self): + self.axis = 0 # type: int + self.batchDims = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + gatherOptions = GatherOptions() + gatherOptions.Init(buf, pos) + return cls.InitFromObj(gatherOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, gatherOptions): + x = GatherOptionsT() + x._UnPack(gatherOptions) + return x + + # GatherOptionsT + def _UnPack(self, gatherOptions): + if gatherOptions is None: + return + self.axis = gatherOptions.Axis() + self.batchDims = gatherOptions.BatchDims() + + # GatherOptionsT + def Pack(self, builder): + GatherOptionsStart(builder) + GatherOptionsAddAxis(builder, self.axis) + GatherOptionsAddBatchDims(builder, self.batchDims) + gatherOptions = GatherOptionsEnd(builder) + return gatherOptions + + +class TransposeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TransposeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTransposeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TransposeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # TransposeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def TransposeOptionsStart(builder): + builder.StartObject(0) + +def TransposeOptionsEnd(builder): + return builder.EndObject() + + + +class TransposeOptionsT(object): + + # TransposeOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + transposeOptions = TransposeOptions() + transposeOptions.Init(buf, pos) + return cls.InitFromObj(transposeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, transposeOptions): + x = TransposeOptionsT() + x._UnPack(transposeOptions) + return x + + # TransposeOptionsT + def _UnPack(self, transposeOptions): + if transposeOptions is None: + return + + # TransposeOptionsT + def Pack(self, builder): + TransposeOptionsStart(builder) + transposeOptions = TransposeOptionsEnd(builder) + return transposeOptions + + +class ExpOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ExpOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsExpOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ExpOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ExpOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ExpOptionsStart(builder): + builder.StartObject(0) + +def ExpOptionsEnd(builder): + return builder.EndObject() + + + +class ExpOptionsT(object): + + # ExpOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + expOptions = ExpOptions() + expOptions.Init(buf, pos) + return cls.InitFromObj(expOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, expOptions): + x = ExpOptionsT() + x._UnPack(expOptions) + return x + + # ExpOptionsT + def _UnPack(self, expOptions): + if expOptions is None: + return + + # ExpOptionsT + def Pack(self, builder): + ExpOptionsStart(builder) + expOptions = ExpOptionsEnd(builder) + return expOptions + + +class CosOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = CosOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCosOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CosOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # CosOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def CosOptionsStart(builder): + builder.StartObject(0) + +def CosOptionsEnd(builder): + return builder.EndObject() + + + +class CosOptionsT(object): + + # CosOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + cosOptions = CosOptions() + cosOptions.Init(buf, pos) + return cls.InitFromObj(cosOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, cosOptions): + x = CosOptionsT() + x._UnPack(cosOptions) + return x + + # CosOptionsT + def _UnPack(self, cosOptions): + if cosOptions is None: + return + + # CosOptionsT + def Pack(self, builder): + CosOptionsStart(builder) + cosOptions = CosOptionsEnd(builder) + return cosOptions + + +class ReducerOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ReducerOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReducerOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReducerOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ReducerOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ReducerOptions + def KeepDims(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def ReducerOptionsStart(builder): + builder.StartObject(1) + +def ReducerOptionsAddKeepDims(builder, keepDims): + builder.PrependBoolSlot(0, keepDims, 0) + +def ReducerOptionsEnd(builder): + return builder.EndObject() + + + +class ReducerOptionsT(object): + + # ReducerOptionsT + def __init__(self): + self.keepDims = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + reducerOptions = ReducerOptions() + reducerOptions.Init(buf, pos) + return cls.InitFromObj(reducerOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, reducerOptions): + x = ReducerOptionsT() + x._UnPack(reducerOptions) + return x + + # ReducerOptionsT + def _UnPack(self, reducerOptions): + if reducerOptions is None: + return + self.keepDims = reducerOptions.KeepDims() + + # ReducerOptionsT + def Pack(self, builder): + ReducerOptionsStart(builder) + ReducerOptionsAddKeepDims(builder, self.keepDims) + reducerOptions = ReducerOptionsEnd(builder) + return reducerOptions + + +class SqueezeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SqueezeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSqueezeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SqueezeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SqueezeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SqueezeOptions + def SqueezeDims(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # SqueezeOptions + def SqueezeDimsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # SqueezeOptions + def SqueezeDimsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SqueezeOptions + def SqueezeDimsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def SqueezeOptionsStart(builder): + builder.StartObject(1) + +def SqueezeOptionsAddSqueezeDims(builder, squeezeDims): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(squeezeDims), 0) + +def SqueezeOptionsStartSqueezeDimsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SqueezeOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class SqueezeOptionsT(object): + + # SqueezeOptionsT + def __init__(self): + self.squeezeDims = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + squeezeOptions = SqueezeOptions() + squeezeOptions.Init(buf, pos) + return cls.InitFromObj(squeezeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, squeezeOptions): + x = SqueezeOptionsT() + x._UnPack(squeezeOptions) + return x + + # SqueezeOptionsT + def _UnPack(self, squeezeOptions): + if squeezeOptions is None: + return + if not squeezeOptions.SqueezeDimsIsNone(): + if np is None: + self.squeezeDims = [] + for i in range(squeezeOptions.SqueezeDimsLength()): + self.squeezeDims.append(squeezeOptions.SqueezeDims(i)) + else: + self.squeezeDims = squeezeOptions.SqueezeDimsAsNumpy() + + # SqueezeOptionsT + def Pack(self, builder): + if self.squeezeDims is not None: + if np is not None and type(self.squeezeDims) is np.ndarray: + squeezeDims = builder.CreateNumpyVector(self.squeezeDims) + else: + SqueezeOptionsStartSqueezeDimsVector(builder, len(self.squeezeDims)) + for i in reversed(range(len(self.squeezeDims))): + builder.PrependInt32(self.squeezeDims[i]) + squeezeDims = builder.EndVector() + SqueezeOptionsStart(builder) + if self.squeezeDims is not None: + SqueezeOptionsAddSqueezeDims(builder, squeezeDims) + squeezeOptions = SqueezeOptionsEnd(builder) + return squeezeOptions + + +class SplitOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SplitOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSplitOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SplitOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SplitOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SplitOptions + def NumSplits(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def SplitOptionsStart(builder): + builder.StartObject(1) + +def SplitOptionsAddNumSplits(builder, numSplits): + builder.PrependInt32Slot(0, numSplits, 0) + +def SplitOptionsEnd(builder): + return builder.EndObject() + + + +class SplitOptionsT(object): + + # SplitOptionsT + def __init__(self): + self.numSplits = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + splitOptions = SplitOptions() + splitOptions.Init(buf, pos) + return cls.InitFromObj(splitOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, splitOptions): + x = SplitOptionsT() + x._UnPack(splitOptions) + return x + + # SplitOptionsT + def _UnPack(self, splitOptions): + if splitOptions is None: + return + self.numSplits = splitOptions.NumSplits() + + # SplitOptionsT + def Pack(self, builder): + SplitOptionsStart(builder) + SplitOptionsAddNumSplits(builder, self.numSplits) + splitOptions = SplitOptionsEnd(builder) + return splitOptions + + +class SplitVOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SplitVOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSplitVOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SplitVOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SplitVOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SplitVOptions + def NumSplits(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def SplitVOptionsStart(builder): + builder.StartObject(1) + +def SplitVOptionsAddNumSplits(builder, numSplits): + builder.PrependInt32Slot(0, numSplits, 0) + +def SplitVOptionsEnd(builder): + return builder.EndObject() + + + +class SplitVOptionsT(object): + + # SplitVOptionsT + def __init__(self): + self.numSplits = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + splitVoptions = SplitVOptions() + splitVoptions.Init(buf, pos) + return cls.InitFromObj(splitVoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, splitVoptions): + x = SplitVOptionsT() + x._UnPack(splitVoptions) + return x + + # SplitVOptionsT + def _UnPack(self, splitVoptions): + if splitVoptions is None: + return + self.numSplits = splitVoptions.NumSplits() + + # SplitVOptionsT + def Pack(self, builder): + SplitVOptionsStart(builder) + SplitVOptionsAddNumSplits(builder, self.numSplits) + splitVoptions = SplitVOptionsEnd(builder) + return splitVoptions + + +class StridedSliceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = StridedSliceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStridedSliceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StridedSliceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # StridedSliceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StridedSliceOptions + def BeginMask(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StridedSliceOptions + def EndMask(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StridedSliceOptions + def EllipsisMask(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StridedSliceOptions + def NewAxisMask(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StridedSliceOptions + def ShrinkAxisMask(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # StridedSliceOptions + def Offset(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def StridedSliceOptionsStart(builder): + builder.StartObject(6) + +def StridedSliceOptionsAddBeginMask(builder, beginMask): + builder.PrependInt32Slot(0, beginMask, 0) + +def StridedSliceOptionsAddEndMask(builder, endMask): + builder.PrependInt32Slot(1, endMask, 0) + +def StridedSliceOptionsAddEllipsisMask(builder, ellipsisMask): + builder.PrependInt32Slot(2, ellipsisMask, 0) + +def StridedSliceOptionsAddNewAxisMask(builder, newAxisMask): + builder.PrependInt32Slot(3, newAxisMask, 0) + +def StridedSliceOptionsAddShrinkAxisMask(builder, shrinkAxisMask): + builder.PrependInt32Slot(4, shrinkAxisMask, 0) + +def StridedSliceOptionsAddOffset(builder, offset): + builder.PrependBoolSlot(5, offset, 0) + +def StridedSliceOptionsEnd(builder): + return builder.EndObject() + + + +class StridedSliceOptionsT(object): + + # StridedSliceOptionsT + def __init__(self): + self.beginMask = 0 # type: int + self.endMask = 0 # type: int + self.ellipsisMask = 0 # type: int + self.newAxisMask = 0 # type: int + self.shrinkAxisMask = 0 # type: int + self.offset = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + stridedSliceOptions = StridedSliceOptions() + stridedSliceOptions.Init(buf, pos) + return cls.InitFromObj(stridedSliceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stridedSliceOptions): + x = StridedSliceOptionsT() + x._UnPack(stridedSliceOptions) + return x + + # StridedSliceOptionsT + def _UnPack(self, stridedSliceOptions): + if stridedSliceOptions is None: + return + self.beginMask = stridedSliceOptions.BeginMask() + self.endMask = stridedSliceOptions.EndMask() + self.ellipsisMask = stridedSliceOptions.EllipsisMask() + self.newAxisMask = stridedSliceOptions.NewAxisMask() + self.shrinkAxisMask = stridedSliceOptions.ShrinkAxisMask() + self.offset = stridedSliceOptions.Offset() + + # StridedSliceOptionsT + def Pack(self, builder): + StridedSliceOptionsStart(builder) + StridedSliceOptionsAddBeginMask(builder, self.beginMask) + StridedSliceOptionsAddEndMask(builder, self.endMask) + StridedSliceOptionsAddEllipsisMask(builder, self.ellipsisMask) + StridedSliceOptionsAddNewAxisMask(builder, self.newAxisMask) + StridedSliceOptionsAddShrinkAxisMask(builder, self.shrinkAxisMask) + StridedSliceOptionsAddOffset(builder, self.offset) + stridedSliceOptions = StridedSliceOptionsEnd(builder) + return stridedSliceOptions + + +class LogSoftmaxOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LogSoftmaxOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLogSoftmaxOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LogSoftmaxOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LogSoftmaxOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def LogSoftmaxOptionsStart(builder): + builder.StartObject(0) + +def LogSoftmaxOptionsEnd(builder): + return builder.EndObject() + + + +class LogSoftmaxOptionsT(object): + + # LogSoftmaxOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + logSoftmaxOptions = LogSoftmaxOptions() + logSoftmaxOptions.Init(buf, pos) + return cls.InitFromObj(logSoftmaxOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, logSoftmaxOptions): + x = LogSoftmaxOptionsT() + x._UnPack(logSoftmaxOptions) + return x + + # LogSoftmaxOptionsT + def _UnPack(self, logSoftmaxOptions): + if logSoftmaxOptions is None: + return + + # LogSoftmaxOptionsT + def Pack(self, builder): + LogSoftmaxOptionsStart(builder) + logSoftmaxOptions = LogSoftmaxOptionsEnd(builder) + return logSoftmaxOptions + + +class CastOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = CastOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCastOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CastOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # CastOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # CastOptions + def InDataType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # CastOptions + def OutDataType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def CastOptionsStart(builder): + builder.StartObject(2) + +def CastOptionsAddInDataType(builder, inDataType): + builder.PrependInt8Slot(0, inDataType, 0) + +def CastOptionsAddOutDataType(builder, outDataType): + builder.PrependInt8Slot(1, outDataType, 0) + +def CastOptionsEnd(builder): + return builder.EndObject() + + + +class CastOptionsT(object): + + # CastOptionsT + def __init__(self): + self.inDataType = 0 # type: int + self.outDataType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + castOptions = CastOptions() + castOptions.Init(buf, pos) + return cls.InitFromObj(castOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, castOptions): + x = CastOptionsT() + x._UnPack(castOptions) + return x + + # CastOptionsT + def _UnPack(self, castOptions): + if castOptions is None: + return + self.inDataType = castOptions.InDataType() + self.outDataType = castOptions.OutDataType() + + # CastOptionsT + def Pack(self, builder): + CastOptionsStart(builder) + CastOptionsAddInDataType(builder, self.inDataType) + CastOptionsAddOutDataType(builder, self.outDataType) + castOptions = CastOptionsEnd(builder) + return castOptions + + +class DequantizeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DequantizeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDequantizeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DequantizeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DequantizeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def DequantizeOptionsStart(builder): + builder.StartObject(0) + +def DequantizeOptionsEnd(builder): + return builder.EndObject() + + + +class DequantizeOptionsT(object): + + # DequantizeOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + dequantizeOptions = DequantizeOptions() + dequantizeOptions.Init(buf, pos) + return cls.InitFromObj(dequantizeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, dequantizeOptions): + x = DequantizeOptionsT() + x._UnPack(dequantizeOptions) + return x + + # DequantizeOptionsT + def _UnPack(self, dequantizeOptions): + if dequantizeOptions is None: + return + + # DequantizeOptionsT + def Pack(self, builder): + DequantizeOptionsStart(builder) + dequantizeOptions = DequantizeOptionsEnd(builder) + return dequantizeOptions + + +class MaximumMinimumOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MaximumMinimumOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMaximumMinimumOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MaximumMinimumOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # MaximumMinimumOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def MaximumMinimumOptionsStart(builder): + builder.StartObject(0) + +def MaximumMinimumOptionsEnd(builder): + return builder.EndObject() + + + +class MaximumMinimumOptionsT(object): + + # MaximumMinimumOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + maximumMinimumOptions = MaximumMinimumOptions() + maximumMinimumOptions.Init(buf, pos) + return cls.InitFromObj(maximumMinimumOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, maximumMinimumOptions): + x = MaximumMinimumOptionsT() + x._UnPack(maximumMinimumOptions) + return x + + # MaximumMinimumOptionsT + def _UnPack(self, maximumMinimumOptions): + if maximumMinimumOptions is None: + return + + # MaximumMinimumOptionsT + def Pack(self, builder): + MaximumMinimumOptionsStart(builder) + maximumMinimumOptions = MaximumMinimumOptionsEnd(builder) + return maximumMinimumOptions + + +class TileOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TileOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTileOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TileOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # TileOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def TileOptionsStart(builder): + builder.StartObject(0) + +def TileOptionsEnd(builder): + return builder.EndObject() + + + +class TileOptionsT(object): + + # TileOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + tileOptions = TileOptions() + tileOptions.Init(buf, pos) + return cls.InitFromObj(tileOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, tileOptions): + x = TileOptionsT() + x._UnPack(tileOptions) + return x + + # TileOptionsT + def _UnPack(self, tileOptions): + if tileOptions is None: + return + + # TileOptionsT + def Pack(self, builder): + TileOptionsStart(builder) + tileOptions = TileOptionsEnd(builder) + return tileOptions + + +class ArgMaxOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ArgMaxOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsArgMaxOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ArgMaxOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ArgMaxOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ArgMaxOptions + def OutputType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def ArgMaxOptionsStart(builder): + builder.StartObject(1) + +def ArgMaxOptionsAddOutputType(builder, outputType): + builder.PrependInt8Slot(0, outputType, 0) + +def ArgMaxOptionsEnd(builder): + return builder.EndObject() + + + +class ArgMaxOptionsT(object): + + # ArgMaxOptionsT + def __init__(self): + self.outputType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + argMaxOptions = ArgMaxOptions() + argMaxOptions.Init(buf, pos) + return cls.InitFromObj(argMaxOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, argMaxOptions): + x = ArgMaxOptionsT() + x._UnPack(argMaxOptions) + return x + + # ArgMaxOptionsT + def _UnPack(self, argMaxOptions): + if argMaxOptions is None: + return + self.outputType = argMaxOptions.OutputType() + + # ArgMaxOptionsT + def Pack(self, builder): + ArgMaxOptionsStart(builder) + ArgMaxOptionsAddOutputType(builder, self.outputType) + argMaxOptions = ArgMaxOptionsEnd(builder) + return argMaxOptions + + +class ArgMinOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ArgMinOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsArgMinOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ArgMinOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ArgMinOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ArgMinOptions + def OutputType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def ArgMinOptionsStart(builder): + builder.StartObject(1) + +def ArgMinOptionsAddOutputType(builder, outputType): + builder.PrependInt8Slot(0, outputType, 0) + +def ArgMinOptionsEnd(builder): + return builder.EndObject() + + + +class ArgMinOptionsT(object): + + # ArgMinOptionsT + def __init__(self): + self.outputType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + argMinOptions = ArgMinOptions() + argMinOptions.Init(buf, pos) + return cls.InitFromObj(argMinOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, argMinOptions): + x = ArgMinOptionsT() + x._UnPack(argMinOptions) + return x + + # ArgMinOptionsT + def _UnPack(self, argMinOptions): + if argMinOptions is None: + return + self.outputType = argMinOptions.OutputType() + + # ArgMinOptionsT + def Pack(self, builder): + ArgMinOptionsStart(builder) + ArgMinOptionsAddOutputType(builder, self.outputType) + argMinOptions = ArgMinOptionsEnd(builder) + return argMinOptions + + +class GreaterOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = GreaterOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGreaterOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def GreaterOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # GreaterOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def GreaterOptionsStart(builder): + builder.StartObject(0) + +def GreaterOptionsEnd(builder): + return builder.EndObject() + + + +class GreaterOptionsT(object): + + # GreaterOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + greaterOptions = GreaterOptions() + greaterOptions.Init(buf, pos) + return cls.InitFromObj(greaterOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, greaterOptions): + x = GreaterOptionsT() + x._UnPack(greaterOptions) + return x + + # GreaterOptionsT + def _UnPack(self, greaterOptions): + if greaterOptions is None: + return + + # GreaterOptionsT + def Pack(self, builder): + GreaterOptionsStart(builder) + greaterOptions = GreaterOptionsEnd(builder) + return greaterOptions + + +class GreaterEqualOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = GreaterEqualOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGreaterEqualOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def GreaterEqualOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # GreaterEqualOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def GreaterEqualOptionsStart(builder): + builder.StartObject(0) + +def GreaterEqualOptionsEnd(builder): + return builder.EndObject() + + + +class GreaterEqualOptionsT(object): + + # GreaterEqualOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + greaterEqualOptions = GreaterEqualOptions() + greaterEqualOptions.Init(buf, pos) + return cls.InitFromObj(greaterEqualOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, greaterEqualOptions): + x = GreaterEqualOptionsT() + x._UnPack(greaterEqualOptions) + return x + + # GreaterEqualOptionsT + def _UnPack(self, greaterEqualOptions): + if greaterEqualOptions is None: + return + + # GreaterEqualOptionsT + def Pack(self, builder): + GreaterEqualOptionsStart(builder) + greaterEqualOptions = GreaterEqualOptionsEnd(builder) + return greaterEqualOptions + + +class LessOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LessOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLessOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LessOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LessOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def LessOptionsStart(builder): + builder.StartObject(0) + +def LessOptionsEnd(builder): + return builder.EndObject() + + + +class LessOptionsT(object): + + # LessOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + lessOptions = LessOptions() + lessOptions.Init(buf, pos) + return cls.InitFromObj(lessOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, lessOptions): + x = LessOptionsT() + x._UnPack(lessOptions) + return x + + # LessOptionsT + def _UnPack(self, lessOptions): + if lessOptions is None: + return + + # LessOptionsT + def Pack(self, builder): + LessOptionsStart(builder) + lessOptions = LessOptionsEnd(builder) + return lessOptions + + +class LessEqualOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LessEqualOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLessEqualOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LessEqualOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LessEqualOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def LessEqualOptionsStart(builder): + builder.StartObject(0) + +def LessEqualOptionsEnd(builder): + return builder.EndObject() + + + +class LessEqualOptionsT(object): + + # LessEqualOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + lessEqualOptions = LessEqualOptions() + lessEqualOptions.Init(buf, pos) + return cls.InitFromObj(lessEqualOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, lessEqualOptions): + x = LessEqualOptionsT() + x._UnPack(lessEqualOptions) + return x + + # LessEqualOptionsT + def _UnPack(self, lessEqualOptions): + if lessEqualOptions is None: + return + + # LessEqualOptionsT + def Pack(self, builder): + LessEqualOptionsStart(builder) + lessEqualOptions = LessEqualOptionsEnd(builder) + return lessEqualOptions + + +class NegOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NegOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNegOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NegOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # NegOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def NegOptionsStart(builder): + builder.StartObject(0) + +def NegOptionsEnd(builder): + return builder.EndObject() + + + +class NegOptionsT(object): + + # NegOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + negOptions = NegOptions() + negOptions.Init(buf, pos) + return cls.InitFromObj(negOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, negOptions): + x = NegOptionsT() + x._UnPack(negOptions) + return x + + # NegOptionsT + def _UnPack(self, negOptions): + if negOptions is None: + return + + # NegOptionsT + def Pack(self, builder): + NegOptionsStart(builder) + negOptions = NegOptionsEnd(builder) + return negOptions + + +class SelectOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SelectOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSelectOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SelectOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SelectOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SelectOptionsStart(builder): + builder.StartObject(0) + +def SelectOptionsEnd(builder): + return builder.EndObject() + + + +class SelectOptionsT(object): + + # SelectOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + selectOptions = SelectOptions() + selectOptions.Init(buf, pos) + return cls.InitFromObj(selectOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, selectOptions): + x = SelectOptionsT() + x._UnPack(selectOptions) + return x + + # SelectOptionsT + def _UnPack(self, selectOptions): + if selectOptions is None: + return + + # SelectOptionsT + def Pack(self, builder): + SelectOptionsStart(builder) + selectOptions = SelectOptionsEnd(builder) + return selectOptions + + +class SliceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SliceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSliceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SliceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SliceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SliceOptionsStart(builder): + builder.StartObject(0) + +def SliceOptionsEnd(builder): + return builder.EndObject() + + + +class SliceOptionsT(object): + + # SliceOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + sliceOptions = SliceOptions() + sliceOptions.Init(buf, pos) + return cls.InitFromObj(sliceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, sliceOptions): + x = SliceOptionsT() + x._UnPack(sliceOptions) + return x + + # SliceOptionsT + def _UnPack(self, sliceOptions): + if sliceOptions is None: + return + + # SliceOptionsT + def Pack(self, builder): + SliceOptionsStart(builder) + sliceOptions = SliceOptionsEnd(builder) + return sliceOptions + + +class TransposeConvOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TransposeConvOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTransposeConvOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TransposeConvOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # TransposeConvOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TransposeConvOptions + def Padding(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # TransposeConvOptions + def StrideW(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # TransposeConvOptions + def StrideH(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # TransposeConvOptions + def FusedActivationFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # TransposeConvOptions + def QuantizedBiasType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def TransposeConvOptionsStart(builder): + builder.StartObject(5) + +def TransposeConvOptionsAddPadding(builder, padding): + builder.PrependInt8Slot(0, padding, 0) + +def TransposeConvOptionsAddStrideW(builder, strideW): + builder.PrependInt32Slot(1, strideW, 0) + +def TransposeConvOptionsAddStrideH(builder, strideH): + builder.PrependInt32Slot(2, strideH, 0) + +def TransposeConvOptionsAddFusedActivationFunction(builder, fusedActivationFunction): + builder.PrependInt8Slot(3, fusedActivationFunction, 0) + +def TransposeConvOptionsAddQuantizedBiasType(builder, quantizedBiasType): + builder.PrependInt8Slot(4, quantizedBiasType, 0) + +def TransposeConvOptionsEnd(builder): + return builder.EndObject() + + + +class TransposeConvOptionsT(object): + + # TransposeConvOptionsT + def __init__(self): + self.padding = 0 # type: int + self.strideW = 0 # type: int + self.strideH = 0 # type: int + self.fusedActivationFunction = 0 # type: int + self.quantizedBiasType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + transposeConvOptions = TransposeConvOptions() + transposeConvOptions.Init(buf, pos) + return cls.InitFromObj(transposeConvOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, transposeConvOptions): + x = TransposeConvOptionsT() + x._UnPack(transposeConvOptions) + return x + + # TransposeConvOptionsT + def _UnPack(self, transposeConvOptions): + if transposeConvOptions is None: + return + self.padding = transposeConvOptions.Padding() + self.strideW = transposeConvOptions.StrideW() + self.strideH = transposeConvOptions.StrideH() + self.fusedActivationFunction = transposeConvOptions.FusedActivationFunction() + self.quantizedBiasType = transposeConvOptions.QuantizedBiasType() + + # TransposeConvOptionsT + def Pack(self, builder): + TransposeConvOptionsStart(builder) + TransposeConvOptionsAddPadding(builder, self.padding) + TransposeConvOptionsAddStrideW(builder, self.strideW) + TransposeConvOptionsAddStrideH(builder, self.strideH) + TransposeConvOptionsAddFusedActivationFunction(builder, self.fusedActivationFunction) + TransposeConvOptionsAddQuantizedBiasType(builder, self.quantizedBiasType) + transposeConvOptions = TransposeConvOptionsEnd(builder) + return transposeConvOptions + + +class ExpandDimsOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ExpandDimsOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsExpandDimsOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ExpandDimsOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ExpandDimsOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ExpandDimsOptionsStart(builder): + builder.StartObject(0) + +def ExpandDimsOptionsEnd(builder): + return builder.EndObject() + + + +class ExpandDimsOptionsT(object): + + # ExpandDimsOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + expandDimsOptions = ExpandDimsOptions() + expandDimsOptions.Init(buf, pos) + return cls.InitFromObj(expandDimsOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, expandDimsOptions): + x = ExpandDimsOptionsT() + x._UnPack(expandDimsOptions) + return x + + # ExpandDimsOptionsT + def _UnPack(self, expandDimsOptions): + if expandDimsOptions is None: + return + + # ExpandDimsOptionsT + def Pack(self, builder): + ExpandDimsOptionsStart(builder) + expandDimsOptions = ExpandDimsOptionsEnd(builder) + return expandDimsOptions + + +class SparseToDenseOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SparseToDenseOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSparseToDenseOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SparseToDenseOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SparseToDenseOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SparseToDenseOptions + def ValidateIndices(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def SparseToDenseOptionsStart(builder): + builder.StartObject(1) + +def SparseToDenseOptionsAddValidateIndices(builder, validateIndices): + builder.PrependBoolSlot(0, validateIndices, 0) + +def SparseToDenseOptionsEnd(builder): + return builder.EndObject() + + + +class SparseToDenseOptionsT(object): + + # SparseToDenseOptionsT + def __init__(self): + self.validateIndices = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + sparseToDenseOptions = SparseToDenseOptions() + sparseToDenseOptions.Init(buf, pos) + return cls.InitFromObj(sparseToDenseOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, sparseToDenseOptions): + x = SparseToDenseOptionsT() + x._UnPack(sparseToDenseOptions) + return x + + # SparseToDenseOptionsT + def _UnPack(self, sparseToDenseOptions): + if sparseToDenseOptions is None: + return + self.validateIndices = sparseToDenseOptions.ValidateIndices() + + # SparseToDenseOptionsT + def Pack(self, builder): + SparseToDenseOptionsStart(builder) + SparseToDenseOptionsAddValidateIndices(builder, self.validateIndices) + sparseToDenseOptions = SparseToDenseOptionsEnd(builder) + return sparseToDenseOptions + + +class EqualOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = EqualOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsEqualOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def EqualOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # EqualOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def EqualOptionsStart(builder): + builder.StartObject(0) + +def EqualOptionsEnd(builder): + return builder.EndObject() + + + +class EqualOptionsT(object): + + # EqualOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + equalOptions = EqualOptions() + equalOptions.Init(buf, pos) + return cls.InitFromObj(equalOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, equalOptions): + x = EqualOptionsT() + x._UnPack(equalOptions) + return x + + # EqualOptionsT + def _UnPack(self, equalOptions): + if equalOptions is None: + return + + # EqualOptionsT + def Pack(self, builder): + EqualOptionsStart(builder) + equalOptions = EqualOptionsEnd(builder) + return equalOptions + + +class NotEqualOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NotEqualOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNotEqualOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NotEqualOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # NotEqualOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def NotEqualOptionsStart(builder): + builder.StartObject(0) + +def NotEqualOptionsEnd(builder): + return builder.EndObject() + + + +class NotEqualOptionsT(object): + + # NotEqualOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + notEqualOptions = NotEqualOptions() + notEqualOptions.Init(buf, pos) + return cls.InitFromObj(notEqualOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, notEqualOptions): + x = NotEqualOptionsT() + x._UnPack(notEqualOptions) + return x + + # NotEqualOptionsT + def _UnPack(self, notEqualOptions): + if notEqualOptions is None: + return + + # NotEqualOptionsT + def Pack(self, builder): + NotEqualOptionsStart(builder) + notEqualOptions = NotEqualOptionsEnd(builder) + return notEqualOptions + + +class ShapeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ShapeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsShapeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ShapeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ShapeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ShapeOptions + def OutType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def ShapeOptionsStart(builder): + builder.StartObject(1) + +def ShapeOptionsAddOutType(builder, outType): + builder.PrependInt8Slot(0, outType, 0) + +def ShapeOptionsEnd(builder): + return builder.EndObject() + + + +class ShapeOptionsT(object): + + # ShapeOptionsT + def __init__(self): + self.outType = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + shapeOptions = ShapeOptions() + shapeOptions.Init(buf, pos) + return cls.InitFromObj(shapeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, shapeOptions): + x = ShapeOptionsT() + x._UnPack(shapeOptions) + return x + + # ShapeOptionsT + def _UnPack(self, shapeOptions): + if shapeOptions is None: + return + self.outType = shapeOptions.OutType() + + # ShapeOptionsT + def Pack(self, builder): + ShapeOptionsStart(builder) + ShapeOptionsAddOutType(builder, self.outType) + shapeOptions = ShapeOptionsEnd(builder) + return shapeOptions + + +class RankOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RankOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRankOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RankOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # RankOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def RankOptionsStart(builder): + builder.StartObject(0) + +def RankOptionsEnd(builder): + return builder.EndObject() + + + +class RankOptionsT(object): + + # RankOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + rankOptions = RankOptions() + rankOptions.Init(buf, pos) + return cls.InitFromObj(rankOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, rankOptions): + x = RankOptionsT() + x._UnPack(rankOptions) + return x + + # RankOptionsT + def _UnPack(self, rankOptions): + if rankOptions is None: + return + + # RankOptionsT + def Pack(self, builder): + RankOptionsStart(builder) + rankOptions = RankOptionsEnd(builder) + return rankOptions + + +class PowOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = PowOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsPowOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def PowOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # PowOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def PowOptionsStart(builder): + builder.StartObject(0) + +def PowOptionsEnd(builder): + return builder.EndObject() + + + +class PowOptionsT(object): + + # PowOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + powOptions = PowOptions() + powOptions.Init(buf, pos) + return cls.InitFromObj(powOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, powOptions): + x = PowOptionsT() + x._UnPack(powOptions) + return x + + # PowOptionsT + def _UnPack(self, powOptions): + if powOptions is None: + return + + # PowOptionsT + def Pack(self, builder): + PowOptionsStart(builder) + powOptions = PowOptionsEnd(builder) + return powOptions + + +class FakeQuantOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = FakeQuantOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsFakeQuantOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def FakeQuantOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # FakeQuantOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # FakeQuantOptions + def Min(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # FakeQuantOptions + def Max(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # FakeQuantOptions + def NumBits(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # FakeQuantOptions + def NarrowRange(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def FakeQuantOptionsStart(builder): + builder.StartObject(4) + +def FakeQuantOptionsAddMin(builder, min): + builder.PrependFloat32Slot(0, min, 0.0) + +def FakeQuantOptionsAddMax(builder, max): + builder.PrependFloat32Slot(1, max, 0.0) + +def FakeQuantOptionsAddNumBits(builder, numBits): + builder.PrependInt32Slot(2, numBits, 0) + +def FakeQuantOptionsAddNarrowRange(builder, narrowRange): + builder.PrependBoolSlot(3, narrowRange, 0) + +def FakeQuantOptionsEnd(builder): + return builder.EndObject() + + + +class FakeQuantOptionsT(object): + + # FakeQuantOptionsT + def __init__(self): + self.min = 0.0 # type: float + self.max = 0.0 # type: float + self.numBits = 0 # type: int + self.narrowRange = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + fakeQuantOptions = FakeQuantOptions() + fakeQuantOptions.Init(buf, pos) + return cls.InitFromObj(fakeQuantOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, fakeQuantOptions): + x = FakeQuantOptionsT() + x._UnPack(fakeQuantOptions) + return x + + # FakeQuantOptionsT + def _UnPack(self, fakeQuantOptions): + if fakeQuantOptions is None: + return + self.min = fakeQuantOptions.Min() + self.max = fakeQuantOptions.Max() + self.numBits = fakeQuantOptions.NumBits() + self.narrowRange = fakeQuantOptions.NarrowRange() + + # FakeQuantOptionsT + def Pack(self, builder): + FakeQuantOptionsStart(builder) + FakeQuantOptionsAddMin(builder, self.min) + FakeQuantOptionsAddMax(builder, self.max) + FakeQuantOptionsAddNumBits(builder, self.numBits) + FakeQuantOptionsAddNarrowRange(builder, self.narrowRange) + fakeQuantOptions = FakeQuantOptionsEnd(builder) + return fakeQuantOptions + + +class PackOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = PackOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsPackOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def PackOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # PackOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # PackOptions + def ValuesCount(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # PackOptions + def Axis(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def PackOptionsStart(builder): + builder.StartObject(2) + +def PackOptionsAddValuesCount(builder, valuesCount): + builder.PrependInt32Slot(0, valuesCount, 0) + +def PackOptionsAddAxis(builder, axis): + builder.PrependInt32Slot(1, axis, 0) + +def PackOptionsEnd(builder): + return builder.EndObject() + + + +class PackOptionsT(object): + + # PackOptionsT + def __init__(self): + self.valuesCount = 0 # type: int + self.axis = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + packOptions = PackOptions() + packOptions.Init(buf, pos) + return cls.InitFromObj(packOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, packOptions): + x = PackOptionsT() + x._UnPack(packOptions) + return x + + # PackOptionsT + def _UnPack(self, packOptions): + if packOptions is None: + return + self.valuesCount = packOptions.ValuesCount() + self.axis = packOptions.Axis() + + # PackOptionsT + def Pack(self, builder): + PackOptionsStart(builder) + PackOptionsAddValuesCount(builder, self.valuesCount) + PackOptionsAddAxis(builder, self.axis) + packOptions = PackOptionsEnd(builder) + return packOptions + + +class LogicalOrOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LogicalOrOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLogicalOrOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LogicalOrOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LogicalOrOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def LogicalOrOptionsStart(builder): + builder.StartObject(0) + +def LogicalOrOptionsEnd(builder): + return builder.EndObject() + + + +class LogicalOrOptionsT(object): + + # LogicalOrOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + logicalOrOptions = LogicalOrOptions() + logicalOrOptions.Init(buf, pos) + return cls.InitFromObj(logicalOrOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, logicalOrOptions): + x = LogicalOrOptionsT() + x._UnPack(logicalOrOptions) + return x + + # LogicalOrOptionsT + def _UnPack(self, logicalOrOptions): + if logicalOrOptions is None: + return + + # LogicalOrOptionsT + def Pack(self, builder): + LogicalOrOptionsStart(builder) + logicalOrOptions = LogicalOrOptionsEnd(builder) + return logicalOrOptions + + +class OneHotOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = OneHotOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsOneHotOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def OneHotOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # OneHotOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # OneHotOptions + def Axis(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def OneHotOptionsStart(builder): + builder.StartObject(1) + +def OneHotOptionsAddAxis(builder, axis): + builder.PrependInt32Slot(0, axis, 0) + +def OneHotOptionsEnd(builder): + return builder.EndObject() + + + +class OneHotOptionsT(object): + + # OneHotOptionsT + def __init__(self): + self.axis = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + oneHotOptions = OneHotOptions() + oneHotOptions.Init(buf, pos) + return cls.InitFromObj(oneHotOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, oneHotOptions): + x = OneHotOptionsT() + x._UnPack(oneHotOptions) + return x + + # OneHotOptionsT + def _UnPack(self, oneHotOptions): + if oneHotOptions is None: + return + self.axis = oneHotOptions.Axis() + + # OneHotOptionsT + def Pack(self, builder): + OneHotOptionsStart(builder) + OneHotOptionsAddAxis(builder, self.axis) + oneHotOptions = OneHotOptionsEnd(builder) + return oneHotOptions + + +class AbsOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = AbsOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsAbsOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def AbsOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # AbsOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def AbsOptionsStart(builder): + builder.StartObject(0) + +def AbsOptionsEnd(builder): + return builder.EndObject() + + + +class AbsOptionsT(object): + + # AbsOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + absOptions = AbsOptions() + absOptions.Init(buf, pos) + return cls.InitFromObj(absOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, absOptions): + x = AbsOptionsT() + x._UnPack(absOptions) + return x + + # AbsOptionsT + def _UnPack(self, absOptions): + if absOptions is None: + return + + # AbsOptionsT + def Pack(self, builder): + AbsOptionsStart(builder) + absOptions = AbsOptionsEnd(builder) + return absOptions + + +class HardSwishOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HardSwishOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHardSwishOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def HardSwishOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # HardSwishOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def HardSwishOptionsStart(builder): + builder.StartObject(0) + +def HardSwishOptionsEnd(builder): + return builder.EndObject() + + + +class HardSwishOptionsT(object): + + # HardSwishOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + hardSwishOptions = HardSwishOptions() + hardSwishOptions.Init(buf, pos) + return cls.InitFromObj(hardSwishOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, hardSwishOptions): + x = HardSwishOptionsT() + x._UnPack(hardSwishOptions) + return x + + # HardSwishOptionsT + def _UnPack(self, hardSwishOptions): + if hardSwishOptions is None: + return + + # HardSwishOptionsT + def Pack(self, builder): + HardSwishOptionsStart(builder) + hardSwishOptions = HardSwishOptionsEnd(builder) + return hardSwishOptions + + +class LogicalAndOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LogicalAndOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLogicalAndOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LogicalAndOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LogicalAndOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def LogicalAndOptionsStart(builder): + builder.StartObject(0) + +def LogicalAndOptionsEnd(builder): + return builder.EndObject() + + + +class LogicalAndOptionsT(object): + + # LogicalAndOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + logicalAndOptions = LogicalAndOptions() + logicalAndOptions.Init(buf, pos) + return cls.InitFromObj(logicalAndOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, logicalAndOptions): + x = LogicalAndOptionsT() + x._UnPack(logicalAndOptions) + return x + + # LogicalAndOptionsT + def _UnPack(self, logicalAndOptions): + if logicalAndOptions is None: + return + + # LogicalAndOptionsT + def Pack(self, builder): + LogicalAndOptionsStart(builder) + logicalAndOptions = LogicalAndOptionsEnd(builder) + return logicalAndOptions + + +class LogicalNotOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LogicalNotOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLogicalNotOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LogicalNotOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LogicalNotOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def LogicalNotOptionsStart(builder): + builder.StartObject(0) + +def LogicalNotOptionsEnd(builder): + return builder.EndObject() + + + +class LogicalNotOptionsT(object): + + # LogicalNotOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + logicalNotOptions = LogicalNotOptions() + logicalNotOptions.Init(buf, pos) + return cls.InitFromObj(logicalNotOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, logicalNotOptions): + x = LogicalNotOptionsT() + x._UnPack(logicalNotOptions) + return x + + # LogicalNotOptionsT + def _UnPack(self, logicalNotOptions): + if logicalNotOptions is None: + return + + # LogicalNotOptionsT + def Pack(self, builder): + LogicalNotOptionsStart(builder) + logicalNotOptions = LogicalNotOptionsEnd(builder) + return logicalNotOptions + + +class UnpackOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UnpackOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUnpackOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UnpackOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UnpackOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # UnpackOptions + def Num(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # UnpackOptions + def Axis(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def UnpackOptionsStart(builder): + builder.StartObject(2) + +def UnpackOptionsAddNum(builder, num): + builder.PrependInt32Slot(0, num, 0) + +def UnpackOptionsAddAxis(builder, axis): + builder.PrependInt32Slot(1, axis, 0) + +def UnpackOptionsEnd(builder): + return builder.EndObject() + + + +class UnpackOptionsT(object): + + # UnpackOptionsT + def __init__(self): + self.num = 0 # type: int + self.axis = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + unpackOptions = UnpackOptions() + unpackOptions.Init(buf, pos) + return cls.InitFromObj(unpackOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, unpackOptions): + x = UnpackOptionsT() + x._UnPack(unpackOptions) + return x + + # UnpackOptionsT + def _UnPack(self, unpackOptions): + if unpackOptions is None: + return + self.num = unpackOptions.Num() + self.axis = unpackOptions.Axis() + + # UnpackOptionsT + def Pack(self, builder): + UnpackOptionsStart(builder) + UnpackOptionsAddNum(builder, self.num) + UnpackOptionsAddAxis(builder, self.axis) + unpackOptions = UnpackOptionsEnd(builder) + return unpackOptions + + +class FloorDivOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = FloorDivOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsFloorDivOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def FloorDivOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # FloorDivOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def FloorDivOptionsStart(builder): + builder.StartObject(0) + +def FloorDivOptionsEnd(builder): + return builder.EndObject() + + + +class FloorDivOptionsT(object): + + # FloorDivOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + floorDivOptions = FloorDivOptions() + floorDivOptions.Init(buf, pos) + return cls.InitFromObj(floorDivOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, floorDivOptions): + x = FloorDivOptionsT() + x._UnPack(floorDivOptions) + return x + + # FloorDivOptionsT + def _UnPack(self, floorDivOptions): + if floorDivOptions is None: + return + + # FloorDivOptionsT + def Pack(self, builder): + FloorDivOptionsStart(builder) + floorDivOptions = FloorDivOptionsEnd(builder) + return floorDivOptions + + +class SquareOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SquareOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSquareOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SquareOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SquareOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SquareOptionsStart(builder): + builder.StartObject(0) + +def SquareOptionsEnd(builder): + return builder.EndObject() + + + +class SquareOptionsT(object): + + # SquareOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + squareOptions = SquareOptions() + squareOptions.Init(buf, pos) + return cls.InitFromObj(squareOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, squareOptions): + x = SquareOptionsT() + x._UnPack(squareOptions) + return x + + # SquareOptionsT + def _UnPack(self, squareOptions): + if squareOptions is None: + return + + # SquareOptionsT + def Pack(self, builder): + SquareOptionsStart(builder) + squareOptions = SquareOptionsEnd(builder) + return squareOptions + + +class ZerosLikeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ZerosLikeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsZerosLikeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ZerosLikeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ZerosLikeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ZerosLikeOptionsStart(builder): + builder.StartObject(0) + +def ZerosLikeOptionsEnd(builder): + return builder.EndObject() + + + +class ZerosLikeOptionsT(object): + + # ZerosLikeOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + zerosLikeOptions = ZerosLikeOptions() + zerosLikeOptions.Init(buf, pos) + return cls.InitFromObj(zerosLikeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, zerosLikeOptions): + x = ZerosLikeOptionsT() + x._UnPack(zerosLikeOptions) + return x + + # ZerosLikeOptionsT + def _UnPack(self, zerosLikeOptions): + if zerosLikeOptions is None: + return + + # ZerosLikeOptionsT + def Pack(self, builder): + ZerosLikeOptionsStart(builder) + zerosLikeOptions = ZerosLikeOptionsEnd(builder) + return zerosLikeOptions + + +class FillOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = FillOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsFillOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def FillOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # FillOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def FillOptionsStart(builder): + builder.StartObject(0) + +def FillOptionsEnd(builder): + return builder.EndObject() + + + +class FillOptionsT(object): + + # FillOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + fillOptions = FillOptions() + fillOptions.Init(buf, pos) + return cls.InitFromObj(fillOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, fillOptions): + x = FillOptionsT() + x._UnPack(fillOptions) + return x + + # FillOptionsT + def _UnPack(self, fillOptions): + if fillOptions is None: + return + + # FillOptionsT + def Pack(self, builder): + FillOptionsStart(builder) + fillOptions = FillOptionsEnd(builder) + return fillOptions + + +class FloorModOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = FloorModOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsFloorModOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def FloorModOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # FloorModOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def FloorModOptionsStart(builder): + builder.StartObject(0) + +def FloorModOptionsEnd(builder): + return builder.EndObject() + + + +class FloorModOptionsT(object): + + # FloorModOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + floorModOptions = FloorModOptions() + floorModOptions.Init(buf, pos) + return cls.InitFromObj(floorModOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, floorModOptions): + x = FloorModOptionsT() + x._UnPack(floorModOptions) + return x + + # FloorModOptionsT + def _UnPack(self, floorModOptions): + if floorModOptions is None: + return + + # FloorModOptionsT + def Pack(self, builder): + FloorModOptionsStart(builder) + floorModOptions = FloorModOptionsEnd(builder) + return floorModOptions + + +class RangeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RangeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRangeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RangeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # RangeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def RangeOptionsStart(builder): + builder.StartObject(0) + +def RangeOptionsEnd(builder): + return builder.EndObject() + + + +class RangeOptionsT(object): + + # RangeOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + rangeOptions = RangeOptions() + rangeOptions.Init(buf, pos) + return cls.InitFromObj(rangeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, rangeOptions): + x = RangeOptionsT() + x._UnPack(rangeOptions) + return x + + # RangeOptionsT + def _UnPack(self, rangeOptions): + if rangeOptions is None: + return + + # RangeOptionsT + def Pack(self, builder): + RangeOptionsStart(builder) + rangeOptions = RangeOptionsEnd(builder) + return rangeOptions + + +class LeakyReluOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = LeakyReluOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsLeakyReluOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def LeakyReluOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # LeakyReluOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # LeakyReluOptions + def Alpha(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + +def LeakyReluOptionsStart(builder): + builder.StartObject(1) + +def LeakyReluOptionsAddAlpha(builder, alpha): + builder.PrependFloat32Slot(0, alpha, 0.0) + +def LeakyReluOptionsEnd(builder): + return builder.EndObject() + + + +class LeakyReluOptionsT(object): + + # LeakyReluOptionsT + def __init__(self): + self.alpha = 0.0 # type: float + + @classmethod + def InitFromBuf(cls, buf, pos): + leakyReluOptions = LeakyReluOptions() + leakyReluOptions.Init(buf, pos) + return cls.InitFromObj(leakyReluOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, leakyReluOptions): + x = LeakyReluOptionsT() + x._UnPack(leakyReluOptions) + return x + + # LeakyReluOptionsT + def _UnPack(self, leakyReluOptions): + if leakyReluOptions is None: + return + self.alpha = leakyReluOptions.Alpha() + + # LeakyReluOptionsT + def Pack(self, builder): + LeakyReluOptionsStart(builder) + LeakyReluOptionsAddAlpha(builder, self.alpha) + leakyReluOptions = LeakyReluOptionsEnd(builder) + return leakyReluOptions + + +class SquaredDifferenceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SquaredDifferenceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSquaredDifferenceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SquaredDifferenceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SquaredDifferenceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SquaredDifferenceOptionsStart(builder): + builder.StartObject(0) + +def SquaredDifferenceOptionsEnd(builder): + return builder.EndObject() + + + +class SquaredDifferenceOptionsT(object): + + # SquaredDifferenceOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + squaredDifferenceOptions = SquaredDifferenceOptions() + squaredDifferenceOptions.Init(buf, pos) + return cls.InitFromObj(squaredDifferenceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, squaredDifferenceOptions): + x = SquaredDifferenceOptionsT() + x._UnPack(squaredDifferenceOptions) + return x + + # SquaredDifferenceOptionsT + def _UnPack(self, squaredDifferenceOptions): + if squaredDifferenceOptions is None: + return + + # SquaredDifferenceOptionsT + def Pack(self, builder): + SquaredDifferenceOptionsStart(builder) + squaredDifferenceOptions = SquaredDifferenceOptionsEnd(builder) + return squaredDifferenceOptions + + +class MirrorPadOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MirrorPadOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMirrorPadOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MirrorPadOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # MirrorPadOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # MirrorPadOptions + def Mode(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def MirrorPadOptionsStart(builder): + builder.StartObject(1) + +def MirrorPadOptionsAddMode(builder, mode): + builder.PrependInt8Slot(0, mode, 0) + +def MirrorPadOptionsEnd(builder): + return builder.EndObject() + + + +class MirrorPadOptionsT(object): + + # MirrorPadOptionsT + def __init__(self): + self.mode = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + mirrorPadOptions = MirrorPadOptions() + mirrorPadOptions.Init(buf, pos) + return cls.InitFromObj(mirrorPadOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, mirrorPadOptions): + x = MirrorPadOptionsT() + x._UnPack(mirrorPadOptions) + return x + + # MirrorPadOptionsT + def _UnPack(self, mirrorPadOptions): + if mirrorPadOptions is None: + return + self.mode = mirrorPadOptions.Mode() + + # MirrorPadOptionsT + def Pack(self, builder): + MirrorPadOptionsStart(builder) + MirrorPadOptionsAddMode(builder, self.mode) + mirrorPadOptions = MirrorPadOptionsEnd(builder) + return mirrorPadOptions + + +class UniqueOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UniqueOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUniqueOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UniqueOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UniqueOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # UniqueOptions + def IdxOutType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 2 + +def UniqueOptionsStart(builder): + builder.StartObject(1) + +def UniqueOptionsAddIdxOutType(builder, idxOutType): + builder.PrependInt8Slot(0, idxOutType, 2) + +def UniqueOptionsEnd(builder): + return builder.EndObject() + + + +class UniqueOptionsT(object): + + # UniqueOptionsT + def __init__(self): + self.idxOutType = 2 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + uniqueOptions = UniqueOptions() + uniqueOptions.Init(buf, pos) + return cls.InitFromObj(uniqueOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, uniqueOptions): + x = UniqueOptionsT() + x._UnPack(uniqueOptions) + return x + + # UniqueOptionsT + def _UnPack(self, uniqueOptions): + if uniqueOptions is None: + return + self.idxOutType = uniqueOptions.IdxOutType() + + # UniqueOptionsT + def Pack(self, builder): + UniqueOptionsStart(builder) + UniqueOptionsAddIdxOutType(builder, self.idxOutType) + uniqueOptions = UniqueOptionsEnd(builder) + return uniqueOptions + + +class ReverseV2Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ReverseV2Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReverseV2Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReverseV2OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ReverseV2Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ReverseV2OptionsStart(builder): + builder.StartObject(0) + +def ReverseV2OptionsEnd(builder): + return builder.EndObject() + + + +class ReverseV2OptionsT(object): + + # ReverseV2OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + reverseV2Options = ReverseV2Options() + reverseV2Options.Init(buf, pos) + return cls.InitFromObj(reverseV2Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, reverseV2Options): + x = ReverseV2OptionsT() + x._UnPack(reverseV2Options) + return x + + # ReverseV2OptionsT + def _UnPack(self, reverseV2Options): + if reverseV2Options is None: + return + + # ReverseV2OptionsT + def Pack(self, builder): + ReverseV2OptionsStart(builder) + reverseV2Options = ReverseV2OptionsEnd(builder) + return reverseV2Options + + +class AddNOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = AddNOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsAddNOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def AddNOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # AddNOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def AddNOptionsStart(builder): + builder.StartObject(0) + +def AddNOptionsEnd(builder): + return builder.EndObject() + + + +class AddNOptionsT(object): + + # AddNOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + addNoptions = AddNOptions() + addNoptions.Init(buf, pos) + return cls.InitFromObj(addNoptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, addNoptions): + x = AddNOptionsT() + x._UnPack(addNoptions) + return x + + # AddNOptionsT + def _UnPack(self, addNoptions): + if addNoptions is None: + return + + # AddNOptionsT + def Pack(self, builder): + AddNOptionsStart(builder) + addNoptions = AddNOptionsEnd(builder) + return addNoptions + + +class GatherNdOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = GatherNdOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGatherNdOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def GatherNdOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # GatherNdOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def GatherNdOptionsStart(builder): + builder.StartObject(0) + +def GatherNdOptionsEnd(builder): + return builder.EndObject() + + + +class GatherNdOptionsT(object): + + # GatherNdOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + gatherNdOptions = GatherNdOptions() + gatherNdOptions.Init(buf, pos) + return cls.InitFromObj(gatherNdOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, gatherNdOptions): + x = GatherNdOptionsT() + x._UnPack(gatherNdOptions) + return x + + # GatherNdOptionsT + def _UnPack(self, gatherNdOptions): + if gatherNdOptions is None: + return + + # GatherNdOptionsT + def Pack(self, builder): + GatherNdOptionsStart(builder) + gatherNdOptions = GatherNdOptionsEnd(builder) + return gatherNdOptions + + +class WhereOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = WhereOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsWhereOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def WhereOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # WhereOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def WhereOptionsStart(builder): + builder.StartObject(0) + +def WhereOptionsEnd(builder): + return builder.EndObject() + + + +class WhereOptionsT(object): + + # WhereOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + whereOptions = WhereOptions() + whereOptions.Init(buf, pos) + return cls.InitFromObj(whereOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, whereOptions): + x = WhereOptionsT() + x._UnPack(whereOptions) + return x + + # WhereOptionsT + def _UnPack(self, whereOptions): + if whereOptions is None: + return + + # WhereOptionsT + def Pack(self, builder): + WhereOptionsStart(builder) + whereOptions = WhereOptionsEnd(builder) + return whereOptions + + +class ReverseSequenceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ReverseSequenceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReverseSequenceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReverseSequenceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ReverseSequenceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ReverseSequenceOptions + def SeqDim(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # ReverseSequenceOptions + def BatchDim(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def ReverseSequenceOptionsStart(builder): + builder.StartObject(2) + +def ReverseSequenceOptionsAddSeqDim(builder, seqDim): + builder.PrependInt32Slot(0, seqDim, 0) + +def ReverseSequenceOptionsAddBatchDim(builder, batchDim): + builder.PrependInt32Slot(1, batchDim, 0) + +def ReverseSequenceOptionsEnd(builder): + return builder.EndObject() + + + +class ReverseSequenceOptionsT(object): + + # ReverseSequenceOptionsT + def __init__(self): + self.seqDim = 0 # type: int + self.batchDim = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + reverseSequenceOptions = ReverseSequenceOptions() + reverseSequenceOptions.Init(buf, pos) + return cls.InitFromObj(reverseSequenceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, reverseSequenceOptions): + x = ReverseSequenceOptionsT() + x._UnPack(reverseSequenceOptions) + return x + + # ReverseSequenceOptionsT + def _UnPack(self, reverseSequenceOptions): + if reverseSequenceOptions is None: + return + self.seqDim = reverseSequenceOptions.SeqDim() + self.batchDim = reverseSequenceOptions.BatchDim() + + # ReverseSequenceOptionsT + def Pack(self, builder): + ReverseSequenceOptionsStart(builder) + ReverseSequenceOptionsAddSeqDim(builder, self.seqDim) + ReverseSequenceOptionsAddBatchDim(builder, self.batchDim) + reverseSequenceOptions = ReverseSequenceOptionsEnd(builder) + return reverseSequenceOptions + + +class MatrixDiagOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MatrixDiagOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMatrixDiagOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MatrixDiagOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # MatrixDiagOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def MatrixDiagOptionsStart(builder): + builder.StartObject(0) + +def MatrixDiagOptionsEnd(builder): + return builder.EndObject() + + + +class MatrixDiagOptionsT(object): + + # MatrixDiagOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + matrixDiagOptions = MatrixDiagOptions() + matrixDiagOptions.Init(buf, pos) + return cls.InitFromObj(matrixDiagOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, matrixDiagOptions): + x = MatrixDiagOptionsT() + x._UnPack(matrixDiagOptions) + return x + + # MatrixDiagOptionsT + def _UnPack(self, matrixDiagOptions): + if matrixDiagOptions is None: + return + + # MatrixDiagOptionsT + def Pack(self, builder): + MatrixDiagOptionsStart(builder) + matrixDiagOptions = MatrixDiagOptionsEnd(builder) + return matrixDiagOptions + + +class QuantizeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = QuantizeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsQuantizeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def QuantizeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # QuantizeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def QuantizeOptionsStart(builder): + builder.StartObject(0) + +def QuantizeOptionsEnd(builder): + return builder.EndObject() + + + +class QuantizeOptionsT(object): + + # QuantizeOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + quantizeOptions = QuantizeOptions() + quantizeOptions.Init(buf, pos) + return cls.InitFromObj(quantizeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, quantizeOptions): + x = QuantizeOptionsT() + x._UnPack(quantizeOptions) + return x + + # QuantizeOptionsT + def _UnPack(self, quantizeOptions): + if quantizeOptions is None: + return + + # QuantizeOptionsT + def Pack(self, builder): + QuantizeOptionsStart(builder) + quantizeOptions = QuantizeOptionsEnd(builder) + return quantizeOptions + + +class MatrixSetDiagOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MatrixSetDiagOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMatrixSetDiagOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MatrixSetDiagOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # MatrixSetDiagOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def MatrixSetDiagOptionsStart(builder): + builder.StartObject(0) + +def MatrixSetDiagOptionsEnd(builder): + return builder.EndObject() + + + +class MatrixSetDiagOptionsT(object): + + # MatrixSetDiagOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + matrixSetDiagOptions = MatrixSetDiagOptions() + matrixSetDiagOptions.Init(buf, pos) + return cls.InitFromObj(matrixSetDiagOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, matrixSetDiagOptions): + x = MatrixSetDiagOptionsT() + x._UnPack(matrixSetDiagOptions) + return x + + # MatrixSetDiagOptionsT + def _UnPack(self, matrixSetDiagOptions): + if matrixSetDiagOptions is None: + return + + # MatrixSetDiagOptionsT + def Pack(self, builder): + MatrixSetDiagOptionsStart(builder) + matrixSetDiagOptions = MatrixSetDiagOptionsEnd(builder) + return matrixSetDiagOptions + + +class IfOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = IfOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsIfOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def IfOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # IfOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # IfOptions + def ThenSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # IfOptions + def ElseSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def IfOptionsStart(builder): + builder.StartObject(2) + +def IfOptionsAddThenSubgraphIndex(builder, thenSubgraphIndex): + builder.PrependInt32Slot(0, thenSubgraphIndex, 0) + +def IfOptionsAddElseSubgraphIndex(builder, elseSubgraphIndex): + builder.PrependInt32Slot(1, elseSubgraphIndex, 0) + +def IfOptionsEnd(builder): + return builder.EndObject() + + + +class IfOptionsT(object): + + # IfOptionsT + def __init__(self): + self.thenSubgraphIndex = 0 # type: int + self.elseSubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + ifOptions = IfOptions() + ifOptions.Init(buf, pos) + return cls.InitFromObj(ifOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, ifOptions): + x = IfOptionsT() + x._UnPack(ifOptions) + return x + + # IfOptionsT + def _UnPack(self, ifOptions): + if ifOptions is None: + return + self.thenSubgraphIndex = ifOptions.ThenSubgraphIndex() + self.elseSubgraphIndex = ifOptions.ElseSubgraphIndex() + + # IfOptionsT + def Pack(self, builder): + IfOptionsStart(builder) + IfOptionsAddThenSubgraphIndex(builder, self.thenSubgraphIndex) + IfOptionsAddElseSubgraphIndex(builder, self.elseSubgraphIndex) + ifOptions = IfOptionsEnd(builder) + return ifOptions + + +class CallOnceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = CallOnceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCallOnceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CallOnceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # CallOnceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # CallOnceOptions + def InitSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def CallOnceOptionsStart(builder): + builder.StartObject(1) + +def CallOnceOptionsAddInitSubgraphIndex(builder, initSubgraphIndex): + builder.PrependInt32Slot(0, initSubgraphIndex, 0) + +def CallOnceOptionsEnd(builder): + return builder.EndObject() + + + +class CallOnceOptionsT(object): + + # CallOnceOptionsT + def __init__(self): + self.initSubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + callOnceOptions = CallOnceOptions() + callOnceOptions.Init(buf, pos) + return cls.InitFromObj(callOnceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, callOnceOptions): + x = CallOnceOptionsT() + x._UnPack(callOnceOptions) + return x + + # CallOnceOptionsT + def _UnPack(self, callOnceOptions): + if callOnceOptions is None: + return + self.initSubgraphIndex = callOnceOptions.InitSubgraphIndex() + + # CallOnceOptionsT + def Pack(self, builder): + CallOnceOptionsStart(builder) + CallOnceOptionsAddInitSubgraphIndex(builder, self.initSubgraphIndex) + callOnceOptions = CallOnceOptionsEnd(builder) + return callOnceOptions + + +class WhileOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = WhileOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsWhileOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def WhileOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # WhileOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # WhileOptions + def CondSubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # WhileOptions + def BodySubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def WhileOptionsStart(builder): + builder.StartObject(2) + +def WhileOptionsAddCondSubgraphIndex(builder, condSubgraphIndex): + builder.PrependInt32Slot(0, condSubgraphIndex, 0) + +def WhileOptionsAddBodySubgraphIndex(builder, bodySubgraphIndex): + builder.PrependInt32Slot(1, bodySubgraphIndex, 0) + +def WhileOptionsEnd(builder): + return builder.EndObject() + + + +class WhileOptionsT(object): + + # WhileOptionsT + def __init__(self): + self.condSubgraphIndex = 0 # type: int + self.bodySubgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + whileOptions = WhileOptions() + whileOptions.Init(buf, pos) + return cls.InitFromObj(whileOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, whileOptions): + x = WhileOptionsT() + x._UnPack(whileOptions) + return x + + # WhileOptionsT + def _UnPack(self, whileOptions): + if whileOptions is None: + return + self.condSubgraphIndex = whileOptions.CondSubgraphIndex() + self.bodySubgraphIndex = whileOptions.BodySubgraphIndex() + + # WhileOptionsT + def Pack(self, builder): + WhileOptionsStart(builder) + WhileOptionsAddCondSubgraphIndex(builder, self.condSubgraphIndex) + WhileOptionsAddBodySubgraphIndex(builder, self.bodySubgraphIndex) + whileOptions = WhileOptionsEnd(builder) + return whileOptions + + +class NonMaxSuppressionV4Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NonMaxSuppressionV4Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNonMaxSuppressionV4Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NonMaxSuppressionV4OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # NonMaxSuppressionV4Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def NonMaxSuppressionV4OptionsStart(builder): + builder.StartObject(0) + +def NonMaxSuppressionV4OptionsEnd(builder): + return builder.EndObject() + + + +class NonMaxSuppressionV4OptionsT(object): + + # NonMaxSuppressionV4OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + nonMaxSuppressionV4Options = NonMaxSuppressionV4Options() + nonMaxSuppressionV4Options.Init(buf, pos) + return cls.InitFromObj(nonMaxSuppressionV4Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, nonMaxSuppressionV4Options): + x = NonMaxSuppressionV4OptionsT() + x._UnPack(nonMaxSuppressionV4Options) + return x + + # NonMaxSuppressionV4OptionsT + def _UnPack(self, nonMaxSuppressionV4Options): + if nonMaxSuppressionV4Options is None: + return + + # NonMaxSuppressionV4OptionsT + def Pack(self, builder): + NonMaxSuppressionV4OptionsStart(builder) + nonMaxSuppressionV4Options = NonMaxSuppressionV4OptionsEnd(builder) + return nonMaxSuppressionV4Options + + +class NonMaxSuppressionV5Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NonMaxSuppressionV5Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNonMaxSuppressionV5Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def NonMaxSuppressionV5OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # NonMaxSuppressionV5Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def NonMaxSuppressionV5OptionsStart(builder): + builder.StartObject(0) + +def NonMaxSuppressionV5OptionsEnd(builder): + return builder.EndObject() + + + +class NonMaxSuppressionV5OptionsT(object): + + # NonMaxSuppressionV5OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + nonMaxSuppressionV5Options = NonMaxSuppressionV5Options() + nonMaxSuppressionV5Options.Init(buf, pos) + return cls.InitFromObj(nonMaxSuppressionV5Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, nonMaxSuppressionV5Options): + x = NonMaxSuppressionV5OptionsT() + x._UnPack(nonMaxSuppressionV5Options) + return x + + # NonMaxSuppressionV5OptionsT + def _UnPack(self, nonMaxSuppressionV5Options): + if nonMaxSuppressionV5Options is None: + return + + # NonMaxSuppressionV5OptionsT + def Pack(self, builder): + NonMaxSuppressionV5OptionsStart(builder) + nonMaxSuppressionV5Options = NonMaxSuppressionV5OptionsEnd(builder) + return nonMaxSuppressionV5Options + + +class ScatterNdOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ScatterNdOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsScatterNdOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ScatterNdOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ScatterNdOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ScatterNdOptionsStart(builder): + builder.StartObject(0) + +def ScatterNdOptionsEnd(builder): + return builder.EndObject() + + + +class ScatterNdOptionsT(object): + + # ScatterNdOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + scatterNdOptions = ScatterNdOptions() + scatterNdOptions.Init(buf, pos) + return cls.InitFromObj(scatterNdOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, scatterNdOptions): + x = ScatterNdOptionsT() + x._UnPack(scatterNdOptions) + return x + + # ScatterNdOptionsT + def _UnPack(self, scatterNdOptions): + if scatterNdOptions is None: + return + + # ScatterNdOptionsT + def Pack(self, builder): + ScatterNdOptionsStart(builder) + scatterNdOptions = ScatterNdOptionsEnd(builder) + return scatterNdOptions + + +class SelectV2Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SelectV2Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSelectV2Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SelectV2OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SelectV2Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SelectV2OptionsStart(builder): + builder.StartObject(0) + +def SelectV2OptionsEnd(builder): + return builder.EndObject() + + + +class SelectV2OptionsT(object): + + # SelectV2OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + selectV2Options = SelectV2Options() + selectV2Options.Init(buf, pos) + return cls.InitFromObj(selectV2Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, selectV2Options): + x = SelectV2OptionsT() + x._UnPack(selectV2Options) + return x + + # SelectV2OptionsT + def _UnPack(self, selectV2Options): + if selectV2Options is None: + return + + # SelectV2OptionsT + def Pack(self, builder): + SelectV2OptionsStart(builder) + selectV2Options = SelectV2OptionsEnd(builder) + return selectV2Options + + +class DensifyOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DensifyOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDensifyOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DensifyOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DensifyOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def DensifyOptionsStart(builder): + builder.StartObject(0) + +def DensifyOptionsEnd(builder): + return builder.EndObject() + + + +class DensifyOptionsT(object): + + # DensifyOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + densifyOptions = DensifyOptions() + densifyOptions.Init(buf, pos) + return cls.InitFromObj(densifyOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, densifyOptions): + x = DensifyOptionsT() + x._UnPack(densifyOptions) + return x + + # DensifyOptionsT + def _UnPack(self, densifyOptions): + if densifyOptions is None: + return + + # DensifyOptionsT + def Pack(self, builder): + DensifyOptionsStart(builder) + densifyOptions = DensifyOptionsEnd(builder) + return densifyOptions + + +class SegmentSumOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SegmentSumOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSegmentSumOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SegmentSumOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SegmentSumOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SegmentSumOptionsStart(builder): + builder.StartObject(0) + +def SegmentSumOptionsEnd(builder): + return builder.EndObject() + + + +class SegmentSumOptionsT(object): + + # SegmentSumOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + segmentSumOptions = SegmentSumOptions() + segmentSumOptions.Init(buf, pos) + return cls.InitFromObj(segmentSumOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, segmentSumOptions): + x = SegmentSumOptionsT() + x._UnPack(segmentSumOptions) + return x + + # SegmentSumOptionsT + def _UnPack(self, segmentSumOptions): + if segmentSumOptions is None: + return + + # SegmentSumOptionsT + def Pack(self, builder): + SegmentSumOptionsStart(builder) + segmentSumOptions = SegmentSumOptionsEnd(builder) + return segmentSumOptions + + +class BatchMatMulOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BatchMatMulOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBatchMatMulOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BatchMatMulOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BatchMatMulOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # BatchMatMulOptions + def AdjX(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # BatchMatMulOptions + def AdjY(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # BatchMatMulOptions + def AsymmetricQuantizeInputs(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def BatchMatMulOptionsStart(builder): + builder.StartObject(3) + +def BatchMatMulOptionsAddAdjX(builder, adjX): + builder.PrependBoolSlot(0, adjX, 0) + +def BatchMatMulOptionsAddAdjY(builder, adjY): + builder.PrependBoolSlot(1, adjY, 0) + +def BatchMatMulOptionsAddAsymmetricQuantizeInputs(builder, asymmetricQuantizeInputs): + builder.PrependBoolSlot(2, asymmetricQuantizeInputs, 0) + +def BatchMatMulOptionsEnd(builder): + return builder.EndObject() + + + +class BatchMatMulOptionsT(object): + + # BatchMatMulOptionsT + def __init__(self): + self.adjX = False # type: bool + self.adjY = False # type: bool + self.asymmetricQuantizeInputs = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + batchMatMulOptions = BatchMatMulOptions() + batchMatMulOptions.Init(buf, pos) + return cls.InitFromObj(batchMatMulOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, batchMatMulOptions): + x = BatchMatMulOptionsT() + x._UnPack(batchMatMulOptions) + return x + + # BatchMatMulOptionsT + def _UnPack(self, batchMatMulOptions): + if batchMatMulOptions is None: + return + self.adjX = batchMatMulOptions.AdjX() + self.adjY = batchMatMulOptions.AdjY() + self.asymmetricQuantizeInputs = batchMatMulOptions.AsymmetricQuantizeInputs() + + # BatchMatMulOptionsT + def Pack(self, builder): + BatchMatMulOptionsStart(builder) + BatchMatMulOptionsAddAdjX(builder, self.adjX) + BatchMatMulOptionsAddAdjY(builder, self.adjY) + BatchMatMulOptionsAddAsymmetricQuantizeInputs(builder, self.asymmetricQuantizeInputs) + batchMatMulOptions = BatchMatMulOptionsEnd(builder) + return batchMatMulOptions + + +class CumsumOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = CumsumOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsCumsumOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def CumsumOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # CumsumOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # CumsumOptions + def Exclusive(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # CumsumOptions + def Reverse(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def CumsumOptionsStart(builder): + builder.StartObject(2) + +def CumsumOptionsAddExclusive(builder, exclusive): + builder.PrependBoolSlot(0, exclusive, 0) + +def CumsumOptionsAddReverse(builder, reverse): + builder.PrependBoolSlot(1, reverse, 0) + +def CumsumOptionsEnd(builder): + return builder.EndObject() + + + +class CumsumOptionsT(object): + + # CumsumOptionsT + def __init__(self): + self.exclusive = False # type: bool + self.reverse = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + cumsumOptions = CumsumOptions() + cumsumOptions.Init(buf, pos) + return cls.InitFromObj(cumsumOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, cumsumOptions): + x = CumsumOptionsT() + x._UnPack(cumsumOptions) + return x + + # CumsumOptionsT + def _UnPack(self, cumsumOptions): + if cumsumOptions is None: + return + self.exclusive = cumsumOptions.Exclusive() + self.reverse = cumsumOptions.Reverse() + + # CumsumOptionsT + def Pack(self, builder): + CumsumOptionsStart(builder) + CumsumOptionsAddExclusive(builder, self.exclusive) + CumsumOptionsAddReverse(builder, self.reverse) + cumsumOptions = CumsumOptionsEnd(builder) + return cumsumOptions + + +class BroadcastToOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BroadcastToOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBroadcastToOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BroadcastToOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BroadcastToOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def BroadcastToOptionsStart(builder): + builder.StartObject(0) + +def BroadcastToOptionsEnd(builder): + return builder.EndObject() + + + +class BroadcastToOptionsT(object): + + # BroadcastToOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + broadcastToOptions = BroadcastToOptions() + broadcastToOptions.Init(buf, pos) + return cls.InitFromObj(broadcastToOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, broadcastToOptions): + x = BroadcastToOptionsT() + x._UnPack(broadcastToOptions) + return x + + # BroadcastToOptionsT + def _UnPack(self, broadcastToOptions): + if broadcastToOptions is None: + return + + # BroadcastToOptionsT + def Pack(self, builder): + BroadcastToOptionsStart(builder) + broadcastToOptions = BroadcastToOptionsEnd(builder) + return broadcastToOptions + + +class Rfft2dOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Rfft2dOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRfft2dOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def Rfft2dOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Rfft2dOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def Rfft2dOptionsStart(builder): + builder.StartObject(0) + +def Rfft2dOptionsEnd(builder): + return builder.EndObject() + + + +class Rfft2dOptionsT(object): + + # Rfft2dOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + rfft2dOptions = Rfft2dOptions() + rfft2dOptions.Init(buf, pos) + return cls.InitFromObj(rfft2dOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, rfft2dOptions): + x = Rfft2dOptionsT() + x._UnPack(rfft2dOptions) + return x + + # Rfft2dOptionsT + def _UnPack(self, rfft2dOptions): + if rfft2dOptions is None: + return + + # Rfft2dOptionsT + def Pack(self, builder): + Rfft2dOptionsStart(builder) + rfft2dOptions = Rfft2dOptionsEnd(builder) + return rfft2dOptions + + +class HashtableOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HashtableOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHashtableOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def HashtableOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # HashtableOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # HashtableOptions + def TableId(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # HashtableOptions + def KeyDtype(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # HashtableOptions + def ValueDtype(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + +def HashtableOptionsStart(builder): + builder.StartObject(3) + +def HashtableOptionsAddTableId(builder, tableId): + builder.PrependInt32Slot(0, tableId, 0) + +def HashtableOptionsAddKeyDtype(builder, keyDtype): + builder.PrependInt8Slot(1, keyDtype, 0) + +def HashtableOptionsAddValueDtype(builder, valueDtype): + builder.PrependInt8Slot(2, valueDtype, 0) + +def HashtableOptionsEnd(builder): + return builder.EndObject() + + + +class HashtableOptionsT(object): + + # HashtableOptionsT + def __init__(self): + self.tableId = 0 # type: int + self.keyDtype = 0 # type: int + self.valueDtype = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + hashtableOptions = HashtableOptions() + hashtableOptions.Init(buf, pos) + return cls.InitFromObj(hashtableOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, hashtableOptions): + x = HashtableOptionsT() + x._UnPack(hashtableOptions) + return x + + # HashtableOptionsT + def _UnPack(self, hashtableOptions): + if hashtableOptions is None: + return + self.tableId = hashtableOptions.TableId() + self.keyDtype = hashtableOptions.KeyDtype() + self.valueDtype = hashtableOptions.ValueDtype() + + # HashtableOptionsT + def Pack(self, builder): + HashtableOptionsStart(builder) + HashtableOptionsAddTableId(builder, self.tableId) + HashtableOptionsAddKeyDtype(builder, self.keyDtype) + HashtableOptionsAddValueDtype(builder, self.valueDtype) + hashtableOptions = HashtableOptionsEnd(builder) + return hashtableOptions + + +class HashtableFindOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HashtableFindOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHashtableFindOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def HashtableFindOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # HashtableFindOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def HashtableFindOptionsStart(builder): + builder.StartObject(0) + +def HashtableFindOptionsEnd(builder): + return builder.EndObject() + + + +class HashtableFindOptionsT(object): + + # HashtableFindOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + hashtableFindOptions = HashtableFindOptions() + hashtableFindOptions.Init(buf, pos) + return cls.InitFromObj(hashtableFindOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, hashtableFindOptions): + x = HashtableFindOptionsT() + x._UnPack(hashtableFindOptions) + return x + + # HashtableFindOptionsT + def _UnPack(self, hashtableFindOptions): + if hashtableFindOptions is None: + return + + # HashtableFindOptionsT + def Pack(self, builder): + HashtableFindOptionsStart(builder) + hashtableFindOptions = HashtableFindOptionsEnd(builder) + return hashtableFindOptions + + +class HashtableImportOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HashtableImportOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHashtableImportOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def HashtableImportOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # HashtableImportOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def HashtableImportOptionsStart(builder): + builder.StartObject(0) + +def HashtableImportOptionsEnd(builder): + return builder.EndObject() + + + +class HashtableImportOptionsT(object): + + # HashtableImportOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + hashtableImportOptions = HashtableImportOptions() + hashtableImportOptions.Init(buf, pos) + return cls.InitFromObj(hashtableImportOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, hashtableImportOptions): + x = HashtableImportOptionsT() + x._UnPack(hashtableImportOptions) + return x + + # HashtableImportOptionsT + def _UnPack(self, hashtableImportOptions): + if hashtableImportOptions is None: + return + + # HashtableImportOptionsT + def Pack(self, builder): + HashtableImportOptionsStart(builder) + hashtableImportOptions = HashtableImportOptionsEnd(builder) + return hashtableImportOptions + + +class HashtableSizeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HashtableSizeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHashtableSizeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def HashtableSizeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # HashtableSizeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def HashtableSizeOptionsStart(builder): + builder.StartObject(0) + +def HashtableSizeOptionsEnd(builder): + return builder.EndObject() + + + +class HashtableSizeOptionsT(object): + + # HashtableSizeOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + hashtableSizeOptions = HashtableSizeOptions() + hashtableSizeOptions.Init(buf, pos) + return cls.InitFromObj(hashtableSizeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, hashtableSizeOptions): + x = HashtableSizeOptionsT() + x._UnPack(hashtableSizeOptions) + return x + + # HashtableSizeOptionsT + def _UnPack(self, hashtableSizeOptions): + if hashtableSizeOptions is None: + return + + # HashtableSizeOptionsT + def Pack(self, builder): + HashtableSizeOptionsStart(builder) + hashtableSizeOptions = HashtableSizeOptionsEnd(builder) + return hashtableSizeOptions + + +class VarHandleOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = VarHandleOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsVarHandleOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def VarHandleOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # VarHandleOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # VarHandleOptions + def Container(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # VarHandleOptions + def SharedName(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + +def VarHandleOptionsStart(builder): + builder.StartObject(2) + +def VarHandleOptionsAddContainer(builder, container): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(container), 0) + +def VarHandleOptionsAddSharedName(builder, sharedName): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(sharedName), 0) + +def VarHandleOptionsEnd(builder): + return builder.EndObject() + + + +class VarHandleOptionsT(object): + + # VarHandleOptionsT + def __init__(self): + self.container = None # type: str + self.sharedName = None # type: str + + @classmethod + def InitFromBuf(cls, buf, pos): + varHandleOptions = VarHandleOptions() + varHandleOptions.Init(buf, pos) + return cls.InitFromObj(varHandleOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, varHandleOptions): + x = VarHandleOptionsT() + x._UnPack(varHandleOptions) + return x + + # VarHandleOptionsT + def _UnPack(self, varHandleOptions): + if varHandleOptions is None: + return + self.container = varHandleOptions.Container() + self.sharedName = varHandleOptions.SharedName() + + # VarHandleOptionsT + def Pack(self, builder): + if self.container is not None: + container = builder.CreateString(self.container) + if self.sharedName is not None: + sharedName = builder.CreateString(self.sharedName) + VarHandleOptionsStart(builder) + if self.container is not None: + VarHandleOptionsAddContainer(builder, container) + if self.sharedName is not None: + VarHandleOptionsAddSharedName(builder, sharedName) + varHandleOptions = VarHandleOptionsEnd(builder) + return varHandleOptions + + +class ReadVariableOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ReadVariableOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReadVariableOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReadVariableOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ReadVariableOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ReadVariableOptionsStart(builder): + builder.StartObject(0) + +def ReadVariableOptionsEnd(builder): + return builder.EndObject() + + + +class ReadVariableOptionsT(object): + + # ReadVariableOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + readVariableOptions = ReadVariableOptions() + readVariableOptions.Init(buf, pos) + return cls.InitFromObj(readVariableOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, readVariableOptions): + x = ReadVariableOptionsT() + x._UnPack(readVariableOptions) + return x + + # ReadVariableOptionsT + def _UnPack(self, readVariableOptions): + if readVariableOptions is None: + return + + # ReadVariableOptionsT + def Pack(self, builder): + ReadVariableOptionsStart(builder) + readVariableOptions = ReadVariableOptionsEnd(builder) + return readVariableOptions + + +class AssignVariableOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = AssignVariableOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsAssignVariableOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def AssignVariableOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # AssignVariableOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def AssignVariableOptionsStart(builder): + builder.StartObject(0) + +def AssignVariableOptionsEnd(builder): + return builder.EndObject() + + + +class AssignVariableOptionsT(object): + + # AssignVariableOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + assignVariableOptions = AssignVariableOptions() + assignVariableOptions.Init(buf, pos) + return cls.InitFromObj(assignVariableOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, assignVariableOptions): + x = AssignVariableOptionsT() + x._UnPack(assignVariableOptions) + return x + + # AssignVariableOptionsT + def _UnPack(self, assignVariableOptions): + if assignVariableOptions is None: + return + + # AssignVariableOptionsT + def Pack(self, builder): + AssignVariableOptionsStart(builder) + assignVariableOptions = AssignVariableOptionsEnd(builder) + return assignVariableOptions + + +class RandomOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RandomOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRandomOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RandomOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # RandomOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # RandomOptions + def Seed(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # RandomOptions + def Seed2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + +def RandomOptionsStart(builder): + builder.StartObject(2) + +def RandomOptionsAddSeed(builder, seed): + builder.PrependInt64Slot(0, seed, 0) + +def RandomOptionsAddSeed2(builder, seed2): + builder.PrependInt64Slot(1, seed2, 0) + +def RandomOptionsEnd(builder): + return builder.EndObject() + + + +class RandomOptionsT(object): + + # RandomOptionsT + def __init__(self): + self.seed = 0 # type: int + self.seed2 = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + randomOptions = RandomOptions() + randomOptions.Init(buf, pos) + return cls.InitFromObj(randomOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, randomOptions): + x = RandomOptionsT() + x._UnPack(randomOptions) + return x + + # RandomOptionsT + def _UnPack(self, randomOptions): + if randomOptions is None: + return + self.seed = randomOptions.Seed() + self.seed2 = randomOptions.Seed2() + + # RandomOptionsT + def Pack(self, builder): + RandomOptionsStart(builder) + RandomOptionsAddSeed(builder, self.seed) + RandomOptionsAddSeed2(builder, self.seed2) + randomOptions = RandomOptionsEnd(builder) + return randomOptions + + +class BucketizeOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BucketizeOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBucketizeOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BucketizeOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BucketizeOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # BucketizeOptions + def Boundaries(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # BucketizeOptions + def BoundariesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float32Flags, o) + return 0 + + # BucketizeOptions + def BoundariesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # BucketizeOptions + def BoundariesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + +def BucketizeOptionsStart(builder): + builder.StartObject(1) + +def BucketizeOptionsAddBoundaries(builder, boundaries): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(boundaries), 0) + +def BucketizeOptionsStartBoundariesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def BucketizeOptionsEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class BucketizeOptionsT(object): + + # BucketizeOptionsT + def __init__(self): + self.boundaries = None # type: List[float] + + @classmethod + def InitFromBuf(cls, buf, pos): + bucketizeOptions = BucketizeOptions() + bucketizeOptions.Init(buf, pos) + return cls.InitFromObj(bucketizeOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, bucketizeOptions): + x = BucketizeOptionsT() + x._UnPack(bucketizeOptions) + return x + + # BucketizeOptionsT + def _UnPack(self, bucketizeOptions): + if bucketizeOptions is None: + return + if not bucketizeOptions.BoundariesIsNone(): + if np is None: + self.boundaries = [] + for i in range(bucketizeOptions.BoundariesLength()): + self.boundaries.append(bucketizeOptions.Boundaries(i)) + else: + self.boundaries = bucketizeOptions.BoundariesAsNumpy() + + # BucketizeOptionsT + def Pack(self, builder): + if self.boundaries is not None: + if np is not None and type(self.boundaries) is np.ndarray: + boundaries = builder.CreateNumpyVector(self.boundaries) + else: + BucketizeOptionsStartBoundariesVector(builder, len(self.boundaries)) + for i in reversed(range(len(self.boundaries))): + builder.PrependFloat32(self.boundaries[i]) + boundaries = builder.EndVector() + BucketizeOptionsStart(builder) + if self.boundaries is not None: + BucketizeOptionsAddBoundaries(builder, boundaries) + bucketizeOptions = BucketizeOptionsEnd(builder) + return bucketizeOptions + + +class GeluOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = GeluOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGeluOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def GeluOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # GeluOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # GeluOptions + def Approximate(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + +def GeluOptionsStart(builder): + builder.StartObject(1) + +def GeluOptionsAddApproximate(builder, approximate): + builder.PrependBoolSlot(0, approximate, 0) + +def GeluOptionsEnd(builder): + return builder.EndObject() + + + +class GeluOptionsT(object): + + # GeluOptionsT + def __init__(self): + self.approximate = False # type: bool + + @classmethod + def InitFromBuf(cls, buf, pos): + geluOptions = GeluOptions() + geluOptions.Init(buf, pos) + return cls.InitFromObj(geluOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, geluOptions): + x = GeluOptionsT() + x._UnPack(geluOptions) + return x + + # GeluOptionsT + def _UnPack(self, geluOptions): + if geluOptions is None: + return + self.approximate = geluOptions.Approximate() + + # GeluOptionsT + def Pack(self, builder): + GeluOptionsStart(builder) + GeluOptionsAddApproximate(builder, self.approximate) + geluOptions = GeluOptionsEnd(builder) + return geluOptions + + +class DynamicUpdateSliceOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DynamicUpdateSliceOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDynamicUpdateSliceOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DynamicUpdateSliceOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DynamicUpdateSliceOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def DynamicUpdateSliceOptionsStart(builder): + builder.StartObject(0) + +def DynamicUpdateSliceOptionsEnd(builder): + return builder.EndObject() + + + +class DynamicUpdateSliceOptionsT(object): + + # DynamicUpdateSliceOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + dynamicUpdateSliceOptions = DynamicUpdateSliceOptions() + dynamicUpdateSliceOptions.Init(buf, pos) + return cls.InitFromObj(dynamicUpdateSliceOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, dynamicUpdateSliceOptions): + x = DynamicUpdateSliceOptionsT() + x._UnPack(dynamicUpdateSliceOptions) + return x + + # DynamicUpdateSliceOptionsT + def _UnPack(self, dynamicUpdateSliceOptions): + if dynamicUpdateSliceOptions is None: + return + + # DynamicUpdateSliceOptionsT + def Pack(self, builder): + DynamicUpdateSliceOptionsStart(builder) + dynamicUpdateSliceOptions = DynamicUpdateSliceOptionsEnd(builder) + return dynamicUpdateSliceOptions + + +class UnsortedSegmentProdOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UnsortedSegmentProdOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUnsortedSegmentProdOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UnsortedSegmentProdOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UnsortedSegmentProdOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def UnsortedSegmentProdOptionsStart(builder): + builder.StartObject(0) + +def UnsortedSegmentProdOptionsEnd(builder): + return builder.EndObject() + + + +class UnsortedSegmentProdOptionsT(object): + + # UnsortedSegmentProdOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + unsortedSegmentProdOptions = UnsortedSegmentProdOptions() + unsortedSegmentProdOptions.Init(buf, pos) + return cls.InitFromObj(unsortedSegmentProdOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, unsortedSegmentProdOptions): + x = UnsortedSegmentProdOptionsT() + x._UnPack(unsortedSegmentProdOptions) + return x + + # UnsortedSegmentProdOptionsT + def _UnPack(self, unsortedSegmentProdOptions): + if unsortedSegmentProdOptions is None: + return + + # UnsortedSegmentProdOptionsT + def Pack(self, builder): + UnsortedSegmentProdOptionsStart(builder) + unsortedSegmentProdOptions = UnsortedSegmentProdOptionsEnd(builder) + return unsortedSegmentProdOptions + + +class UnsortedSegmentMaxOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UnsortedSegmentMaxOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUnsortedSegmentMaxOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UnsortedSegmentMaxOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UnsortedSegmentMaxOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def UnsortedSegmentMaxOptionsStart(builder): + builder.StartObject(0) + +def UnsortedSegmentMaxOptionsEnd(builder): + return builder.EndObject() + + + +class UnsortedSegmentMaxOptionsT(object): + + # UnsortedSegmentMaxOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + unsortedSegmentMaxOptions = UnsortedSegmentMaxOptions() + unsortedSegmentMaxOptions.Init(buf, pos) + return cls.InitFromObj(unsortedSegmentMaxOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, unsortedSegmentMaxOptions): + x = UnsortedSegmentMaxOptionsT() + x._UnPack(unsortedSegmentMaxOptions) + return x + + # UnsortedSegmentMaxOptionsT + def _UnPack(self, unsortedSegmentMaxOptions): + if unsortedSegmentMaxOptions is None: + return + + # UnsortedSegmentMaxOptionsT + def Pack(self, builder): + UnsortedSegmentMaxOptionsStart(builder) + unsortedSegmentMaxOptions = UnsortedSegmentMaxOptionsEnd(builder) + return unsortedSegmentMaxOptions + + +class UnsortedSegmentSumOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UnsortedSegmentSumOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUnsortedSegmentSumOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UnsortedSegmentSumOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UnsortedSegmentSumOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def UnsortedSegmentSumOptionsStart(builder): + builder.StartObject(0) + +def UnsortedSegmentSumOptionsEnd(builder): + return builder.EndObject() + + + +class UnsortedSegmentSumOptionsT(object): + + # UnsortedSegmentSumOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + unsortedSegmentSumOptions = UnsortedSegmentSumOptions() + unsortedSegmentSumOptions.Init(buf, pos) + return cls.InitFromObj(unsortedSegmentSumOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, unsortedSegmentSumOptions): + x = UnsortedSegmentSumOptionsT() + x._UnPack(unsortedSegmentSumOptions) + return x + + # UnsortedSegmentSumOptionsT + def _UnPack(self, unsortedSegmentSumOptions): + if unsortedSegmentSumOptions is None: + return + + # UnsortedSegmentSumOptionsT + def Pack(self, builder): + UnsortedSegmentSumOptionsStart(builder) + unsortedSegmentSumOptions = UnsortedSegmentSumOptionsEnd(builder) + return unsortedSegmentSumOptions + + +class ATan2Options(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ATan2Options() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsATan2Options(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ATan2OptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ATan2Options + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def ATan2OptionsStart(builder): + builder.StartObject(0) + +def ATan2OptionsEnd(builder): + return builder.EndObject() + + + +class ATan2OptionsT(object): + + # ATan2OptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + atan2Options = ATan2Options() + atan2Options.Init(buf, pos) + return cls.InitFromObj(atan2Options) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, atan2Options): + x = ATan2OptionsT() + x._UnPack(atan2Options) + return x + + # ATan2OptionsT + def _UnPack(self, atan2Options): + if atan2Options is None: + return + + # ATan2OptionsT + def Pack(self, builder): + ATan2OptionsStart(builder) + atan2Options = ATan2OptionsEnd(builder) + return atan2Options + + +class UnsortedSegmentMinOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = UnsortedSegmentMinOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUnsortedSegmentMinOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def UnsortedSegmentMinOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # UnsortedSegmentMinOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def UnsortedSegmentMinOptionsStart(builder): + builder.StartObject(0) + +def UnsortedSegmentMinOptionsEnd(builder): + return builder.EndObject() + + + +class UnsortedSegmentMinOptionsT(object): + + # UnsortedSegmentMinOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + unsortedSegmentMinOptions = UnsortedSegmentMinOptions() + unsortedSegmentMinOptions.Init(buf, pos) + return cls.InitFromObj(unsortedSegmentMinOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, unsortedSegmentMinOptions): + x = UnsortedSegmentMinOptionsT() + x._UnPack(unsortedSegmentMinOptions) + return x + + # UnsortedSegmentMinOptionsT + def _UnPack(self, unsortedSegmentMinOptions): + if unsortedSegmentMinOptions is None: + return + + # UnsortedSegmentMinOptionsT + def Pack(self, builder): + UnsortedSegmentMinOptionsStart(builder) + unsortedSegmentMinOptions = UnsortedSegmentMinOptionsEnd(builder) + return unsortedSegmentMinOptions + + +class SignOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SignOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSignOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SignOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SignOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def SignOptionsStart(builder): + builder.StartObject(0) + +def SignOptionsEnd(builder): + return builder.EndObject() + + + +class SignOptionsT(object): + + # SignOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + signOptions = SignOptions() + signOptions.Init(buf, pos) + return cls.InitFromObj(signOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, signOptions): + x = SignOptionsT() + x._UnPack(signOptions) + return x + + # SignOptionsT + def _UnPack(self, signOptions): + if signOptions is None: + return + + # SignOptionsT + def Pack(self, builder): + SignOptionsStart(builder) + signOptions = SignOptionsEnd(builder) + return signOptions + + +class BitcastOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BitcastOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBitcastOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BitcastOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BitcastOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def BitcastOptionsStart(builder): + builder.StartObject(0) + +def BitcastOptionsEnd(builder): + return builder.EndObject() + + + +class BitcastOptionsT(object): + + # BitcastOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + bitcastOptions = BitcastOptions() + bitcastOptions.Init(buf, pos) + return cls.InitFromObj(bitcastOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, bitcastOptions): + x = BitcastOptionsT() + x._UnPack(bitcastOptions) + return x + + # BitcastOptionsT + def _UnPack(self, bitcastOptions): + if bitcastOptions is None: + return + + # BitcastOptionsT + def Pack(self, builder): + BitcastOptionsStart(builder) + bitcastOptions = BitcastOptionsEnd(builder) + return bitcastOptions + + +class BitwiseXorOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = BitwiseXorOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBitwiseXorOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BitwiseXorOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # BitwiseXorOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def BitwiseXorOptionsStart(builder): + builder.StartObject(0) + +def BitwiseXorOptionsEnd(builder): + return builder.EndObject() + + + +class BitwiseXorOptionsT(object): + + # BitwiseXorOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + bitwiseXorOptions = BitwiseXorOptions() + bitwiseXorOptions.Init(buf, pos) + return cls.InitFromObj(bitwiseXorOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, bitwiseXorOptions): + x = BitwiseXorOptionsT() + x._UnPack(bitwiseXorOptions) + return x + + # BitwiseXorOptionsT + def _UnPack(self, bitwiseXorOptions): + if bitwiseXorOptions is None: + return + + # BitwiseXorOptionsT + def Pack(self, builder): + BitwiseXorOptionsStart(builder) + bitwiseXorOptions = BitwiseXorOptionsEnd(builder) + return bitwiseXorOptions + + +class RightShiftOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = RightShiftOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsRightShiftOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def RightShiftOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # RightShiftOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def RightShiftOptionsStart(builder): + builder.StartObject(0) + +def RightShiftOptionsEnd(builder): + return builder.EndObject() + + + +class RightShiftOptionsT(object): + + # RightShiftOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + rightShiftOptions = RightShiftOptions() + rightShiftOptions.Init(buf, pos) + return cls.InitFromObj(rightShiftOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, rightShiftOptions): + x = RightShiftOptionsT() + x._UnPack(rightShiftOptions) + return x + + # RightShiftOptionsT + def _UnPack(self, rightShiftOptions): + if rightShiftOptions is None: + return + + # RightShiftOptionsT + def Pack(self, builder): + RightShiftOptionsStart(builder) + rightShiftOptions = RightShiftOptionsEnd(builder) + return rightShiftOptions + + +class DilateOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = DilateOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsDilateOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def DilateOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # DilateOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def DilateOptionsStart(builder): + builder.StartObject(0) + +def DilateOptionsEnd(builder): + return builder.EndObject() + + + +class DilateOptionsT(object): + + # DilateOptionsT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + dilateOptions = DilateOptions() + dilateOptions.Init(buf, pos) + return cls.InitFromObj(dilateOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, dilateOptions): + x = DilateOptionsT() + x._UnPack(dilateOptions) + return x + + # DilateOptionsT + def _UnPack(self, dilateOptions): + if dilateOptions is None: + return + + # DilateOptionsT + def Pack(self, builder): + DilateOptionsStart(builder) + dilateOptions = DilateOptionsEnd(builder) + return dilateOptions + + +class ReduceWindowOptions(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ReduceWindowOptions() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReduceWindowOptions(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReduceWindowOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # ReduceWindowOptions + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ReduceWindowOptions + def ReduceFunction(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def ReduceWindowOptionsStart(builder): + builder.StartObject(1) + +def ReduceWindowOptionsAddReduceFunction(builder, reduceFunction): + builder.PrependInt32Slot(0, reduceFunction, 0) + +def ReduceWindowOptionsEnd(builder): + return builder.EndObject() + + + +class ReduceWindowOptionsT(object): + + # ReduceWindowOptionsT + def __init__(self): + self.reduceFunction = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + reduceWindowOptions = ReduceWindowOptions() + reduceWindowOptions.Init(buf, pos) + return cls.InitFromObj(reduceWindowOptions) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, reduceWindowOptions): + x = ReduceWindowOptionsT() + x._UnPack(reduceWindowOptions) + return x + + # ReduceWindowOptionsT + def _UnPack(self, reduceWindowOptions): + if reduceWindowOptions is None: + return + self.reduceFunction = reduceWindowOptions.ReduceFunction() + + # ReduceWindowOptionsT + def Pack(self, builder): + ReduceWindowOptionsStart(builder) + ReduceWindowOptionsAddReduceFunction(builder, self.reduceFunction) + reduceWindowOptions = ReduceWindowOptionsEnd(builder) + return reduceWindowOptions + + +class OperatorCode(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = OperatorCode() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsOperatorCode(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def OperatorCodeBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # OperatorCode + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # OperatorCode + def DeprecatedBuiltinCode(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # OperatorCode + def CustomCode(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # OperatorCode + def Version(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 1 + + # OperatorCode + def BuiltinCode(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def OperatorCodeStart(builder): + builder.StartObject(4) + +def OperatorCodeAddDeprecatedBuiltinCode(builder, deprecatedBuiltinCode): + builder.PrependInt8Slot(0, deprecatedBuiltinCode, 0) + +def OperatorCodeAddCustomCode(builder, customCode): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(customCode), 0) + +def OperatorCodeAddVersion(builder, version): + builder.PrependInt32Slot(2, version, 1) + +def OperatorCodeAddBuiltinCode(builder, builtinCode): + builder.PrependInt32Slot(3, builtinCode, 0) + +def OperatorCodeEnd(builder): + return builder.EndObject() + + + +class OperatorCodeT(object): + + # OperatorCodeT + def __init__(self): + self.deprecatedBuiltinCode = 0 # type: int + self.customCode = None # type: str + self.version = 1 # type: int + self.builtinCode = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + operatorCode = OperatorCode() + operatorCode.Init(buf, pos) + return cls.InitFromObj(operatorCode) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, operatorCode): + x = OperatorCodeT() + x._UnPack(operatorCode) + return x + + # OperatorCodeT + def _UnPack(self, operatorCode): + if operatorCode is None: + return + self.deprecatedBuiltinCode = operatorCode.DeprecatedBuiltinCode() + self.customCode = operatorCode.CustomCode() + self.version = operatorCode.Version() + self.builtinCode = operatorCode.BuiltinCode() + + # OperatorCodeT + def Pack(self, builder): + if self.customCode is not None: + customCode = builder.CreateString(self.customCode) + OperatorCodeStart(builder) + OperatorCodeAddDeprecatedBuiltinCode(builder, self.deprecatedBuiltinCode) + if self.customCode is not None: + OperatorCodeAddCustomCode(builder, customCode) + OperatorCodeAddVersion(builder, self.version) + OperatorCodeAddBuiltinCode(builder, self.builtinCode) + operatorCode = OperatorCodeEnd(builder) + return operatorCode + + +class Operator(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Operator() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsOperator(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def OperatorBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Operator + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Operator + def OpcodeIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Operator + def Inputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Operator + def InputsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Operator + def InputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Operator + def InputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # Operator + def Outputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Operator + def OutputsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Operator + def OutputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Operator + def OutputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # Operator + def BuiltinOptionsType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Operator + def BuiltinOptions(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Operator + def CustomOptions(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Operator + def CustomOptionsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Operator + def CustomOptionsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Operator + def CustomOptionsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + + # Operator + def CustomOptionsFormat(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # Operator + def MutatingVariableInputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.BoolFlags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Operator + def MutatingVariableInputsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.BoolFlags, o) + return 0 + + # Operator + def MutatingVariableInputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Operator + def MutatingVariableInputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + return o == 0 + + # Operator + def Intermediates(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Operator + def IntermediatesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Operator + def IntermediatesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Operator + def IntermediatesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + return o == 0 + + # Operator + def LargeCustomOptionsOffset(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Operator + def LargeCustomOptionsSize(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Operator + def BuiltinOptions2Type(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Operator + def BuiltinOptions2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + +def OperatorStart(builder): + builder.StartObject(13) + +def OperatorAddOpcodeIndex(builder, opcodeIndex): + builder.PrependUint32Slot(0, opcodeIndex, 0) + +def OperatorAddInputs(builder, inputs): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(inputs), 0) + +def OperatorStartInputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def OperatorAddOutputs(builder, outputs): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(outputs), 0) + +def OperatorStartOutputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def OperatorAddBuiltinOptionsType(builder, builtinOptionsType): + builder.PrependUint8Slot(3, builtinOptionsType, 0) + +def OperatorAddBuiltinOptions(builder, builtinOptions): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(builtinOptions), 0) + +def OperatorAddCustomOptions(builder, customOptions): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(customOptions), 0) + +def OperatorStartCustomOptionsVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def OperatorAddCustomOptionsFormat(builder, customOptionsFormat): + builder.PrependInt8Slot(6, customOptionsFormat, 0) + +def OperatorAddMutatingVariableInputs(builder, mutatingVariableInputs): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(mutatingVariableInputs), 0) + +def OperatorStartMutatingVariableInputsVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def OperatorAddIntermediates(builder, intermediates): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(intermediates), 0) + +def OperatorStartIntermediatesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def OperatorAddLargeCustomOptionsOffset(builder, largeCustomOptionsOffset): + builder.PrependUint64Slot(9, largeCustomOptionsOffset, 0) + +def OperatorAddLargeCustomOptionsSize(builder, largeCustomOptionsSize): + builder.PrependUint64Slot(10, largeCustomOptionsSize, 0) + +def OperatorAddBuiltinOptions2Type(builder, builtinOptions2Type): + builder.PrependUint8Slot(11, builtinOptions2Type, 0) + +def OperatorAddBuiltinOptions2(builder, builtinOptions2): + builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(builtinOptions2), 0) + +def OperatorEnd(builder): + return builder.EndObject() + + +try: + from typing import List, Union +except: + pass + +class OperatorT(object): + + # OperatorT + def __init__(self): + self.opcodeIndex = 0 # type: int + self.inputs = None # type: List[int] + self.outputs = None # type: List[int] + self.builtinOptionsType = 0 # type: int + self.builtinOptions = None # type: Union[None, Conv2DOptionsT, DepthwiseConv2DOptionsT, ConcatEmbeddingsOptionsT, LSHProjectionOptionsT, Pool2DOptionsT, SVDFOptionsT, RNNOptionsT, FullyConnectedOptionsT, SoftmaxOptionsT, ConcatenationOptionsT, AddOptionsT, L2NormOptionsT, LocalResponseNormalizationOptionsT, LSTMOptionsT, ResizeBilinearOptionsT, CallOptionsT, ReshapeOptionsT, SkipGramOptionsT, SpaceToDepthOptionsT, EmbeddingLookupSparseOptionsT, MulOptionsT, PadOptionsT, GatherOptionsT, BatchToSpaceNDOptionsT, SpaceToBatchNDOptionsT, TransposeOptionsT, ReducerOptionsT, SubOptionsT, DivOptionsT, SqueezeOptionsT, SequenceRNNOptionsT, StridedSliceOptionsT, ExpOptionsT, TopKV2OptionsT, SplitOptionsT, LogSoftmaxOptionsT, CastOptionsT, DequantizeOptionsT, MaximumMinimumOptionsT, ArgMaxOptionsT, LessOptionsT, NegOptionsT, PadV2OptionsT, GreaterOptionsT, GreaterEqualOptionsT, LessEqualOptionsT, SelectOptionsT, SliceOptionsT, TransposeConvOptionsT, SparseToDenseOptionsT, TileOptionsT, ExpandDimsOptionsT, EqualOptionsT, NotEqualOptionsT, ShapeOptionsT, PowOptionsT, ArgMinOptionsT, FakeQuantOptionsT, PackOptionsT, LogicalOrOptionsT, OneHotOptionsT, LogicalAndOptionsT, LogicalNotOptionsT, UnpackOptionsT, FloorDivOptionsT, SquareOptionsT, ZerosLikeOptionsT, FillOptionsT, BidirectionalSequenceLSTMOptionsT, BidirectionalSequenceRNNOptionsT, UnidirectionalSequenceLSTMOptionsT, FloorModOptionsT, RangeOptionsT, ResizeNearestNeighborOptionsT, LeakyReluOptionsT, SquaredDifferenceOptionsT, MirrorPadOptionsT, AbsOptionsT, SplitVOptionsT, UniqueOptionsT, ReverseV2OptionsT, AddNOptionsT, GatherNdOptionsT, CosOptionsT, WhereOptionsT, RankOptionsT, ReverseSequenceOptionsT, MatrixDiagOptionsT, QuantizeOptionsT, MatrixSetDiagOptionsT, HardSwishOptionsT, IfOptionsT, WhileOptionsT, DepthToSpaceOptionsT, NonMaxSuppressionV4OptionsT, NonMaxSuppressionV5OptionsT, ScatterNdOptionsT, SelectV2OptionsT, DensifyOptionsT, SegmentSumOptionsT, BatchMatMulOptionsT, CumsumOptionsT, CallOnceOptionsT, BroadcastToOptionsT, Rfft2dOptionsT, Conv3DOptionsT, HashtableOptionsT, HashtableFindOptionsT, HashtableImportOptionsT, HashtableSizeOptionsT, VarHandleOptionsT, ReadVariableOptionsT, AssignVariableOptionsT, RandomOptionsT, BucketizeOptionsT, GeluOptionsT, DynamicUpdateSliceOptionsT, UnsortedSegmentProdOptionsT, UnsortedSegmentMaxOptionsT, UnsortedSegmentMinOptionsT, UnsortedSegmentSumOptionsT, ATan2OptionsT, SignOptionsT, BitcastOptionsT, BitwiseXorOptionsT, RightShiftOptionsT] + self.customOptions = None # type: List[int] + self.customOptionsFormat = 0 # type: int + self.mutatingVariableInputs = None # type: List[bool] + self.intermediates = None # type: List[int] + self.largeCustomOptionsOffset = 0 # type: int + self.largeCustomOptionsSize = 0 # type: int + self.builtinOptions2Type = 0 # type: int + self.builtinOptions2 = None # type: Union[None, StablehloConcatenateOptionsT, StablehloBroadcastInDimOptionsT, StablehloSliceOptionsT, StablehloConvolutionOptionsT, StablehloCustomCallOptionsT, StablehloReduceOptionsT, StablehloScatterOptionsT, StablehloCompareOptionsT, StablehloDynamicSliceOptionsT, StablehloPadOptionsT, StablehloIotaOptionsT, StablehloDotGeneralOptionsT, StablehloReduceWindowOptionsT, StablehloSortOptionsT, StablehloWhileOptionsT, StablehloGatherOptionsT, StablehloTransposeOptionsT, DilateOptionsT, StablehloRngBitGeneratorOptionsT, ReduceWindowOptionsT] + + @classmethod + def InitFromBuf(cls, buf, pos): + operator = Operator() + operator.Init(buf, pos) + return cls.InitFromObj(operator) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, operator): + x = OperatorT() + x._UnPack(operator) + return x + + # OperatorT + def _UnPack(self, operator): + if operator is None: + return + self.opcodeIndex = operator.OpcodeIndex() + if not operator.InputsIsNone(): + if np is None: + self.inputs = [] + for i in range(operator.InputsLength()): + self.inputs.append(operator.Inputs(i)) + else: + self.inputs = operator.InputsAsNumpy() + if not operator.OutputsIsNone(): + if np is None: + self.outputs = [] + for i in range(operator.OutputsLength()): + self.outputs.append(operator.Outputs(i)) + else: + self.outputs = operator.OutputsAsNumpy() + self.builtinOptionsType = operator.BuiltinOptionsType() + self.builtinOptions = BuiltinOptionsCreator(self.builtinOptionsType, operator.BuiltinOptions()) + if not operator.CustomOptionsIsNone(): + if np is None: + self.customOptions = [] + for i in range(operator.CustomOptionsLength()): + self.customOptions.append(operator.CustomOptions(i)) + else: + self.customOptions = operator.CustomOptionsAsNumpy() + self.customOptionsFormat = operator.CustomOptionsFormat() + if not operator.MutatingVariableInputsIsNone(): + if np is None: + self.mutatingVariableInputs = [] + for i in range(operator.MutatingVariableInputsLength()): + self.mutatingVariableInputs.append(operator.MutatingVariableInputs(i)) + else: + self.mutatingVariableInputs = operator.MutatingVariableInputsAsNumpy() + if not operator.IntermediatesIsNone(): + if np is None: + self.intermediates = [] + for i in range(operator.IntermediatesLength()): + self.intermediates.append(operator.Intermediates(i)) + else: + self.intermediates = operator.IntermediatesAsNumpy() + self.largeCustomOptionsOffset = operator.LargeCustomOptionsOffset() + self.largeCustomOptionsSize = operator.LargeCustomOptionsSize() + self.builtinOptions2Type = operator.BuiltinOptions2Type() + self.builtinOptions2 = BuiltinOptions2Creator(self.builtinOptions2Type, operator.BuiltinOptions2()) + + # OperatorT + def Pack(self, builder): + if self.inputs is not None: + if np is not None and type(self.inputs) is np.ndarray: + inputs = builder.CreateNumpyVector(self.inputs) + else: + OperatorStartInputsVector(builder, len(self.inputs)) + for i in reversed(range(len(self.inputs))): + builder.PrependInt32(self.inputs[i]) + inputs = builder.EndVector() + if self.outputs is not None: + if np is not None and type(self.outputs) is np.ndarray: + outputs = builder.CreateNumpyVector(self.outputs) + else: + OperatorStartOutputsVector(builder, len(self.outputs)) + for i in reversed(range(len(self.outputs))): + builder.PrependInt32(self.outputs[i]) + outputs = builder.EndVector() + if self.builtinOptions is not None: + builtinOptions = self.builtinOptions.Pack(builder) + if self.customOptions is not None: + if np is not None and type(self.customOptions) is np.ndarray: + customOptions = builder.CreateNumpyVector(self.customOptions) + else: + OperatorStartCustomOptionsVector(builder, len(self.customOptions)) + for i in reversed(range(len(self.customOptions))): + builder.PrependUint8(self.customOptions[i]) + customOptions = builder.EndVector() + if self.mutatingVariableInputs is not None: + if np is not None and type(self.mutatingVariableInputs) is np.ndarray: + mutatingVariableInputs = builder.CreateNumpyVector(self.mutatingVariableInputs) + else: + OperatorStartMutatingVariableInputsVector(builder, len(self.mutatingVariableInputs)) + for i in reversed(range(len(self.mutatingVariableInputs))): + builder.PrependBool(self.mutatingVariableInputs[i]) + mutatingVariableInputs = builder.EndVector() + if self.intermediates is not None: + if np is not None and type(self.intermediates) is np.ndarray: + intermediates = builder.CreateNumpyVector(self.intermediates) + else: + OperatorStartIntermediatesVector(builder, len(self.intermediates)) + for i in reversed(range(len(self.intermediates))): + builder.PrependInt32(self.intermediates[i]) + intermediates = builder.EndVector() + if self.builtinOptions2 is not None: + builtinOptions2 = self.builtinOptions2.Pack(builder) + OperatorStart(builder) + OperatorAddOpcodeIndex(builder, self.opcodeIndex) + if self.inputs is not None: + OperatorAddInputs(builder, inputs) + if self.outputs is not None: + OperatorAddOutputs(builder, outputs) + OperatorAddBuiltinOptionsType(builder, self.builtinOptionsType) + if self.builtinOptions is not None: + OperatorAddBuiltinOptions(builder, builtinOptions) + if self.customOptions is not None: + OperatorAddCustomOptions(builder, customOptions) + OperatorAddCustomOptionsFormat(builder, self.customOptionsFormat) + if self.mutatingVariableInputs is not None: + OperatorAddMutatingVariableInputs(builder, mutatingVariableInputs) + if self.intermediates is not None: + OperatorAddIntermediates(builder, intermediates) + OperatorAddLargeCustomOptionsOffset(builder, self.largeCustomOptionsOffset) + OperatorAddLargeCustomOptionsSize(builder, self.largeCustomOptionsSize) + OperatorAddBuiltinOptions2Type(builder, self.builtinOptions2Type) + if self.builtinOptions2 is not None: + OperatorAddBuiltinOptions2(builder, builtinOptions2) + operator = OperatorEnd(builder) + return operator + + +class SubGraph(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SubGraph() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSubGraph(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SubGraphBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SubGraph + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SubGraph + def Tensors(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Tensor() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SubGraph + def TensorsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SubGraph + def TensorsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # SubGraph + def Inputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # SubGraph + def InputsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # SubGraph + def InputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SubGraph + def InputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # SubGraph + def Outputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # SubGraph + def OutputsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # SubGraph + def OutputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SubGraph + def OutputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # SubGraph + def Operators(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Operator() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SubGraph + def OperatorsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SubGraph + def OperatorsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + return o == 0 + + # SubGraph + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + +def SubGraphStart(builder): + builder.StartObject(5) + +def SubGraphAddTensors(builder, tensors): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(tensors), 0) + +def SubGraphStartTensorsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SubGraphAddInputs(builder, inputs): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(inputs), 0) + +def SubGraphStartInputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SubGraphAddOutputs(builder, outputs): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(outputs), 0) + +def SubGraphStartOutputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SubGraphAddOperators(builder, operators): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(operators), 0) + +def SubGraphStartOperatorsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SubGraphAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def SubGraphEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class SubGraphT(object): + + # SubGraphT + def __init__(self): + self.tensors = None # type: List[TensorT] + self.inputs = None # type: List[int] + self.outputs = None # type: List[int] + self.operators = None # type: List[OperatorT] + self.name = None # type: str + + @classmethod + def InitFromBuf(cls, buf, pos): + subGraph = SubGraph() + subGraph.Init(buf, pos) + return cls.InitFromObj(subGraph) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, subGraph): + x = SubGraphT() + x._UnPack(subGraph) + return x + + # SubGraphT + def _UnPack(self, subGraph): + if subGraph is None: + return + if not subGraph.TensorsIsNone(): + self.tensors = [] + for i in range(subGraph.TensorsLength()): + if subGraph.Tensors(i) is None: + self.tensors.append(None) + else: + tensor_ = TensorT.InitFromObj(subGraph.Tensors(i)) + self.tensors.append(tensor_) + if not subGraph.InputsIsNone(): + if np is None: + self.inputs = [] + for i in range(subGraph.InputsLength()): + self.inputs.append(subGraph.Inputs(i)) + else: + self.inputs = subGraph.InputsAsNumpy() + if not subGraph.OutputsIsNone(): + if np is None: + self.outputs = [] + for i in range(subGraph.OutputsLength()): + self.outputs.append(subGraph.Outputs(i)) + else: + self.outputs = subGraph.OutputsAsNumpy() + if not subGraph.OperatorsIsNone(): + self.operators = [] + for i in range(subGraph.OperatorsLength()): + if subGraph.Operators(i) is None: + self.operators.append(None) + else: + operator_ = OperatorT.InitFromObj(subGraph.Operators(i)) + self.operators.append(operator_) + self.name = subGraph.Name() + + # SubGraphT + def Pack(self, builder): + if self.tensors is not None: + tensorslist = [] + for i in range(len(self.tensors)): + tensorslist.append(self.tensors[i].Pack(builder)) + SubGraphStartTensorsVector(builder, len(self.tensors)) + for i in reversed(range(len(self.tensors))): + builder.PrependUOffsetTRelative(tensorslist[i]) + tensors = builder.EndVector() + if self.inputs is not None: + if np is not None and type(self.inputs) is np.ndarray: + inputs = builder.CreateNumpyVector(self.inputs) + else: + SubGraphStartInputsVector(builder, len(self.inputs)) + for i in reversed(range(len(self.inputs))): + builder.PrependInt32(self.inputs[i]) + inputs = builder.EndVector() + if self.outputs is not None: + if np is not None and type(self.outputs) is np.ndarray: + outputs = builder.CreateNumpyVector(self.outputs) + else: + SubGraphStartOutputsVector(builder, len(self.outputs)) + for i in reversed(range(len(self.outputs))): + builder.PrependInt32(self.outputs[i]) + outputs = builder.EndVector() + if self.operators is not None: + operatorslist = [] + for i in range(len(self.operators)): + operatorslist.append(self.operators[i].Pack(builder)) + SubGraphStartOperatorsVector(builder, len(self.operators)) + for i in reversed(range(len(self.operators))): + builder.PrependUOffsetTRelative(operatorslist[i]) + operators = builder.EndVector() + if self.name is not None: + name = builder.CreateString(self.name) + SubGraphStart(builder) + if self.tensors is not None: + SubGraphAddTensors(builder, tensors) + if self.inputs is not None: + SubGraphAddInputs(builder, inputs) + if self.outputs is not None: + SubGraphAddOutputs(builder, outputs) + if self.operators is not None: + SubGraphAddOperators(builder, operators) + if self.name is not None: + SubGraphAddName(builder, name) + subGraph = SubGraphEnd(builder) + return subGraph + + +class Buffer(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Buffer() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsBuffer(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def BufferBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Buffer + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Buffer + def Data(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Buffer + def DataAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Buffer + def DataLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Buffer + def DataIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # Buffer + def Offset(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Buffer + def Size(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + +def BufferStart(builder): + builder.StartObject(3) + +def BufferAddData(builder, data): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(data), 0) + +def BufferStartDataVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def BufferAddOffset(builder, offset): + builder.PrependUint64Slot(1, offset, 0) + +def BufferAddSize(builder, size): + builder.PrependUint64Slot(2, size, 0) + +def BufferEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class BufferT(object): + + # BufferT + def __init__(self): + self.data = None # type: List[int] + self.offset = 0 # type: int + self.size = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + buffer = Buffer() + buffer.Init(buf, pos) + return cls.InitFromObj(buffer) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, buffer): + x = BufferT() + x._UnPack(buffer) + return x + + # BufferT + def _UnPack(self, buffer): + if buffer is None: + return + if not buffer.DataIsNone(): + if np is None: + self.data = [] + for i in range(buffer.DataLength()): + self.data.append(buffer.Data(i)) + else: + self.data = buffer.DataAsNumpy() + self.offset = buffer.Offset() + self.size = buffer.Size() + + # BufferT + def Pack(self, builder): + if self.data is not None: + if np is not None and type(self.data) is np.ndarray: + data = builder.CreateNumpyVector(self.data) + else: + BufferStartDataVector(builder, len(self.data)) + for i in reversed(range(len(self.data))): + builder.PrependUint8(self.data[i]) + data = builder.EndVector() + BufferStart(builder) + if self.data is not None: + BufferAddData(builder, data) + BufferAddOffset(builder, self.offset) + BufferAddSize(builder, self.size) + buffer = BufferEnd(builder) + return buffer + + +class Metadata(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Metadata() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMetadata(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MetadataBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Metadata + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Metadata + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Metadata + def Buffer(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def MetadataStart(builder): + builder.StartObject(2) + +def MetadataAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def MetadataAddBuffer(builder, buffer): + builder.PrependUint32Slot(1, buffer, 0) + +def MetadataEnd(builder): + return builder.EndObject() + + + +class MetadataT(object): + + # MetadataT + def __init__(self): + self.name = None # type: str + self.buffer = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + metadata = Metadata() + metadata.Init(buf, pos) + return cls.InitFromObj(metadata) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, metadata): + x = MetadataT() + x._UnPack(metadata) + return x + + # MetadataT + def _UnPack(self, metadata): + if metadata is None: + return + self.name = metadata.Name() + self.buffer = metadata.Buffer() + + # MetadataT + def Pack(self, builder): + if self.name is not None: + name = builder.CreateString(self.name) + MetadataStart(builder) + if self.name is not None: + MetadataAddName(builder, name) + MetadataAddBuffer(builder, self.buffer) + metadata = MetadataEnd(builder) + return metadata + + +class TensorMap(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TensorMap() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTensorMap(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TensorMapBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # TensorMap + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TensorMap + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # TensorMap + def TensorIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def TensorMapStart(builder): + builder.StartObject(2) + +def TensorMapAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def TensorMapAddTensorIndex(builder, tensorIndex): + builder.PrependUint32Slot(1, tensorIndex, 0) + +def TensorMapEnd(builder): + return builder.EndObject() + + + +class TensorMapT(object): + + # TensorMapT + def __init__(self): + self.name = None # type: str + self.tensorIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + tensorMap = TensorMap() + tensorMap.Init(buf, pos) + return cls.InitFromObj(tensorMap) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, tensorMap): + x = TensorMapT() + x._UnPack(tensorMap) + return x + + # TensorMapT + def _UnPack(self, tensorMap): + if tensorMap is None: + return + self.name = tensorMap.Name() + self.tensorIndex = tensorMap.TensorIndex() + + # TensorMapT + def Pack(self, builder): + if self.name is not None: + name = builder.CreateString(self.name) + TensorMapStart(builder) + if self.name is not None: + TensorMapAddName(builder, name) + TensorMapAddTensorIndex(builder, self.tensorIndex) + tensorMap = TensorMapEnd(builder) + return tensorMap + + +class SignatureDef(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SignatureDef() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSignatureDef(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def SignatureDefBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # SignatureDef + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SignatureDef + def Inputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = TensorMap() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SignatureDef + def InputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SignatureDef + def InputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + return o == 0 + + # SignatureDef + def Outputs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = TensorMap() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # SignatureDef + def OutputsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # SignatureDef + def OutputsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # SignatureDef + def SignatureKey(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # SignatureDef + def SubgraphIndex(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + +def SignatureDefStart(builder): + builder.StartObject(5) + +def SignatureDefAddInputs(builder, inputs): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(inputs), 0) + +def SignatureDefStartInputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SignatureDefAddOutputs(builder, outputs): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(outputs), 0) + +def SignatureDefStartOutputsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def SignatureDefAddSignatureKey(builder, signatureKey): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(signatureKey), 0) + +def SignatureDefAddSubgraphIndex(builder, subgraphIndex): + builder.PrependUint32Slot(4, subgraphIndex, 0) + +def SignatureDefEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class SignatureDefT(object): + + # SignatureDefT + def __init__(self): + self.inputs = None # type: List[TensorMapT] + self.outputs = None # type: List[TensorMapT] + self.signatureKey = None # type: str + self.subgraphIndex = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + signatureDef = SignatureDef() + signatureDef.Init(buf, pos) + return cls.InitFromObj(signatureDef) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, signatureDef): + x = SignatureDefT() + x._UnPack(signatureDef) + return x + + # SignatureDefT + def _UnPack(self, signatureDef): + if signatureDef is None: + return + if not signatureDef.InputsIsNone(): + self.inputs = [] + for i in range(signatureDef.InputsLength()): + if signatureDef.Inputs(i) is None: + self.inputs.append(None) + else: + tensorMap_ = TensorMapT.InitFromObj(signatureDef.Inputs(i)) + self.inputs.append(tensorMap_) + if not signatureDef.OutputsIsNone(): + self.outputs = [] + for i in range(signatureDef.OutputsLength()): + if signatureDef.Outputs(i) is None: + self.outputs.append(None) + else: + tensorMap_ = TensorMapT.InitFromObj(signatureDef.Outputs(i)) + self.outputs.append(tensorMap_) + self.signatureKey = signatureDef.SignatureKey() + self.subgraphIndex = signatureDef.SubgraphIndex() + + # SignatureDefT + def Pack(self, builder): + if self.inputs is not None: + inputslist = [] + for i in range(len(self.inputs)): + inputslist.append(self.inputs[i].Pack(builder)) + SignatureDefStartInputsVector(builder, len(self.inputs)) + for i in reversed(range(len(self.inputs))): + builder.PrependUOffsetTRelative(inputslist[i]) + inputs = builder.EndVector() + if self.outputs is not None: + outputslist = [] + for i in range(len(self.outputs)): + outputslist.append(self.outputs[i].Pack(builder)) + SignatureDefStartOutputsVector(builder, len(self.outputs)) + for i in reversed(range(len(self.outputs))): + builder.PrependUOffsetTRelative(outputslist[i]) + outputs = builder.EndVector() + if self.signatureKey is not None: + signatureKey = builder.CreateString(self.signatureKey) + SignatureDefStart(builder) + if self.inputs is not None: + SignatureDefAddInputs(builder, inputs) + if self.outputs is not None: + SignatureDefAddOutputs(builder, outputs) + if self.signatureKey is not None: + SignatureDefAddSignatureKey(builder, signatureKey) + SignatureDefAddSubgraphIndex(builder, self.subgraphIndex) + signatureDef = SignatureDefEnd(builder) + return signatureDef + + +class Model(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Model() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsModel(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ModelBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) + + # Model + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Model + def Version(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Model + def OperatorCodes(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = OperatorCode() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def OperatorCodesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def OperatorCodesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + + # Model + def Subgraphs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = SubGraph() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def SubgraphsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def SubgraphsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + return o == 0 + + # Model + def Description(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Model + def Buffers(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Buffer() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def BuffersLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def BuffersIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + return o == 0 + + # Model + def MetadataBuffer(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # Model + def MetadataBufferAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int32Flags, o) + return 0 + + # Model + def MetadataBufferLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def MetadataBufferIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + + # Model + def Metadata(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Metadata() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def MetadataLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def MetadataIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + return o == 0 + + # Model + def SignatureDefs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = SignatureDef() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Model + def SignatureDefsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Model + def SignatureDefsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + return o == 0 + +def ModelStart(builder): + builder.StartObject(8) + +def ModelAddVersion(builder, version): + builder.PrependUint32Slot(0, version, 0) + +def ModelAddOperatorCodes(builder, operatorCodes): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(operatorCodes), 0) + +def ModelStartOperatorCodesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ModelAddSubgraphs(builder, subgraphs): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(subgraphs), 0) + +def ModelStartSubgraphsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ModelAddDescription(builder, description): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(description), 0) + +def ModelAddBuffers(builder, buffers): + builder.PrependUOffsetTRelativeSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(buffers), 0) + +def ModelStartBuffersVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ModelAddMetadataBuffer(builder, metadataBuffer): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(metadataBuffer), 0) + +def ModelStartMetadataBufferVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ModelAddMetadata(builder, metadata): + builder.PrependUOffsetTRelativeSlot(6, flatbuffers.number_types.UOffsetTFlags.py_type(metadata), 0) + +def ModelStartMetadataVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ModelAddSignatureDefs(builder, signatureDefs): + builder.PrependUOffsetTRelativeSlot(7, flatbuffers.number_types.UOffsetTFlags.py_type(signatureDefs), 0) + +def ModelStartSignatureDefsVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def ModelEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class ModelT(object): + + # ModelT + def __init__(self): + self.version = 0 # type: int + self.operatorCodes = None # type: List[OperatorCodeT] + self.subgraphs = None # type: List[SubGraphT] + self.description = None # type: str + self.buffers = None # type: List[BufferT] + self.metadataBuffer = None # type: List[int] + self.metadata = None # type: List[MetadataT] + self.signatureDefs = None # type: List[SignatureDefT] + + @classmethod + def InitFromBuf(cls, buf, pos): + model = Model() + model.Init(buf, pos) + return cls.InitFromObj(model) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, model): + x = ModelT() + x._UnPack(model) + return x + + # ModelT + def _UnPack(self, model): + if model is None: + return + self.version = model.Version() + if not model.OperatorCodesIsNone(): + self.operatorCodes = [] + for i in range(model.OperatorCodesLength()): + if model.OperatorCodes(i) is None: + self.operatorCodes.append(None) + else: + operatorCode_ = OperatorCodeT.InitFromObj(model.OperatorCodes(i)) + self.operatorCodes.append(operatorCode_) + if not model.SubgraphsIsNone(): + self.subgraphs = [] + for i in range(model.SubgraphsLength()): + if model.Subgraphs(i) is None: + self.subgraphs.append(None) + else: + subGraph_ = SubGraphT.InitFromObj(model.Subgraphs(i)) + self.subgraphs.append(subGraph_) + self.description = model.Description() + if not model.BuffersIsNone(): + self.buffers = [] + for i in range(model.BuffersLength()): + if model.Buffers(i) is None: + self.buffers.append(None) + else: + buffer_ = BufferT.InitFromObj(model.Buffers(i)) + self.buffers.append(buffer_) + if not model.MetadataBufferIsNone(): + if np is None: + self.metadataBuffer = [] + for i in range(model.MetadataBufferLength()): + self.metadataBuffer.append(model.MetadataBuffer(i)) + else: + self.metadataBuffer = model.MetadataBufferAsNumpy() + if not model.MetadataIsNone(): + self.metadata = [] + for i in range(model.MetadataLength()): + if model.Metadata(i) is None: + self.metadata.append(None) + else: + metadata_ = MetadataT.InitFromObj(model.Metadata(i)) + self.metadata.append(metadata_) + if not model.SignatureDefsIsNone(): + self.signatureDefs = [] + for i in range(model.SignatureDefsLength()): + if model.SignatureDefs(i) is None: + self.signatureDefs.append(None) + else: + signatureDef_ = SignatureDefT.InitFromObj(model.SignatureDefs(i)) + self.signatureDefs.append(signatureDef_) + + # ModelT + def Pack(self, builder): + if self.operatorCodes is not None: + operatorCodeslist = [] + for i in range(len(self.operatorCodes)): + operatorCodeslist.append(self.operatorCodes[i].Pack(builder)) + ModelStartOperatorCodesVector(builder, len(self.operatorCodes)) + for i in reversed(range(len(self.operatorCodes))): + builder.PrependUOffsetTRelative(operatorCodeslist[i]) + operatorCodes = builder.EndVector() + if self.subgraphs is not None: + subgraphslist = [] + for i in range(len(self.subgraphs)): + subgraphslist.append(self.subgraphs[i].Pack(builder)) + ModelStartSubgraphsVector(builder, len(self.subgraphs)) + for i in reversed(range(len(self.subgraphs))): + builder.PrependUOffsetTRelative(subgraphslist[i]) + subgraphs = builder.EndVector() + if self.description is not None: + description = builder.CreateString(self.description) + if self.buffers is not None: + bufferslist = [] + for i in range(len(self.buffers)): + bufferslist.append(self.buffers[i].Pack(builder)) + ModelStartBuffersVector(builder, len(self.buffers)) + for i in reversed(range(len(self.buffers))): + builder.PrependUOffsetTRelative(bufferslist[i]) + buffers = builder.EndVector() + if self.metadataBuffer is not None: + if np is not None and type(self.metadataBuffer) is np.ndarray: + metadataBuffer = builder.CreateNumpyVector(self.metadataBuffer) + else: + ModelStartMetadataBufferVector(builder, len(self.metadataBuffer)) + for i in reversed(range(len(self.metadataBuffer))): + builder.PrependInt32(self.metadataBuffer[i]) + metadataBuffer = builder.EndVector() + if self.metadata is not None: + metadatalist = [] + for i in range(len(self.metadata)): + metadatalist.append(self.metadata[i].Pack(builder)) + ModelStartMetadataVector(builder, len(self.metadata)) + for i in reversed(range(len(self.metadata))): + builder.PrependUOffsetTRelative(metadatalist[i]) + metadata = builder.EndVector() + if self.signatureDefs is not None: + signatureDefslist = [] + for i in range(len(self.signatureDefs)): + signatureDefslist.append(self.signatureDefs[i].Pack(builder)) + ModelStartSignatureDefsVector(builder, len(self.signatureDefs)) + for i in reversed(range(len(self.signatureDefs))): + builder.PrependUOffsetTRelative(signatureDefslist[i]) + signatureDefs = builder.EndVector() + ModelStart(builder) + ModelAddVersion(builder, self.version) + if self.operatorCodes is not None: + ModelAddOperatorCodes(builder, operatorCodes) + if self.subgraphs is not None: + ModelAddSubgraphs(builder, subgraphs) + if self.description is not None: + ModelAddDescription(builder, description) + if self.buffers is not None: + ModelAddBuffers(builder, buffers) + if self.metadataBuffer is not None: + ModelAddMetadataBuffer(builder, metadataBuffer) + if self.metadata is not None: + ModelAddMetadata(builder, metadata) + if self.signatureDefs is not None: + ModelAddSignatureDefs(builder, signatureDefs) + model = ModelEnd(builder) + return model + + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e898a47318d38a388b8ca661bef89dda53222593 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/schema_util.py @@ -0,0 +1,45 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Schema utilities to get builtin code from operator code.""" + +from tensorflow.python.util import all_util + + +def get_builtin_code_from_operator_code(opcode): + """Return the builtin code of the given operator code. + + The following method is introduced to resolve op builtin code shortage + problem. The new builtin operator will be assigned to the extended builtin + code field in the flatbuffer schema. Those methods helps to hide builtin code + details. + + Args: + opcode: Operator code. + + Returns: + The builtin code of the given operator code. + """ + # Access BuiltinCode() method first if available. + if hasattr(opcode, 'BuiltinCode') and callable(opcode.BuiltinCode): + return max(opcode.BuiltinCode(), opcode.DeprecatedBuiltinCode()) + + return max(opcode.builtinCode, opcode.deprecatedBuiltinCode) + + +_allowed_symbols = [ + 'get_builtin_code_from_operator_code', +] + +all_util.remove_undocumented(__name__, _allowed_symbols) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_convert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..ba049747582d116192b907c89c5b8748b27682bc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_convert.py @@ -0,0 +1,694 @@ +# 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. +# ============================================================================== +"""Python command line interface for converting TF models to TFLite models.""" + +import argparse +import os +import sys +import warnings + +from absl import app +import tensorflow as tf # pylint: disable=unused-import + +from tensorflow.lite.python import lite +from tensorflow.lite.python.convert import register_custom_opdefs +from tensorflow.lite.toco import toco_flags_pb2 as _toco_flags_pb2 +from tensorflow.lite.toco.logging import gen_html +from tensorflow.python import tf2 +from tensorflow.python.framework import dtypes +from tensorflow.python.platform import gfile +from tensorflow.python.util import keras_deps + +# Needed to enable TF2 by default. + + +def _parse_array(values, type_fn=str): + if values is not None: + return [type_fn(val) for val in values.split(",") if val] + return None + + +def _parse_set(values): + if values is not None: + return set([item for item in values.split(",") if item]) + return None + + +def _parse_inference_type(value, flag): + """Converts the inference type to the value of the constant. + + Args: + value: str representing the inference type. + flag: str representing the flag name. + + Returns: + tf.dtype. + + Raises: + ValueError: Unsupported value. + """ + if value == "FLOAT": + return dtypes.float32 + if value == "INT8": + return dtypes.int8 + if value == "UINT8" or value == "QUANTIZED_UINT8": + return dtypes.uint8 + raise ValueError( + "Unsupported value for `{}` flag. Expected FLOAT, INT8, UINT8, or " + "QUANTIZED_UINT8 instead got {}.".format(flag, value)) + + +class _ParseBooleanFlag(argparse.Action): + """Helper class to parse boolean flag that optionally accepts truth value.""" + + def __init__(self, option_strings, dest, nargs=None, **kwargs): + if nargs != "?": + # This should never happen. This class is only used once below with + # nargs="?". + raise ValueError( + "This parser only supports nargs='?' (0 or 1 additional arguments)") + super(_ParseBooleanFlag, self).__init__( + option_strings, dest, nargs=nargs, **kwargs) + + def __call__(self, parser, namespace, values, option_string=None): + if values is None: + # Handling `--boolean_flag`. + # Without additional arguments, it implies true. + flag_value = True + elif values.lower() == "true": + # Handling `--boolean_flag=true`. + # (Case insensitive after the equal sign) + flag_value = True + elif values.lower() == "false": + # Handling `--boolean_flag=false`. + # (Case insensitive after the equal sign) + flag_value = False + else: + raise ValueError("Invalid argument to --{}. Must use flag alone," + " or specify true/false.".format(self.dest)) + setattr(namespace, self.dest, flag_value) + + +def _get_tflite_converter(flags): + """Makes a TFLiteConverter object based on the flags provided. + + Args: + flags: argparse.Namespace object containing TFLite flags. + + Returns: + TFLiteConverter object. + + Raises: + ValueError: Invalid flags. + """ + # Parse input and output arrays. + input_arrays = _parse_array(flags.input_arrays) + input_shapes = None + if flags.input_shapes: + input_shapes_list = [ + _parse_array(shape, type_fn=int) + for shape in flags.input_shapes.split(":") + ] + input_shapes = dict(list(zip(input_arrays, input_shapes_list))) + output_arrays = _parse_array(flags.output_arrays) + + converter_kwargs = { + "input_arrays": input_arrays, + "input_shapes": input_shapes, + "output_arrays": output_arrays + } + + # Create TFLiteConverter. + if flags.graph_def_file: + converter_fn = lite.TFLiteConverter.from_frozen_graph + converter_kwargs["graph_def_file"] = flags.graph_def_file + elif flags.saved_model_dir: + converter_fn = lite.TFLiteConverter.from_saved_model + converter_kwargs["saved_model_dir"] = flags.saved_model_dir + converter_kwargs["tag_set"] = _parse_set(flags.saved_model_tag_set) + converter_kwargs["signature_key"] = flags.saved_model_signature_key + elif flags.keras_model_file: + converter_fn = lite.TFLiteConverter.from_keras_model_file + converter_kwargs["model_file"] = flags.keras_model_file + else: + raise ValueError("--graph_def_file, --saved_model_dir, or " + "--keras_model_file must be specified.") + + return converter_fn(**converter_kwargs) + + +def _convert_tf1_model(flags): + """Calls function to convert the TensorFlow 1.X model into a TFLite model. + + Args: + flags: argparse.Namespace object. + + Raises: + ValueError: Invalid flags. + """ + # Register custom opdefs before converter object creation. + if flags.custom_opdefs: + register_custom_opdefs(_parse_array(flags.custom_opdefs)) + + # Create converter. + converter = _get_tflite_converter(flags) + if flags.inference_type: + converter.inference_type = _parse_inference_type(flags.inference_type, + "inference_type") + if flags.inference_input_type: + converter.inference_input_type = _parse_inference_type( + flags.inference_input_type, "inference_input_type") + if flags.output_format: + converter.output_format = _toco_flags_pb2.FileFormat.Value( + flags.output_format) + + if flags.mean_values and flags.std_dev_values: + input_arrays = converter.get_input_arrays() + std_dev_values = _parse_array(flags.std_dev_values, type_fn=float) + + # In quantized inference, mean_value has to be integer so that the real + # value 0.0 is exactly representable. + if converter.inference_type == dtypes.float32: + mean_values = _parse_array(flags.mean_values, type_fn=float) + else: + mean_values = _parse_array(flags.mean_values, type_fn=int) + quant_stats = list(zip(mean_values, std_dev_values)) + if ((not flags.input_arrays and len(input_arrays) > 1) or + (len(input_arrays) != len(quant_stats))): + raise ValueError("Mismatching --input_arrays, --std_dev_values, and " + "--mean_values. The flags must have the same number of " + "items. The current input arrays are '{0}'. " + "--input_arrays must be present when specifying " + "--std_dev_values and --mean_values with multiple input " + "tensors in order to map between names and " + "values.".format(",".join(input_arrays))) + converter.quantized_input_stats = dict(list(zip(input_arrays, quant_stats))) + if (flags.default_ranges_min is not None) and (flags.default_ranges_max is + not None): + converter.default_ranges_stats = (flags.default_ranges_min, + flags.default_ranges_max) + + if flags.drop_control_dependency: + converter.drop_control_dependency = flags.drop_control_dependency + if flags.reorder_across_fake_quant: + converter.reorder_across_fake_quant = flags.reorder_across_fake_quant + if flags.change_concat_input_ranges: + converter.change_concat_input_ranges = ( + flags.change_concat_input_ranges == "TRUE") + + if flags.allow_custom_ops: + converter.allow_custom_ops = flags.allow_custom_ops + + if flags.target_ops: + ops_set_options = lite.OpsSet.get_options() + converter.target_spec.supported_ops = set() + for option in flags.target_ops.split(","): + if option not in ops_set_options: + raise ValueError("Invalid value for --target_ops. Options: " + "{0}".format(",".join(ops_set_options))) + converter.target_spec.supported_ops.add(lite.OpsSet(option)) + + if flags.experimental_select_user_tf_ops: + if lite.OpsSet.SELECT_TF_OPS not in converter.target_spec.supported_ops: + raise ValueError("--experimental_select_user_tf_ops can only be set if " + "--target_ops contains SELECT_TF_OPS.") + user_op_set = set() + for op_name in flags.experimental_select_user_tf_ops.split(","): + user_op_set.add(op_name) + converter.target_spec.experimental_select_user_tf_ops = list(user_op_set) + + if flags.post_training_quantize: + converter.optimizations = [lite.Optimize.DEFAULT] + if converter.inference_type != dtypes.float32: + print("--post_training_quantize quantizes a graph of inference_type " + "FLOAT. Overriding inference_type to FLOAT.") + converter.inference_type = dtypes.float32 + + if flags.quantize_to_float16: + converter.target_spec.supported_types = [dtypes.float16] + if not flags.post_training_quantize: + print("--quantize_to_float16 will only take effect with the " + "--post_training_quantize flag enabled.") + + if flags.dump_graphviz_dir: + converter.dump_graphviz_dir = flags.dump_graphviz_dir + if flags.dump_graphviz_video: + converter.dump_graphviz_vode = flags.dump_graphviz_video + if flags.conversion_summary_dir: + converter.conversion_summary_dir = flags.conversion_summary_dir + + converter.experimental_new_converter = flags.experimental_new_converter + + if flags.experimental_new_quantizer is not None: + converter.experimental_new_quantizer = flags.experimental_new_quantizer + + # Convert model. + output_data = converter.convert() + with gfile.GFile(flags.output_file, "wb") as f: + f.write(output_data) + + +def _convert_tf2_model(flags): + """Calls function to convert the TensorFlow 2.0 model into a TFLite model. + + Args: + flags: argparse.Namespace object. + + Raises: + ValueError: Unsupported file format. + """ + # Load the model. + if flags.saved_model_dir: + converter = lite.TFLiteConverterV2.from_saved_model( + flags.saved_model_dir, + signature_keys=_parse_array(flags.saved_model_signature_key), + tags=_parse_set(flags.saved_model_tag_set)) + elif flags.keras_model_file: + model = keras_deps.get_load_model_function()(flags.keras_model_file) + converter = lite.TFLiteConverterV2.from_keras_model(model) + + converter.experimental_new_converter = flags.experimental_new_converter + + if flags.experimental_new_quantizer is not None: + converter.experimental_new_quantizer = flags.experimental_new_quantizer + + # Convert the model. + tflite_model = converter.convert() + with gfile.GFile(flags.output_file, "wb") as f: + f.write(tflite_model) + + +def _check_tf1_flags(flags, unparsed): + """Checks the parsed and unparsed flags to ensure they are valid in 1.X. + + Raises an error if previously support unparsed flags are found. Raises an + error for parsed flags that don't meet the required conditions. + + Args: + flags: argparse.Namespace object containing TFLite flags. + unparsed: List of unparsed flags. + + Raises: + ValueError: Invalid flags. + """ + + # Check unparsed flags for common mistakes based on previous TOCO. + def _get_message_unparsed(flag, orig_flag, new_flag): + if flag.startswith(orig_flag): + return "\n Use {0} instead of {1}".format(new_flag, orig_flag) + return "" + + if unparsed: + output = "" + for flag in unparsed: + output += _get_message_unparsed(flag, "--input_file", "--graph_def_file") + output += _get_message_unparsed(flag, "--savedmodel_directory", + "--saved_model_dir") + output += _get_message_unparsed(flag, "--std_value", "--std_dev_values") + output += _get_message_unparsed(flag, "--batch_size", "--input_shapes") + output += _get_message_unparsed(flag, "--dump_graphviz", + "--dump_graphviz_dir") + if output: + raise ValueError(output) + + # Check that flags are valid. + if flags.graph_def_file and (not flags.input_arrays or + not flags.output_arrays): + raise ValueError("--input_arrays and --output_arrays are required with " + "--graph_def_file") + + if flags.input_shapes: + if not flags.input_arrays: + raise ValueError("--input_shapes must be used with --input_arrays") + if flags.input_shapes.count(":") != flags.input_arrays.count(","): + raise ValueError("--input_shapes and --input_arrays must have the same " + "number of items") + + if flags.std_dev_values or flags.mean_values: + if bool(flags.std_dev_values) != bool(flags.mean_values): + raise ValueError("--std_dev_values and --mean_values must be used " + "together") + if flags.std_dev_values.count(",") != flags.mean_values.count(","): + raise ValueError("--std_dev_values, --mean_values must have the same " + "number of items") + + if (flags.default_ranges_min is None) != (flags.default_ranges_max is None): + raise ValueError("--default_ranges_min and --default_ranges_max must be " + "used together") + + if flags.dump_graphviz_video and not flags.dump_graphviz_dir: + raise ValueError("--dump_graphviz_video must be used with " + "--dump_graphviz_dir") + + if flags.custom_opdefs and not flags.experimental_new_converter: + raise ValueError("--custom_opdefs must be used with " + "--experimental_new_converter") + if flags.custom_opdefs and not flags.allow_custom_ops: + raise ValueError("--custom_opdefs must be used with --allow_custom_ops") + if (flags.experimental_select_user_tf_ops and + not flags.experimental_new_converter): + raise ValueError("--experimental_select_user_tf_ops must be used with " + "--experimental_new_converter") + + +def _check_tf2_flags(flags): + """Checks the parsed and unparsed flags to ensure they are valid in 2.X. + + Args: + flags: argparse.Namespace object containing TFLite flags. + + Raises: + ValueError: Invalid flags. + """ + if not flags.keras_model_file and not flags.saved_model_dir: + raise ValueError("one of the arguments --saved_model_dir " + "--keras_model_file is required") + + +def _get_tf1_flags(parser): + """Returns ArgumentParser for tflite_convert for TensorFlow 1.X. + + Args: + parser: ArgumentParser + """ + # Input file flags. + input_file_group = parser.add_mutually_exclusive_group(required=True) + input_file_group.add_argument( + "--graph_def_file", + type=str, + help="Full filepath of file containing frozen TensorFlow GraphDef.") + input_file_group.add_argument( + "--saved_model_dir", + type=str, + help="Full filepath of directory containing the SavedModel.") + input_file_group.add_argument( + "--keras_model_file", + type=str, + help="Full filepath of HDF5 file containing tf.Keras model.") + + # Model format flags. + parser.add_argument( + "--output_format", + type=str.upper, + choices=["TFLITE", "GRAPHVIZ_DOT"], + help="Output file format.") + parser.add_argument( + "--inference_type", + type=str.upper, + default="FLOAT", + help=("Target data type of real-number arrays in the output file. " + "Must be either FLOAT, INT8 or UINT8.")) + parser.add_argument( + "--inference_input_type", + type=str.upper, + help=("Target data type of real-number input arrays. Allows for a " + "different type for input arrays in the case of quantization. " + "Must be either FLOAT, INT8 or UINT8.")) + + # Input and output arrays flags. + parser.add_argument( + "--input_arrays", + type=str, + help="Names of the input arrays, comma-separated.") + parser.add_argument( + "--input_shapes", + type=str, + help="Shapes corresponding to --input_arrays, colon-separated.") + parser.add_argument( + "--output_arrays", + type=str, + help="Names of the output arrays, comma-separated.") + + # SavedModel related flags. + parser.add_argument( + "--saved_model_tag_set", + type=str, + help=("Comma-separated set of tags identifying the MetaGraphDef within " + "the SavedModel to analyze. All tags must be present. In order to " + "pass in an empty tag set, pass in \"\". (default \"serve\")")) + parser.add_argument( + "--saved_model_signature_key", + type=str, + help=("Key identifying the SignatureDef containing inputs and outputs. " + "(default DEFAULT_SERVING_SIGNATURE_DEF_KEY)")) + + # Quantization flags. + parser.add_argument( + "--std_dev_values", + type=str, + help=("Standard deviation of training data for each input tensor, " + "comma-separated floats. Used for quantized input tensors. " + "(default None)")) + parser.add_argument( + "--mean_values", + type=str, + help=("Mean of training data for each input tensor, comma-separated " + "floats. Used for quantized input tensors. (default None)")) + parser.add_argument( + "--default_ranges_min", + type=float, + help=("Default value for min bound of min/max range values used for all " + "arrays without a specified range, Intended for experimenting with " + "quantization via \"dummy quantization\". (default None)")) + parser.add_argument( + "--default_ranges_max", + type=float, + help=("Default value for max bound of min/max range values used for all " + "arrays without a specified range, Intended for experimenting with " + "quantization via \"dummy quantization\". (default None)")) + # quantize_weights is DEPRECATED. + parser.add_argument( + "--quantize_weights", + dest="post_training_quantize", + action="store_true", + help=argparse.SUPPRESS) + parser.add_argument( + "--post_training_quantize", + dest="post_training_quantize", + action="store_true", + help=( + "Boolean indicating whether to quantize the weights of the " + "converted float model. Model size will be reduced and there will " + "be latency improvements (at the cost of accuracy). (default False)")) + parser.add_argument( + "--quantize_to_float16", + dest="quantize_to_float16", + action="store_true", + help=("Boolean indicating whether to quantize weights to fp16 instead of " + "the default int8 when post-training quantization " + "(--post_training_quantize) is enabled. (default False)")) + # Graph manipulation flags. + parser.add_argument( + "--drop_control_dependency", + action="store_true", + help=("Boolean indicating whether to drop control dependencies silently. " + "This is due to TensorFlow not supporting control dependencies. " + "(default True)")) + parser.add_argument( + "--reorder_across_fake_quant", + action="store_true", + help=("Boolean indicating whether to reorder FakeQuant nodes in " + "unexpected locations. Used when the location of the FakeQuant " + "nodes is preventing graph transformations necessary to convert " + "the graph. Results in a graph that differs from the quantized " + "training graph, potentially causing differing arithmetic " + "behavior. (default False)")) + # Usage for this flag is --change_concat_input_ranges=true or + # --change_concat_input_ranges=false in order to make it clear what the flag + # is set to. This keeps the usage consistent with other usages of the flag + # where the default is different. The default value here is False. + parser.add_argument( + "--change_concat_input_ranges", + type=str.upper, + choices=["TRUE", "FALSE"], + help=("Boolean to change behavior of min/max ranges for inputs and " + "outputs of the concat operator for quantized models. Changes the " + "ranges of concat operator overlap when true. (default False)")) + + # Permitted ops flags. + parser.add_argument( + "--allow_custom_ops", + action=_ParseBooleanFlag, + nargs="?", + help=("Boolean indicating whether to allow custom operations. When false " + "any unknown operation is an error. When true, custom ops are " + "created for any op that is unknown. The developer will need to " + "provide these to the TensorFlow Lite runtime with a custom " + "resolver. (default False)")) + parser.add_argument( + "--custom_opdefs", + type=str, + help=("String representing a list of custom ops OpDefs delineated with " + "commas that are included in the GraphDef. Required when using " + "custom operations with --experimental_new_converter.")) + parser.add_argument( + "--target_ops", + type=str, + help=("Experimental flag, subject to change. Set of OpsSet options " + "indicating which converter to use. Options: {0}. One or more " + "option may be specified. (default set([OpsSet.TFLITE_BUILTINS]))" + "".format(",".join(lite.OpsSet.get_options())))) + parser.add_argument( + "--experimental_select_user_tf_ops", + type=str, + help=("Experimental flag, subject to change. Comma separated list of " + "user's defined TensorFlow operators required in the runtime.")) + + # Logging flags. + parser.add_argument( + "--dump_graphviz_dir", + type=str, + help=("Full filepath of folder to dump the graphs at various stages of " + "processing GraphViz .dot files. Preferred over --output_format=" + "GRAPHVIZ_DOT in order to keep the requirements of the output " + "file.")) + parser.add_argument( + "--dump_graphviz_video", + action="store_true", + help=("Boolean indicating whether to dump the graph after every graph " + "transformation")) + parser.add_argument( + "--conversion_summary_dir", + type=str, + help=("Full filepath to store the conversion logs, which includes " + "graphviz of the model before/after the conversion, an HTML report " + "and the conversion proto buffers. This will only be generated " + "when passing --experimental_new_converter")) + + +def _get_tf2_flags(parser): + """Returns ArgumentParser for tflite_convert for TensorFlow 2.0. + + Args: + parser: ArgumentParser + """ + # Input file flags. + input_file_group = parser.add_mutually_exclusive_group() + input_file_group.add_argument( + "--saved_model_dir", + type=str, + help="Full path of the directory containing the SavedModel.") + input_file_group.add_argument( + "--keras_model_file", + type=str, + help="Full filepath of HDF5 file containing tf.Keras model.") + # SavedModel related flags. + parser.add_argument( + "--saved_model_tag_set", + type=str, + help=("Comma-separated set of tags identifying the MetaGraphDef within " + "the SavedModel to analyze. All tags must be present. In order to " + "pass in an empty tag set, pass in \"\". (default \"serve\")")) + parser.add_argument( + "--saved_model_signature_key", + type=str, + help=("Key identifying the SignatureDef containing inputs and outputs. " + "(default DEFAULT_SERVING_SIGNATURE_DEF_KEY)")) + + # Enables 1.X converter in 2.X. + parser.add_argument( + "--enable_v1_converter", + action="store_true", + help=("Enables the TensorFlow V1 converter in 2.0")) + + +def _get_parser(use_v2_converter): + """Returns an ArgumentParser for tflite_convert. + + Args: + use_v2_converter: Indicates which converter to return. + Return: ArgumentParser. + """ + parser = argparse.ArgumentParser( + description=("Command line tool to run TensorFlow Lite Converter.")) + + # Output file flag. + parser.add_argument( + "--output_file", + type=str, + help="Full filepath of the output file.", + required=True) + + if use_v2_converter: + _get_tf2_flags(parser) + else: + _get_tf1_flags(parser) + + parser.add_argument( + "--experimental_new_converter", + action=_ParseBooleanFlag, + nargs="?", + default=True, + help=("Experimental flag, subject to change. Enables MLIR-based " + "conversion instead of TOCO conversion. (default True)")) + + parser.add_argument( + "--experimental_new_quantizer", + action=_ParseBooleanFlag, + nargs="?", + help=("Experimental flag, subject to change. Enables MLIR-based " + "quantizer instead of flatbuffer conversion. (default True)")) + return parser + + +def run_main(_): + """Main in tflite_convert.py.""" + use_v2_converter = tf2.enabled() + parser = _get_parser(use_v2_converter) + tflite_flags, unparsed = parser.parse_known_args(args=sys.argv[1:]) + + # If the user is running TensorFlow 2.X but has passed in enable_v1_converter + # then parse the flags again with the 1.X converter flags. + if tf2.enabled() and tflite_flags.enable_v1_converter: + use_v2_converter = False + parser = _get_parser(use_v2_converter) + tflite_flags, unparsed = parser.parse_known_args(args=sys.argv[1:]) + + # Checks if the flags are valid. + try: + if use_v2_converter: + _check_tf2_flags(tflite_flags) + else: + _check_tf1_flags(tflite_flags, unparsed) + except ValueError as e: + parser.print_usage() + file_name = os.path.basename(sys.argv[0]) + sys.stderr.write("{0}: error: {1}\n".format(file_name, str(e))) + sys.exit(1) + + # Convert the model according to the user provided flag. + if use_v2_converter: + _convert_tf2_model(tflite_flags) + else: + try: + _convert_tf1_model(tflite_flags) + finally: + if tflite_flags.conversion_summary_dir: + if tflite_flags.experimental_new_converter: + gen_html.gen_conversion_log_html(tflite_flags.conversion_summary_dir, + tflite_flags.post_training_quantize, + tflite_flags.output_file) + else: + warnings.warn( + "Conversion summary will only be generated when enabling" + " the new converter via --experimental_new_converter. ") + + +def main(): + app.run(main=run_main, argv=sys.argv[:1]) + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_keras_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_keras_util.py new file mode 100644 index 0000000000000000000000000000000000000000..80434edd09c520d0e12863aa10f6f9f4766372bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/tflite_keras_util.py @@ -0,0 +1,194 @@ +# 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. +# ============================================================================== + +"""Keras functions required by TensorFlow Lite. + +The functions defined in this library have been copied over from Keras in order +to remove the dependency from TensorFlow Lite to Keras. The functions which +could not be copied over are accessed using the dependency inversion principle. +(for details, refer to tensorflow/python/util/keras_deps.py). +""" + +import copy + +from tensorflow.python.eager import def_function +from tensorflow.python.util import keras_deps +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc + + +def _enforce_names_consistency(specs): + """Enforces that either all specs have names or none do.""" + + def _has_name(spec): + return hasattr(spec, 'name') and spec.name is not None + + def _clear_name(spec): + spec = copy.deepcopy(spec) + if hasattr(spec, 'name'): + spec._name = None # pylint:disable=protected-access + return spec + + flat_specs = nest.flatten(specs) + name_inconsistency = ( + any(_has_name(s) for s in flat_specs) and + not all(_has_name(s) for s in flat_specs)) + + if name_inconsistency: + specs = nest.map_structure(_clear_name, specs) + return specs + + +def model_input_signature(model, keep_original_batch_size=False): + """Inspect model to get its input signature. + + The model's input signature is a list with a single (possibly-nested) object. + This is due to the Keras-enforced restriction that tensor inputs must be + passed in as the first argument. + + For example, a model with input {'feature1': , 'feature2': } + will have input signature: [{'feature1': TensorSpec, 'feature2': TensorSpec}] + + Args: + model: Keras Model object. + keep_original_batch_size: A boolean indicating whether we want to keep using + the original batch size or set it to None. Default is `False`, which means + that the batch dim of the returned input signature will always be set to + `None`. + + Returns: + A list containing either a single TensorSpec or an object with nested + TensorSpecs. This list does not contain the `training` argument. + """ + if hasattr(model, 'save_spec'): + input_specs = model.save_spec(dynamic_batch=not keep_original_batch_size) + if input_specs is None: + return None + # The model's save spec returns (args, kwargs). Extract the first input arg + # to use as the input spec. + # TODO(b/188105669): Add support for multiple tensor arguments. + input_specs = input_specs[0][0] + else: + input_specs = model._get_save_spec( # pylint: disable=protected-access + dynamic_batch=not keep_original_batch_size) + if input_specs is None: + return None + input_specs = _enforce_names_consistency(input_specs) + # Return a list with a single element as the model's input signature. + if isinstance(input_specs, + collections_abc.Sequence) and len(input_specs) == 1: + # Note that the isinstance check filters out single-element dictionaries, + # which should also be wrapped as a single-element list. + return input_specs + else: + return [input_specs] + + +def raise_model_input_error(model): + raise ValueError( + 'Model {} cannot be saved because the input shapes have not been ' + 'set. Usually, input shapes are automatically determined from calling' + ' `.fit()` or `.predict()`. To manually set the shapes, call ' + '`model.build(input_shape)`.'.format(model)) + + +def _create_pseudo_names(tensors, prefix): + """Creates pseudo {input | output} names for subclassed Models. + + Warning: this function should only be used to define default + names for `Metics` and `SavedModel`. No other use cases should + rely on a `Model`'s input or output names. + + Example with dict: + + `{'a': [x1, x2], 'b': x3}` becomes: + `['a_1', 'a_2', 'b']` + + Example with list: + + `[x, y]` becomes: + `['output_1', 'output_2']` + + Args: + tensors: `Model`'s outputs or inputs. + prefix: 'output_' for outputs, 'input_' for inputs. + + Returns: + Flattened list of pseudo names. + """ + + def one_index(ele): + # Start with "output_1" instead of "output_0". + if isinstance(ele, int): + return ele + 1 + return ele + + flat_paths = list(nest.yield_flat_paths(tensors)) + flat_paths = nest.map_structure(one_index, flat_paths) + names = [] + for path in flat_paths: + if not path: + name = prefix + '1' # Single output. + else: + name = '_'.join(str(p) for p in path) + if isinstance(path[0], int): + name = prefix + name + names.append(name) + return names + + +def create_pseudo_output_names(outputs): + """Create pseudo output names for a subclassed Model.""" + return _create_pseudo_names(outputs, prefix='output_') + + +def trace_model_call(model, input_signature=None): + """Trace the model call to create a tf.function for exporting a Keras model. + + Args: + model: A Keras model. + input_signature: optional, a list of tf.TensorSpec objects specifying the + inputs to the model. + + Returns: + A tf.function wrapping the model's call function with input signatures set. + + Raises: + ValueError: if input signature cannot be inferred from the model. + """ + if input_signature is None: + if isinstance(model.call, def_function.Function): + input_signature = model.call.input_signature + + if input_signature is None: + input_signature = model_input_signature(model) + + if input_signature is None: + raise_model_input_error(model) + + @def_function.function(input_signature=input_signature, autograph=False) + def _wrapped_model(*args): + """A concrete tf.function that wraps the model's call function.""" + # When given a single input, Keras models will call the model on the tensor + # rather than a list consisting of the single tensor. + inputs = args[0] if len(input_signature) == 1 else list(args) + + with keras_deps.get_call_context_function()().enter( + model, inputs=inputs, build_graph=False, training=False, saving=True): + outputs = model(inputs, training=False) + + return outputs + + return _wrapped_model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/util.py new file mode 100644 index 0000000000000000000000000000000000000000..55b88cfc3dc443fdc6afff57cfbc54241bcae218 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/util.py @@ -0,0 +1,1070 @@ +# 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. +# ============================================================================== +"""Functions used by multiple converter files.""" + +import copy +import datetime +import sys + +from absl import logging +import flatbuffers + +from tensorflow.core.protobuf import config_pb2 as _config_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 as _meta_graph_pb2 +from tensorflow.lite.python import conversion_metadata_schema_py_generated as conversion_metadata_fb +from tensorflow.lite.python import schema_py_generated as schema_fb +from tensorflow.lite.python import schema_util +from tensorflow.lite.python import tflite_keras_util as _tflite_keras_util +from tensorflow.lite.python.op_hint import convert_op_hints_to_stubs +from tensorflow.lite.python.op_hint import find_all_hinted_output_nodes +from tensorflow.lite.tools import flatbuffer_utils +from tensorflow.python.eager import function +from tensorflow.python.framework import convert_to_constants as _convert_to_constants +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import error_interpolation as _error_interpolation +from tensorflow.python.grappler import tf_optimizer +from tensorflow.python.training.saver import export_meta_graph as _export_meta_graph + +# The field name of conversion metadata in the flatbuffer file. +CONVERSION_METADATA_FIELD_NAME = "CONVERSION_METADATA" + +# Keras functions used by TFLite +model_input_signature = _tflite_keras_util.model_input_signature +trace_model_call = _tflite_keras_util.trace_model_call + +# Jax functions used by TFLite +# pylint: disable=g-import-not-at-top +# pylint: disable=unused-import +try: + from jax import xla_computation as _xla_computation +except ImportError: + _xla_computation = None +# pylint: enable=g-import-not-at-top +# pylint: enable=unused-import + +# Defined as per TFLite schema +_MAP_TFLITE_ENUM_TO_TF_TYPES = { + 0: dtypes.float32, + 1: dtypes.float16, + 2: dtypes.int32, + 3: dtypes.uint8, + 4: dtypes.int64, + 5: dtypes.string, + 6: dtypes.bool, + 7: dtypes.int16, + 8: dtypes.complex64, + 9: dtypes.int8, + 10: dtypes.float64, + 11: dtypes.complex128, + 16: dtypes.uint32, +} + +_TFLITE_FILE_IDENTIFIER = b"TFL3" + +_MAP_QUANT_TO_IO_TYPES = { + dtypes.int8: {dtypes.int8, dtypes.uint8}, + dtypes.int16: {dtypes.int16}, +} + + +def _convert_tflite_enum_type_to_tf_type(tflite_enum_type): + """Converts tflite enum type (eg: 0) to tf type (eg: tf.float32). + + Args: + tflite_enum_type: tflite enum type (eg: 0, that corresponds to float32) + + Raises: + ValueError: If an invalid tflite enum type is provided. + + Returns: + tf type (eg: tf.float32) + """ + tf_type = _MAP_TFLITE_ENUM_TO_TF_TYPES.get(tflite_enum_type) + if tf_type is None: + raise ValueError( + "Unsupported enum {}. The valid map of enum to tf types is : {}" + .format(tflite_enum_type, _MAP_TFLITE_ENUM_TO_TF_TYPES)) + return tf_type + + +def get_tf_type_name(tf_type): + """Converts tf.dtype (eg: tf.float32) to str (eg: "tf.float32").""" + return "tf." + tf_type.name if tf_type else None + + +def get_tensor_name(tensor): + """Returns name of the input tensor. + + Args: + tensor: tf.Tensor + + Returns: + str + """ + parts = tensor.name.split(":") + if len(parts) > 2: + raise ValueError("Tensor name invalid. Expect 0 or 1 colon, got {0}".format( + len(parts) - 1)) + + # To be consistent with the tensor naming scheme in tensorflow, we need + # drop the ':0' suffix for the first tensor. + if len(parts) > 1 and parts[1] != "0": + return tensor.name + return parts[0] + + +def get_tensors_from_tensor_names(graph, tensor_names): + """Gets the Tensors associated with the `tensor_names` in the provided graph. + + Args: + graph: TensorFlow Graph. + tensor_names: List of strings that represent names of tensors in the graph. + + Returns: + A list of Tensor objects in the same order the names are provided. + + Raises: + ValueError: + tensor_names contains an invalid tensor name. + """ + # Get the list of all of the tensors. + tensor_name_to_tensor = {} + for op in graph.get_operations(): + for tensor in op.values(): + tensor_name_to_tensor[get_tensor_name(tensor)] = tensor + + # Get the tensors associated with tensor_names. + tensors = [] + invalid_tensors = [] + for name in tensor_names: + if not isinstance(name, str): + raise ValueError("Invalid type for a tensor name in the provided graph. " + "Expected type for a tensor name is 'str', instead got " + "type '{}' for tensor name '{}'".format( + type(name), name)) + + tensor = tensor_name_to_tensor.get(name) + if tensor is None: + invalid_tensors.append(name) + else: + tensors.append(tensor) + + # Throw ValueError if any user input names are not valid tensors. + if invalid_tensors: + raise ValueError("Invalid tensors '{}' were found.".format( + ",".join(invalid_tensors))) + return tensors + + +def set_tensor_shapes(tensors, shapes): + """Sets Tensor shape for each tensor if the shape is defined. + + Args: + tensors: TensorFlow tensor.Tensor. + shapes: Dict of strings representing input tensor names to list of + integers representing input shapes (e.g., {"foo": : [1, 16, 16, 3]}). + + Raises: + ValueError: + `shapes` contains an invalid tensor. + `shapes` contains an invalid shape for a valid tensor. + """ + if shapes: + tensor_names_to_tensor = { + get_tensor_name(tensor): tensor for tensor in tensors + } + for name, shape in shapes.items(): + if name not in tensor_names_to_tensor: + raise ValueError("Invalid tensor \'{}\' found in tensor shapes " + "map.".format(name)) + if shape is not None: + tensor = tensor_names_to_tensor[name] + try: + tensor.set_shape(shape) + except ValueError as error: + message = ("The shape of tensor '{0}' cannot be changed from {1} to " + "{2}. {3}".format(name, tensor.shape, shape, str(error))) + raise ValueError(message) + + +def get_grappler_config(optimizers_list): + """Creates a tf.compat.v1.ConfigProto for configuring Grappler. + + Args: + optimizers_list: List of strings that represents the list of optimizers. + + Returns: + tf.ConfigProto. + """ + config = _config_pb2.ConfigProto() + rewrite_options = config.graph_options.rewrite_options + for optimizer in optimizers_list: + rewrite_options.optimizers.append(optimizer) + return config + + +def run_graph_optimizations(graph_def, + input_arrays, + output_arrays, + config, + graph=None): + """Apply standard TensorFlow optimizations to the graph_def. + + Args: + graph_def: Frozen GraphDef to be optimized. + input_arrays: List of arrays that are considered inputs of the graph. + output_arrays: List of arrays that are considered outputs of the graph. + config: tf.ConfigProto. + graph: TensorFlow Graph. Required when Eager mode is enabled. (default None) + + Returns: + A new, optimized GraphDef. + """ + meta_graph = _export_meta_graph(graph_def=graph_def, graph=graph) + + signature = _meta_graph_pb2.SignatureDef() + for array in input_arrays: + signature.inputs[array.name].name = array.name + signature.inputs[array.name].dtype = array.dtype.as_datatype_enum + signature.inputs[array.name].tensor_shape.CopyFrom(array.shape.as_proto()) + + for array in output_arrays: + signature.outputs[array.name].name = array.name + signature.outputs[array.name].dtype = array.dtype.as_datatype_enum + signature.outputs[array.name].tensor_shape.CopyFrom(array.shape.as_proto()) + + meta_graph.signature_def["not_used_key"].CopyFrom(signature) + + # We need to add a collection called 'train_op' so that grappler + # knows what the outputs are. + fetch_collection = _meta_graph_pb2.CollectionDef() + for array in input_arrays + output_arrays: + fetch_collection.node_list.value.append(array.name) + meta_graph.collection_def["train_op"].CopyFrom(fetch_collection) + + return tf_optimizer.OptimizeGraph(config, meta_graph) + + +def _convert_op_hints_if_present(sess, graph_def, output_tensors, + hinted_outputs_nodes): + if is_frozen_graph(sess): + raise ValueError("Try to convert op hints, needs unfrozen graph.") + output_arrays = [get_tensor_name(tensor) for tensor in output_tensors] + graph_def = _convert_to_constants.convert_variables_to_constants( + sess, graph_def, output_arrays + hinted_outputs_nodes) + graph_def = convert_op_hints_to_stubs(graph_def=graph_def) + return graph_def + + +def freeze_graph(sess, input_tensors, output_tensors): + """Returns a frozen GraphDef. + + Runs a Grappler pass and freezes a graph with Variables in it. Otherwise the + existing GraphDef is returned. The Grappler pass is only run on models that + are frozen in order to inline the functions in the graph. + If OpHints is present, it will try to convert the OpHint graph. + + Args: + sess: TensorFlow Session. + input_tensors: List of input tensors. + output_tensors: List of output tensors (only .name is used from this). + + Returns: + Frozen GraphDef. + """ + # Runs a Grappler pass in order to inline any functions in the graph. + # Asides from inlining any simple function, Grappler will also try to lower + # while loop into switch merge representation which is undesired for Ophints, + # so we simply remove those attributes to prevent Grappler from doing so. + graph_def = _convert_to_constants.disable_lower_using_switch_merge( + sess.graph_def) + config = get_grappler_config(["function"]) + graph_def = run_graph_optimizations( + graph_def, input_tensors, output_tensors, config, graph=sess.graph) + + # If ophints are present, just convert them. + hinted_outputs_nodes = find_all_hinted_output_nodes(sess) + if hinted_outputs_nodes: + return _convert_op_hints_if_present(sess, graph_def, output_tensors, + hinted_outputs_nodes) + + if not is_frozen_graph(sess): + output_node_names = [tensor.name.split(":")[0] for tensor in output_tensors] + return _convert_to_constants.convert_variables_to_constants( + sess, graph_def, output_node_names + ) + else: + return sess.graph_def + + +def is_frozen_graph(sess): + """Determines if the graph is frozen. + + Determines if a graph has previously been frozen by checking for any + operations of type Variable*. If variables are found, the graph is not frozen. + + Args: + sess: TensorFlow Session. + + Returns: + Bool. + """ + for op in sess.graph.get_operations(): + if op.type.startswith("Variable") or op.type.endswith("VariableOp"): + return False + return True + + +def build_debug_info_func(original_graph): + """Returns a method to retrieve the `GraphDebugInfo` from the original graph. + + Args: + original_graph: The original `Graph` containing all the op stack traces. + + Returns: + A function which retrieves the stack traces from the original graph and + converts them to a `GraphDebugInfo` for a given set of nodes. + """ + + def f(original_nodes): + """Function to create `GraphDebugInfo` for the given `original_nodes`.""" + if not original_graph: + return None + # For the given nodes, gets all the op definitions in the original graph. + useful_ops = [] + for func, name in original_nodes: + try: + if not func: + useful_ops.append((func, original_graph.get_operation_by_name(name))) + else: + sub_func = original_graph._get_function(func) # pylint: disable=protected-access + if isinstance(sub_func, function.AtomicFunction): # pylint: disable=protected-access + useful_ops.append( + (func, sub_func.graph.get_operation_by_name(name))) + else: + sys.stderr.write( + "Use '@tf.function' or '@defun' to decorate the function.\n") + continue + except KeyError: + # New node created by graph optimizer. No stack trace from source code. + continue + # Convert all the op definitions to stack traces in terms of GraphDebugInfo. + return _error_interpolation.create_graph_debug_info_def(useful_ops) + + return f + + +def convert_debug_info_func(saved_debug_info): + """Returns a method to retrieve the `GraphDebugInfo` from the original graph. + + Args: + saved_debug_info: The `GraphDebugInfo` containing all the debug info. + + Returns: + A function which retrieves the stack traces from the original graph and + converts them to a `GraphDebugInfo` for a given set of nodes. + """ + + def f(original_nodes): + """Function to create `GraphDebugInfo` for the given `original_nodes`.""" + del original_nodes + return saved_debug_info + + return f + + +def get_debug_info(nodes_to_debug_info_func, converted_graph): + """Returns the debug info for the original nodes in the `converted_graph`. + + Args: + nodes_to_debug_info_func: The method to collect the op debug info for the + nodes. + converted_graph: A `GraphDef` after optimization and transformation. + + Returns: + `GraphDebugInfo` for all the original nodes in `converted_graph`. + """ + if not nodes_to_debug_info_func: + return None + + # Collect all the debug info nodes from the converted_graph + original_nodes = set() + for node in converted_graph.node: + debug_nodes = node.experimental_debug_info.original_node_names + debug_funcs = node.experimental_debug_info.original_func_names + # If the `original_node_names` are empty, uses the node name directly. + if not debug_nodes: + original_nodes.add(("", node.name)) + else: + for i in range(len(debug_nodes)): + debug_func = "" if i >= len(debug_funcs) else debug_funcs[i] + original_nodes.add((debug_func, debug_nodes[i])) + + # Convert the nodes to the debug info proto object. + return nodes_to_debug_info_func(original_nodes) + + +def convert_bytes_to_c_source(data, + array_name, + max_line_width=80, + include_guard=None, + include_path=None, + use_tensorflow_license=False): + """Returns strings representing a C constant array containing `data`. + + Args: + data: Byte array that will be converted into a C constant. + array_name: String to use as the variable name for the constant array. + max_line_width: The longest line length, for formatting purposes. + include_guard: Name to use for the include guard macro definition. + include_path: Optional path to include in the source file. + use_tensorflow_license: Whether to include the standard TensorFlow Apache2 + license in the generated files. + + Returns: + Text that can be compiled as a C source file to link in the data as a + literal array of values. + Text that can be used as a C header file to reference the literal array. + """ + + starting_pad = " " + array_lines = [] + array_line = starting_pad + for value in bytearray(data): + if (len(array_line) + 4) > max_line_width: + array_lines.append(array_line + "\n") + array_line = starting_pad + array_line += " 0x%02x," % (value,) + if len(array_line) > len(starting_pad): + array_lines.append(array_line + "\n") + array_values = "".join(array_lines) + + if include_guard is None: + include_guard = "TENSORFLOW_LITE_UTIL_" + array_name.upper() + "_DATA_H_" + + if include_path is not None: + include_line = "#include \"{include_path}\"\n".format( + include_path=include_path) + else: + include_line = "" + + if use_tensorflow_license: + license_text = """ +/* Copyright {year} The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +""".format(year=datetime.date.today().year) + else: + license_text = "" + + source_template = """{license_text} +// This is a TensorFlow Lite model file that has been converted into a C data +// array using the tensorflow.lite.util.convert_bytes_to_c_source() function. +// This form is useful for compiling into a binary for devices that don't have a +// file system. + +{include_line} +// We need to keep the data array aligned on some architectures. +#ifdef __has_attribute +#define HAVE_ATTRIBUTE(x) __has_attribute(x) +#else +#define HAVE_ATTRIBUTE(x) 0 +#endif +#if HAVE_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__)) +#define DATA_ALIGN_ATTRIBUTE __attribute__((aligned(4))) +#else +#define DATA_ALIGN_ATTRIBUTE +#endif + +const unsigned char {array_name}[] DATA_ALIGN_ATTRIBUTE = {{ +{array_values}}}; +const int {array_name}_len = {array_length}; +""" + + source_text = source_template.format( + array_name=array_name, + array_length=len(data), + array_values=array_values, + license_text=license_text, + include_line=include_line) + + header_template = """ +{license_text} + +// This is a TensorFlow Lite model file that has been converted into a C data +// array using the tensorflow.lite.util.convert_bytes_to_c_source() function. +// This form is useful for compiling into a binary for devices that don't have a +// file system. + +#ifndef {include_guard} +#define {include_guard} + +extern const unsigned char {array_name}[]; +extern const int {array_name}_len; + +#endif // {include_guard} +""" + + header_text = header_template.format( + array_name=array_name, + include_guard=include_guard, + license_text=license_text) + + return source_text, header_text + + +def _convert_model_from_bytearray_to_object(model_bytearray): + """Converts a tflite model from a bytearray into a parsable object.""" + model_object = schema_fb.Model.GetRootAsModel(model_bytearray, 0) + model_object = schema_fb.ModelT.InitFromObj(model_object) + model_object = copy.deepcopy(model_object) + return model_object + + +def _convert_model_from_object_to_bytearray(model_object): + """Converts a tflite model from a parsable object into a bytearray.""" + # Initial size of the buffer, which will grow automatically if needed + builder = flatbuffers.Builder(1024) + model_offset = model_object.Pack(builder) + builder.Finish(model_offset, file_identifier=_TFLITE_FILE_IDENTIFIER) + return bytes(builder.Output()) + + +def get_quantize_opcode_idx(model): + """Returns the quantize op idx.""" + quant_opcode_idxs = [] + for idx, opcode in enumerate(model.operatorCodes): + builtin_code = schema_util.get_builtin_code_from_operator_code(opcode) + if builtin_code == schema_fb.BuiltinOperator.QUANTIZE: + quant_opcode_idxs.append(idx) + return quant_opcode_idxs + + +def get_dequantize_opcode_idx(model): + """Returns the quantize op idx.""" + quant_opcode_idxs = [] + for idx, opcode in enumerate(model.operatorCodes): + builtin_code = schema_util.get_builtin_code_from_operator_code(opcode) + if builtin_code == schema_fb.BuiltinOperator.DEQUANTIZE: + quant_opcode_idxs.append(idx) + return quant_opcode_idxs + + +def _update_signature_def_tensors(tensor_maps, map_old_to_new_tensors): + """Update the tensors in the SignatureDef's TensorMaps.""" + for i in range(len(tensor_maps)): + if tensor_maps[i].tensorIndex in map_old_to_new_tensors: + tensor_maps[i].tensorIndex = ( + map_old_to_new_tensors[tensor_maps[i].tensorIndex]) + + +def _remove_tensors_from_model(model, remove_tensors_idxs): + """Remove tensors from model.""" + if not remove_tensors_idxs: + return + if len(model.subgraphs) > 1: + logging.info("Skipping the removal of dangled tensors since the model has " + "multiple subgraphs and tensors can be used in the different " + "subgraph(s)") + return + subgraph = model.subgraphs[0] + tensors = subgraph.tensors + operators = subgraph.operators + + logging.debug("Removing tensors at indices : %s", remove_tensors_idxs) + # An optimized check to validate if "remove_tensors_idxs" (eg: [4,5,6]) is an + # exact subset, with ordering, of "tensors" indices (eg: [0,1,2,3,4,5,6]). + if min(remove_tensors_idxs) == len(tensors) - len(remove_tensors_idxs): + logging.debug("Removing tensors only at the end of the tensor list") + del tensors[min(remove_tensors_idxs):] + else: + logging.debug("Removing tensors requires updating the model") + # Map the old tensor indices to new tensor indices + d_old_to_new_tensors = {} + left_shift_by = 0 + for idx in range(len(tensors)): + if idx in remove_tensors_idxs: + left_shift_by += 1 + else: + d_old_to_new_tensors[idx] = idx - left_shift_by + logging.debug("Old to new tensors map: %s", d_old_to_new_tensors.__str__()) + # Update tensor indices referenced throughout the model + def update_tensors(tensor_idxs): + for i, ti in enumerate(tensor_idxs): + tensor_idxs[i] = d_old_to_new_tensors.get(ti, -1) + update_tensors(subgraph.inputs) + update_tensors(subgraph.outputs) + for op in operators: + update_tensors(op.inputs) + update_tensors(op.outputs) + if model.signatureDefs: + signature_def = model.signatureDefs[0] + _update_signature_def_tensors(signature_def.inputs, d_old_to_new_tensors) + _update_signature_def_tensors(signature_def.outputs, d_old_to_new_tensors) + # Delete the tensors + for idx in sorted(remove_tensors_idxs, reverse=True): + tensors.pop(idx) + logging.debug("Removed tensors marked for deletion") + + +def _modify_model_input_type(model, inference_input_type=dtypes.float32): + """Modify model input type.""" + if inference_input_type == dtypes.float32: + return + + if not model.signatureDefs: + _modify_model_input_type_per_subgraph(model, 0, -1, inference_input_type) + return + + for signature_index, signature_def in enumerate(model.signatureDefs): + _modify_model_input_type_per_subgraph(model, signature_def.subgraphIndex, + signature_index, inference_input_type) + + +def _modify_model_input_type_per_subgraph(model, subgraph_index, + signature_index, + inference_input_type): + """Modify model input type per subgraph.""" + subgraph = model.subgraphs[subgraph_index] + tensors = subgraph.tensors + operators = subgraph.operators + + # Find all quantize operators + quant_opcode_idxs = get_quantize_opcode_idx(model) + if operators and not quant_opcode_idxs: + for input_idx in subgraph.inputs: + input_type = _convert_tflite_enum_type_to_tf_type(tensors[input_idx].type) + if input_type == dtypes.float32: + raise ValueError("Model input is not dequantized.") + # None of the inputs have float32, then they must be int16, int8, or bool + return + + # Validate that the model input is quantized + input_quant_ops = [] + for op in operators: + # Find operators that quantize model input + if op.opcodeIndex in quant_opcode_idxs and op.inputs[0] in subgraph.inputs: + float_tensor, quant_tensor = tensors[op.inputs[0]], tensors[op.outputs[0]] + # If found, validate that the operator's input type is float + float_type = _convert_tflite_enum_type_to_tf_type(float_tensor.type) + if float_type != dtypes.float32: + if float_type == inference_input_type: + continue + else: + raise ValueError( + "Initial model input type must be tf.float32. Expected type for " + "tensor with name '{}' is tf.float32, instead type is {}".format( + float_tensor.name, get_tf_type_name(float_type))) + # If found, validate that the operator output is quantized and compatible + # with the final model input type + quant_type = _convert_tflite_enum_type_to_tf_type(quant_tensor.type) + if quant_type not in _MAP_QUANT_TO_IO_TYPES: + raise ValueError( + "Initial model input is not quantized. Expected type for " + "tensor with name '{}' should be in {}, instead type is {}".format( + quant_tensor.name, + tuple(get_tf_type_name(t) for t in + _MAP_QUANT_TO_IO_TYPES.keys()), + get_tf_type_name(quant_type))) + else: + inference_io_types = _MAP_QUANT_TO_IO_TYPES[quant_type] + if inference_input_type not in inference_io_types: + raise ValueError( + "Unsupported `inference_input_type` value. Expected to be in " + "{}, instead got {}.".format( + tuple(get_tf_type_name(t) for t in inference_io_types), + get_tf_type_name(inference_input_type))) + input_quant_ops.append(op) + + if len(subgraph.inputs) != len(input_quant_ops): + logging.warning( + "For model inputs containing unsupported operations which cannot be " + "quantized, the `inference_input_type` attribute will default to the " + "original type." + ) + + # Modify model input type + if inference_input_type == dtypes.uint8: + # Change quant op (float to int8) to quant op (uint8 to int8) + for op in input_quant_ops: + int8_quantization = tensors[op.outputs[0]].quantization + uint8_quantization = schema_fb.QuantizationParametersT() + uint8_quantization.scale = [int8_quantization.scale[0]] + uint8_quantization.zeroPoint = [int8_quantization.zeroPoint[0] + 128] + tensors[op.inputs[0]].quantization = uint8_quantization + tensors[op.inputs[0]].type = schema_fb.TensorType.UINT8 + elif inference_input_type in _MAP_QUANT_TO_IO_TYPES: + # Remove the inputs and the quant operator + remove_tensors_idxs = set() + for op in input_quant_ops: + subgraph.inputs[subgraph.inputs == op.inputs[0]] = op.outputs[0] + if signature_index >= 0: + signature_def = model.signatureDefs[signature_index] + for i in range(len(signature_def.inputs)): + if signature_def.inputs[i].tensorIndex == op.inputs[0]: + signature_def.inputs[i].tensorIndex = op.outputs[0] + remove_tensors_idxs.add(op.inputs[0]) + operators.remove(op) + # Remove tensors marked for deletion. + _remove_tensors_from_model(model, remove_tensors_idxs) + else: + raise ValueError( + "Unsupported `inference_input_type` value {}.".format( + get_tf_type_name(inference_input_type))) + + +def _modify_model_output_type(model, inference_output_type=dtypes.float32): + """Modify model output type.""" + if inference_output_type == dtypes.float32: + return + + if not model.signatureDefs: + _modify_model_output_type_per_subgraph(model, 0, -1, inference_output_type) + return + + for signature_index, signature_def in enumerate(model.signatureDefs): + _modify_model_output_type_per_subgraph(model, signature_def.subgraphIndex, + signature_index, + inference_output_type) + + +def _modify_model_output_type_per_subgraph(model, subgraph_index, + signature_index, + inference_output_type): + """Modify model output type per subgraph.""" + subgraph = model.subgraphs[subgraph_index] + tensors = subgraph.tensors + operators = subgraph.operators + + # Find all dequantize operators + dequant_opcode_idxs = get_dequantize_opcode_idx(model) + if operators and not dequant_opcode_idxs: + for output in subgraph.outputs: + output_type = _convert_tflite_enum_type_to_tf_type(tensors[output].type) + if output_type == dtypes.float32: + raise ValueError("Model output is not dequantized.") + # None of the outputs have float32, then they must be int16, int8, or bool + return + + # Validate that the model output is dequantized + output_dequant_ops = [] + for op in operators: + # Find operators that dequantize model output + if (op.opcodeIndex in dequant_opcode_idxs and + op.outputs[0] in subgraph.outputs): + # If found, validate that the operator's output type is float + quant_tensor, float_tensor = tensors[op.inputs[0]], tensors[op.outputs[0]] + float_type = _convert_tflite_enum_type_to_tf_type(float_tensor.type) + if float_type != dtypes.float32: + if float_type == inference_output_type: + continue + else: + raise ValueError( + "Initial model output type must be tf.float32. Expected type for " + "tensor with name '{}' is tf.float32, instead type is {}".format( + float_tensor.name, get_tf_type_name(float_type))) + # If found, validate that the operator input is quantized and compatible + # with the final model output type + quant_type = _convert_tflite_enum_type_to_tf_type(quant_tensor.type) + if quant_type not in _MAP_QUANT_TO_IO_TYPES: + raise ValueError( + "Initial model output is not dequantized. Expected type for " + "tensor with name '{}' should be in {}, instead type is {}".format( + quant_tensor.name, + tuple(get_tf_type_name(t) for t in + _MAP_QUANT_TO_IO_TYPES.keys()), + get_tf_type_name(quant_type))) + else: + inference_io_types = _MAP_QUANT_TO_IO_TYPES[quant_type] + if inference_output_type not in inference_io_types: + raise ValueError( + "Unsupported `inference_output_type` value. Expected to be in " + "{}, instead got {}.".format( + tuple(get_tf_type_name(t) for t in inference_io_types), + get_tf_type_name(inference_output_type))) + output_dequant_ops.append(op) + + if len(subgraph.outputs) != len(output_dequant_ops): + logging.warning( + "For model outputs containing unsupported operations which cannot be " + "quantized, the `inference_output_type` attribute will default to the " + "original type." + ) + + # Modify model output type + if inference_output_type == dtypes.uint8: + # Find a quantize operator + quant_opcode_idx = -1 + for idx, opcode in enumerate(model.operatorCodes): + builtin_code = schema_util.get_builtin_code_from_operator_code(opcode) + if builtin_code == schema_fb.BuiltinOperator.QUANTIZE: + quant_opcode_idx = idx + break + # Create a quantize operator, if none exist + if quant_opcode_idx == -1: + quant_op = schema_fb.OperatorCodeT() + quant_op.builtinCode = schema_fb.BuiltinOperator.QUANTIZE + quant_op.deprecatedBuiltinCode = schema_fb.BuiltinOperator.QUANTIZE + model.operatorCodes.append(quant_op) + quant_opcode_idx = len(model.operatorCodes) - 1 + # Change dequant op (int8 to float) to quant op (int8 to uint8) + for op in output_dequant_ops: + op.opcodeIndex = quant_opcode_idx + int8_quantization = tensors[op.inputs[0]].quantization + uint8_quantization = schema_fb.QuantizationParametersT() + uint8_quantization.scale = [int8_quantization.scale[0]] + uint8_quantization.zeroPoint = [int8_quantization.zeroPoint[0] + 128] + tensors[op.outputs[0]].quantization = uint8_quantization + tensors[op.outputs[0]].type = schema_fb.TensorType.UINT8 + elif inference_output_type in _MAP_QUANT_TO_IO_TYPES: + # Remove the outputs and the dequant operator + remove_tensors_idxs = set() + for op in output_dequant_ops: + subgraph.outputs[subgraph.outputs == op.outputs[0]] = op.inputs[0] + if signature_index >= 0: + signature_def = model.signatureDefs[signature_index] + for i in range(len(signature_def.outputs)): + if signature_def.outputs[i].tensorIndex == op.outputs[0]: + signature_def.outputs[i].tensorIndex = op.inputs[0] + remove_tensors_idxs.add(op.outputs[0]) + operators.remove(op) + # Remove tensors marked for deletion. + _remove_tensors_from_model(model, remove_tensors_idxs) + else: + raise ValueError( + "Unsupported `inference_output_type` value {}.".format( + get_tf_type_name(inference_output_type))) + + +def _remove_redundant_quantize_ops(model): + """Finds back to back quantize ops and remove the first quantize op.""" + if not model.signatureDefs: + _remove_redundant_quantize_ops_per_subgraph(model, 0, -1) + return + + for signature_index, signature_def in enumerate(model.signatureDefs): + _remove_redundant_quantize_ops_per_subgraph(model, + signature_def.subgraphIndex, + signature_index) + + +def _remove_redundant_quantize_ops_per_subgraph(model, subgraph_index, + signature_index): + """Remove redundant quantize ops per subgraph.""" + subgraph = model.subgraphs[subgraph_index] + tensors = subgraph.tensors + operators = subgraph.operators + + # Find all quantize operators. + quant_opcode_idxs = get_quantize_opcode_idx(model) + dequant_opcode_idxs = get_dequantize_opcode_idx(model) + + # Find all redundant quant tensors. + all_quant_ops = [] + redundant_quant_tensors = {} + output_dequant_tensors = {} + for op in operators: + if op.opcodeIndex in quant_opcode_idxs: + all_quant_ops.append(op) + input_tensor = tensors[op.inputs[0]] + output_tensor = tensors[op.outputs[0]] + input_type = _convert_tflite_enum_type_to_tf_type(input_tensor.type) + output_type = _convert_tflite_enum_type_to_tf_type(output_tensor.type) + # This is a requantize op, so write down its input tensor index. + if input_type != dtypes.float32 and output_type != dtypes.float32: + redundant_quant_tensors[op.inputs[0]] = op + if (op.opcodeIndex in dequant_opcode_idxs and + op.outputs[0] in subgraph.outputs): + output_dequant_tensors[op.inputs[0]] = op + + # Remove all the quant ops which produce the redundant quant tensors. + for op in all_quant_ops: + output_tensor_idx = op.outputs[0] + if output_tensor_idx in redundant_quant_tensors: + requantize_op = redundant_quant_tensors[output_tensor_idx] + if model.signatureDefs: + signature_def = model.signatureDefs[0] + for output in signature_def.outputs: + if output.tensorIndex == op.outputs[0]: + output.tensorIndex = op.inputs[0] + deleted_tensor = requantize_op.inputs[0] + # Reset the input of the requantize op to the float input + requantize_op.inputs[0] = op.inputs[0] + # Migrate other operator users to output tensor of requantize op + for op_user in operators: + if deleted_tensor in op_user.inputs and op_user != requantize_op: + for idx, input_tensor in enumerate(op_user.inputs): + if input_tensor == deleted_tensor: + op_user.inputs[idx] = requantize_op.outputs[0] + operators.remove(op) + + # Remove all the quant ops which connect to the output dequant op. + for op in all_quant_ops: + output_tensor_idx = op.outputs[0] + if output_tensor_idx in output_dequant_tensors: + dequant_op = output_dequant_tensors[output_tensor_idx] + subgraph.outputs[subgraph.outputs == dequant_op.outputs[0]] = op.inputs[0] + if signature_index >= 0: + signature_def = model.signatureDefs[signature_index] + for output in signature_def.outputs: + if output.tensorIndex == dequant_op.outputs[0]: + output.tensorIndex = op.inputs[0] + operators.remove(op) + operators.remove(dequant_op) + + +def modify_model_io_type( + model, inference_input_type=dtypes.float32, + inference_output_type=dtypes.float32): + """Modify the input/output type of a tflite model. + + Args: + model: A tflite model. + inference_input_type: tf.DType representing modified input type. + (default tf.float32. If model input is int8 quantized, it must be in + {tf.float32, tf.int8,tf.uint8}, else if model input is int16 quantized, + it must be in {tf.float32, tf.int16}, else it must be tf.float32) + inference_output_type: tf.DType representing modified output type. + (default tf.float32. If model output is int8 dequantized, it must be in + {tf.float32, tf.int8,tf.uint8}, else if model output is int16 dequantized, + it must be in {tf.float32, tf.int16}, else it must be tf.float32) + Returns: + A tflite model with modified input/output type. + + Raises: + ValueError: If `inference_input_type`/`inference_output_type` is unsupported + or a supported integer type is specified for a model whose input/output is + not quantized/dequantized. + RuntimeError: If the modification was unsuccessful. + + """ + if (inference_input_type == dtypes.float32 and + inference_output_type == dtypes.float32): + return model + + model_object = _convert_model_from_bytearray_to_object(model) + + _modify_model_input_type(model_object, inference_input_type) + + _modify_model_output_type(model_object, inference_output_type) + + _remove_redundant_quantize_ops(model_object) + + return _convert_model_from_object_to_bytearray(model_object) + + +def get_sparsity_modes(model_object): + """Get sparsity modes used in a tflite model. + + The sparsity modes are listed in conversion_metadata.fbs file. + + Args: + model_object: A tflite model in object form. + + Returns: + The list of sparsity modes used in the model. + """ + if not model_object or not model_object.metadata: + return [] + + result = set() + for subgraph in model_object.subgraphs: + for tensor in subgraph.tensors: + if not tensor.sparsity: + continue + + # Block map is the list if indexes where the block size is larger than 1. + # So empty block map means it is random sparsity. + if not tensor.sparsity.blockMap: + result.add( + conversion_metadata_fb.ModelOptimizationMode.RANDOM_SPARSITY) + else: + result.add( + conversion_metadata_fb.ModelOptimizationMode.BLOCK_SPARSITY) + + return list(result) + + +def populate_conversion_metadata(model_object, metadata): + """Add or update conversion metadata to a tflite model. + + Args: + model_object: A tflite model in object form. + metadata: The conversion metadata. + + Returns: + A tflite model object with embedded conversion metadata. + """ + try: + metadata_builder = flatbuffers.Builder(0) + metadata_builder.Finish(metadata.Pack(metadata_builder)) + buffer_field = schema_fb.BufferT() + buffer_field.data = metadata_builder.Output() + + if not model_object.metadata: + model_object.metadata = [] + else: + # Check if metadata has already been populated. + for meta in model_object.metadata: + if meta.name.decode("utf-8") == CONVERSION_METADATA_FIELD_NAME: + model_object.buffers[meta.buffer] = buffer_field + return model_object + + if not model_object.buffers: + model_object.buffers = [] + model_object.buffers.append(buffer_field) + # Creates a new metadata field. + metadata_field = schema_fb.MetadataT() + metadata_field.name = CONVERSION_METADATA_FIELD_NAME + metadata_field.buffer = len(model_object.buffers) - 1 + model_object.metadata.append(metadata_field) + + return model_object + except Exception: # pylint: disable=broad-except + return model_object + + +def get_conversion_metadata(model_buffer): + """Read conversion metadata from a tflite model. + + Args: + model_buffer: A tflite model. + + Returns: + The conversion metadata or None if it is not populated. + """ + model_object = flatbuffer_utils.convert_bytearray_to_object(model_buffer) + if not model_object or not model_object.metadata: + return None + + for meta in model_object.metadata: + if meta.name.decode("utf-8") == CONVERSION_METADATA_FIELD_NAME: + metadata_buf = model_object.buffers[meta.buffer].data.tobytes() + return conversion_metadata_fb.ConversionMetadataT.InitFromObj( + conversion_metadata_fb.ConversionMetadata.GetRootAsConversionMetadata( + metadata_buf, 0)) + + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/wrap_toco.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/wrap_toco.py new file mode 100644 index 0000000000000000000000000000000000000000..049d2babf36ff8be40b9b75b9daea5af1b1746f1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/python/wrap_toco.py @@ -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. +# ============================================================================== +"""Wraps toco interface with python lazy loader.""" +# We need to import pywrap_tensorflow prior to the toco wrapper. +# pylint: disable=invalid-import-order,g-bad-import-order +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python import _pywrap_toco_api + +# TODO(b/137402359): Remove lazy loading wrapper + + +def wrapped_toco_convert(model_flags_str, toco_flags_str, input_data_str, + debug_info_str, enable_mlir_converter): + """Wraps TocoConvert with lazy loader.""" + return _pywrap_toco_api.TocoConvert( + model_flags_str, + toco_flags_str, + input_data_str, + False, # extended_return + debug_info_str, + enable_mlir_converter) + + +def wrapped_experimental_mlir_quantize( + input_data_str, disable_per_channel, fully_quantize, inference_type, + input_data_type, output_data_type, enable_numeric_verify, + enable_whole_model_verify, denylisted_ops, denylisted_nodes, + enable_variable_quantization): + """Wraps experimental mlir quantize model.""" + return _pywrap_toco_api.ExperimentalMlirQuantizeModel( + input_data_str, disable_per_channel, fully_quantize, inference_type, + input_data_type, output_data_type, enable_numeric_verify, + enable_whole_model_verify, denylisted_ops, denylisted_nodes, + enable_variable_quantization) + + +def wrapped_experimental_mlir_sparsify(input_data_str): + """Wraps experimental mlir sparsify model.""" + return _pywrap_toco_api.ExperimentalMlirSparsifyModel(input_data_str) + + +def wrapped_register_custom_opdefs(custom_opdefs_list): + """Wraps RegisterCustomOpdefs with lazy loader.""" + return _pywrap_toco_api.RegisterCustomOpdefs(custom_opdefs_list) + + +def wrapped_retrieve_collected_errors(): + """Wraps RetrieveCollectedErrors with lazy loader.""" + return _pywrap_toco_api.RetrieveCollectedErrors() + + +def wrapped_flat_buffer_file_to_mlir(model, input_is_filepath): + """Wraps FlatBufferFileToMlir with lazy loader.""" + return _pywrap_toco_api.FlatBufferToMlir(model, input_is_filepath) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/gen_html.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/gen_html.py new file mode 100644 index 0000000000000000000000000000000000000000..02f2a83f8fc15dc4c5aedbe16d758b79bb69c3c7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/gen_html.py @@ -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. +# ============================================================================== +"""A utility class to generate the report HTML based on a common template.""" + +import io +import os + +from tensorflow.lite.toco.logging import toco_conversion_log_pb2 as _toco_conversion_log_pb2 +from tensorflow.python.lib.io import file_io as _file_io +from tensorflow.python.platform import resource_loader as _resource_loader + +html_escape_table = { + "&": "&", + '"': """, + "'": "'", + ">": ">", + "<": "<", +} + + +def html_escape(text): + return "".join(html_escape_table.get(c, c) for c in text) + + +def get_input_type_from_signature(op_signature): + """Parses op_signature and returns a string denoting the input tensor type. + + Args: + op_signature: a string specifying the signature of a particular operator. + The signature of an operator contains the input tensor's shape and type, + output tensor's shape and type, operator's name and its version. It has + the following schema: + INPUT:input_1_shape::input_1_type::input_2_shape::input_2_type::.. + ::OUTPUT:output_1_shape::output_1_type::output_2_shape::output_2_type:: + ..::NAME:operator_name ::VERSION:operator_version + An example of an operator signature is: + INPUT:[1,73,73,160]::float::[64,1,1,160]::float::[64]::float:: + OUTPUT:[1,73,73,64]::float::NAME:Conv::VERSION:1 + + Returns: + A string denoting the input tensors' type. In the form of shape/type + separated + by comma. For example: + shape:[1,73,73,160],type:float,shape:[64,1,1,160],type:float,shape:[64], + type:float + """ + start = op_signature.find(":") + end = op_signature.find("::OUTPUT") + inputs = op_signature[start + 1:end] + lst = inputs.split("::") + out_str = "" + for i in range(len(lst)): + if i % 2 == 0: + out_str += "shape:" + else: + out_str += "type:" + out_str += lst[i] + out_str += "," + return out_str[:-1] + + +def get_operator_type(op_name, conversion_log): + if op_name in conversion_log.built_in_ops: + return "BUILT-IN" + elif op_name in conversion_log.custom_ops: + return "CUSTOM OP" + else: + return "SELECT OP" + + +class HTMLGenerator: + """Utility class to generate an HTML report.""" + + def __init__(self, html_template_path, export_report_path): + """Reads the HTML template content. + + Args: + html_template_path: A string, path to the template HTML file. + export_report_path: A string, path to the generated HTML report. This path + should point to a '.html' file with date and time in its name. + e.g. 2019-01-01-10:05.toco_report.html. + + Raises: + IOError: File doesn't exist. + """ + # Load the template HTML. + if not _file_io.file_exists(html_template_path): + raise IOError("File '{0}' does not exist.".format(html_template_path)) + with _file_io.FileIO(html_template_path, "r") as f: + self.html_template = f.read() + + _file_io.recursive_create_dir(os.path.dirname(export_report_path)) + self.export_report_path = export_report_path + + def generate(self, + toco_conversion_log_before, + toco_conversion_log_after, + post_training_quant_enabled, + dot_before, + dot_after, + toco_err_log="", + tflite_graph_path=""): + """Generates the HTML report and writes it to local directory. + + This function uses the fields in `toco_conversion_log_before` and + `toco_conversion_log_after` to populate the HTML content. Certain markers + (placeholders) in the HTML template are then substituted with the fields + from the protos. Once finished it will write the HTML file to the specified + local file path. + + Args: + toco_conversion_log_before: A `TocoConversionLog` protobuf generated + before the model is converted by TOCO. + toco_conversion_log_after: A `TocoConversionLog` protobuf generated after + the model is converted by TOCO. + post_training_quant_enabled: A boolean, whether post-training quantization + is enabled. + dot_before: A string, the dot representation of the model + before the conversion. + dot_after: A string, the dot representation of the model after + the conversion. + toco_err_log: A string, the logs emitted by TOCO during conversion. Caller + need to ensure that this string is properly anonymized (any kind of + user data should be eliminated). + tflite_graph_path: A string, the filepath to the converted TFLite model. + + Raises: + RuntimeError: When error occurs while generating the template. + """ + html_dict = {} + html_dict[""] = ( + r'Fail' + ) if toco_err_log else r'Success' + html_dict[""] = str( + toco_conversion_log_before.model_size) + html_dict[""] = str( + toco_conversion_log_after.model_size) + html_dict[""] = str( + sum(toco_conversion_log_after.built_in_ops.values())) + html_dict[""] = str( + sum(toco_conversion_log_after.select_ops.values())) + html_dict[""] = str( + sum(toco_conversion_log_after.custom_ops.values())) + html_dict[""] = ( + "is" if post_training_quant_enabled else "isn't") + + pre_op_profile = "" + post_op_profile = "" + + # Generate pre-conversion op profiles as a list of HTML table rows. + for i in range(len(toco_conversion_log_before.op_list)): + # Append operator name column. + pre_op_profile += "" + toco_conversion_log_before.op_list[ + i] + "" + # Append input type column. + if i < len(toco_conversion_log_before.op_signatures): + pre_op_profile += "" + get_input_type_from_signature( + toco_conversion_log_before.op_signatures[i]) + "" + else: + pre_op_profile += "" + + # Generate post-conversion op profiles as a list of HTML table rows. + for op in toco_conversion_log_after.op_list: + supported_type = get_operator_type(op, toco_conversion_log_after) + post_op_profile += ("" + op + "" + supported_type + + "") + + html_dict[""] = pre_op_profile + html_dict[""] = post_op_profile + html_dict[""] = dot_before + html_dict[""] = dot_after + if toco_err_log: + html_dict[""] = html_escape(toco_err_log) + else: + success_info = ("TFLite graph conversion successful. You can preview the " + "converted model at: ") + tflite_graph_path + html_dict[""] = html_escape(success_info) + + # Replace each marker (as keys of html_dict) with the actual text (as values + # of html_dict) in the HTML template string. + template = self.html_template + for marker in html_dict: + template = template.replace(marker, html_dict[marker], 1) + # Check that the marker text is replaced. + if template.find(marker) != -1: + raise RuntimeError("Could not populate marker text %r" % marker) + + with _file_io.FileIO(self.export_report_path, "w") as f: + f.write(template) + + +def gen_conversion_log_html(conversion_log_dir, quantization_enabled, + tflite_graph_path): + """Generates an HTML report about the conversion process. + + Args: + conversion_log_dir: A string specifying the file directory of the conversion + logs. It's required that before calling this function, the + `conversion_log_dir` + already contains the following files: `toco_log_before.pb`, + `toco_log_after.pb`, `toco_tf_graph.dot`, + `toco_tflite_graph.dot`. + quantization_enabled: A boolean, passed from the tflite converter to + indicate whether post-training quantization is enabled during conversion. + tflite_graph_path: A string, the filepath to the converted TFLite model. + + Raises: + IOError: When any of the required files doesn't exist. + """ + template_filename = _resource_loader.get_path_to_datafile("template.html") + if not os.path.exists(template_filename): + raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( + template_filename)) + + toco_log_before_path = os.path.join(conversion_log_dir, "toco_log_before.pb") + toco_log_after_path = os.path.join(conversion_log_dir, "toco_log_after.pb") + dot_before_path = os.path.join(conversion_log_dir, "toco_tf_graph.dot") + dot_after_path = os.path.join(conversion_log_dir, "toco_tflite_graph.dot") + if not os.path.exists(toco_log_before_path): + raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( + toco_log_before_path)) + if not os.path.exists(toco_log_after_path): + raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( + toco_log_after_path)) + if not os.path.exists(dot_before_path): + raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( + dot_before_path)) + if not os.path.exists(dot_after_path): + raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( + dot_after_path)) + + html_generator = HTMLGenerator( + template_filename, + os.path.join(conversion_log_dir, "toco_conversion_summary.html")) + + # Parse the generated `TocoConversionLog`. + toco_conversion_log_before = _toco_conversion_log_pb2.TocoConversionLog() + toco_conversion_log_after = _toco_conversion_log_pb2.TocoConversionLog() + with open(toco_log_before_path, "rb") as f: + toco_conversion_log_before.ParseFromString(f.read()) + with open(toco_log_after_path, "rb") as f: + toco_conversion_log_after.ParseFromString(f.read()) + + # Read the dot file before/after the conversion. + with io.open(dot_before_path, "r", encoding="utf-8") as f: + dot_before = f.read().rstrip() + with io.open(dot_after_path, "r", encoding="utf-8") as f: + dot_after = f.read().rstrip() + + html_generator.generate(toco_conversion_log_before, toco_conversion_log_after, + quantization_enabled, dot_before, dot_after, + toco_conversion_log_after.toco_err_logs, + tflite_graph_path) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/toco_conversion_log_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/toco_conversion_log_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..9c45e243b45fb305038a76bbb936a0b3bc705728 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/logging/toco_conversion_log_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/lite/toco/logging/toco_conversion_log.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n6tensorflow/lite/toco/logging/toco_conversion_log.proto\x12\x04toco\"\xc9\x04\n\x11TocoConversionLog\x12\x0f\n\x07op_list\x18\x01 \x03(\t\x12=\n\x0c\x62uilt_in_ops\x18\x02 \x03(\x0b\x32\'.toco.TocoConversionLog.BuiltInOpsEntry\x12:\n\ncustom_ops\x18\x03 \x03(\x0b\x32&.toco.TocoConversionLog.CustomOpsEntry\x12:\n\nselect_ops\x18\x04 \x03(\x0b\x32&.toco.TocoConversionLog.SelectOpsEntry\x12\x15\n\rop_signatures\x18\x05 \x03(\t\x12\x1a\n\x12input_tensor_types\x18\x06 \x03(\t\x12\x1b\n\x13output_tensor_types\x18\x07 \x03(\t\x12\x19\n\x11log_generation_ts\x18\x08 \x01(\x03\x12\x12\n\nmodel_size\x18\t \x01(\x05\x12\x17\n\x0ftf_lite_version\x18\n \x01(\t\x12\x12\n\nos_version\x18\x0b \x01(\t\x12\x12\n\nmodel_hash\x18\x0c \x01(\t\x12\x15\n\rtoco_err_logs\x18\r \x01(\t\x1a\x31\n\x0f\x42uiltInOpsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0e\x43ustomOpsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\x1a\x30\n\x0eSelectOpsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.logging.toco_conversion_log_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _TOCOCONVERSIONLOG_BUILTINOPSENTRY._options = None + _TOCOCONVERSIONLOG_BUILTINOPSENTRY._serialized_options = b'8\001' + _TOCOCONVERSIONLOG_CUSTOMOPSENTRY._options = None + _TOCOCONVERSIONLOG_CUSTOMOPSENTRY._serialized_options = b'8\001' + _TOCOCONVERSIONLOG_SELECTOPSENTRY._options = None + _TOCOCONVERSIONLOG_SELECTOPSENTRY._serialized_options = b'8\001' + _TOCOCONVERSIONLOG._serialized_start=65 + _TOCOCONVERSIONLOG._serialized_end=650 + _TOCOCONVERSIONLOG_BUILTINOPSENTRY._serialized_start=501 + _TOCOCONVERSIONLOG_BUILTINOPSENTRY._serialized_end=550 + _TOCOCONVERSIONLOG_CUSTOMOPSENTRY._serialized_start=552 + _TOCOCONVERSIONLOG_CUSTOMOPSENTRY._serialized_end=600 + _TOCOCONVERSIONLOG_SELECTOPSENTRY._serialized_start=602 + _TOCOCONVERSIONLOG_SELECTOPSENTRY._serialized_end=650 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/model_flags_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/model_flags_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7f933dad926a13cb4dc40d24a2e65d8764f2acbb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/model_flags_pb2.py @@ -0,0 +1,40 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/lite/toco/model_flags.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from tensorflow.lite.toco import types_pb2 as tensorflow_dot_lite_dot_toco_dot_types__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n&tensorflow/lite/toco/model_flags.proto\x12\x04toco\x1a tensorflow/lite/toco/types.proto\"5\n\x0fInputArrayShape\x12\x0c\n\x04\x64ims\x18\x02 \x03(\x05\x12\x14\n\x0cunknown_rank\x18\x03 \x01(\x08\"\x8f\x01\n\nInputArray\x12\x0c\n\x04name\x18\x01 \x01(\t\x12$\n\x05shape\x18\x06 \x01(\x0b\x32\x15.toco.InputArrayShape\x12\x12\n\nmean_value\x18\x03 \x01(\x02\x12\x14\n\tstd_value\x18\x04 \x01(\x02:\x01\x31\x12#\n\tdata_type\x18\x05 \x01(\x0e\x32\x10.toco.IODataType\"t\n\x08RnnState\x12\x13\n\x0bstate_array\x18\x01 \x01(\t\x12\x1e\n\x16\x62\x61\x63k_edge_source_array\x18\x02 \x01(\t\x12\x13\n\x0b\x64iscardable\x18\x05 \x01(\x08\x12\x0c\n\x04size\x18\x03 \x01(\x05\x12\x10\n\x08num_dims\x18\x04 \x01(\x05\"\xef\x01\n\x0f\x41rraysExtraInfo\x12,\n\x07\x65ntries\x18\x01 \x03(\x0b\x32\x1b.toco.ArraysExtraInfo.Entry\x1a\xad\x01\n\x05\x45ntry\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x0bname_regexp\x18\x07 \x01(\t\x12\x0b\n\x03min\x18\x02 \x01(\x01\x12\x0b\n\x03max\x18\x03 \x01(\x01\x12#\n\tdata_type\x18\x04 \x01(\x0e\x32\x10.toco.IODataType\x12$\n\x05shape\x18\x05 \x01(\x0b\x32\x15.toco.InputArrayShape\x12\x1c\n\x14\x63onstant_float_value\x18\x06 \x01(\x02\"\xc6\x05\n\nModelFlags\x12&\n\x0cinput_arrays\x18\x01 \x03(\x0b\x32\x10.toco.InputArray\x12\x15\n\routput_arrays\x18\x02 \x03(\t\x12\x1d\n\x15\x63ontrol_output_arrays\x18\x18 \x03(\t\x12\x16\n\x0evariable_batch\x18\n \x01(\x08\x12\"\n\nrnn_states\x18\x0c \x03(\x0b\x32\x0e.toco.RnnState\x12\x31\n\x0cmodel_checks\x18\x0e \x03(\x0b\x32\x1b.toco.ModelFlags.ModelCheck\x12 \n\x18\x61llow_nonexistent_arrays\x18\x10 \x01(\x08\x12\x1d\n\x15\x61llow_nonascii_arrays\x18\x11 \x01(\x08\x12\x30\n\x11\x61rrays_extra_info\x18\x12 \x01(\x0b\x32\x15.toco.ArraysExtraInfo\x12(\n\x1a\x63hange_concat_input_ranges\x18\x13 \x01(\x08:\x04true\x12\x17\n\x0fsaved_model_dir\x18\x14 \x01(\t\x12\x1b\n\x13saved_model_version\x18\x15 \x01(\x05\x12\x18\n\x10saved_model_tags\x18\x16 \x03(\t\x12\"\n\x1asaved_model_exported_names\x18\x17 \x03(\t\x12\x16\n\x0euse_hlo_import\x18\x19 \x01(\x08\x12\x33\n\rhlo_file_type\x18\x1a \x01(\x0e\x32\x1c.toco.ModelFlags.HloFileType\x1aT\n\nModelCheck\x12\x18\n\ncount_type\x18\x01 \x01(\t:\x04None\x12\x15\n\tcount_min\x18\x02 \x01(\x05:\x02-1\x12\x15\n\tcount_max\x18\x03 \x01(\x05:\x02-1\"7\n\x0bHloFileType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x0c\n\x08HLO_TEXT\x10\x01\x12\r\n\tHLO_PROTO\x10\x02') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.model_flags_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _INPUTARRAYSHAPE._serialized_start=82 + _INPUTARRAYSHAPE._serialized_end=135 + _INPUTARRAY._serialized_start=138 + _INPUTARRAY._serialized_end=281 + _RNNSTATE._serialized_start=283 + _RNNSTATE._serialized_end=399 + _ARRAYSEXTRAINFO._serialized_start=402 + _ARRAYSEXTRAINFO._serialized_end=641 + _ARRAYSEXTRAINFO_ENTRY._serialized_start=468 + _ARRAYSEXTRAINFO_ENTRY._serialized_end=641 + _MODELFLAGS._serialized_start=644 + _MODELFLAGS._serialized_end=1354 + _MODELFLAGS_MODELCHECK._serialized_start=1213 + _MODELFLAGS_MODELCHECK._serialized_end=1297 + _MODELFLAGS_HLOFILETYPE._serialized_start=1299 + _MODELFLAGS_HLOFILETYPE._serialized_end=1354 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/toco_from_protos.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/toco_from_protos.py new file mode 100644 index 0000000000000000000000000000000000000000..617b5e9093d7953899b88de7d97b442c5cfb5627 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/python/toco_from_protos.py @@ -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. +# ============================================================================== +"""Python console command to invoke TOCO from serialized protos.""" +import argparse +import sys + +# We need to import pywrap_tensorflow prior to the toco wrapper. +# pylint: disable=invalid-import-order,g-bad-import-order +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python import _pywrap_toco_api +from absl import app + +FLAGS = None + + +def execute(unused_args): + """Runs the converter.""" + with open(FLAGS.model_proto_file, "rb") as model_file: + model_str = model_file.read() + + with open(FLAGS.toco_proto_file, "rb") as toco_file: + toco_str = toco_file.read() + + with open(FLAGS.model_input_file, "rb") as input_file: + input_str = input_file.read() + + debug_info_str = None + if FLAGS.debug_proto_file: + with open(FLAGS.debug_proto_file, "rb") as debug_info_file: + debug_info_str = debug_info_file.read() + + enable_mlir_converter = FLAGS.enable_mlir_converter + + output_str = _pywrap_toco_api.TocoConvert( + model_str, + toco_str, + input_str, + False, # extended_return + debug_info_str, + enable_mlir_converter) + open(FLAGS.model_output_file, "wb").write(output_str) + sys.exit(0) + + +def main(): + global FLAGS + parser = argparse.ArgumentParser( + description="Invoke toco using protos as input.") + parser.add_argument( + "model_proto_file", + type=str, + help="File containing serialized proto that describes the model.") + parser.add_argument( + "toco_proto_file", + type=str, + help="File containing serialized proto describing how TOCO should run.") + parser.add_argument( + "model_input_file", type=str, help="Input model is read from this file.") + parser.add_argument( + "model_output_file", + type=str, + help="Result of applying TOCO conversion is written here.") + parser.add_argument( + "--debug_proto_file", + type=str, + default="", + help=("File containing serialized `GraphDebugInfo` proto that describes " + "logging information.")) + parser.add_argument( + "--enable_mlir_converter", + action="store_true", + help=("Boolean indicating whether to enable MLIR-based conversion " + "instead of TOCO conversion. (default False)")) + + FLAGS, unparsed = parser.parse_known_args() + + app.run(main=execute, argv=[sys.argv[0]] + unparsed) + + +if __name__ == "__main__": + main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/toco_flags_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/toco_flags_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..da25f97bbfef17f838204ff300152a27a75bd46c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/toco_flags_pb2.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/lite/toco/toco_flags.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from tensorflow.compiler.mlir.lite.debug import debug_options_pb2 as tensorflow_dot_compiler_dot_mlir_dot_lite_dot_debug_dot_debug__options__pb2 +from tensorflow.compiler.mlir.quantization.stablehlo import quantization_options_pb2 as tensorflow_dot_compiler_dot_mlir_dot_quantization_dot_stablehlo_dot_quantization__options__pb2 +from tensorflow.lite.toco import types_pb2 as tensorflow_dot_lite_dot_toco_dot_types__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%tensorflow/lite/toco/toco_flags.proto\x12\x04toco\x1a\x37tensorflow/compiler/mlir/lite/debug/debug_options.proto\x1aJtensorflow/compiler/mlir/quantization/stablehlo/quantization_options.proto\x1a tensorflow/lite/toco/types.proto\"\xdc\x10\n\tTocoFlags\x12&\n\x0cinput_format\x18\x01 \x01(\x0e\x32\x10.toco.FileFormat\x12\'\n\routput_format\x18\x02 \x01(\x0e\x32\x10.toco.FileFormat\x12.\n\x14inference_input_type\x18\x0b \x01(\x0e\x32\x10.toco.IODataType\x12(\n\x0einference_type\x18\x04 \x01(\x0e\x32\x10.toco.IODataType\x12\x1a\n\x12\x64\x65\x66\x61ult_ranges_min\x18\x05 \x01(\x02\x12\x1a\n\x12\x64\x65\x66\x61ult_ranges_max\x18\x06 \x01(\x02\x12 \n\x18\x64\x65\x66\x61ult_int16_ranges_min\x18\x0f \x01(\x02\x12 \n\x18\x64\x65\x66\x61ult_int16_ranges_max\x18\x10 \x01(\x02\x12\x17\n\x0f\x64rop_fake_quant\x18\x07 \x01(\x08\x12!\n\x19reorder_across_fake_quant\x18\x08 \x01(\x08\x12\x18\n\x10\x61llow_custom_ops\x18\n \x01(\x08\x12\x1f\n\x17\x64rop_control_dependency\x18\x0c \x01(\x08\x12+\n#debug_disable_recurrent_cell_fusion\x18\r \x01(\x08\x12%\n\x1dpropagate_fake_quant_num_bits\x18\x0e \x01(\x08\x12\x35\n-allow_nudging_weights_to_use_fast_gemm_kernel\x18\x11 \x01(\x08\x12\'\n\x1b\x64\x65\x64upe_array_min_size_bytes\x18\x12 \x01(\x03:\x02\x36\x34\x12&\n\x18split_tflite_lstm_inputs\x18\x13 \x01(\x08:\x04true\x12\x1f\n\x10quantize_weights\x18\x14 \x01(\x08:\x05\x66\x61lse\x12\x19\n\x11\x64ump_graphviz_dir\x18\x18 \x01(\t\x12#\n\x1b\x64ump_graphviz_include_video\x18\x19 \x01(\x08\x12%\n\x16post_training_quantize\x18\x1a \x01(\x08:\x05\x66\x61lse\x12#\n\x14\x65nable_select_tf_ops\x18\x1b \x01(\x08:\x05\x66\x61lse\x12\"\n\x13\x66orce_select_tf_ops\x18\x1c \x01(\x08:\x05\x66\x61lse\x12\"\n\x13quantize_to_float16\x18\x1d \x01(\x08:\x05\x66\x61lse\x12#\n\x15\x61llow_dynamic_tensors\x18\x1e \x01(\x08:\x04true\x12\x1e\n\x16\x63onversion_summary_dir\x18\x1f \x01(\t\x12\x19\n\rcustom_opdefs\x18 \x03(\tB\x02\x18\x01\x12\x1a\n\x12select_user_tf_ops\x18! \x03(\t\x12.\n enable_tflite_resource_variables\x18\" \x01(\x08:\x04true\x12!\n\x12unfold_batchmatmul\x18# \x01(\x08:\x05\x66\x61lse\x12#\n\x15lower_tensor_list_ops\x18$ \x01(\x08:\x04true\x12+\n\x11\x61\x63\x63umulation_type\x18% \x01(\x0e\x32\x10.toco.IODataType\x12\x1d\n\x0e\x61llow_bfloat16\x18& \x01(\x08:\x05\x66\x61lse\x12\x1f\n\x17\x61llow_all_select_tf_ops\x18\' \x01(\x08\x12*\n\x1bunfold_large_splat_constant\x18( \x01(\x08:\x05\x66\x61lse\x12\x1a\n\x12supported_backends\x18) \x03(\t\x12\x39\n*default_to_single_batch_in_tensor_list_ops\x18* \x01(\x08:\x05\x66\x61lse\x12/\n disable_per_channel_quantization\x18+ \x01(\x08:\x05\x66\x61lse\x12\x32\n#enable_mlir_dynamic_range_quantizer\x18, \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x14tf_quantization_mode\x18- \x01(\t\x12)\n\x1a\x64isable_infer_tensor_range\x18. \x01(\x08:\x05\x66\x61lse\x12&\n\x17use_fake_quant_num_bits\x18/ \x01(\x08:\x05\x66\x61lse\x12*\n\x1b\x65nable_dynamic_update_slice\x18\x30 \x01(\x08:\x05\x66\x61lse\x12!\n\x12preserve_assert_op\x18\x31 \x01(\x08:\x05\x66\x61lse\x12*\n\x1bguarantee_all_funcs_one_use\x18\x32 \x01(\x08:\x05\x66\x61lse\x12#\n\x14\x63onvert_to_stablehlo\x18\x33 \x01(\x08:\x05\x66\x61lse\x12\x30\n!enable_mlir_variable_quantization\x18\x34 \x01(\x08:\x05\x66\x61lse\x12&\n\x17\x64isable_fuse_mul_and_fc\x18\x35 \x01(\x08:\x05\x66\x61lse\x12I\n\x14quantization_options\x18\x36 \x01(\x0b\x32+.stablehlo.quantization.QuantizationOptions\x12.\n\x1b\x65nable_hlo_to_tf_conversion\x18\x37 \x01(\x08:\x05\x66\x61lseB\x02\x18\x01\x12\x39\n\rdebug_options\x18\x38 \x01(\x0b\x32\".tensorflow.converter.DebugOptions\x12 \n\x11use_buffer_offset\x18\x39 \x01(\x08:\x05\x66\x61lse\x12.\n\x1flegalize_custom_tensor_list_ops\x18: \x01(\x08:\x05\x66\x61lse\x12$\n\x15reduce_type_precision\x18; \x01(\x08:\x05\x66\x61lse*\\\n\nFileFormat\x12\x17\n\x13\x46ILE_FORMAT_UNKNOWN\x10\x00\x12\x17\n\x13TENSORFLOW_GRAPHDEF\x10\x01\x12\n\n\x06TFLITE\x10\x02\x12\x10\n\x0cGRAPHVIZ_DOT\x10\x03') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.toco_flags_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _TOCOFLAGS.fields_by_name['custom_opdefs']._options = None + _TOCOFLAGS.fields_by_name['custom_opdefs']._serialized_options = b'\030\001' + _TOCOFLAGS.fields_by_name['enable_hlo_to_tf_conversion']._options = None + _TOCOFLAGS.fields_by_name['enable_hlo_to_tf_conversion']._serialized_options = b'\030\001' + _FILEFORMAT._serialized_start=2357 + _FILEFORMAT._serialized_end=2449 + _TOCOFLAGS._serialized_start=215 + _TOCOFLAGS._serialized_end=2355 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/types_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/types_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..897496121719af0e5e2b2dc59a940e602cd53595 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/toco/types_pb2.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/lite/toco/types.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n tensorflow/lite/toco/types.proto\x12\x04toco*\xb3\x02\n\nIODataType\x12\x18\n\x14IO_DATA_TYPE_UNKNOWN\x10\x00\x12\t\n\x05\x46LOAT\x10\x01\x12\x13\n\x0fQUANTIZED_UINT8\x10\x02\x12\t\n\x05INT32\x10\x03\x12\t\n\x05INT64\x10\x04\x12\n\n\x06STRING\x10\x05\x12\x13\n\x0fQUANTIZED_INT16\x10\x06\x12\x08\n\x04\x42OOL\x10\x07\x12\r\n\tCOMPLEX64\x10\x08\x12\x12\n\x0eQUANTIZED_INT8\x10\t\x12\x0b\n\x07\x46LOAT16\x10\n\x12\x0b\n\x07\x46LOAT64\x10\x0b\x12\x0e\n\nCOMPLEX128\x10\x0c\x12\n\n\x06UINT64\x10\r\x12\x0c\n\x08RESOURCE\x10\x0e\x12\x0b\n\x07VARIANT\x10\x0f\x12\n\n\x06UINT32\x10\x10\x12\t\n\x05UINT8\x10\x11\x12\x08\n\x04INT8\x10\x12\x12\t\n\x05INT16\x10\x13\x12\n\n\x06UINT16\x10\x14') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.lite.toco.types_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + _IODATATYPE._serialized_start=43 + _IODATATYPE._serialized_end=350 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/flatbuffer_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/flatbuffer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6c7d80f8892d45d1f5b77f2114cf871c657a83 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/flatbuffer_utils.py @@ -0,0 +1,432 @@ +# 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. +# ============================================================================== +"""Utility functions for FlatBuffers. + +All functions that are commonly used to work with FlatBuffers. + +Refer to the tensorflow lite flatbuffer schema here: +tensorflow/lite/schema/schema.fbs +""" + +import copy +import random +import re +import struct +import sys + +import flatbuffers + +from tensorflow.lite.python import schema_py_generated as schema_fb +from tensorflow.lite.python import schema_util +from tensorflow.python.platform import gfile + +_TFLITE_FILE_IDENTIFIER = b'TFL3' + + +def convert_bytearray_to_object(model_bytearray): + """Converts a tflite model from a bytearray to an object for parsing.""" + model_object = schema_fb.Model.GetRootAsModel(model_bytearray, 0) + return schema_fb.ModelT.InitFromObj(model_object) + + +def read_model(input_tflite_file): + """Reads a tflite model as a python object. + + Args: + input_tflite_file: Full path name to the input tflite file + + Raises: + RuntimeError: If input_tflite_file path is invalid. + IOError: If input_tflite_file cannot be opened. + + Returns: + A python object corresponding to the input tflite file. + """ + if not gfile.Exists(input_tflite_file): + raise RuntimeError('Input file not found at %r\n' % input_tflite_file) + with gfile.GFile(input_tflite_file, 'rb') as input_file_handle: + model_bytearray = bytearray(input_file_handle.read()) + model = convert_bytearray_to_object(model_bytearray) + if sys.byteorder == 'big': + byte_swap_tflite_model_obj(model, 'little', 'big') + return model + + +def read_model_with_mutable_tensors(input_tflite_file): + """Reads a tflite model as a python object with mutable tensors. + + Similar to read_model() with the addition that the returned object has + mutable tensors (read_model() returns an object with immutable tensors). + + NOTE: This API only works for TFLite generated with + _experimental_use_buffer_offset=false + + Args: + input_tflite_file: Full path name to the input tflite file + + Raises: + RuntimeError: If input_tflite_file path is invalid. + IOError: If input_tflite_file cannot be opened. + + Returns: + A mutable python object corresponding to the input tflite file. + """ + return copy.deepcopy(read_model(input_tflite_file)) + + +def convert_object_to_bytearray(model_object, extra_buffer=b''): + """Converts a tflite model from an object to a immutable bytearray.""" + # Initial size of the buffer, which will grow automatically if needed + builder = flatbuffers.Builder(1024) + model_offset = model_object.Pack(builder) + builder.Finish(model_offset, file_identifier=_TFLITE_FILE_IDENTIFIER) + model_bytearray = bytes(builder.Output()) + model_bytearray = model_bytearray + extra_buffer + return model_bytearray + + +def write_model(model_object, output_tflite_file): + """Writes the tflite model, a python object, into the output file. + + NOTE: This API only works for TFLite generated with + _experimental_use_buffer_offset=false + + Args: + model_object: A tflite model as a python object + output_tflite_file: Full path name to the output tflite file. + + Raises: + IOError: If output_tflite_file path is invalid or cannot be opened. + """ + if sys.byteorder == 'big': + model_object = copy.deepcopy(model_object) + byte_swap_tflite_model_obj(model_object, 'big', 'little') + model_bytearray = convert_object_to_bytearray(model_object) + with gfile.GFile(output_tflite_file, 'wb') as output_file_handle: + output_file_handle.write(model_bytearray) + + +def strip_strings(model): + """Strips all nonessential strings from the model to reduce model size. + + We remove the following strings: + (find strings by searching ":string" in the tensorflow lite flatbuffer schema) + 1. Model description + 2. SubGraph name + 3. Tensor names + We retain OperatorCode custom_code and Metadata name. + + Args: + model: The model from which to remove nonessential strings. + """ + + model.description = None + for subgraph in model.subgraphs: + subgraph.name = None + for tensor in subgraph.tensors: + tensor.name = None + # We clear all signature_def structure, since without names it is useless. + model.signatureDefs = None + + +def type_to_name(tensor_type): + """Converts a numerical enum to a readable tensor type.""" + for name, value in schema_fb.TensorType.__dict__.items(): + if value == tensor_type: + return name + return None + + +def randomize_weights(model, random_seed=0, buffers_to_skip=None): + """Randomize weights in a model. + + Args: + model: The model in which to randomize weights. + random_seed: The input to the random number generator (default value is 0). + buffers_to_skip: The list of buffer indices to skip. The weights in these + buffers are left unmodified. + """ + + # The input to the random seed generator. The default value is 0. + random.seed(random_seed) + + # Parse model buffers which store the model weights + buffers = model.buffers + buffer_ids = range(1, len(buffers)) # ignore index 0 as it's always None + if buffers_to_skip is not None: + buffer_ids = [idx for idx in buffer_ids if idx not in buffers_to_skip] + + buffer_types = {} + for graph in model.subgraphs: + for op in graph.operators: + if op.inputs is None: + break + for input_idx in op.inputs: + tensor = graph.tensors[input_idx] + buffer_types[tensor.buffer] = type_to_name(tensor.type) + + for i in buffer_ids: + buffer_i_data = buffers[i].data + buffer_i_size = 0 if buffer_i_data is None else buffer_i_data.size + if buffer_i_size == 0: + continue + + # Raw data buffers are of type ubyte (or uint8) whose values lie in the + # range [0, 255]. Those ubytes (or unint8s) are the underlying + # representation of each datatype. For example, a bias tensor of type + # int32 appears as a buffer 4 times it's length of type ubyte (or uint8). + # For floats, we need to generate a valid float and then pack it into + # the raw bytes in place. + buffer_type = buffer_types.get(i, 'INT8') + if buffer_type.startswith('FLOAT'): + format_code = 'e' if buffer_type == 'FLOAT16' else 'f' + for offset in range(0, buffer_i_size, struct.calcsize(format_code)): + value = random.uniform(-0.5, 0.5) # See http://b/152324470#comment2 + struct.pack_into(format_code, buffer_i_data, offset, value) + else: + for j in range(buffer_i_size): + buffer_i_data[j] = random.randint(0, 255) + + +def rename_custom_ops(model, map_custom_op_renames): + """Rename custom ops so they use the same naming style as builtin ops. + + Args: + model: The input tflite model. + map_custom_op_renames: A mapping from old to new custom op names. + """ + for op_code in model.operatorCodes: + if op_code.customCode: + op_code_str = op_code.customCode.decode('ascii') + if op_code_str in map_custom_op_renames: + op_code.customCode = map_custom_op_renames[op_code_str].encode('ascii') + + +def opcode_to_name(model, op_code): + """Converts a TFLite op_code to the human readable name. + + Args: + model: The input tflite model. + op_code: The op_code to resolve to a readable name. + + Returns: + A string containing the human readable op name, or None if not resolvable. + """ + op = model.operatorCodes[op_code] + code = max(op.builtinCode, op.deprecatedBuiltinCode) + for name, value in vars(schema_fb.BuiltinOperator).items(): + if value == code: + return name + return None + + +def xxd_output_to_bytes(input_cc_file): + """Converts xxd output C++ source file to bytes (immutable). + + Args: + input_cc_file: Full path name to th C++ source file dumped by xxd + + Raises: + RuntimeError: If input_cc_file path is invalid. + IOError: If input_cc_file cannot be opened. + + Returns: + A bytearray corresponding to the input cc file array. + """ + # Match hex values in the string with comma as separator + pattern = re.compile(r'\W*(0x[0-9a-fA-F,x ]+).*') + + model_bytearray = bytearray() + + with open(input_cc_file) as file_handle: + for line in file_handle: + values_match = pattern.match(line) + + if values_match is None: + continue + + # Match in the parentheses (hex array only) + list_text = values_match.group(1) + + # Extract hex values (text) from the line + # e.g. 0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, + values_text = filter(None, list_text.split(',')) + + # Convert to hex + values = [int(x, base=16) for x in values_text] + model_bytearray.extend(values) + + return bytes(model_bytearray) + + +def xxd_output_to_object(input_cc_file): + """Converts xxd output C++ source file to object. + + Args: + input_cc_file: Full path name to th C++ source file dumped by xxd + + Raises: + RuntimeError: If input_cc_file path is invalid. + IOError: If input_cc_file cannot be opened. + + Returns: + A python object corresponding to the input tflite file. + """ + model_bytes = xxd_output_to_bytes(input_cc_file) + return convert_bytearray_to_object(model_bytes) + + +def byte_swap_buffer_content(buffer, chunksize, from_endiness, to_endiness): + """Helper function for byte-swapping the buffers field.""" + to_swap = [ + buffer.data[i : i + chunksize] + for i in range(0, len(buffer.data), chunksize) + ] + buffer.data = b''.join( + [ + int.from_bytes(byteswap, from_endiness).to_bytes( + chunksize, to_endiness + ) + for byteswap in to_swap + ] + ) + + +def byte_swap_string_content(buffer, from_endiness, to_endiness): + """Helper function for byte-swapping the string buffer. + + Args: + buffer: TFLite string buffer of from_endiness format. + from_endiness: The original endianness format of the string buffer. + to_endiness: The destined endianness format of the string buffer. + """ + num_of_strings = int.from_bytes(buffer.data[0:4], from_endiness) + string_content = bytearray(buffer.data[4 * (num_of_strings + 2) :]) + prefix_data = b''.join( + [ + int.from_bytes(buffer.data[i : i + 4], from_endiness).to_bytes( + 4, to_endiness + ) + for i in range(0, (num_of_strings + 1) * 4 + 1, 4) + ] + ) + buffer.data = prefix_data + string_content + + +def byte_swap_tflite_model_obj(model, from_endiness, to_endiness): + """Byte swaps the buffers field in a TFLite model. + + Args: + model: TFLite model object of from_endiness format. + from_endiness: The original endianness format of the buffers in model. + to_endiness: The destined endianness format of the buffers in model. + """ + if model is None: + return + # Get all the constant buffers, byte swapping them as per their data types + buffer_swapped = [] + types_of_16_bits = [ + schema_fb.TensorType.FLOAT16, + schema_fb.TensorType.INT16, + schema_fb.TensorType.UINT16, + ] + types_of_32_bits = [ + schema_fb.TensorType.FLOAT32, + schema_fb.TensorType.INT32, + schema_fb.TensorType.COMPLEX64, + schema_fb.TensorType.UINT32, + ] + types_of_64_bits = [ + schema_fb.TensorType.INT64, + schema_fb.TensorType.FLOAT64, + schema_fb.TensorType.COMPLEX128, + schema_fb.TensorType.UINT64, + ] + for subgraph in model.subgraphs: + for tensor in subgraph.tensors: + if ( + tensor.buffer > 0 + and tensor.buffer < len(model.buffers) + and tensor.buffer not in buffer_swapped + and model.buffers[tensor.buffer].data is not None + ): + if tensor.type == schema_fb.TensorType.STRING: + byte_swap_string_content( + model.buffers[tensor.buffer], from_endiness, to_endiness + ) + elif tensor.type in types_of_16_bits: + byte_swap_buffer_content( + model.buffers[tensor.buffer], 2, from_endiness, to_endiness + ) + elif tensor.type in types_of_32_bits: + byte_swap_buffer_content( + model.buffers[tensor.buffer], 4, from_endiness, to_endiness + ) + elif tensor.type in types_of_64_bits: + byte_swap_buffer_content( + model.buffers[tensor.buffer], 8, from_endiness, to_endiness + ) + else: + continue + buffer_swapped.append(tensor.buffer) + + +def byte_swap_tflite_buffer(tflite_model, from_endiness, to_endiness): + """Generates a new model byte array after byte swapping its buffers field. + + Args: + tflite_model: TFLite flatbuffer in a byte array. + from_endiness: The original endianness format of the buffers in + tflite_model. + to_endiness: The destined endianness format of the buffers in tflite_model. + + Returns: + TFLite flatbuffer in a byte array, after being byte swapped to to_endiness + format. + """ + if tflite_model is None: + return None + # Load TFLite Flatbuffer byte array into an object. + model = convert_bytearray_to_object(tflite_model) + + # Byte swapping the constant buffers as per their data types + byte_swap_tflite_model_obj(model, from_endiness, to_endiness) + + # Return a TFLite flatbuffer as a byte array. + return convert_object_to_bytearray(model) + + +def count_resource_variables(model): + """Calculates the number of unique resource variables in a model. + + Args: + model: the input tflite model, either as bytearray or object. + + Returns: + An integer number representing the number of unique resource variables. + """ + if not isinstance(model, schema_fb.ModelT): + model = convert_bytearray_to_object(model) + unique_shared_names = set() + for subgraph in model.subgraphs: + if subgraph.operators is None: + continue + for op in subgraph.operators: + builtin_code = schema_util.get_builtin_code_from_operator_code( + model.operatorCodes[op.opcodeIndex] + ) + if builtin_code == schema_fb.BuiltinOperator.VAR_HANDLE: + unique_shared_names.add(op.builtinOptions.sharedName) + return len(unique_shared_names) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/python/debugger.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/python/debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..c748d6ef62b706be01c704f36786428b4f675bfe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/optimize/debugging/python/debugger.py @@ -0,0 +1,549 @@ +# 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. +# ============================================================================== +"""Python TF-Lite QuantizationDebugger.""" +import collections +import csv +import re +from typing import (Any, Callable, Dict, IO, Iterable, List, Mapping, Optional, + Sequence, Tuple) + +import numpy as np + +from tensorflow.lite.python import convert +from tensorflow.lite.python import interpreter as _interpreter +from tensorflow.lite.python.metrics import metrics as metrics_stub # type: ignore +from tensorflow.python.util import tf_export + + +# TODO(b/198099651): move converter implementation out of lite.py +TFLiteConverter = Any # importing tf.lite creates circular dependency + +# Returns metrics based on difference of values for quantized/float ops. +_DEFAULT_LAYER_DEBUG_METRICS = { + 'num_elements': lambda diffs: diffs.size, + 'stddev': np.std, + 'mean_error': np.average, + 'max_abs_error': lambda diffs: np.max(np.abs(diffs)), + 'mean_squared_error': lambda diffs: np.average(diffs**2), +} + +_NUMERIC_VERIFY_OP_NAME = 'NumericVerify' + + +def _get_quant_params( + tensor_detail: Mapping[str, Any]) -> Optional[Tuple[float, int]]: + """Returns first scale and zero point from tensor detail, if present.""" + quant_params = tensor_detail['quantization_parameters'] + if not quant_params: + return None + if quant_params['scales'] and quant_params['zero_points']: + return (quant_params['scales'][0], quant_params['zero_points'][0]) + return None + + +@tf_export.tf_export('lite.experimental.QuantizationDebugOptions') +class QuantizationDebugOptions: + """Debug options to set up a given QuantizationDebugger.""" + + def __init__(self, + layer_debug_metrics: Optional[Mapping[str, + Callable[[np.ndarray], + float]]] = None, + model_debug_metrics: Optional[Mapping[ + str, Callable[[Sequence[np.ndarray], Sequence[np.ndarray]], + float]]] = None, + layer_direct_compare_metrics: Optional[Mapping[str, Callable[ + [Sequence[np.ndarray], Sequence[np.ndarray], float, int], + float]]] = None, + denylisted_ops: Optional[List[str]] = None, + denylisted_nodes: Optional[List[str]] = None, + fully_quantize: bool = False) -> None: + """Initializes debugger options. + + Args: + layer_debug_metrics: a dict to specify layer debug functions + {function_name_str: function} where the function accepts result of + NumericVerify Op, which is value difference between float and + dequantized op results. The function returns single scalar value. + model_debug_metrics: a dict to specify model debug functions + {function_name_str: function} where the function accepts outputs from + two models, and returns single scalar value for a metric. (e.g. + accuracy, IoU) + layer_direct_compare_metrics: a dict to specify layer debug functions + {function_name_str: function}. The signature is different from that of + `layer_debug_metrics`, and this one gets passed (original float value, + original quantized value, scale, zero point). The function's + implementation is responsible for correctly dequantize the quantized + value to compare. Use this one when comparing diff is not enough. + (Note) quantized value is passed as int8, so cast to int32 is needed. + denylisted_ops: a list of op names which is expected to be removed from + quantization. + denylisted_nodes: a list of op's output tensor names to be removed from + quantization. + fully_quantize: Bool indicating whether to fully quantize the model. + Besides model body, the input/output will be quantized as well. + Corresponding to mlir_quantize's fully_quantize parameter. + + Raises: + ValueError: when there are duplicate keys + """ + self.layer_debug_metrics = layer_debug_metrics + self.model_debug_metrics = model_debug_metrics + self.layer_direct_compare_metrics = layer_direct_compare_metrics + + keys = [] + for metrics in [ + layer_debug_metrics, model_debug_metrics, layer_direct_compare_metrics + ]: + if metrics is not None: + keys.extend(metrics.keys()) + if len(keys) != len(set(keys)): + raise ValueError('Provided metrics have duplicate keys.') + + self.denylisted_ops = denylisted_ops + self.denylisted_nodes = denylisted_nodes + self.fully_quantize = fully_quantize + + +@tf_export.tf_export('lite.experimental.QuantizationDebugger') +class QuantizationDebugger: + """Debugger for Quantized TensorFlow Lite debug mode models. + + This can run the TensorFlow Lite converted models equipped with debug ops and + collect debug information. This debugger calculates statistics from + user-defined post-processing functions as well as default ones. + """ + + def __init__(self, + quant_debug_model_path: Optional[str] = None, + quant_debug_model_content: Optional[bytes] = None, + float_model_path: Optional[str] = None, + float_model_content: Optional[bytes] = None, + debug_dataset: Optional[Callable[ + [], Iterable[Sequence[np.ndarray]]]] = None, + debug_options: Optional[QuantizationDebugOptions] = None, + converter: Optional[TFLiteConverter] = None) -> None: + """Runs the TFLite debugging model with given debug options. + + Args: + quant_debug_model_path: Path to the quantized debug TFLite model file. + quant_debug_model_content: Content of the quantized debug TFLite model. + float_model_path: Path to float TFLite model file. + float_model_content: Content of the float TFLite model. + debug_dataset: a factory function that returns dataset generator which is + used to generate input samples (list of np.ndarray) for the model. The + generated elements must have same types and shape as inputs to the + model. + debug_options: Debug options to debug the given model. + converter: Optional, use converter instead of quantized model. + + Raises: + ValueError: If the debugger was unable to be created. + + Attributes: + layer_statistics: results of error metrics for each NumericVerify op + results. in {layer_name: {metric_name: metric}} format. + model_statistics: results of error metrics for difference between float + and quantized models. in {metric_name: metric} format. + """ + self._data_gen = debug_dataset + self._debug_options = debug_options or QuantizationDebugOptions() + self.converter = None + self.calibrated_model = None + self.float_model = None + self._float_interpreter = None + if converter is not None: + if self._debug_options.model_debug_metrics: + old_optimizations = converter.optimizations + self.converter = self._set_converter_options_for_float(converter) + self.float_model = self.converter.convert() + converter.optimizations = old_optimizations + + self.converter = self._set_converter_options_for_calibration(converter) + self.calibrated_model = self.converter.convert() + # Converter should be already set up with all options + self._init_from_converter( + self._debug_options, + self.converter, + self.calibrated_model, + float_model=self.float_model) + else: + self._quant_interpreter = _interpreter.Interpreter( + quant_debug_model_path, + quant_debug_model_content, + experimental_preserve_all_tensors=( + self._debug_options.layer_direct_compare_metrics is not None)) + if self._debug_options.model_debug_metrics: + self._float_interpreter = _interpreter.Interpreter( + float_model_path, float_model_content) + self._initialize_stats() + + @property + def options(self) -> QuantizationDebugOptions: + return self._debug_options + + @options.setter + def options(self, options: QuantizationDebugOptions) -> None: + self._debug_options = options + if not self.converter or not self.calibrated_model: + return + self._init_from_converter( + self._debug_options, + self.converter, + self.calibrated_model, + float_model=self.float_model) + self._initialize_stats() + + def _initialize_stats(self): + """Helper function initializes stats.""" + # TODO(b/177749613) : Fix the dependency on tf.lite._get_ops_details() + # Following code is needed to get op's name from the output tensor index, + # since NumericVerify op only provides its quantized input tensor index. + self._defining_op = dict() + for op_info in self._quant_interpreter._get_ops_details(): # pylint: disable=protected-access + self._defining_op.update( + {tensor_idx: op_info['index'] for tensor_idx in op_info['outputs']}) + + self._numeric_verify_tensor_details = None + self._numeric_verify_op_details = None + if not self._get_numeric_verify_tensor_details(): + raise ValueError('Please check if the quantized model is in debug mode') + + self._layer_debug_metrics = _DEFAULT_LAYER_DEBUG_METRICS.copy() + if self._debug_options.layer_debug_metrics: + self._layer_debug_metrics.update(self._debug_options.layer_debug_metrics) + + self.layer_statistics = None + self.model_statistics = None + + self._metrics = metrics_stub.TFLiteMetrics() + self._metrics.increase_counter_debugger_creation() + + def _get_quantized_model(self, is_debug: bool) -> bytes: + if not self.converter: + raise ValueError('No converter found, use this function with the ' + 'converter option in the constructor.') + + return convert.mlir_quantize( + self.calibrated_model, + disable_per_channel=self.converter._experimental_disable_per_channel, # pylint: disable=protected-access + fully_quantize=self._debug_options.fully_quantize, + enable_numeric_verify=is_debug, + denylisted_ops=self._debug_options.denylisted_ops, + denylisted_nodes=self._debug_options.denylisted_nodes) + + def get_nondebug_quantized_model(self) -> bytes: + """Returns a non-instrumented quantized model. + + Convert the quantized model with the initialized converter and + return bytes for nondebug model. The model will not be instrumented with + numeric verification operations. + + Returns: + Model bytes corresponding to the model. + Raises: + ValueError: if converter is not passed to the debugger. + """ + return self._get_quantized_model(is_debug=False) + + def get_debug_quantized_model(self) -> bytes: + """Returns an instrumented quantized model. + + Convert the quantized model with the initialized converter and + return bytes for model. The model will be instrumented with numeric + verification operations and should only be used for debugging. + + Returns: + Model bytes corresponding to the model. + Raises: + ValueError: if converter is not passed to the debugger. + """ + return self._get_quantized_model(is_debug=True) + + def _init_from_converter(self, + options: QuantizationDebugOptions, + converter: TFLiteConverter, + calibrated_model: Optional[bytes] = None, + float_model: Optional[bytes] = None) -> None: + """Convert the model and apply options. + + Converts the quantized model and initializes a quantized model interpreter + with the quantized model. Returns a float model interpreter if float model + is provided. + + Args: + options: a QuantizationDebugOptions object. + converter: an initialized tf.lite.TFLiteConverter. + calibrated_model: Calibrated model bytes. + float_model: Float model bytes. + """ + self.quant_model = convert.mlir_quantize( + calibrated_model, + disable_per_channel=converter._experimental_disable_per_channel, # pylint: disable=protected-access + fully_quantize=options.fully_quantize, + enable_numeric_verify=True, + denylisted_ops=options.denylisted_ops, + denylisted_nodes=options.denylisted_nodes) + self._quant_interpreter = _interpreter.Interpreter( + model_content=self.quant_model) + self._float_interpreter = None + if float_model is not None: + self._float_interpreter = _interpreter.Interpreter( + model_content=float_model) + + def _set_converter_options_for_float( + self, converter: TFLiteConverter) -> TFLiteConverter: + """Verify converter options and set required experimental options.""" + if converter.optimizations: + converter.optimizations = [] + return converter + + def _set_converter_options_for_calibration( + self, converter: TFLiteConverter) -> TFLiteConverter: + """Verify converter options and set required experimental options.""" + if not converter.optimizations: + raise ValueError( + 'converter object must set optimizations to lite.Optimize.DEFAULT') + if not converter.representative_dataset: + raise ValueError('converter object must set representative_dataset') + + converter.experimental_mlir_quantizer = True + converter._experimental_calibrate_only = True # pylint: disable=protected-access + return converter + + def run(self) -> None: + """Runs models and gets metrics.""" + self.layer_statistics = self._collect_layer_statistics() + if self._debug_options.model_debug_metrics: + self.model_statistics = self._collect_model_statistics() + + def _collect_layer_statistics(self) -> Dict[str, Dict[str, float]]: + """Collects layer statistics by applying layer debug metrics. + + For all data from the given RepresentativeDataset, collect statistics per + example by getting the NumericVerify op results in _quant_interpreter + and calculating layer debug metrics on the results. + + Returns: + aggregated per-layer statistics of NumericVerify results. + {layer_name: {metric_name: metric}} + """ + layer_statistics = collections.defaultdict( + lambda: collections.defaultdict(list)) + + initialize = True + for tensor_data in self._data_gen(): + self._set_input_tensors(self._quant_interpreter, tensor_data, initialize) + initialize = False + + # Run the model. + self._quant_interpreter.invoke() + + # Collect the statistics of this invoke result. + for tensor_detail in self._get_numeric_verify_tensor_details(): + tensor_name = tensor_detail['name'] # pytype: disable=unsupported-operands # dynamic-method-lookup + diffs = self._quant_interpreter.get_tensor(tensor_detail['index']) # pytype: disable=unsupported-operands # dynamic-method-lookup + for metric_name, metric_fn in self._layer_debug_metrics.items(): + layer_statistics[tensor_name][metric_name].append(metric_fn(diffs)) + + if self._debug_options.layer_direct_compare_metrics is not None: + for tensor_detail in self._get_numeric_verify_tensor_details(): + tensor_name = tensor_detail['name'] # pytype: disable=unsupported-operands # dynamic-method-lookup + op_idx = self._defining_op[tensor_detail['index']] # pytype: disable=unsupported-operands # dynamic-method-lookup + op_detail = self._quant_interpreter._get_op_details(op_idx) # pylint: disable=protected-access + q_idx, f_idx = op_detail['inputs'] + quant_input_detail = self._quant_interpreter._get_tensor_details( # pylint: disable=protected-access + q_idx, subgraph_index=0) + for (metric_name, metric_fn + ) in self._debug_options.layer_direct_compare_metrics.items(): + layer_statistics[tensor_name][metric_name].append( + metric_fn( + self._quant_interpreter.get_tensor(f_idx), + self._quant_interpreter.get_tensor(q_idx), + quant_input_detail['quantization_parameters']['scales'][0], + quant_input_detail['quantization_parameters']['zero_points'] + [0])) + + # Calculate final aggregated metrics for each layer. + for metrics in layer_statistics.values(): + for metric_name in metrics: + metrics[metric_name] = np.nanmean(metrics[metric_name]) + + return layer_statistics + + def _collect_model_statistics(self) -> Dict[str, float]: + """Collects model output metrics. + + For all data from the given RepresentativeDataset, collect all model output + results from float model & quantized debug model, and calculate metrics + by using model output functions. As a result, self.model_results is filled, + + where self.model_results[model_output_function_name] = `aggregated model + output function value` (a scalar). + + Returns: + aggregated per-model output discrepancy metrics. + {metric_name: aggregated_metric} + """ + + model_statistics = collections.defaultdict(list) + + initialize = True + for tensor_data in self._data_gen(): + # Run quantized debug model and collect output results. + self._set_input_tensors(self._quant_interpreter, tensor_data, initialize) + self._quant_interpreter.invoke() + quant_tensor_data = self._get_output_tensors(self._quant_interpreter) + + # Run float model if it's initialized. + float_tensor_data = [] + if self._float_interpreter: + self._set_input_tensors( + self._float_interpreter, tensor_data, initialize) + self._float_interpreter.invoke() + float_tensor_data = self._get_output_tensors(self._float_interpreter) + + initialize = False + + # Calculate the metrics. + for (metric_name, + metric_fn) in self._debug_options.model_debug_metrics.items(): + model_statistics[metric_name].append( + metric_fn(float_tensor_data, quant_tensor_data)) + + # Calculate final aggregated metrics for each outputs. + return { + metric_name: np.mean(metric) + for metric_name, metric in model_statistics.items() + } + + def _set_input_tensors(self, interpreter: _interpreter.Interpreter, + tensor_data: Sequence[np.ndarray], + initialize: bool) -> None: + """Sets input tensors into TFLite model Interpreter. + + Args: + interpreter: a tf.lite.Interpreter object with allocated tensors. + tensor_data: a list of Numpy array data. + initialize: set to true when input is first set for the interpreter, to + set input shapes and allocate tensors. + + Raises: + ValueError: when inputs can't be set, or size of provided inputs does not + match size of model inputs. + """ + input_details = interpreter.get_input_details() + if len(input_details) != len(tensor_data): + raise ValueError( + 'Number of inputs provided ({}) does not match number of inputs to ' + 'the model ({})'.format(len(tensor_data), len(input_details))) + + if initialize: + for input_detail, tensor in zip(input_details, tensor_data): + interpreter.resize_tensor_input(input_detail['index'], tensor.shape) + interpreter.allocate_tensors() + + for input_detail, tensor in zip(input_details, tensor_data): + if tensor.dtype == np.float32 and input_detail['dtype'] == np.int8: + quant_params = _get_quant_params(input_detail) + if quant_params: + scale, zero_point = quant_params + tensor = np.round((tensor / scale) + zero_point).astype(np.int8) + interpreter.set_tensor(input_detail['index'], tensor) + + def _get_output_tensors( + self, interpreter: _interpreter.Interpreter) -> List[np.ndarray]: + """Returns output tensors of given TFLite model Interpreter. + + Args: + interpreter: a tf.lite.Interpreter object with allocated tensors. + + Returns: + a list of numpy arrays representing output tensor results. + """ + + outputs = [] + for output_detail in interpreter.get_output_details(): + tensor = interpreter.get_tensor(output_detail['index']) + if output_detail['dtype'] == np.int8: + quant_params = _get_quant_params(output_detail) + if quant_params: + scale, zero_point = quant_params + tensor = ((tensor.astype(np.float32) - zero_point) * scale).astype( + np.float32) + outputs.append(tensor) + + return outputs + + def _get_numeric_verify_tensor_details(self) -> List[str]: + """Returns all names of all tensors from NumericVerify op.""" + # pylint: disable=protected-access + if not self._numeric_verify_tensor_details: + self._numeric_verify_tensor_details = [] + self._numeric_verify_op_details = {} + for op_info in self._quant_interpreter._get_ops_details(): + if op_info['op_name'] == _NUMERIC_VERIFY_OP_NAME: + self._numeric_verify_tensor_details.append( + self._quant_interpreter._get_tensor_details( + op_info['outputs'][0], subgraph_index=0)) + tensor_name = self._numeric_verify_tensor_details[-1]['name'] + self._numeric_verify_op_details[tensor_name] = op_info + # pylint: enable=protected-access + return self._numeric_verify_tensor_details + + def _get_operand_name_and_index(self, + numeric_verify_name: str) -> Tuple[str, int]: + """Gets the index and name of NumericVerify Op's quantized input tensor. + + Args: + numeric_verify_name: name of the NumericVerify op's output tensor. It has + format of `NumericVerify/{quantized_tensor_name}:{quantized_tensor_idx}` + + Returns: + Tuple of (tensor_name, tensor_idx) for quantized op's output tensor. + """ + tensor_name, tensor_idx = numeric_verify_name.rsplit(':', 1) + float_tensor_name = tensor_name[len(_NUMERIC_VERIFY_OP_NAME) + 1:] + if re.match(r'\d', float_tensor_name[-1]): + float_tensor_name = float_tensor_name[:-1] + + return (float_tensor_name, int(tensor_idx)) + + def layer_statistics_dump(self, file: IO[str]) -> None: + """Dumps layer statistics into file, in csv format. + + Args: + file: file, or file-like object to write. + """ + # order of `fields` is the order of fields in csv. + fields = ['op_name', 'tensor_idx'] + list(self._layer_debug_metrics.keys()) + if self._debug_options.layer_direct_compare_metrics is not None: + fields += list(self._debug_options.layer_direct_compare_metrics.keys()) + fields += ['scale', 'zero_point', 'tensor_name'] + writer = csv.DictWriter(file, fields) + writer.writeheader() + if self.layer_statistics: + for name, metrics in self.layer_statistics.items(): + data = metrics.copy() + (data['tensor_name'], _) = self._get_operand_name_and_index(name) + data['tensor_idx'] = self._numeric_verify_op_details[name]['inputs'][0] + data['op_name'] = self._quant_interpreter._get_op_details( # pylint: disable=protected-access + self._defining_op[data['tensor_idx']])['op_name'] + details = self._quant_interpreter._get_tensor_details( # pylint: disable=protected-access + data['tensor_idx'], subgraph_index=0) + data['scale'], data['zero_point'] = ( + details['quantization_parameters']['scales'][0], + details['quantization_parameters']['zero_points'][0]) + writer.writerow(data) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/visualize.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..3dca3f62b798212ab5d589ed5c4901e072a308ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/lite/tools/visualize.py @@ -0,0 +1,549 @@ +#!/usr/bin/env python +# 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 tool creates an html visualization of a TensorFlow Lite graph. + +Example usage: + +python visualize.py foo.tflite foo.html +""" + +import json +import os +import re +import sys +import numpy as np + +# pylint: disable=g-import-not-at-top +if not os.path.splitext(__file__)[0].endswith( + os.path.join("tflite_runtime", "visualize")): + # This file is part of tensorflow package. + from tensorflow.lite.python import schema_py_generated as schema_fb +else: + # This file is part of tflite_runtime package. + from tflite_runtime import schema_py_generated as schema_fb + +# A CSS description for making the visualizer +_CSS = """ + + + + + + + + +""" + +_D3_HTML_TEMPLATE = """ + +""" + + +def TensorTypeToName(tensor_type): + """Converts a numerical enum to a readable tensor type.""" + for name, value in schema_fb.TensorType.__dict__.items(): + if value == tensor_type: + return name + return None + + +def BuiltinCodeToName(code): + """Converts a builtin op code enum to a readable name.""" + for name, value in schema_fb.BuiltinOperator.__dict__.items(): + if value == code: + return name + return None + + +def NameListToString(name_list): + """Converts a list of integers to the equivalent ASCII string.""" + if isinstance(name_list, str): + return name_list + else: + result = "" + if name_list is not None: + for val in name_list: + result = result + chr(int(val)) + return result + + +class OpCodeMapper: + """Maps an opcode index to an op name.""" + + def __init__(self, data): + self.code_to_name = {} + for idx, d in enumerate(data["operator_codes"]): + self.code_to_name[idx] = BuiltinCodeToName(d["builtin_code"]) + if self.code_to_name[idx] == "CUSTOM": + self.code_to_name[idx] = NameListToString(d["custom_code"]) + + def __call__(self, x): + if x not in self.code_to_name: + s = "" + else: + s = self.code_to_name[x] + return "%s (%d)" % (s, x) + + +class DataSizeMapper: + """For buffers, report the number of bytes.""" + + def __call__(self, x): + if x is not None: + return "%d bytes" % len(x) + else: + return "--" + + +class TensorMapper: + """Maps a list of tensor indices to a tooltip hoverable indicator of more.""" + + def __init__(self, subgraph_data): + self.data = subgraph_data + + def __call__(self, x): + html = "" + if x is None: + return html + + html += "" + for i in x: + tensor = self.data["tensors"][i] + html += str(i) + " " + html += NameListToString(tensor["name"]) + " " + html += TensorTypeToName(tensor["type"]) + " " + html += (repr(tensor["shape"]) if "shape" in tensor else "[]") + html += (repr(tensor["shape_signature"]) + if "shape_signature" in tensor else "[]") + "
" + html += "
" + html += repr(x) + html += "
" + return html + + +def GenerateGraph(subgraph_idx, g, opcode_mapper): + """Produces the HTML required to have a d3 visualization of the dag.""" + + def TensorName(idx): + return "t%d" % idx + + def OpName(idx): + return "o%d" % idx + + edges = [] + nodes = [] + first = {} + second = {} + pixel_mult = 200 # TODO(aselle): multiplier for initial placement + width_mult = 170 # TODO(aselle): multiplier for initial placement + for op_index, op in enumerate(g["operators"] or []): + if op["inputs"] is not None: + for tensor_input_position, tensor_index in enumerate(op["inputs"]): + if tensor_index not in first: + first[tensor_index] = ((op_index - 0.5 + 1) * pixel_mult, + (tensor_input_position + 1) * width_mult) + edges.append({ + "source": TensorName(tensor_index), + "target": OpName(op_index) + }) + if op["outputs"] is not None: + for tensor_output_position, tensor_index in enumerate(op["outputs"]): + if tensor_index not in second: + second[tensor_index] = ((op_index + 0.5 + 1) * pixel_mult, + (tensor_output_position + 1) * width_mult) + edges.append({ + "target": TensorName(tensor_index), + "source": OpName(op_index) + }) + + nodes.append({ + "id": OpName(op_index), + "name": opcode_mapper(op["opcode_index"]), + "group": 2, + "x": pixel_mult, + "y": (op_index + 1) * pixel_mult + }) + for tensor_index, tensor in enumerate(g["tensors"]): + initial_y = ( + first[tensor_index] if tensor_index in first else + second[tensor_index] if tensor_index in second else (0, 0)) + + nodes.append({ + "id": TensorName(tensor_index), + "name": "%r (%d)" % (getattr(tensor, "shape", []), tensor_index), + "group": 1, + "x": initial_y[1], + "y": initial_y[0] + }) + graph_str = json.dumps({"nodes": nodes, "edges": edges}) + + html = _D3_HTML_TEMPLATE % (graph_str, subgraph_idx) + return html + + +def GenerateTableHtml(items, keys_to_print, display_index=True): + """Given a list of object values and keys to print, make an HTML table. + + Args: + items: Items to print an array of dicts. + keys_to_print: (key, display_fn). `key` is a key in the object. i.e. + items[0][key] should exist. display_fn is the mapping function on display. + i.e. the displayed html cell will have the string returned by + `mapping_fn(items[0][key])`. + display_index: add a column which is the index of each row in `items`. + + Returns: + An html table. + """ + html = "" + # Print the list of items + html += "\n" + html += "\n" + if display_index: + html += "" + for h, mapper in keys_to_print: + html += "" % h + html += "\n" + for idx, tensor in enumerate(items): + html += "\n" + if display_index: + html += "" % idx + # print tensor.keys() + for h, mapper in keys_to_print: + val = tensor[h] if h in tensor else None + val = val if mapper is None else mapper(val) + html += "\n" % val + + html += "\n" + html += "
index%s
%d%s
\n" + return html + + +def CamelCaseToSnakeCase(camel_case_input): + """Converts an identifier in CamelCase to snake_case.""" + s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", camel_case_input) + return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower() + + +def FlatbufferToDict(fb, preserve_as_numpy): + """Converts a hierarchy of FB objects into a nested dict. + + We avoid transforming big parts of the flat buffer into python arrays. This + speeds conversion from ten minutes to a few seconds on big graphs. + + Args: + fb: a flat buffer structure. (i.e. ModelT) + preserve_as_numpy: true if all downstream np.arrays should be preserved. + false if all downstream np.array should become python arrays + Returns: + A dictionary representing the flatbuffer rather than a flatbuffer object. + """ + if isinstance(fb, int) or isinstance(fb, float) or isinstance(fb, str): + return fb + elif hasattr(fb, "__dict__"): + result = {} + for attribute_name in dir(fb): + attribute = fb.__getattribute__(attribute_name) + if not callable(attribute) and attribute_name[0] != "_": + snake_name = CamelCaseToSnakeCase(attribute_name) + preserve = True if attribute_name == "buffers" else preserve_as_numpy + result[snake_name] = FlatbufferToDict(attribute, preserve) + return result + elif isinstance(fb, np.ndarray): + return fb if preserve_as_numpy else fb.tolist() + elif hasattr(fb, "__len__"): + return [FlatbufferToDict(entry, preserve_as_numpy) for entry in fb] + else: + return fb + + +def CreateDictFromFlatbuffer(buffer_data): + model_obj = schema_fb.Model.GetRootAsModel(buffer_data, 0) + model = schema_fb.ModelT.InitFromObj(model_obj) + return FlatbufferToDict(model, preserve_as_numpy=False) + + +def create_html(tflite_input, input_is_filepath=True): # pylint: disable=invalid-name + """Returns html description with the given tflite model. + + Args: + tflite_input: TFLite flatbuffer model path or model object. + input_is_filepath: Tells if tflite_input is a model path or a model object. + + Returns: + Dump of the given tflite model in HTML format. + + Raises: + RuntimeError: If the input is not valid. + """ + + # Convert the model into a JSON flatbuffer using flatc (build if doesn't + # exist. + if input_is_filepath: + if not os.path.exists(tflite_input): + raise RuntimeError("Invalid filename %r" % tflite_input) + if tflite_input.endswith(".tflite") or tflite_input.endswith(".bin"): + with open(tflite_input, "rb") as file_handle: + file_data = bytearray(file_handle.read()) + data = CreateDictFromFlatbuffer(file_data) + elif tflite_input.endswith(".json"): + data = json.load(open(tflite_input)) + else: + raise RuntimeError("Input file was not .tflite or .json") + else: + data = CreateDictFromFlatbuffer(tflite_input) + html = "" + html += _CSS + html += "

TensorFlow Lite Model

" + + data["filename"] = tflite_input if input_is_filepath else ( + "Null (used model object)") # Avoid special case + + toplevel_stuff = [("filename", None), ("version", None), + ("description", None)] + + html += "\n" + for key, mapping in toplevel_stuff: + if not mapping: + mapping = lambda x: x + html += "\n" % (key, mapping(data.get(key))) + html += "
%s%s
\n" + + # Spec on what keys to display + buffer_keys_to_display = [("data", DataSizeMapper())] + operator_keys_to_display = [("builtin_code", BuiltinCodeToName), + ("custom_code", NameListToString), + ("version", None)] + + # Update builtin code fields. + for d in data["operator_codes"]: + d["builtin_code"] = max(d["builtin_code"], d["deprecated_builtin_code"]) + + for subgraph_idx, g in enumerate(data["subgraphs"]): + # Subgraph local specs on what to display + html += "
" + tensor_mapper = TensorMapper(g) + opcode_mapper = OpCodeMapper(data) + op_keys_to_display = [("inputs", tensor_mapper), ("outputs", tensor_mapper), + ("builtin_options", None), + ("opcode_index", opcode_mapper)] + tensor_keys_to_display = [("name", NameListToString), + ("type", TensorTypeToName), ("shape", None), + ("shape_signature", None), ("buffer", None), + ("quantization", None)] + + html += "

Subgraph %d

\n" % subgraph_idx + + # Inputs and outputs. + html += "

Inputs/Outputs

\n" + html += GenerateTableHtml([{ + "inputs": g["inputs"], + "outputs": g["outputs"] + }], [("inputs", tensor_mapper), ("outputs", tensor_mapper)], + display_index=False) + + # Print the tensors. + html += "

Tensors

\n" + html += GenerateTableHtml(g["tensors"], tensor_keys_to_display) + + # Print the ops. + if g["operators"]: + html += "

Ops

\n" + html += GenerateTableHtml(g["operators"], op_keys_to_display) + + # Visual graph. + html += "\n" % ( + subgraph_idx,) + html += GenerateGraph(subgraph_idx, g, opcode_mapper) + html += "
" + + # Buffers have no data, but maybe in the future they will + html += "

Buffers

\n" + html += GenerateTableHtml(data["buffers"], buffer_keys_to_display) + + # Operator codes + html += "

Operator Codes

\n" + html += GenerateTableHtml(data["operator_codes"], operator_keys_to_display) + + html += "\n" + + return html + + +def main(argv): + try: + tflite_input = argv[1] + html_output = argv[2] + except IndexError: + print("Usage: %s " % (argv[0])) + else: + html = create_html(tflite_input) + with open(html_output, "w") as output_file: + output_file.write(html) + + +if __name__ == "__main__": + main(sys.argv) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9c52b712be159878b8f950e0111c05ac157d7025 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/__init__.py @@ -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. +# ============================================================================== +"""TensorFlow Python init file.""" + +# Do not add code to //third_party/tensorflow/python/__init__.py. +# This file is imported whenever TensorFlow is imported. +# Additional imports in this file could cause the internal +# import time of TensorFlow to increase by multiple seconds. + + +# Special dunders that we choose to export: +_exported_dunders = set([ + '__version__', + '__git_version__', + '__compiler_version__', + '__cxx11_abi_flag__', + '__monolithic_build__', +]) + +# Expose symbols minus dunders, unless they are allowlisted above. +# This is necessary to export our dunders. +__all__ = [s for s in dir() if s in _exported_dunders or not s.startswith('_')] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_parallel_device.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_parallel_device.pyi new file mode 100644 index 0000000000000000000000000000000000000000..acd2eceacc90f955d309e4e3479d1670807748b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_parallel_device.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def GetParallelDeviceCapsules(arg0: str, arg1: list[str]) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_quantize_training.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_quantize_training.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4eb758e65323e4fe9b1f9483f1968bc05d2f3d3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_quantize_training.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def DoQuantizeTrainingOnGraphDefHelper(arg0: object, arg1: int) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_sanitizers.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_sanitizers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ebf08fa1ed7a48ffac83ffb4ec4f2f33a1cd0d2c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_sanitizers.pyi @@ -0,0 +1,19 @@ +# 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. +# ============================================================================== + +def is_asan_enabled() -> bool: ... +def is_msan_enabled() -> bool: ... +def is_tsan_enabled() -> bool: ... +def is_ubsan_enabled() -> bool: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_tfcompile.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_tfcompile.pyi new file mode 100644 index 0000000000000000000000000000000000000000..db1fbce93fc4ebf8e2aa22556be038ba2efb0730 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_tfcompile.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def Compile(graph: str = ..., config: str = ..., target_triple: str = ..., target_cpu: str = ..., target_features: str = ..., entry_point: str = ..., cpp_class: str = ..., out_function_object: str = ..., out_metadata_object: str = ..., out_header: str = ..., out_session_module: str = ..., mlir_components: str = ..., gen_name_to_index: bool = ..., gen_program_shape: bool = ...) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_tfe.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_tfe.pyi new file mode 100644 index 0000000000000000000000000000000000000000..4fbf8aea6e11a70c6a354921cfdbba8c5def9e21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_tfe.pyi @@ -0,0 +1,372 @@ +# 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. +# ============================================================================== + +from typing import ClassVar + +TFE_DEVICE_PLACEMENT_EXPLICIT: TFE_ContextDevicePlacementPolicy +TFE_DEVICE_PLACEMENT_SILENT: TFE_ContextDevicePlacementPolicy +TFE_DEVICE_PLACEMENT_SILENT_FOR_INT32: TFE_ContextDevicePlacementPolicy +TFE_DEVICE_PLACEMENT_WARN: TFE_ContextDevicePlacementPolicy +TF_ATTR_BOOL: TF_AttrType +TF_ATTR_FLOAT: TF_AttrType +TF_ATTR_FUNC: TF_AttrType +TF_ATTR_INT: TF_AttrType +TF_ATTR_PLACEHOLDER: TF_AttrType +TF_ATTR_SHAPE: TF_AttrType +TF_ATTR_STRING: TF_AttrType +TF_ATTR_TENSOR: TF_AttrType +TF_ATTR_TYPE: TF_AttrType + +class EagerContextThreadLocalData: + device_name: object + device_spec: object + executor: object + function_call_options: object + invoking_op_callbacks: bool + is_eager: bool + op_callbacks: object + scope_name: object + def __init__(self, py_eager_context: object, is_eager: object, device_spec: object) -> None: ... + +class TFE_CancellationManager: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_ContextDevicePlacementPolicy: + __members__: ClassVar[dict] = ... # read-only + TFE_DEVICE_PLACEMENT_EXPLICIT: ClassVar[TFE_ContextDevicePlacementPolicy] = ... + TFE_DEVICE_PLACEMENT_SILENT: ClassVar[TFE_ContextDevicePlacementPolicy] = ... + TFE_DEVICE_PLACEMENT_SILENT_FOR_INT32: ClassVar[TFE_ContextDevicePlacementPolicy] = ... + TFE_DEVICE_PLACEMENT_WARN: ClassVar[TFE_ContextDevicePlacementPolicy] = ... + __entries: ClassVar[dict] = ... + def __init__(self, value: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> None: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class TFE_ContextOptions: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_Executor: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringBoolGauge0: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringBoolGauge1: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringBoolGauge2: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringBoolGaugeCell: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringBuckets: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringCounter0: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringCounter1: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringCounter2: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringCounterCell: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringIntGauge0: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringIntGauge1: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringIntGauge2: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringIntGaugeCell: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringSampler0: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringSampler1: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringSampler2: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringSamplerCell: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringStringGauge0: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringStringGauge1: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringStringGauge2: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringStringGauge3: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringStringGauge4: + def __init__(self, *args, **kwargs) -> None: ... + +class TFE_MonitoringStringGaugeCell: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_AttrType: + __members__: ClassVar[dict] = ... # read-only + TF_ATTR_BOOL: ClassVar[TF_AttrType] = ... + TF_ATTR_FLOAT: ClassVar[TF_AttrType] = ... + TF_ATTR_FUNC: ClassVar[TF_AttrType] = ... + TF_ATTR_INT: ClassVar[TF_AttrType] = ... + TF_ATTR_PLACEHOLDER: ClassVar[TF_AttrType] = ... + TF_ATTR_SHAPE: ClassVar[TF_AttrType] = ... + TF_ATTR_STRING: ClassVar[TF_AttrType] = ... + TF_ATTR_TENSOR: ClassVar[TF_AttrType] = ... + TF_ATTR_TYPE: ClassVar[TF_AttrType] = ... + __entries: ClassVar[dict] = ... + def __init__(self, value: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> None: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class TF_Buffer: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_DeviceList: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Function: + def __init__(self, *args, **kwargs) -> None: ... + +def TFE_AbortCollectiveOps(arg0: object, arg1: int, arg2: str) -> None: ... +def TFE_CancellationManagerIsCancelled(arg0: TFE_CancellationManager) -> bool: ... +def TFE_CancellationManagerStartCancel(arg0: TFE_CancellationManager) -> None: ... +def TFE_ClearScalarCache() -> object: ... +def TFE_CollectiveOpsCheckPeerHealth(arg0: object, arg1: str, arg2: int) -> None: ... +def TFE_ContextAddFunction(arg0: object, arg1: TF_Function) -> None: ... +def TFE_ContextAddFunctionDef(arg0: object, arg1: str, arg2: int) -> None: ... +def TFE_ContextCheckAlive(arg0: object, arg1: str) -> bool: ... +def TFE_ContextClearCaches(arg0: object) -> None: ... +def TFE_ContextClearExecutors(arg0: object) -> None: ... +def TFE_ContextDisableGraphCollection(arg0: object) -> None: ... +def TFE_ContextDisableRunMetadata(arg0: object) -> None: ... +def TFE_ContextEnableGraphCollection(arg0: object) -> None: ... +def TFE_ContextEnableRunMetadata(arg0: object) -> None: ... +def TFE_ContextExportRunMetadata(arg0: object, arg1: TF_Buffer) -> None: ... +def TFE_ContextGetDevicePlacementPolicy(arg0: object) -> TFE_ContextDevicePlacementPolicy: ... +def TFE_ContextGetExecutorForThread(arg0: object) -> TFE_Executor: ... +def TFE_ContextGetFunction(arg0: object, arg1: str) -> TF_Function: ... +def TFE_ContextGetFunctionDef(arg0: object, arg1: str, arg2: TF_Buffer) -> None: ... +def TFE_ContextGetGraphDebugInfo(arg0: object, arg1: str, arg2: TF_Buffer) -> None: ... +def TFE_ContextHasFunction(arg0: object, arg1: str) -> int: ... +def TFE_ContextListDevices(arg0: object) -> TF_DeviceList: ... +def TFE_ContextListFunctionNames(arg0: object) -> list[str]: ... +def TFE_ContextOptionsSetAsync(arg0: TFE_ContextOptions, arg1: int) -> None: ... +def TFE_ContextOptionsSetConfig(arg0: TFE_ContextOptions, arg1: bytes) -> None: ... +def TFE_ContextOptionsSetDevicePlacementPolicy(arg0: TFE_ContextOptions, arg1: TFE_ContextDevicePlacementPolicy) -> None: ... +def TFE_ContextOptionsSetJitCompileRewrite(arg0: TFE_ContextOptions, arg1: bool) -> None: ... +def TFE_ContextOptionsSetRunEagerOpAsFunction(arg0: TFE_ContextOptions, arg1: bool) -> None: ... +def TFE_ContextOptionsSetTfrt(arg0: TFE_ContextOptions, arg1: bool) -> None: ... +def TFE_ContextRemoveFunction(arg0: object, arg1: str) -> None: ... +def TFE_ContextSetExecutorForThread(arg0: object, arg1: TFE_Executor) -> None: ... +def TFE_ContextSetJitCompileRewrite(arg0: object, arg1: bool) -> None: ... +def TFE_ContextSetLogDevicePlacement(arg0: object, arg1: bool) -> None: ... +def TFE_ContextSetRunEagerOpAsFunction(arg0: object, arg1: bool) -> None: ... +def TFE_ContextSetServerDef(arg0: object, arg1: int, arg2: bytes) -> None: ... +def TFE_ContextSetServerDefWithTimeoutAndRetries(arg0: object, arg1: int, arg2: bytes, arg3: int, arg4: int) -> None: ... +def TFE_ContextSetSoftDevicePlacement(arg0: object, arg1: bool) -> None: ... +def TFE_ContextSetThreadLocalDevicePlacementPolicy(arg0: object, arg1: TFE_ContextDevicePlacementPolicy) -> None: ... +def TFE_ContextSyncExecutors(arg0: object) -> None: ... +def TFE_ContextUpdateServerDef(arg0: object, arg1: int, arg2: bytes) -> None: ... +def TFE_DeleteConfigKeyValue(arg0: object, arg1: str) -> None: ... +def TFE_DeleteContext(arg0: object) -> None: ... +def TFE_DeleteContextOptions(arg0: TFE_ContextOptions) -> None: ... +def TFE_DeleteExecutor(arg0: TFE_Executor) -> None: ... +def TFE_EnableCollectiveOps(arg0: object, arg1: bytes) -> None: ... +def TFE_ExecutorClearError(arg0: TFE_Executor) -> None: ... +def TFE_ExecutorIsAsync(arg0: TFE_Executor) -> bool: ... +def TFE_ExecutorWaitForAllPendingNodes(arg0: TFE_Executor) -> None: ... +def TFE_FromDlpackCapsule(arg0, arg1: object) -> object: ... +def TFE_GetConfigKeyValue(arg0: object, arg1: str, arg2: int, arg3: TF_Buffer) -> None: ... +def TFE_GetContextId(arg0: object) -> int: ... +def TFE_GetMemoryInfo(arg0: object, arg1: str) -> dict[str,int]: ... +def TFE_GetTaskStates(arg0: object, arg1: list[str], arg2: list[int]) -> object: ... +def TFE_HostAddressSpace(arg0: object, arg1: TF_Buffer) -> None: ... +def TFE_InsertConfigKeyValue(arg0: object, arg1: str, arg2: str) -> None: ... +def TFE_MonitoringBoolGaugeCellSet(arg0: TFE_MonitoringBoolGaugeCell, arg1: bool) -> None: ... +def TFE_MonitoringBoolGaugeCellValue(arg0: TFE_MonitoringBoolGaugeCell) -> bool: ... +def TFE_MonitoringCounterCellIncrementBy(arg0: TFE_MonitoringCounterCell, arg1: int) -> None: ... +def TFE_MonitoringCounterCellValue(arg0: TFE_MonitoringCounterCell) -> int: ... +def TFE_MonitoringDeleteBoolGauge0(arg0: TFE_MonitoringBoolGauge0) -> None: ... +def TFE_MonitoringDeleteBoolGauge1(arg0: TFE_MonitoringBoolGauge1) -> None: ... +def TFE_MonitoringDeleteBoolGauge2(arg0: TFE_MonitoringBoolGauge2) -> None: ... +def TFE_MonitoringDeleteBuckets(arg0: TFE_MonitoringBuckets) -> None: ... +def TFE_MonitoringDeleteCounter0(arg0: TFE_MonitoringCounter0) -> None: ... +def TFE_MonitoringDeleteCounter1(arg0: TFE_MonitoringCounter1) -> None: ... +def TFE_MonitoringDeleteCounter2(arg0: TFE_MonitoringCounter2) -> None: ... +def TFE_MonitoringDeleteIntGauge0(arg0: TFE_MonitoringIntGauge0) -> None: ... +def TFE_MonitoringDeleteIntGauge1(arg0: TFE_MonitoringIntGauge1) -> None: ... +def TFE_MonitoringDeleteIntGauge2(arg0: TFE_MonitoringIntGauge2) -> None: ... +def TFE_MonitoringDeleteSampler0(arg0: TFE_MonitoringSampler0) -> None: ... +def TFE_MonitoringDeleteSampler1(arg0: TFE_MonitoringSampler1) -> None: ... +def TFE_MonitoringDeleteSampler2(arg0: TFE_MonitoringSampler2) -> None: ... +def TFE_MonitoringDeleteStringGauge0(arg0: TFE_MonitoringStringGauge0) -> None: ... +def TFE_MonitoringDeleteStringGauge1(arg0: TFE_MonitoringStringGauge1) -> None: ... +def TFE_MonitoringDeleteStringGauge2(arg0: TFE_MonitoringStringGauge2) -> None: ... +def TFE_MonitoringDeleteStringGauge3(arg0: TFE_MonitoringStringGauge3) -> None: ... +def TFE_MonitoringDeleteStringGauge4(arg0: TFE_MonitoringStringGauge4) -> None: ... +def TFE_MonitoringGetCellBoolGauge0(arg0: TFE_MonitoringBoolGauge0) -> TFE_MonitoringBoolGaugeCell: ... +def TFE_MonitoringGetCellBoolGauge1(arg0: TFE_MonitoringBoolGauge1, arg1: str) -> TFE_MonitoringBoolGaugeCell: ... +def TFE_MonitoringGetCellBoolGauge2(arg0: TFE_MonitoringBoolGauge2, arg1: str, arg2: str) -> TFE_MonitoringBoolGaugeCell: ... +def TFE_MonitoringGetCellCounter0(arg0: TFE_MonitoringCounter0) -> TFE_MonitoringCounterCell: ... +def TFE_MonitoringGetCellCounter1(arg0: TFE_MonitoringCounter1, arg1: str) -> TFE_MonitoringCounterCell: ... +def TFE_MonitoringGetCellCounter2(arg0: TFE_MonitoringCounter2, arg1: str, arg2: str) -> TFE_MonitoringCounterCell: ... +def TFE_MonitoringGetCellIntGauge0(arg0: TFE_MonitoringIntGauge0) -> TFE_MonitoringIntGaugeCell: ... +def TFE_MonitoringGetCellIntGauge1(arg0: TFE_MonitoringIntGauge1, arg1: str) -> TFE_MonitoringIntGaugeCell: ... +def TFE_MonitoringGetCellIntGauge2(arg0: TFE_MonitoringIntGauge2, arg1: str, arg2: str) -> TFE_MonitoringIntGaugeCell: ... +def TFE_MonitoringGetCellSampler0(arg0: TFE_MonitoringSampler0) -> TFE_MonitoringSamplerCell: ... +def TFE_MonitoringGetCellSampler1(arg0: TFE_MonitoringSampler1, arg1: str) -> TFE_MonitoringSamplerCell: ... +def TFE_MonitoringGetCellSampler2(arg0: TFE_MonitoringSampler2, arg1: str, arg2: str) -> TFE_MonitoringSamplerCell: ... +def TFE_MonitoringGetCellStringGauge0(arg0: TFE_MonitoringStringGauge0) -> TFE_MonitoringStringGaugeCell: ... +def TFE_MonitoringGetCellStringGauge1(arg0: TFE_MonitoringStringGauge1, arg1: str) -> TFE_MonitoringStringGaugeCell: ... +def TFE_MonitoringGetCellStringGauge2(arg0: TFE_MonitoringStringGauge2, arg1: str, arg2: str) -> TFE_MonitoringStringGaugeCell: ... +def TFE_MonitoringGetCellStringGauge3(arg0: TFE_MonitoringStringGauge3, arg1: str, arg2: str, arg3: str) -> TFE_MonitoringStringGaugeCell: ... +def TFE_MonitoringGetCellStringGauge4(arg0: TFE_MonitoringStringGauge4, arg1: str, arg2: str, arg3: str, arg4: str) -> TFE_MonitoringStringGaugeCell: ... +def TFE_MonitoringIntGaugeCellSet(arg0: TFE_MonitoringIntGaugeCell, arg1: int) -> None: ... +def TFE_MonitoringIntGaugeCellValue(arg0: TFE_MonitoringIntGaugeCell) -> int: ... +def TFE_MonitoringNewBoolGauge0(arg0: str, arg1: str) -> TFE_MonitoringBoolGauge0: ... +def TFE_MonitoringNewBoolGauge1(arg0: str, arg1: str, arg2: str) -> TFE_MonitoringBoolGauge1: ... +def TFE_MonitoringNewBoolGauge2(arg0: str, arg1: str, arg2: str, arg3: str) -> TFE_MonitoringBoolGauge2: ... +def TFE_MonitoringNewCounter0(arg0: str, arg1: str) -> TFE_MonitoringCounter0: ... +def TFE_MonitoringNewCounter1(arg0: str, arg1: str, arg2: str) -> TFE_MonitoringCounter1: ... +def TFE_MonitoringNewCounter2(arg0: str, arg1: str, arg2: str, arg3: str) -> TFE_MonitoringCounter2: ... +def TFE_MonitoringNewExponentialBuckets(arg0: float, arg1: float, arg2: int) -> TFE_MonitoringBuckets: ... +def TFE_MonitoringNewIntGauge0(arg0: str, arg1: str) -> TFE_MonitoringIntGauge0: ... +def TFE_MonitoringNewIntGauge1(arg0: str, arg1: str, arg2: str) -> TFE_MonitoringIntGauge1: ... +def TFE_MonitoringNewIntGauge2(arg0: str, arg1: str, arg2: str, arg3: str) -> TFE_MonitoringIntGauge2: ... +def TFE_MonitoringNewSampler0(arg0: str, arg1: TFE_MonitoringBuckets, arg2: str) -> TFE_MonitoringSampler0: ... +def TFE_MonitoringNewSampler1(arg0: str, arg1: TFE_MonitoringBuckets, arg2: str, arg3: str) -> TFE_MonitoringSampler1: ... +def TFE_MonitoringNewSampler2(arg0: str, arg1: TFE_MonitoringBuckets, arg2: str, arg3: str, arg4: str) -> TFE_MonitoringSampler2: ... +def TFE_MonitoringNewStringGauge0(arg0: str, arg1: str) -> TFE_MonitoringStringGauge0: ... +def TFE_MonitoringNewStringGauge1(arg0: str, arg1: str, arg2: str) -> TFE_MonitoringStringGauge1: ... +def TFE_MonitoringNewStringGauge2(arg0: str, arg1: str, arg2: str, arg3: str) -> TFE_MonitoringStringGauge2: ... +def TFE_MonitoringNewStringGauge3(arg0: str, arg1: str, arg2: str, arg3: str, arg4: str) -> TFE_MonitoringStringGauge3: ... +def TFE_MonitoringNewStringGauge4(arg0: str, arg1: str, arg2: str, arg3: str, arg4: str, arg5: str) -> TFE_MonitoringStringGauge4: ... +def TFE_MonitoringSamplerCellAdd(arg0: TFE_MonitoringSamplerCell, arg1: float) -> None: ... +def TFE_MonitoringSamplerCellValue(arg0: TFE_MonitoringSamplerCell, arg1: TF_Buffer) -> None: ... +def TFE_MonitoringStringGaugeCellSet(arg0: TFE_MonitoringStringGaugeCell, arg1: str) -> None: ... +def TFE_MonitoringStringGaugeCellValue(arg0: TFE_MonitoringStringGaugeCell, arg1: TF_Buffer) -> None: ... +def TFE_NewCancellationManager() -> TFE_CancellationManager: ... +def TFE_NewContext(arg0: TFE_ContextOptions) -> object: ... +def TFE_NewContextOptions() -> TFE_ContextOptions: ... +def TFE_NewExecutor(arg0: bool, arg1: bool, arg2: int) -> TFE_Executor: ... +def TFE_OpNameGetAttrType(arg0: object, arg1: str, arg2: str) -> object: ... +def TFE_Py_EnableInteractivePythonLogging() -> None: ... +def TFE_Py_Execute(arg0: object, arg1: str, arg2: str, arg3: object, arg4: object, arg5: object) -> object: ... +def TFE_Py_ExecuteCancelable(arg0: object, arg1: str, arg2: str, arg3: object, arg4: object, arg5: TFE_CancellationManager, arg6: object) -> object: ... +def TFE_Py_FastPathExecute(*args) -> object: ... +def TFE_Py_ForwardAccumulatorJVP(arg0: object, arg1: object) -> object: ... +def TFE_Py_ForwardAccumulatorNew(arg0: bool) -> object: ... +def TFE_Py_ForwardAccumulatorPopState() -> object: ... +def TFE_Py_ForwardAccumulatorPushState() -> object: ... +def TFE_Py_ForwardAccumulatorSetAdd(arg0: object) -> object: ... +def TFE_Py_ForwardAccumulatorSetRemove(arg0: object) -> None: ... +def TFE_Py_ForwardAccumulatorWatch(arg0: object, arg1: object, arg2: object) -> None: ... +def TFE_Py_InitEagerTensor(arg0: object) -> object: ... +def TFE_Py_IsCustomDevice(arg0: object, arg1: str) -> bool: ... +def TFE_Py_PackEagerTensors(arg0: object, arg1: object) -> object: ... +def TFE_Py_PackJVPs(arg0: object) -> object: ... +def TFE_Py_RecordGradient(arg0: object, arg1: object, arg2: object, arg3: object, arg4: object) -> object: ... +def TFE_Py_RegisterCustomDevice(arg0: object, arg1, arg2: str, arg3) -> None: ... +def TFE_Py_RegisterExceptionClass(arg0: object) -> object: ... +def TFE_Py_RegisterFallbackExceptionClass(arg0: object) -> object: ... +def TFE_Py_RegisterGradientFunction(arg0: object) -> object: ... +def TFE_Py_RegisterJVPFunction(arg0: object) -> object: ... +def TFE_Py_RegisterVSpace(arg0: object) -> object: ... +def TFE_Py_SetCEagerContext(arg0: object) -> None: ... +def TFE_Py_SetEagerContext(arg0: object) -> object: ... +def TFE_Py_SetEagerTensorProfiler(arg0: object) -> object: ... +def TFE_Py_TapeGradient(arg0: object, arg1: object, arg2: object, arg3: object, arg4: object, arg5: object) -> object: ... +def TFE_Py_TapeSetAdd(arg0: object) -> None: ... +def TFE_Py_TapeSetDeleteTrace(arg0: int) -> None: ... +def TFE_Py_TapeSetIsEmpty() -> object: ... +def TFE_Py_TapeSetIsStopped() -> object: ... +def TFE_Py_TapeSetNew(arg0: object, arg1: object) -> object: ... +def TFE_Py_TapeSetPossibleGradientTypes(arg0: object) -> object: ... +def TFE_Py_TapeSetRecordOperation(arg0: object, arg1: object, arg2: object, arg3: object, arg4: object) -> object: ... +def TFE_Py_TapeSetRecordOperationBackprop(arg0: object, arg1: object, arg2: object, arg3: object) -> object: ... +def TFE_Py_TapeSetRecordOperationForwardprop(arg0: object, arg1: object, arg2: object, arg3: object, arg4: object) -> object: ... +def TFE_Py_TapeSetRemove(arg0: object) -> None: ... +def TFE_Py_TapeSetRestartOnThread() -> None: ... +def TFE_Py_TapeSetShouldRecordBackprop(arg0: object) -> object: ... +def TFE_Py_TapeSetStopOnThread() -> None: ... +def TFE_Py_TapeVariableAccessed(arg0: object) -> None: ... +def TFE_Py_TapeWatch(arg0: object, arg1: object) -> None: ... +def TFE_Py_TapeWatchVariable(arg0: object, arg1: object) -> None: ... +def TFE_Py_TapeWatchedVariables(arg0: object) -> object: ... +def TFE_Py_TensorShapeOnDevice(arg0: object, arg1: int) -> object: ... +def TFE_Py_TensorShapeSlice(arg0: object, arg1: int) -> object: ... +def TFE_Py_UID() -> object: ... +def TFE_Py_VariableWatcherNew() -> object: ... +def TFE_Py_VariableWatcherRemove(arg0: object) -> None: ... +def TFE_Py_VariableWatcherVariableAccessed(arg0: object) -> None: ... +def TFE_Py_VariableWatcherWatchedVariables(arg0: object) -> object: ... +def TFE_ReportErrorToCluster(arg0: object, arg1: int, arg2: str) -> None: ... +def TFE_ResetMemoryStats(arg0: object, arg1: str) -> None: ... +def TFE_SetLogicalCpuDevices(arg0: object, arg1: int, arg2: str) -> None: ... +def TFE_ToDlpackCapsule(arg0: object): ... +def TFE_WaitAtBarrier(arg0: object, arg1: str, arg2: int) -> None: ... +def TF_DeleteDeviceList(arg0: TF_DeviceList) -> None: ... +def TF_DeviceListCount(arg0: TF_DeviceList) -> int: ... +def TF_DeviceListName(arg0: TF_DeviceList, arg1: int) -> str: ... +def TF_DeviceListType(arg0: TF_DeviceList, arg1: int) -> str: ... +def TF_EnableMlirBridge(arg0: bool) -> None: ... +def TF_EnableXlaDevices() -> None: ... +def TF_GetCompilerIr(arg0: object, arg1: str, arg2: str, arg3: str, arg4: object, arg5: object) -> bytes: ... +def TF_GetDeviceDetails(arg0: int) -> dict[str,str]: ... +def TF_GetXlaConstantFoldingDisabled() -> int: ... +def TF_IsMlirBridgeEnabled() -> int: ... +def TF_ListPhysicalDevices() -> object: ... +def TF_ListPluggablePhysicalDevices() -> object: ... +def TF_NewBufferFromString(arg0, arg1: int) -> TF_Buffer: ... +def TF_PickUnusedPortOrDie() -> int: ... +def TF_ResetJitCompilerFlags() -> None: ... +def TF_SetTfXlaCpuGlobalJit(arg0: int) -> int: ... +def TF_SetXlaAutoJitMode(arg0: str) -> None: ... +def TF_SetXlaConstantFoldingDisabled(arg0: int) -> None: ... +def TF_SetXlaEnableLazyCompilation(arg0: int) -> int: ... +def TF_SetXlaMinClusterSize(arg0: int) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_toco_api.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_toco_api.pyi new file mode 100644 index 0000000000000000000000000000000000000000..619c686c336c3254a69d8710a129d7df415ad5ae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/_pywrap_toco_api.pyi @@ -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. +# ============================================================================== + +def ExperimentalMlirQuantizeModel(input_contents_txt_raw: object, disable_per_channel: bool = ..., fully_quantize: bool = ..., inference_type: int = ..., input_data_type: int = ..., output_data_type: int = ..., enable_numeric_verify: bool = ..., enable_whole_model_verify: bool = ..., op_blocklist: object = ..., node_blocklist: object = ..., enable_variable_quantization: bool = ...) -> object: ... +def ExperimentalMlirSparsifyModel(input_contents_txt_raw: object) -> object: ... +def FlatBufferToMlir(arg0: str, arg1: bool) -> str: ... +def RegisterCustomOpdefs(custom_opdefs_txt_raw: object) -> object: ... +def RetrieveCollectedErrors() -> list: ... +def TocoConvert(model_flags_proto_txt_raw: object, toco_flags_proto_txt_raw: object, input_contents_txt_raw: object, extended_return: bool = ..., debug_info_txt_raw: object = ..., enable_mlir_converter: bool = ...) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e37691961fb3f6c6e611edce7fa7247ce648b5cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/__init__.py @@ -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. +# ============================================================================== +"""Conversion of eager-style Python into TensorFlow graph code. + +NOTE: In TensorFlow 2.0, AutoGraph is automatically applied when using +`tf.function`. This module contains lower-level APIs for advanced use. + +AutoGraph transforms a subset of Python which operates on TensorFlow objects +into equivalent TensorFlow graph code. When executing the graph, it has the same +effect as if you ran the original code in eager mode. +Python code which doesn't operate on TensorFlow objects remains functionally +unchanged, but keep in mind that `tf.function` only executes such code at trace +time, and generally will not be consistent with eager execution. + +For more information, see the +[AutoGraph reference documentation](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/index.md), +and the [tf.function guide](https://www.tensorflow.org/guide/function#autograph_transformations). +""" + +from tensorflow.python.util.all_util import remove_undocumented + +# TODO(mdan): Revisit this list once we finalize the generated code mechanism. +_allowed_symbols = [ + # Main API + 'AutoGraphError', + 'ConversionOptions', + 'Feature', + 'StackTraceMapper', + 'convert', + 'converted_call', + 'do_not_convert', + 'to_code', + 'to_graph', + # Overloaded operators + 'operators', + # Python language "extensions" + 'set_element_type', + 'set_loop_options', + 'stack', + 'tensor_list', + # Utilities: to be removed + 'utils', +] + +remove_undocumented(__name__, _allowed_symbols) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/asserts.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/asserts.py new file mode 100644 index 0000000000000000000000000000000000000000..68f20a7fca5a666fb559c8f64428ec3fc8ed1fcc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/asserts.py @@ -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. +# ============================================================================== +"""Converts assert statements to their corresponding TF calls.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import templates + + +class AssertTransformer(converter.Base): + """Transforms Assert nodes to Call so they can be handled as functions.""" + + def visit_Assert(self, node): + self.generic_visit(node) + + # Note: The lone tf.Assert call will be wrapped with control_dependencies + # by side_effect_guards. + template = """ + ag__.assert_stmt(test, lambda: msg) + """ + + if node.msg is None: + return templates.replace( + template, + test=node.test, + msg=gast.Constant('Assertion error', kind=None)) + elif isinstance(node.msg, gast.Constant): + return templates.replace(template, test=node.test, msg=node.msg) + else: + raise NotImplementedError('can only convert string messages for now.') + + +def transform(node, ctx): + node = AssertTransformer(ctx).visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/break_statements.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/break_statements.py new file mode 100644 index 0000000000000000000000000000000000000000..f91c943f2145ef4c7ea6b10dce7fd1cf0d56a7bd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/break_statements.py @@ -0,0 +1,185 @@ +# 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. +# ============================================================================== +"""Lowers break statements to conditionals.""" + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno + + +class _Break(object): + + def __init__(self): + self.used = False + self.control_var_name = None + + def __repr__(self): + return 'used: %s, var: %s' % (self.used, self.control_var_name) + + +class BreakTransformer(converter.Base): + """Canonicalizes break statements into additional conditionals.""" + + def visit_Break(self, node): + self.state[_Break].used = True + var_name = self.state[_Break].control_var_name + # TODO(mdan): This will fail when expanded inside a top-level else block. + template = """ + var_name = True + continue + """ + return templates.replace(template, var_name=var_name) + + def _guard_if_present(self, block, var_name): + """Prevents the block from executing if var_name is set.""" + if not block: + return block + + template = """ + if not var_name: + block + """ + node = templates.replace( + template, + var_name=var_name, + block=block) + return node + + def _process_body(self, nodes, break_var): + self.state[_Break].enter() + self.state[_Break].control_var_name = break_var + nodes = self.visit_block(nodes) + break_used = self.state[_Break].used + self.state[_Break].exit() + return nodes, break_used + + def visit_While(self, node): + original_node = node + scope = anno.getanno(node, NodeAnno.BODY_SCOPE) + break_var = self.ctx.namer.new_symbol('break_', scope.referenced) + + node.test = self.visit(node.test) + node.body, break_used = self._process_body(node.body, break_var) + # A break in the else clause applies to the containing scope. + node.orelse = self.visit_block(node.orelse) + + if not break_used: + template = """ + while test: + body + orelse + """ + node = templates.replace( + template, test=node.test, body=node.body, orelse=node.orelse) + + new_while_node = node[0] + anno.copyanno(original_node, new_while_node, anno.Basic.DIRECTIVES) + + return node + + # Python's else clause only triggers if the loop exited cleanly (e.g. + # break did not trigger). + guarded_orelse = self._guard_if_present(node.orelse, break_var) + + template = """ + var_name = False + while not var_name and test: + body + orelse + """ + node = templates.replace( + template, + var_name=break_var, + test=node.test, + body=node.body, + orelse=guarded_orelse) + + new_while_node = node[1] + anno.copyanno(original_node, new_while_node, anno.Basic.DIRECTIVES) + + return node + + def visit_For(self, node): + original_node = node + scope = anno.getanno(node, NodeAnno.BODY_SCOPE) + break_var = self.ctx.namer.new_symbol('break_', scope.referenced) + + node.target = self.visit(node.target) + node.iter = self.visit(node.iter) + node.body, break_used = self._process_body(node.body, break_var) + # A break in the else clause applies to the containing scope. + node.orelse = self.visit_block(node.orelse) + + if not break_used: + template = """ + for target in iter_: + body + orelse + """ + node = templates.replace( + template, + iter_=node.iter, + target=node.target, + body=node.body, + orelse=node.orelse) + + new_for_node = node[0] + anno.copyanno(original_node, new_for_node, anno.Basic.EXTRA_LOOP_TEST) + anno.copyanno(original_node, new_for_node, anno.Basic.DIRECTIVES) + + return node + + # Python's else clause only triggers if the loop exited cleanly (e.g. + # break did not trigger). + guarded_orelse = self._guard_if_present(node.orelse, break_var) + extra_test = templates.replace_as_expression( + 'not var_name', var_name=break_var) + + # The extra test is hidden in the AST, which will confuse the static + # analysis. To mitigate that, we insert a no-op statement that ensures + # the control variable is marked as used. + # TODO(mdan): Use a marker instead, e.g. ag__.condition_loop_on(var_name) + template = """ + var_name = False + for target in iter_: + (var_name,) + body + orelse + """ + node = templates.replace( + template, + var_name=break_var, + iter_=node.iter, + target=node.target, + body=node.body, + orelse=guarded_orelse) + + new_for_node = node[1] + anno.setanno(new_for_node, anno.Basic.EXTRA_LOOP_TEST, extra_test) + anno.copyanno(original_node, new_for_node, anno.Basic.DIRECTIVES) + + return node + + +def transform(node, ctx): + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + + transformer = BreakTransformer(ctx) + node = transformer.visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/call_trees.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/call_trees.py new file mode 100644 index 0000000000000000000000000000000000000000..3d694d45a17b0b7b9d8fc9a256020b81779f8924 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/call_trees.py @@ -0,0 +1,221 @@ +# 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. +# ============================================================================== +"""Handles function calls, by generating compiled function names and calls. + +Note: this transformer does not rename the top level object being converted; +that is the caller's responsibility. + +Requires function_scopes. +""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.utils import ag_logging + + +# TODO(mdan): Rename to FunctionCallsTransformer. + + +class _Function(object): + + no_root = True + + def __init__(self): + self.context_name = None + + +set_trace_warned = False + + +class _ArgTemplateBuilder(object): + """Constructs a tuple representing the positional arguments in a call. + + Example (yes, it's legal Python 3): + + f(*args1, b, *args2, c, d) -> args1 + (b,) + args2 + (c, d) + """ + + def __init__(self): + self._arg_accumulator = [] + self._argspec = [] + self._finalized = False + + def _consume_args(self): + if self._arg_accumulator: + self._argspec.append( + gast.Tuple(elts=self._arg_accumulator, ctx=gast.Load())) + self._arg_accumulator = [] + + def add_arg(self, a): + self._arg_accumulator.append(a) + + def add_stararg(self, a): + self._consume_args() + self._argspec.append( + gast.Call( + gast.Name( + 'tuple', ctx=gast.Load(), annotation=None, type_comment=None), + args=[a], + keywords=())) + + def finalize(self): + self._consume_args() + self._finalized = True + + def to_ast(self): + assert self._finalized + if self._argspec: + result = self._argspec[0] + for i in range(1, len(self._argspec)): + result = gast.BinOp(result, gast.Add(), self._argspec[i]) + return result + return gast.Tuple([], gast.Load()) + + +class CallTreeTransformer(converter.Base): + """Transforms the call tree by renaming transformed symbols.""" + + def visit_Lambda(self, node): + if not anno.hasanno(node, 'function_context_name'): + # Lambda functions created during the conversion process have no + # context manager. + return self.generic_visit(node) + with self.state[_Function] as fn_scope: + fn_scope.context_name = anno.getanno(node, 'function_context_name') + return self.generic_visit(node) + + def visit_FunctionDef(self, node): + # Decorators and arg defaults are part of the outer scope. + node.decorator_list = self.visit_block(node.decorator_list) + node.args.defaults = self.visit_block(node.args.defaults) + for i, d in enumerate(node.args.kw_defaults): + if d is not None: + node.args.kw_defaults[i] = self.visit(d) + with self.state[_Function] as fn_scope: + # Note: if the conversion process ever creates helper functions, this + # assumption will no longer hold. + assert anno.hasanno(node, 'function_context_name'), ( + 'The function_scopes converter always creates a scope for functions.') + fn_scope.context_name = anno.getanno(node, 'function_context_name') + node.body = self.visit_block(node.body) + if node.returns: + node.returns = self.visit(node.returns) + return node + + def visit_With(self, node): + # Context manager calls (in node.items) are not converted. + node.body = self.visit_block(node.body) + return node + + def _args_to_tuple(self, node): + """Ties together all positional and *arg arguments in a single tuple.""" + # TODO(mdan): We could rewrite this to just a call to tuple(). Maybe better? + # For example for + # f(a, b, *args) + # instead of writing: + # (a, b) + args + # just write this? + # tuple(a, b, *args) + builder = _ArgTemplateBuilder() + for a in node.args: + if isinstance(a, gast.Starred): + builder.add_stararg(a.value) + else: + builder.add_arg(a) + builder.finalize() + return builder.to_ast() + + def _kwargs_to_dict(self, node): + """Ties together all keyword and **kwarg arguments in a single dict.""" + if node.keywords: + return gast.Call( + gast.Name( + 'dict', ctx=gast.Load(), annotation=None, type_comment=None), + args=(), + keywords=node.keywords) + else: + return parser.parse_expression('None') + + def visit_Call(self, node): + full_name = str(anno.getanno(node.func, anno.Basic.QN, default='')) + function_context_name = self.state[_Function].context_name + node = self.generic_visit(node) + + # TODO(mdan): Refactor converted_call as a 'Call' operator. + + # Calls to the internal 'ag__' module are never converted (though their + # arguments might be). + if full_name.startswith('ag__.'): + return node + + # Calls to the function context manager (inserted by function_scopes) are + # also safe. + if full_name.startswith(function_context_name + '.'): + return node + + # Calls to pdb.set_trace or ipdb.set_trace are never converted. We don't use + # the normal mechanisms to bypass these literals because they are sensitive + # to the frame they are being called from. + # TODO(mdan): Generalize this to a "static allowlist" config. + if full_name in ('pdb.set_trace', 'ipdb.set_trace', 'breakpoint'): + global set_trace_warned + if not set_trace_warned: + # TODO(mdan): Update and shorten once available on tensorflow.org. + ag_logging.warning( + 'Detected `pdb.set_trace()` in user code. The code' + ' generated by AutoGraph is not optimized for step-by-step' + ' debugging. See https://github.com/tensorflow/tensorflow/' + 'blob/master/tensorflow/python/autograph/g3doc/reference/' + 'debugging.md.') + set_trace_warned = True + return node + + if (full_name == 'print' and + not self.ctx.user.options.uses(converter.Feature.BUILTIN_FUNCTIONS)): + return node + + template = """ + ag__.converted_call(func, args, kwargs, function_ctx) + """ + new_call = templates.replace_as_expression( + template, + func=node.func, + args=self._args_to_tuple(node), + kwargs=self._kwargs_to_dict(node), + function_ctx=function_context_name) + + return new_call + + +def transform(node, ctx): + """Transform function call to the compiled counterparts. + + Args: + node: AST + ctx: EntityContext + Returns: + A tuple (node, new_names): + node: The transformed AST + new_names: set(string), containing any newly-generated names + """ + node = qual_names.resolve(node) + + node = CallTreeTransformer(ctx).visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/conditional_expressions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/conditional_expressions.py new file mode 100644 index 0000000000000000000000000000000000000000..d61a5cd8548eb097cc657ef5403c8699f643a857 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/conditional_expressions.py @@ -0,0 +1,46 @@ +# 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. +# ============================================================================== +"""Converts the ternary conditional operator.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import templates + + +class ConditionalExpressionTransformer(converter.Base): + """Converts conditional expressions to functional form.""" + + def visit_IfExp(self, node): + template = ''' + ag__.if_exp( + test, + lambda: true_expr, + lambda: false_expr, + expr_repr) + ''' + expr_repr = parser.unparse(node.test, include_encoding_marker=False).strip() + return templates.replace_as_expression( + template, + test=node.test, + true_expr=node.body, + false_expr=node.orelse, + expr_repr=gast.Constant(expr_repr, kind=None)) + + +def transform(node, ctx): + node = ConditionalExpressionTransformer(ctx).visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/continue_statements.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/continue_statements.py new file mode 100644 index 0000000000000000000000000000000000000000..5b2854d9244d41c259d9ece4170131c534316fbd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/continue_statements.py @@ -0,0 +1,164 @@ +# 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. +# ============================================================================== +"""Canonicalizes continue statements by de-sugaring into a control boolean.""" + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno + + +class _Continue(object): + + def __init__(self): + self.used = False + self.control_var_name = None + + def __repr__(self): + return '<_Continue(used: {}, var: {})>'.format(self.used, + self.control_var_name) + + +class _Block(object): + """Tracks information about lexical blocks as they are visited in the AST. + + Mainly, this object tracks the creation of block guards that replace + `continue` statements (e.g. `if not continue_:`). + + Attributes: + create_guard_current: bool, whether to create a guard for the current + statement. + create_guard_next: bool, whether to create a guard for the next + statement. + is_loop_type: bool, whether this block is the body of a loop. + """ + + def __init__(self): + self.is_loop_type = False + self.create_guard_current = False + self.create_guard_next = False + + +class ContinueCanonicalizationTransformer(converter.Base): + """Canonicalizes continue statements into additional conditionals.""" + + def visit_Continue(self, node): + self.state[_Continue].used = True + for block in reversed(self.state[_Block].stack): + # See ContinueCanonicalizationTest.test_multiple_continues for an example + # it's necessary to create guards for all enclosing affected blocks, not + # just that of the current block. + block.create_guard_next = True + if block.is_loop_type: + # continue only affects the innermost loop + break + template = """ + var_name = True + """ + return templates.replace( + template, var_name=self.state[_Continue].control_var_name) + + def _postprocess_statement(self, node): + if self.state[_Continue].used: + block = self.state[_Block] + should_wrap_current = block.create_guard_current + # After processing propagate whether to guard the next statement + block.create_guard_current = block.create_guard_next + block.create_guard_next = False + if should_wrap_current: + template = """ + if not var_name: + original_node + """ + cond, = templates.replace( + template, + var_name=self.state[_Continue].control_var_name, + original_node=node) + return cond, cond.body + return node, None + + def _visit_loop_body(self, node, nodes): + self.state[_Continue].enter() + self.state[_Block].enter() + self.state[_Block].is_loop_type = True + scope = anno.getanno(node, NodeAnno.BODY_SCOPE) + continue_var = self.ctx.namer.new_symbol('continue_', scope.referenced) + self.state[_Continue].control_var_name = continue_var + + nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) + + if self.state[_Continue].used: + template = """ + var_name = False + """ + control_var_init = templates.replace(template, var_name=continue_var) + nodes = control_var_init + nodes + + self.state[_Block].exit() + self.state[_Continue].exit() + return nodes + + def _visit_non_loop_body(self, nodes): + self.state[_Block].enter() + nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) + self.state[_Block].exit() + return nodes + + def visit_While(self, node): + node.test = self.visit(node.test) + node.body = self._visit_loop_body(node, node.body) + # A continue in the else clause applies to the containing scope. + node.orelse = self._visit_non_loop_body(node.orelse) + return node + + def visit_For(self, node): + node.target = self.generic_visit(node.target) + node.iter = self.generic_visit(node.iter) + node.body = self._visit_loop_body(node, node.body) + # A continue in the else clause applies to the containing scope. + node.orelse = self._visit_non_loop_body(node.orelse) + return node + + def visit_If(self, node): + node.body = self._visit_non_loop_body(node.body) + node.orelse = self._visit_non_loop_body(node.orelse) + return node + + def visit_With(self, node): + node.items = self.visit_block(node.items) + node.body = self._visit_non_loop_body(node.body) + return node + + def visit_Try(self, node): + node.body = self._visit_non_loop_body(node.body) + node.orelse = self._visit_non_loop_body(node.orelse) + # In Python 3.8 and later continue is allowed in finally blocks + node.finalbody = self._visit_non_loop_body(node.finalbody) + node.handlers = self.visit_block(node.handlers) + return node + + def visit_ExceptHandler(self, node): + node.body = self._visit_non_loop_body(node.body) + return node + + +def transform(node, ctx): + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + + node = ContinueCanonicalizationTransformer(ctx).visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/control_flow.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/control_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..ad50d0338b12efd99de686dc35d765549c2b5d95 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/control_flow.py @@ -0,0 +1,413 @@ +# 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. +# ============================================================================== +"""Handles control flow statements: while, for, if.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.lang import directives +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import cfg +from tensorflow.python.autograph.pyct import origin_info +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis import annos +from tensorflow.python.autograph.pyct.static_analysis import liveness +from tensorflow.python.autograph.pyct.static_analysis import reaching_definitions +from tensorflow.python.autograph.pyct.static_analysis import reaching_fndefs + + +class _Function(object): + + scope = None + + +class ControlFlowTransformer(converter.Base): + """Transforms control flow structures like loops an conditionals.""" + + def visit_Lambda(self, node): + with self.state[_Function] as fn: + fn.scope = anno.getanno(node, anno.Static.SCOPE) + return self.generic_visit(node) + + def visit_FunctionDef(self, node): + with self.state[_Function] as fn: + fn.scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) + return self.generic_visit(node) + + def _create_nonlocal_declarations(self, vars_): + vars_ = set(vars_) + results = [] + global_vars = self.state[_Function].scope.globals & vars_ + + if global_vars: + results.append(gast.Global([str(v) for v in global_vars])) + + nonlocal_vars = [ + v for v in vars_ if not v.is_composite() and v not in global_vars] + if nonlocal_vars: + results.append(gast.Nonlocal([str(v) for v in nonlocal_vars])) + + return results + + def _create_state_functions( + self, block_vars, nonlocal_declarations, getter_name, setter_name): + if not block_vars: + template = """ + def getter_name(): + return () + def setter_name(block_vars): + pass + """ + return templates.replace( + template, getter_name=getter_name, setter_name=setter_name) + + guarded_block_vars = [] + for v in block_vars: + if v.is_simple(): + guarded_block_vars.append(v) + else: + guarded_block_vars.append( + templates.replace_as_expression( + 'ag__.ldu(lambda: var_, name)', + var_=v, + name=gast.Constant(str(v), kind=None))) + + template = """ + def getter_name(): + return guarded_state_vars, + def setter_name(vars_): + nonlocal_declarations + state_vars, = vars_ + """ + return templates.replace( + template, + nonlocal_declarations=nonlocal_declarations, + getter_name=getter_name, + guarded_state_vars=guarded_block_vars, + setter_name=setter_name, + state_vars=tuple(block_vars)) + + def _create_loop_options(self, node): + if not anno.hasanno(node, anno.Basic.DIRECTIVES): + return gast.Dict([], []) + + loop_directives = anno.getanno(node, anno.Basic.DIRECTIVES) + if directives.set_loop_options not in loop_directives: + return gast.Dict([], []) + + opts_dict = loop_directives[directives.set_loop_options] + str_keys, values = zip(*opts_dict.items()) + keys = [gast.Constant(s, kind=None) for s in str_keys] + values = list(values) # ast and gast don't play well with tuples. + return gast.Dict(keys, values) + + def _create_undefined_assigns(self, undefined_symbols): + assignments = [] + for s in undefined_symbols: + template = ''' + var = ag__.Undefined(symbol_name) + ''' + assignments += templates.replace( + template, + var=s, + symbol_name=gast.Constant(s.ssf(), kind=None)) + return assignments + + def _get_block_basic_vars(self, modified, live_in, live_out): + nonlocals = self.state[_Function].scope.nonlocals + basic_scope_vars = [] + for s in modified: + if s.is_composite(): + # TODO(mdan): Raise an error when this happens for a TF scope. + continue + # Variables not live into or out of the scope are considered local to the + # scope. + if s in live_in or s in live_out or s in nonlocals: + basic_scope_vars.append(s) + continue + return frozenset(basic_scope_vars) + + def _get_block_composite_vars(self, modified, live_in): + # The scope variables corresponding to composite symbols (e.g. `self.x`). + composite_scope_vars = [] + for s in modified: + if not s.is_composite(): + continue + # Mutations made to objects created inside the scope will appear as writes + # to composite symbols. Because these mutations appear as modifications + # made to composite symbols, we check whether the composite's parent is + # actually live into the scope. + # Example: + # while cond: + # x = Foo() + # x.foo = 2 * x.foo # x.foo is live into the scope, but x is not. + # + # Note that some parents might not be symbols - for example, in x['foo'], + # 'foo' is a parent, but it's a literal, not a symbol. We don't check the + # liveness of literals. + support_set_symbols = tuple( + sss for sss in s.support_set if sss.is_symbol()) + if not all(sss in live_in for sss in support_set_symbols): + continue + composite_scope_vars.append(s) + return frozenset(composite_scope_vars) + + def _get_block_vars(self, node, modified): + """Determines the variables affected inside a control flow statement.""" + defined_in = anno.getanno(node, anno.Static.DEFINED_VARS_IN) + live_in = anno.getanno(node, anno.Static.LIVE_VARS_IN) + live_out = anno.getanno(node, anno.Static.LIVE_VARS_OUT) + fn_scope = self.state[_Function].scope + + basic_scope_vars = self._get_block_basic_vars( + modified, + live_in, + live_out) + composite_scope_vars = self._get_block_composite_vars(modified, live_in) + scope_vars = tuple(basic_scope_vars | composite_scope_vars) + + # Variables that are modified inside the scope, but not defined + # before entering it. Only simple variables must be defined. The + # composite ones will be implicitly checked at runtime. + possibly_undefined = ( + modified - defined_in - fn_scope.globals - fn_scope.nonlocals) + undefined = tuple(v for v in possibly_undefined if not v.is_composite()) + + # Variables that are modified inside the scope, and depend on values outside + # it. + input_only = basic_scope_vars & live_in - live_out + + # Place the outputs first, then sort lexicographically. + scope_vars = sorted(scope_vars, key=lambda v: (v in input_only, v)) + nouts = len(scope_vars) - len(input_only) + + return scope_vars, undefined, nouts + + def visit_If(self, node): + node = self.generic_visit(node) + body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) + orelse_scope = anno.getanno(node, annos.NodeAnno.ORELSE_SCOPE) + + cond_vars, undefined, nouts = self._get_block_vars( + node, body_scope.bound | orelse_scope.bound) + + undefined_assigns = self._create_undefined_assigns(undefined) + + nonlocal_declarations = self._create_nonlocal_declarations(cond_vars) + + reserved = body_scope.referenced | orelse_scope.referenced + state_getter_name = self.ctx.namer.new_symbol('get_state', reserved) + state_setter_name = self.ctx.namer.new_symbol('set_state', reserved) + state_functions = self._create_state_functions( + cond_vars, nonlocal_declarations, state_getter_name, state_setter_name) + + orelse_body = node.orelse + if not orelse_body: + orelse_body = [gast.Pass()] + + template = """ + state_functions + def body_name(): + nonlocal_declarations + body + def orelse_name(): + nonlocal_declarations + orelse + undefined_assigns + ag__.if_stmt( + test, + body_name, + orelse_name, + state_getter_name, + state_setter_name, + (symbol_names,), + nouts) + """ + new_nodes = templates.replace( + template, + body=node.body, + body_name=self.ctx.namer.new_symbol('if_body', reserved), + orelse=orelse_body, + orelse_name=self.ctx.namer.new_symbol('else_body', reserved), + nonlocal_declarations=nonlocal_declarations, + nouts=gast.Constant(nouts, kind=None), + state_functions=state_functions, + state_getter_name=state_getter_name, + state_setter_name=state_setter_name, + symbol_names=tuple(gast.Constant(str(s), kind=None) for s in cond_vars), + test=node.test, + undefined_assigns=undefined_assigns) + origin_info.copy_origin(node, new_nodes[-1]) + return new_nodes + + def visit_While(self, node): + node = self.generic_visit(node) + body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) + + loop_vars, undefined, _ = self._get_block_vars(node, body_scope.bound) + + undefined_assigns = self._create_undefined_assigns(undefined) + + nonlocal_declarations = self._create_nonlocal_declarations(loop_vars) + + reserved = body_scope.referenced + state_getter_name = self.ctx.namer.new_symbol('get_state', reserved) + state_setter_name = self.ctx.namer.new_symbol('set_state', reserved) + state_functions = self._create_state_functions( + loop_vars, nonlocal_declarations, state_getter_name, state_setter_name) + + opts = self._create_loop_options(node) + + template = """ + state_functions + def body_name(): + nonlocal_declarations + body + def test_name(): + return test + undefined_assigns + ag__.while_stmt( + test_name, + body_name, + state_getter_name, + state_setter_name, + (symbol_names,), + opts) + """ + new_nodes = templates.replace( + template, + body=node.body, + body_name=self.ctx.namer.new_symbol('loop_body', reserved), + nonlocal_declarations=nonlocal_declarations, + opts=opts, + state_functions=state_functions, + state_getter_name=state_getter_name, + state_setter_name=state_setter_name, + symbol_names=tuple(gast.Constant(str(s), kind=None) for s in loop_vars), + test=node.test, + test_name=self.ctx.namer.new_symbol('loop_test', reserved), + undefined_assigns=undefined_assigns) + origin_info.copy_origin(node, new_nodes[-1]) + return new_nodes + + def visit_For(self, node): + node = self.generic_visit(node) + body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) + iter_scope = anno.getanno(node, annos.NodeAnno.ITERATE_SCOPE) + + loop_vars, undefined, _ = self._get_block_vars( + node, body_scope.bound | iter_scope.bound) + + undefined_assigns = self._create_undefined_assigns(undefined) + + nonlocal_declarations = self._create_nonlocal_declarations(loop_vars) + + reserved = body_scope.referenced | iter_scope.referenced + state_getter_name = self.ctx.namer.new_symbol('get_state', reserved) + state_setter_name = self.ctx.namer.new_symbol('set_state', reserved) + state_functions = self._create_state_functions( + loop_vars, nonlocal_declarations, state_getter_name, state_setter_name) + + opts = self._create_loop_options(node) + opts.keys.append(gast.Constant('iterate_names', kind=None)) + opts.values.append(gast.Constant( + parser.unparse(node.target, include_encoding_marker=False), kind=None)) + + if anno.hasanno(node, anno.Basic.EXTRA_LOOP_TEST): + extra_test = anno.getanno(node, anno.Basic.EXTRA_LOOP_TEST) + extra_test_name = self.ctx.namer.new_symbol( + 'extra_test', reserved) + template = """ + def extra_test_name(): + nonlocal_declarations + return extra_test_expr + """ + extra_test_function = templates.replace( + template, + extra_test_expr=extra_test, + extra_test_name=extra_test_name, + loop_vars=loop_vars, + nonlocal_declarations=nonlocal_declarations) + else: + extra_test_name = parser.parse_expression('None') + extra_test_function = [] + + # iterate_arg_name holds a single arg with the iterates, which may be a + # tuple. + iterate_arg_name = self.ctx.namer.new_symbol('itr', reserved) + template = """ + iterates = iterate_arg_name + """ + iterate_expansion = templates.replace( + template, iterate_arg_name=iterate_arg_name, iterates=node.target) + origin_info.copy_origin(node, iterate_expansion) + + template = """ + state_functions + def body_name(iterate_arg_name): + nonlocal_declarations + iterate_expansion + body + extra_test_function + undefined_assigns + ag__.for_stmt( + iterated, + extra_test_name, + body_name, + state_getter_name, + state_setter_name, + (symbol_names,), + opts) + """ + new_nodes = templates.replace( + template, + body=node.body, + body_name=self.ctx.namer.new_symbol('loop_body', reserved), + extra_test_function=extra_test_function, + extra_test_name=extra_test_name, + iterate_arg_name=iterate_arg_name, + iterate_expansion=iterate_expansion, + iterated=node.iter, + nonlocal_declarations=nonlocal_declarations, + opts=opts, + symbol_names=tuple(gast.Constant(str(s), kind=None) for s in loop_vars), + state_functions=state_functions, + state_getter_name=state_getter_name, + state_setter_name=state_setter_name, + undefined_assigns=undefined_assigns) + origin_info.copy_origin(node, new_nodes[-1]) + return new_nodes + + +class AnnotatedDef(reaching_definitions.Definition): + + def __init__(self): + super(AnnotatedDef, self).__init__() + self.directives = {} + + +def transform(node, ctx): + graphs = cfg.build(node) + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + node = reaching_definitions.resolve(node, ctx, graphs) + node = reaching_fndefs.resolve(node, ctx, graphs) + node = liveness.resolve(node, ctx, graphs) + + node = ControlFlowTransformer(ctx).visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/directives.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/directives.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1955d9b85ec622ced6268b77856f2572e3b65a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/directives.py @@ -0,0 +1,177 @@ +# 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. +# ============================================================================== +"""Handles directives. + +This converter removes the directive functions from the code and moves the +information they specify into AST annotations. It is a specialized form of +static analysis, one that is specific to AutoGraph. + +Note that this requires that the actual directive functions are static - that +is, they do not change at runtime. So if you do something like this: + + tf.autograph.set_loop_options = + +Then the directive will may no longer be recognized. Furthermore, if the +converted function is cached, such an action may be irreversible. +""" + +import inspect + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.lang import directives +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.util import tf_inspect + + +STATIC_VALUE = 'static_value' +"""Used for AST annotations, see visit_Name.""" + + +class _LoopScope(object): + + def __init__(self): + self.ast_node = None + self.statements_visited = 0 + + +def _map_args(call_node, function): + """Maps AST call nodes to the actual function's arguments. + + Args: + call_node: ast.Call + function: Callable[..., Any], the actual function matching call_node + Returns: + Dict[Text, ast.AST], mapping each of the function's argument names to + the respective AST node. + Raises: + ValueError: if the default arguments are not correctly set + """ + args = call_node.args + kwds = {kwd.arg: kwd.value for kwd in call_node.keywords} + call_args = tf_inspect.getcallargs(function, *args, **kwds) + + # Keyword arguments not specified in kwds will be mapped to their defaults, + # which are Python values. Since we don't currently have a way to transform + # those into AST references, we simply remove them. By convention, directives + # use UNSPECIFIED as default value for optional arguments. No other + # defaults should be present. + unexpected_defaults = [] + for k in call_args: + if (k not in kwds + and call_args[k] not in args + and call_args[k] is not directives.UNSPECIFIED): + unexpected_defaults.append(k) + if unexpected_defaults: + raise ValueError('Unexpected keyword argument values, %s, for function %s' + % (zip(unexpected_defaults, + [call_args[k] for k in unexpected_defaults]), + function)) + return {k: v for k, v in call_args.items() if v is not directives.UNSPECIFIED} + + +class DirectivesTransformer(converter.Base): + """Parses compiler directives and converts them into AST annotations.""" + + def _process_symbol_directive(self, call_node, directive): + if len(call_node.args) < 1: + raise ValueError('"%s" requires a positional first argument' + ' as the target' % directive.__name__) + target = call_node.args[0] + defs = anno.getanno(target, anno.Static.ORIG_DEFINITIONS) + for def_ in defs: + def_.directives[directive] = _map_args(call_node, directive) + return call_node + + def _process_statement_directive(self, call_node, directive): + if self.state[_LoopScope].statements_visited > 1: + raise ValueError( + '"%s" must be the first statement in the loop block' % ( + directive.__name__)) + if self.state[_LoopScope].level < 2: + raise ValueError( + '"%s" must be used inside a statement' % directive.__name__) + target = self.state[_LoopScope].ast_node + node_anno = anno.getanno(target, anno.Basic.DIRECTIVES, {}) + node_anno[directive] = _map_args(call_node, directive) + anno.setanno(target, anno.Basic.DIRECTIVES, node_anno) + return call_node + + def visit_Name(self, node): + node = self.generic_visit(node) + if isinstance(node.ctx, gast.Load): + defs = anno.getanno(node, anno.Static.DEFINITIONS, ()) + is_defined = bool(defs) + if not is_defined and node.id in self.ctx.info.namespace: + anno.setanno(node, STATIC_VALUE, self.ctx.info.namespace[node.id]) + return node + + def visit_Attribute(self, node): + node = self.generic_visit(node) + parent_val = anno.getanno(node.value, STATIC_VALUE, default=None) + if parent_val is not None and inspect.ismodule(parent_val): + if hasattr(parent_val, node.attr): + anno.setanno(node, STATIC_VALUE, getattr(parent_val, node.attr)) + return node + + def visit_Assign(self, node): + self.state[_LoopScope].statements_visited += 1 + return self.generic_visit(node) + + def visit_AugAssign(self, node): + self.state[_LoopScope].statements_visited += 1 + return self.generic_visit(node) + + def visit_Expr(self, node): + self.state[_LoopScope].statements_visited += 1 + node = self.generic_visit(node) + if isinstance(node.value, gast.Call): + call_node = node.value + static_val = anno.getanno(call_node.func, STATIC_VALUE, default=None) + if static_val is not None: + # Note: directive calls are not output in the generated code, hence + # the removal from the code by returning None. + + if static_val is directives.set_element_type: + self._process_symbol_directive(call_node, static_val) + return None + elif static_val is directives.set_loop_options: + self._process_statement_directive(call_node, static_val) + return None + return node + + # TODO(mdan): This will be insufficient for other control flow. + # That means that if we ever have a directive that affects things other than + # loops, we'll need support for parallel scopes, or have multiple converters. + def _track_and_visit_loop(self, node): + self.state[_LoopScope].enter() + self.state[_LoopScope].ast_node = node + node = self.generic_visit(node) + # Edge case: a loop with just one directive statement would become empty. + if not node.body: + node.body = [gast.Pass()] + self.state[_LoopScope].exit() + return node + + def visit_While(self, node): + return self._track_and_visit_loop(node) + + def visit_For(self, node): + return self._track_and_visit_loop(node) + + +def transform(node, ctx): + return DirectivesTransformer(ctx).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/functions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..72c5b5eac7884f0e86cd5b3a422c00923a7e1c24 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/functions.py @@ -0,0 +1,134 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Converts function definitions and lambdas by adding necessary boilerplate.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis import annos + + +class _Function(object): + + def __init__(self): + self.context_name = None + + +class FunctionTransformer(converter.Base): + """Wraps function bodies around autograph-specific boilerplate.""" + + def _function_scope_options(self, fn_scope): + """Returns the options with which to create function scopes.""" + # Top-level function receive the options that were directly requested. + # All others receive the options corresponding to a recursive conversion. + # Note: this mainly controls the user_requested flag, which is important + # primarily because the FunctionScope context also creates a + # ControlStatusCtx(autograph=ENABLED) when user_requested is True. See + # function_wrappers.py. + if fn_scope.level == 2: + return self.ctx.user.options + return self.ctx.user.options.call_options() + + def visit_Lambda(self, node): + with self.state[_Function] as fn_scope: + node = self.generic_visit(node) + + # TODO(mdan): Fix the tests so that we can always add this decorator. + if fn_scope.level > 2: + return templates.replace_as_expression( + 'ag__.autograph_artifact(l)', l=node) + + scope = anno.getanno(node, anno.Static.SCOPE) + function_context_name = self.ctx.namer.new_symbol('lscope', + scope.referenced) + fn_scope.context_name = function_context_name + anno.setanno(node, 'function_context_name', function_context_name) + + template = """ + ag__.with_function_scope( + lambda function_context: body, function_context_name, options) + """ + node.body = templates.replace_as_expression( + template, + options=self._function_scope_options(fn_scope).to_ast(), + function_context=function_context_name, + function_context_name=gast.Constant(function_context_name, kind=None), + body=node.body) + + return node + + def visit_FunctionDef(self, node): + with self.state[_Function] as fn_scope: + scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) + + function_context_name = self.ctx.namer.new_symbol('fscope', + scope.referenced) + fn_scope.context_name = function_context_name + anno.setanno(node, 'function_context_name', function_context_name) + + node = self.generic_visit(node) + + if fn_scope.level <= 2: + # Top-level functions lose their decorator because the conversion is + # always just-in-time and by the time it happens the decorators are + # already set to be applied. + node.decorator_list = [] + else: + # TODO(mdan): Fix the tests so that we can always add this decorator. + # Inner functions are converted already, so we insert a decorator to + # prevent double conversion. Double conversion would work too, but this + # saves the overhead. + node.decorator_list.append( + parser.parse_expression('ag__.autograph_artifact')) + + docstring_node = None + if node.body: + first_statement = node.body[0] + if (isinstance(first_statement, gast.Expr) and + isinstance(first_statement.value, gast.Constant)): + docstring_node = first_statement + node.body = node.body[1:] + + template = """ + with ag__.FunctionScope( + function_name, context_name, options) as function_context: + body + """ + wrapped_body = templates.replace( + template, + function_name=gast.Constant(node.name, kind=None), + context_name=gast.Constant(function_context_name, kind=None), + options=self._function_scope_options(fn_scope).to_ast(), + function_context=function_context_name, + body=node.body) + + if docstring_node is not None: + wrapped_body = [docstring_node] + wrapped_body + + node.body = wrapped_body + + return node + + +def transform(node, ctx): + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + + return FunctionTransformer(ctx).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/lists.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/lists.py new file mode 100644 index 0000000000000000000000000000000000000000..4cff920c1ebe59ed9d5d8b29129afe32b7949367 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/lists.py @@ -0,0 +1,239 @@ +# 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. +# ============================================================================== +"""Converter for list operations. + +This includes converting Python lists to TensorArray/TensorList. +""" + +# TODO(mdan): Elaborate the logic here. +# TODO(mdan): Does it even make sense to attempt to try to use TAs? +# The current rule (always convert to TensorArray) is naive and insufficient. +# In general, a better mechanism could look like: +# * convert to TensorList by default +# * leave as Python list if the user explicitly forbids it +# * convert to TensorArray only when complete write once behavior can be +# guaranteed (e.g. list comprehensions) + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.lang import directives +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno + + +class _Statement(object): + + def __init__(self): + self.pop_uses = None + + +class ListTransformer(converter.Base): + """Converts lists and related operations to their TF counterpart.""" + + def visit_List(self, node): + node = self.generic_visit(node) + template = """ + ag__.new_list(elements) + """ + return templates.replace_as_expression(template, elements=node) + + def _replace_append_call(self, node): + assert len(node.args) == 1 + assert isinstance(node.func, gast.Attribute) + template = """ + target = ag__.list_append(target, element) + """ + return templates.replace( + template, + target=node.func.value, + element=node.args[0]) + + def _replace_pop_call(self, node): + # Expressions that use pop() are converted to a statement + expression. + # + # For example: + # + # print(target.pop()) + # + # ... is converted to: + # + # target, target_pop = ag__.list_pop(target) + # print(target_pop) + # + # Here, we just generate the variable name and swap it in, + # and _generate_pop_operation will handle the rest. + # + # Multiple uses of pop() are allowed: + # + # print(tartget.pop(), target.pop()) + # print(tartget.pop().pop()) + # + assert isinstance(node.func, gast.Attribute) + scope = anno.getanno(node, NodeAnno.ARGS_SCOPE) + target_node = node.func.value + + # Attempt to use a related name if one exists. Otherwise use something + # generic. + if anno.hasanno(target_node, anno.Basic.QN): + target_name = anno.getanno(target_node, anno.Basic.QN).ssf() + else: + target_name = 'list_' + pop_var_name = self.ctx.namer.new_symbol(target_name, scope.referenced) + + stmt = self.state[_Statement] + if stmt.pop_uses is None: + stmt.pop_uses = [] + stmt.pop_uses.append((node, pop_var_name)) + + return templates.replace_as_expression('var_name', var_name=pop_var_name) + + def _replace_stack_call(self, node): + assert len(node.args) == 1 + dtype = self.get_definition_directive( + node.args[0], + directives.set_element_type, + 'dtype', + default=templates.replace_as_expression('None')) + template = """ + ag__.list_stack( + target, + opts=ag__.ListStackOpts( + element_dtype=dtype, + original_call=orig_call)) + """ + return templates.replace_as_expression( + template, + dtype=dtype, + target=node.args[0], + orig_call=node.func) + + def visit_Call(self, node): + node = self.generic_visit(node) + + # TODO(mdan): This is insufficient if target is a function argument. + # In the case of function arguments, we need to add the list to the + # function's return value, because it is being modified. + # TODO(mdan): Checking just the name is brittle, can it be improved? + if isinstance(node.func, gast.Attribute): + func_name = node.func.attr + if func_name == 'append' and (len(node.args) == 1): + node = self._replace_append_call(node) + elif func_name == 'pop' and (len(node.args) <= 1): + node = self._replace_pop_call(node) + elif (func_name == 'stack' and (len(node.args) == 1) and + (not node.keywords or node.keywords[0].arg == 'strict')): + # This avoids false positives with keyword args. + # TODO(mdan): handle kwargs properly. + node = self._replace_stack_call(node) + + return node + + def _generate_pop_operation(self, original_call_node, pop_var_name): + assert isinstance(original_call_node.func, gast.Attribute) + + if original_call_node.args: + pop_element = original_call_node.args[0] + else: + pop_element = parser.parse_expression('None') + + # The call will be something like "target.pop()", and the dtype is hooked to + # target, hence the func.value. + # TODO(mdan): For lists of lists, this won't work. + # The reason why it won't work is because it's unclear how to annotate + # the list as a "list of lists with a certain element type" when using + # operations like `l.pop().pop()`. + dtype = self.get_definition_directive( + original_call_node.func.value, + directives.set_element_type, + 'dtype', + default=templates.replace_as_expression('None')) + shape = self.get_definition_directive( + original_call_node.func.value, + directives.set_element_type, + 'shape', + default=templates.replace_as_expression('None')) + + template = """ + target, pop_var_name = ag__.list_pop( + target, element, + opts=ag__.ListPopOpts(element_dtype=dtype, element_shape=shape)) + """ + return templates.replace( + template, + target=original_call_node.func.value, + pop_var_name=pop_var_name, + element=pop_element, + dtype=dtype, + shape=shape) + + def _postprocess_statement(self, node): + """Inserts any separate pop() calls that node may use.""" + pop_uses = self.state[_Statement].pop_uses + if pop_uses: + replacements = [] + for original_call_node, pop_var_name in pop_uses: + replacements.extend( + self._generate_pop_operation(original_call_node, pop_var_name)) + replacements.append(node) + node = replacements + self.state[_Statement].exit() + return node, None + + def _visit_and_process_block(self, block): + return self.visit_block( + block, + before_visit=self.state[_Statement].enter, + after_visit=self._postprocess_statement) + + def visit_FunctionDef(self, node): + node.args = self.generic_visit(node.args) + node.decorator_list = self.visit_block(node.decorator_list) + node.body = self._visit_and_process_block(node.body) + return node + + def visit_For(self, node): + node.target = self.visit(node.target) + node.body = self._visit_and_process_block(node.body) + node.orelse = self._visit_and_process_block(node.orelse) + return node + + def visit_While(self, node): + node.test = self.visit(node.test) + node.body = self._visit_and_process_block(node.body) + node.orelse = self._visit_and_process_block(node.orelse) + return node + + def visit_If(self, node): + node.test = self.visit(node.test) + node.body = self._visit_and_process_block(node.body) + node.orelse = self._visit_and_process_block(node.orelse) + return node + + def visit_With(self, node): + node.items = self.visit_block(node.items) + node.body = self._visit_and_process_block(node.body) + return node + + +def transform(node, ctx): + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + + return ListTransformer(ctx).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/logical_expressions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/logical_expressions.py new file mode 100644 index 0000000000000000000000000000000000000000..ba99aeaaf7cb5406044b5070b412f03fbc2c280b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/logical_expressions.py @@ -0,0 +1,131 @@ +# 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. +# ============================================================================== +"""Converter for logical expressions, e.g. `a and b -> tf.logical_and(a, b)`.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import templates + +# TODO(mdan): Properly extract boolean ops according to lazy eval rules. +# Note that this isn't completely safe either, because tensors may have control +# dependencies. +# Note that for loops that should be done after the loop was converted to +# tf.while_loop so that the expanded conditionals are properly scoped. + +# Used to signal that an operand is safe for non-lazy evaluation. +SAFE_BOOLEAN_OPERAND = 'SAFE_BOOLEAN_OPERAND' + + +LOGICAL_OPERATORS = { + gast.And: 'ag__.and_', + gast.Not: 'ag__.not_', + gast.Or: 'ag__.or_', +} + +EQUALITY_OPERATORS = { + gast.Eq: 'ag__.eq', + gast.NotEq: 'ag__.not_eq', +} + + +class LogicalExpressionTransformer(converter.Base): + """Converts logical expressions to corresponding TF calls.""" + + def _overload_of(self, operator): + op_type = type(operator) + if op_type in LOGICAL_OPERATORS: + return LOGICAL_OPERATORS[op_type] + if self.ctx.user.options.uses(converter.Feature.EQUALITY_OPERATORS): + if op_type in EQUALITY_OPERATORS: + return EQUALITY_OPERATORS[op_type] + return None + + def _as_lambda(self, expr): + return templates.replace_as_expression('lambda: expr', expr=expr) + + def _as_binary_function(self, func_name, arg1, arg2): + return templates.replace_as_expression( + 'func_name(arg1, arg2)', + func_name=parser.parse_expression(func_name), + arg1=arg1, + arg2=arg2) + + def _as_binary_operation(self, op, arg1, arg2): + template = templates.replace_as_expression( + 'arg1 is arg2', # Note: `is` will be replaced with `op` below. + arg1=arg1, + arg2=arg2) + template.ops[0] = op + return template + + def _as_unary_function(self, func_name, arg): + return templates.replace_as_expression( + 'func_name(arg)', func_name=parser.parse_expression(func_name), arg=arg) + + def _process_binop(self, op, left, right): + overload = self._overload_of(op) + if overload is None: + return self._as_binary_operation(op, left, right) + return self._as_binary_function(overload, left, right) + + def visit_Compare(self, node): + node = self.generic_visit(node) + + ops_and_comps = list(zip(node.ops, node.comparators)) + left = node.left + + # Repeated comparisons are converted to conjunctions: + # a < b < c -> a < b and b < c + op_tree = None + while ops_and_comps: + op, right = ops_and_comps.pop(0) + binary_comparison = self._process_binop(op, left, right) + if op_tree is not None: + op_tree = self._as_binary_function('ag__.and_', + self._as_lambda(op_tree), + self._as_lambda(binary_comparison)) + else: + op_tree = binary_comparison + left = right + + assert op_tree is not None + return op_tree + + def visit_UnaryOp(self, node): + node = self.generic_visit(node) + + overload = self._overload_of(node.op) + if overload is None: + return node + + return self._as_unary_function(overload, node.operand) + + def visit_BoolOp(self, node): + node = self.generic_visit(node) + node_values = node.values + right = node.values.pop() + while node_values: + left = node_values.pop() + right = self._as_binary_function( + self._overload_of(node.op), self._as_lambda(left), + self._as_lambda(right)) + return right + + +def transform(node, ctx): + transformer = LogicalExpressionTransformer(ctx) + return transformer.visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/return_statements.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/return_statements.py new file mode 100644 index 0000000000000000000000000000000000000000..fa611f3cc35c75bdcfbb7e829f08a69196f6b7ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/return_statements.py @@ -0,0 +1,402 @@ +# 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. +# ============================================================================== +"""Canonicalizes functions with multiple returns to use just one.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno + + +BODY_DEFINITELY_RETURNS = 'BODY_DEFINITELY_RETURNS' +ORELSE_DEFINITELY_RETURNS = 'ORELSE_DEFINITELY_RETURNS' +STMT_DEFINITELY_RETURNS = 'STMT_DEFINITELY_RETURNS' + + +class _RewriteBlock(object): + + def __init__(self): + self.definitely_returns = False + + +class ConditionalReturnRewriter(converter.Base): + """Rewrites a pattern where it's unobvious that all paths return a value. + + This rewrite allows avoiding intermediate None return values. + + The following pattern: + + if cond: + + return + else: + + + + is converted to: + + if cond: + + return + else: + + + + and vice-versa (if the else returns, subsequent statements are moved under the + if branch). + """ + + def visit_Return(self, node): + self.state[_RewriteBlock].definitely_returns = True + return node + + def _postprocess_statement(self, node): + # If the node definitely returns (e.g. it's a with statement with a + # return statement in it), then the current block also definitely returns. + if anno.getanno(node, STMT_DEFINITELY_RETURNS, default=False): + self.state[_RewriteBlock].definitely_returns = True + + # The special case: collapse a typical conditional return pattern into + # a single conditional with possibly returns on both branches. This + # reduces the use of None return values, which don't work with TF + # conditionals. + if (isinstance(node, gast.If) + and anno.getanno(node, BODY_DEFINITELY_RETURNS, default=False)): + return node, node.orelse + elif (isinstance(node, gast.If) + and anno.getanno(node, ORELSE_DEFINITELY_RETURNS, default=False)): + return node, node.body + + return node, None + + def _visit_statement_block(self, node, nodes): + self.state[_RewriteBlock].enter() + new_nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) + block_definitely_returns = self.state[_RewriteBlock].definitely_returns + self.state[_RewriteBlock].exit() + return new_nodes, block_definitely_returns + + def visit_While(self, node): + node.test = self.visit(node.test) + node.body, _ = self._visit_statement_block(node, node.body) + node.orelse, _ = self._visit_statement_block(node, node.orelse) + return node + + def visit_For(self, node): + node.iter = self.visit(node.iter) + node.target = self.visit(node.target) + node.body, _ = self._visit_statement_block(node, node.body) + node.orelse, _ = self._visit_statement_block(node, node.orelse) + return node + + def visit_With(self, node): + node.items = self.visit_block(node.items) + node.body, definitely_returns = self._visit_statement_block(node, node.body) + if definitely_returns: + anno.setanno(node, STMT_DEFINITELY_RETURNS, True) + return node + + def visit_Try(self, node): + # We could decide whether a 'try' DEFINITELY_RETURNS based on its components + # It is not clear whether we want to do anything with this given + # a 'try' is likely to throw an exception in some circumstances. + node.body, _ = self._visit_statement_block(node, node.body) + node.orelse, _ = self._visit_statement_block(node, node.orelse) + node.finalbody, _ = self._visit_statement_block(node, node.finalbody) + node.handlers = self.visit_block(node.handlers) + return node + + def visit_ExceptHandler(self, node): + # To determine whether `try` DEFINITELY_RETURNS we need to revisit this. + node.body, _ = self._visit_statement_block(node, node.body) + return node + + def visit_If(self, node): + node.test = self.visit(node.test) + + node.body, body_definitely_returns = self._visit_statement_block( + node, node.body) + if body_definitely_returns: + anno.setanno(node, BODY_DEFINITELY_RETURNS, True) + + node.orelse, orelse_definitely_returns = self._visit_statement_block( + node, node.orelse) + if orelse_definitely_returns: + anno.setanno(node, ORELSE_DEFINITELY_RETURNS, True) + + if body_definitely_returns and orelse_definitely_returns: + self.state[_RewriteBlock].definitely_returns = True + + return node + + def visit_FunctionDef(self, node): + node.args = self.visit(node.args) + node.body, _ = self._visit_statement_block(node, node.body) + return node + + +class _Block(object): + + def __init__(self): + self.is_function = False + self.return_used = False + self.create_guard_next = False + self.create_guard_now = False + + def __repr__(self): + return 'used: {}'.format( + self.return_used) + + +class _Function(object): + + def __init__(self): + self.do_return_var_name = None + self.retval_var_name = None + + def __repr__(self): + return 'return control: {}, return value: {}'.format( + self.do_return_var_name, self.retval_var_name) + + +class ReturnStatementsTransformer(converter.Base): + """Lowers return statements into variables and conditionals. + + Specifically, the following pattern: + + + return val + + + is converted to: + + do_return = False + retval = None + + + + do_return = True + retval = val + + if not do_return: + + + return retval + + The conversion adjusts loops as well: + + + while cond: + + return retval + + is converted to: + + + while not do_return and cond: + + do_return = True + retval = val + """ + + def __init__(self, ctx, allow_missing_return): + super(ReturnStatementsTransformer, self).__init__(ctx) + self.allow_missing_return = allow_missing_return + + def visit_Return(self, node): + for block in reversed(self.state[_Block].stack): + block.return_used = True + block.create_guard_next = True + if block.is_function: + break + + retval = node.value if node.value else parser.parse_expression('None') + + # Note: If `return raises, then the return is aborted. + # The try-catch below ensures the variables remain consistent in that case. + template = """ + try: + do_return_var_name = True + retval_var_name = retval + except: + do_return_var_name = False + raise + """ + node = templates.replace( + template, + do_return_var_name=self.state[_Function].do_return_var_name, + retval_var_name=self.state[_Function].retval_var_name, + retval=retval) + + return node + + def _postprocess_statement(self, node): + if not self.state[_Block].return_used: + return node, None + + state = self.state[_Block] + if state.create_guard_now: + template = """ + if not do_return_var_name: + original_node + """ + cond, = templates.replace( + template, + do_return_var_name=self.state[_Function].do_return_var_name, + original_node=node) + node, block = cond, cond.body + else: + node, block = node, None + + state.create_guard_now = state.create_guard_next + state.create_guard_next = False + + return node, block + + def _visit_statement_block(self, node, nodes): + self.state[_Block].enter() + nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) + self.state[_Block].exit() + return nodes + + def visit_While(self, node): + node.test = self.visit(node.test) + + # Add the check for return to the loop condition. + node.body = self._visit_statement_block(node, node.body) + if self.state[_Block].return_used: + node.test = templates.replace_as_expression( + 'not control_var and test', + test=node.test, + control_var=self.state[_Function].do_return_var_name) + + node.orelse = self._visit_statement_block(node, node.orelse) + return node + + def visit_For(self, node): + node.iter = self.visit(node.iter) + node.target = self.visit(node.target) + + # Add the check for return to the loop condition. + node.body = self._visit_statement_block(node, node.body) + if self.state[_Block].return_used: + extra_test = anno.getanno(node, anno.Basic.EXTRA_LOOP_TEST, default=None) + if extra_test is not None: + extra_test = templates.replace_as_expression( + 'not control_var and extra_test', + extra_test=extra_test, + control_var=self.state[_Function].do_return_var_name) + else: + extra_test = templates.replace_as_expression( + 'not control_var', + control_var=self.state[_Function].do_return_var_name) + anno.setanno(node, anno.Basic.EXTRA_LOOP_TEST, extra_test) + + node.orelse = self._visit_statement_block(node, node.orelse) + return node + + def visit_With(self, node): + node.items = self.visit_block(node.items) + node.body = self._visit_statement_block(node, node.body) + return node + + def visit_Try(self, node): + node.body = self._visit_statement_block(node, node.body) + node.orelse = self._visit_statement_block(node, node.orelse) + node.finalbody = self._visit_statement_block(node, node.finalbody) + node.handlers = self.visit_block(node.handlers) + return node + + def visit_ExceptHandler(self, node): + node.body = self._visit_statement_block(node, node.body) + return node + + def visit_If(self, node): + node.test = self.visit(node.test) + node.body = self._visit_statement_block(node, node.body) + node.orelse = self._visit_statement_block(node, node.orelse) + return node + + def visit_FunctionDef(self, node): + with self.state[_Function] as fn: + with self.state[_Block] as block: + block.is_function = True + + scope = anno.getanno(node, NodeAnno.BODY_SCOPE) + do_return_var_name = self.ctx.namer.new_symbol('do_return', + scope.referenced) + retval_var_name = self.ctx.namer.new_symbol('retval_', scope.referenced) + fn.do_return_var_name = do_return_var_name + fn.retval_var_name = retval_var_name + + node.body = self._visit_statement_block(node, node.body) + + if block.return_used: + + if self.allow_missing_return: + # The function would have a single `with` node that wraps the + # entire body. If the function had a docstring, the body has two + # nodes, with the `with` as the second node. + wrapper_node = node.body[-1] + assert isinstance(wrapper_node, gast.With), ( + 'This transformer requires the functions converter.') + + template = """ + do_return_var_name = False + retval_var_name = ag__.UndefinedReturnValue() + body + return function_context.ret(retval_var_name, do_return_var_name) + """ + + wrapper_node.body = templates.replace( + template, + body=wrapper_node.body, + do_return_var_name=do_return_var_name, + function_context=anno.getanno(node, 'function_context_name'), + retval_var_name=retval_var_name) + else: + template = """ + body + return retval_var_name + """ + node.body = templates.replace( + template, + body=node.body, + do_return_var_name=do_return_var_name, + retval_var_name=retval_var_name) + + return node + + +def transform(node, ctx, default_to_null_return=True): + """Ensure a function has only a single return, at the end.""" + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + + # Note: Technically, these two could be merged into a single walk, but + # keeping them separate helps with readability. + node = ConditionalReturnRewriter(ctx).visit(node) + + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + transformer = ReturnStatementsTransformer( + ctx, allow_missing_return=default_to_null_return) + node = transformer.visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/slices.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/slices.py new file mode 100644 index 0000000000000000000000000000000000000000..f7af271d805315ea677835ad18c026e68a334276 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/slices.py @@ -0,0 +1,83 @@ +# 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. +# ============================================================================== +"""Converter for slice operations.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.lang import directives +from tensorflow.python.autograph.pyct import templates + + +class SliceTransformer(converter.Base): + """Converts slicing operations to their TF counterpart. + + Currently, relying on the default slice operator that Tensor uses is + insufficient, because TensorArray and tensor lists use dedicated index read + and write functions. + """ + + def _process_single_assignment(self, target, value): + if not isinstance(target, gast.Subscript): + return None + s = target.slice + if isinstance(s, (gast.Tuple, gast.Slice)): + return None + + template = """ + target = ag__.set_item(target, key, item) + """ + return templates.replace( + template, target=target.value, key=target.slice, item=value) + + def visit_Assign(self, node): + node = self.generic_visit(node) + # TODO(mdan): Support unpackings and multiple assignments. + if len(node.targets) != 1: + raise NotImplementedError('multiple assignment') + replacement = self._process_single_assignment(node.targets[0], node.value) + if replacement is not None: + return replacement + return node + + def visit_Subscript(self, node): + node = self.generic_visit(node) + s = node.slice + if isinstance(s, (gast.Tuple, gast.Slice)): + return node + + if not isinstance(node.ctx, gast.Load): + # Index writes are handled at a higher level, one at which the rvalue is + # also available. + return node + + dtype = self.get_definition_directive( + node.value, + directives.set_element_type, + 'dtype', + default=templates.replace_as_expression('None')) + + template = """ + ag__.get_item( + target, + key, + opts=ag__.GetItemOpts(element_dtype=dtype)) + """ + return templates.replace_as_expression( + template, target=node.value, key=s, dtype=dtype) + + +def transform(node, ctx): + return SliceTransformer(ctx).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/variables.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/variables.py new file mode 100644 index 0000000000000000000000000000000000000000..cea96a89f685cc956adba6965a3845c8a03a025c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/converters/variables.py @@ -0,0 +1,97 @@ +# 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. +# ============================================================================== +"""Overloads all variable read operations.""" + +import gast + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import templates + + +class VariableAccessTransformer(converter.Base): + """Rewrites basic symbol reads. + + This transformer rewrites variable reads with a "read" operator which allows + tracking activity. + + Example: + + For a basic statement: + + a = b + c + + This is translated to: + + a = ld(b) + ld(c) + + Augmented assignment operations also introduce a `ld` operator: + + a += b + + The assignment target also receives an operator to properly represent the + read: + + a = ld(a) + a += ld(b) + """ + + def visit_Name(self, node): + # Only the loads which existed in the original code are overloaded. + if not anno.hasanno(node, anno.Static.ORIG_DEFINITIONS): + return node + if isinstance(node.ctx, gast.Load): + node = templates.replace_as_expression('ag__.ld(var_)', var_=node) + return node + + def visit_Delete(self, node): + node = self.generic_visit(node) + + rewrite_targets = [] + for tgt in node.targets: + # Don't rewrite composites like `del a[0]`. + if isinstance(tgt, gast.Name): + rewrite_targets.append(tgt) + + if not rewrite_targets: + return node + + results = [] + for tgt in rewrite_targets: + template = """ + var_ = ag__.Undefined(var_name) + """ + results.extend(templates.replace( + template, var_=tgt, var_name=gast.Constant(tgt.id, kind=None))) + remaining_targets = [n for n in node.targets if n not in rewrite_targets] + if remaining_targets: + results.append(gast.Delete(targets=remaining_targets)) + + return results + + def visit_AugAssign(self, node): + if isinstance(node.target, gast.Name): + template = """ + var_ = ag__.ld(var_) + original + """ + node = templates.replace(template, var_=node.target, original=node) + else: + node = self.generic_visit(node) + return node + + +def transform(node, ctx): + return VariableAccessTransformer(ctx).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/ag_ctx.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/ag_ctx.py new file mode 100644 index 0000000000000000000000000000000000000000..d174ee5cd616c4ca28f1e183fe5a021b9216d0ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/ag_ctx.py @@ -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. +# ============================================================================== +"""Thread-local context managers for AutoGraph.""" + +import enum +import inspect +import threading + +from tensorflow.python.autograph.utils import ag_logging +from tensorflow.python.util.tf_export import tf_export + + +stacks = threading.local() + + +def _control_ctx(): + if not hasattr(stacks, 'control_status'): + stacks.control_status = [_default_control_status_ctx()] + return stacks.control_status + + +@tf_export('__internal__.autograph.control_status_ctx', v1=[]) +def control_status_ctx(): + """Returns the current control context for autograph. + + This method is useful when calling `tf.__internal__.autograph.tf_convert`, + The context will be used by tf_convert to determine whether it should convert + the input function. See the sample usage like below: + + ``` + def foo(func): + return tf.__internal__.autograph.tf_convert( + input_fn, ctx=tf.__internal__.autograph.control_status_ctx())() + ``` + + Returns: + The current control context of autograph. + """ + ret = _control_ctx()[-1] + return ret + + +class Status(enum.Enum): + UNSPECIFIED = 0 + ENABLED = 1 + DISABLED = 2 + + +class ControlStatusCtx(object): + """A context that tracks whether autograph is enabled by the user.""" + + def __init__(self, status, options=None): + self.status = status + self.options = options + + def __enter__(self): + _control_ctx().append(self) + return self + + def __repr__(self): + return '{}[status={}, options={}]'.format( + self.__class__.__name__, self.status, self.options) + + def __exit__(self, unused_type, unused_value, unused_traceback): + assert _control_ctx()[-1] is self + _control_ctx().pop() + + +class NullCtx(object): + """Helper substitute for contextlib.nullcontext.""" + + def __enter__(self): + pass + + def __exit__(self, unused_type, unused_value, unused_traceback): + pass + + +def _default_control_status_ctx(): + return ControlStatusCtx(status=Status.UNSPECIFIED) + + +INSPECT_SOURCE_SUPPORTED = True +try: + inspect.getsource(ag_logging.log) +except OSError: + INSPECT_SOURCE_SUPPORTED = False + ag_logging.warning( + 'AutoGraph is not available in this environment: functions lack code' + ' information. This is typical of some environments like the interactive' + ' Python shell. See' + ' https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#access-to-source-code' + ' for more information.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6686b35d526fdcb45dbffd32f6c52c6e96eccd94 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/config.py @@ -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. +# ============================================================================== +"""Global configuration.""" + +from tensorflow.python.autograph.core import config_lib + +Action = config_lib.Action +Convert = config_lib.Convert +DoNotConvert = config_lib.DoNotConvert + + +# This list is evaluated in order and stops at the first rule that tests True +# for a definitely_convert of definitely_bypass call. +CONVERSION_RULES = ( + # Known packages + Convert('tensorflow.python.training.experimental'), + + # Builtin modules + DoNotConvert('collections'), + DoNotConvert('copy'), + DoNotConvert('cProfile'), + DoNotConvert('inspect'), + DoNotConvert('ipdb'), + DoNotConvert('linecache'), + DoNotConvert('mock'), + DoNotConvert('pathlib'), + DoNotConvert('pdb'), + DoNotConvert('posixpath'), + DoNotConvert('pstats'), + DoNotConvert('re'), + DoNotConvert('threading'), + DoNotConvert('urllib'), + + # Known libraries + DoNotConvert('matplotlib'), + DoNotConvert('numpy'), + DoNotConvert('pandas'), + DoNotConvert('tensorflow'), + DoNotConvert('PIL'), + DoNotConvert('absl.logging'), + + # TODO(b/133417201): Remove. + DoNotConvert('tensorflow_probability'), + + # TODO(b/133842282): Remove. + DoNotConvert('tensorflow_datasets.core'), + + DoNotConvert('keras'), +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/config_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/config_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..9065bf361dc6e3bc0cf791e9e922cc36390c7e82 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/config_lib.py @@ -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. +# ============================================================================== +"""Global configuration support.""" + +import enum + + +# TODO(mdan): For better performance, allow each rule to take a set names. + + +class Rule(object): + """Base class for conversion rules.""" + + def __init__(self, module_prefix): + self._prefix = module_prefix + + def matches(self, module_name): + return (module_name.startswith(self._prefix + '.') or + module_name == self._prefix) + + +class Action(enum.Enum): + NONE = 0 + CONVERT = 1 + DO_NOT_CONVERT = 2 + + +class DoNotConvert(Rule): + """Indicates that this module should be not converted.""" + + def __str__(self): + return 'DoNotConvert rule for {}'.format(self._prefix) + + def get_action(self, module): + if self.matches(module.__name__): + return Action.DO_NOT_CONVERT + return Action.NONE + + +class Convert(Rule): + """Indicates that this module should be converted.""" + + def __str__(self): + return 'Convert rule for {}'.format(self._prefix) + + def get_action(self, module): + if self.matches(module.__name__): + return Action.CONVERT + return Action.NONE diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/converter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/converter.py new file mode 100644 index 0000000000000000000000000000000000000000..1a8ebeddbc7ccf3bcb9853e7d612d642f1544b41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/converter.py @@ -0,0 +1,316 @@ +# 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. +# ============================================================================== +"""Converter construction support. + +This module contains a base class for all converters, as well as supporting +structures. These structures are referred to as contexts. + +The class hierarchy is as follows: + + + [extends] converter.Base + [extends] transformer.Base + [extends] gast.nodeTransformer + [uses] transformer.SourceInfo + [uses] converter.EntityContext + [uses] converter.ProgramContext + [uses] transformer.SourceInfo + +converter.Base is a specialization of transformer.Base for AutoGraph. It's a +very lightweight subclass that adds a `ctx` attribute holding the corresponding +EntityContext object (see below). Note that converters are not reusable, and +`visit` will raise an error if called more than once. + +converter.EntityContext contains mutable state associated with an entity that +the converter processes. + +converter.ProgramContext contains mutable state across related entities. For +example, when converting several functions that call one another, the +ProgramContext should be shared across these entities. + +Below is the overall flow at conversion: + + program_ctx = ProgramContext(, , ...) + while : + entity, source_info = + entity_ctx = EntityContext(program_ctx, source_info) + for : + converter = ConverterClass(entity_ctx) + + # May update entity_ctx and program_ctx + entity = converter.visit(entity) + + + +Note that pyct contains a small number of transformers used for static analysis. +These implement transformer.Base, rather than converter.Base, to avoid a +dependency on AutoGraph. +""" + +import enum + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import ast_util +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct import transformer +from tensorflow.python.util.tf_export import tf_export + +# TODO(mdan): These contexts can be refactored into first class objects. +# For example, we could define Program and Entity abstractions that hold on +# to the actual entity and have conversion methods. + +# TODO(mdan): Add a test specific to this converter. + + +@tf_export('autograph.experimental.Feature') +class Feature(enum.Enum): + """This enumeration represents optional conversion options. + + These conversion options are experimental. They are subject to change without + notice and offer no guarantees. + + _Example Usage_ + + ```python + optionals= tf.autograph.experimental.Feature.EQUALITY_OPERATORS + @tf.function(experimental_autograph_options=optionals) + def f(i): + if i == 0: # EQUALITY_OPERATORS allows the use of == here. + tf.print('i is zero') + ``` + + Attributes: + ALL: Enable all features. + AUTO_CONTROL_DEPS: Insert of control dependencies in the generated code. + ASSERT_STATEMENTS: Convert Tensor-dependent assert statements to tf.Assert. + BUILTIN_FUNCTIONS: Convert builtin functions applied to Tensors to + their TF counterparts. + EQUALITY_OPERATORS: Whether to convert the equality operator ('==') to + tf.math.equal. + LISTS: Convert list idioms, like initializers, slices, append, etc. + NAME_SCOPES: Insert name scopes that name ops according to context, like the + function they were defined in. + """ + + ALL = 'ALL' + + AUTO_CONTROL_DEPS = 'AUTO_CONTROL_DEPS' + ASSERT_STATEMENTS = 'ASSERT_STATEMENTS' + BUILTIN_FUNCTIONS = 'BUILTIN_FUNCTIONS' + EQUALITY_OPERATORS = 'EQUALITY_OPERATORS' + LISTS = 'LISTS' + NAME_SCOPES = 'NAME_SCOPES' + + @classmethod + def all(cls): + """Returns a tuple that enables all options.""" + return tuple(cls.__members__.values()) + + @classmethod + def all_but(cls, exclude): + """Returns a tuple that enables all but the excluded options.""" + if not isinstance(exclude, (list, tuple, set)): + exclude = (exclude,) + return tuple(set(cls.all()) - set(exclude) - {cls.ALL}) + + +STANDARD_OPTIONS = None # Forward definition. + + +class ConversionOptions(object): + """Immutable container for global conversion flags. + + Attributes: + recursive: bool, whether to recursively convert any user functions or + classes that the converted function may use. + user_requested: bool, whether the conversion was explicitly requested by + the user, as opposed to being performed as a result of other logic. This + value always auto-resets to False in child conversions. + optional_features: Union[Feature, Set[Feature]], controls the use of + optional features in the conversion process. See Feature for available + options. + """ + + def __init__(self, + recursive=False, + user_requested=False, + internal_convert_user_code=True, + optional_features=Feature.ALL): + self.recursive = recursive + self.user_requested = user_requested + # TODO(mdan): Rename to conversion_recursion_depth? + self.internal_convert_user_code = internal_convert_user_code + + if optional_features is None: + optional_features = () + elif isinstance(optional_features, Feature): + optional_features = (optional_features,) + optional_features = frozenset(optional_features) + self.optional_features = optional_features + + def as_tuple(self): + return (self.recursive, self.user_requested, + self.internal_convert_user_code, self.optional_features) + + def __hash__(self): + return hash(self.as_tuple()) + + def __eq__(self, other): + assert isinstance(other, ConversionOptions) + return self.as_tuple() == other.as_tuple() + + def __str__(self): + return 'ConversionOptions[{}]' + + def uses(self, feature): + return (Feature.ALL in self.optional_features or + feature in self.optional_features) + + def call_options(self): + """Returns the corresponding options to be used for recursive conversion.""" + return ConversionOptions( + recursive=self.recursive, + user_requested=False, + internal_convert_user_code=self.recursive, + optional_features=self.optional_features) + + def to_ast(self): + """Returns a representation of this object as an AST node. + + The AST node encodes a constructor that would create an object with the + same contents. + + Returns: + ast.Node + """ + if self == STANDARD_OPTIONS: + return parser.parse_expression('ag__.STD') + + template = """ + ag__.ConversionOptions( + recursive=recursive_val, + user_requested=user_requested_val, + optional_features=optional_features_val, + internal_convert_user_code=internal_convert_user_code_val) + """ + + def list_of_features(values): + return parser.parse_expression('({})'.format(', '.join( + 'ag__.{}'.format(str(v)) for v in values))) + + expr_ast = templates.replace( + template, + recursive_val=parser.parse_expression(str(self.recursive)), + user_requested_val=parser.parse_expression(str(self.user_requested)), + internal_convert_user_code_val=parser.parse_expression( + str(self.internal_convert_user_code)), + optional_features_val=list_of_features(self.optional_features)) + return expr_ast[0].value + + +STANDARD_OPTIONS = ConversionOptions( + recursive=True, + user_requested=False, + internal_convert_user_code=True, + optional_features=None) + + +class ProgramContext(object): + """ProgramContext keeps track of converting function hierarchies. + + Attributes: + options: ConversionOptions + autograph_module: Deprecated. Do not use. + """ + + def __init__(self, options, autograph_module=None): + self.options = options + self.autograph_module = autograph_module + + +class Base(transformer.Base): + """All converters should inherit from this class. + + Attributes: + ctx: EntityContext + """ + + def __init__(self, ctx): + super(Base, self).__init__(ctx) + + self._used = False + self._ast_depth = 0 + + def get_definition_directive(self, node, directive, arg, default): + """Returns the unique directive argument for a symbol. + + See lang/directives.py for details on directives. + + Example: + # Given a directive in the code: + ag.foo_directive(bar, baz=1) + + # One can write for an AST node Name(id='bar'): + get_definition_directive(node, ag.foo_directive, 'baz') + + Args: + node: ast.AST, the node representing the symbol for which the directive + argument is needed. + directive: Callable[..., Any], the directive to search. + arg: str, the directive argument to return. + default: Any + + Raises: + ValueError: if conflicting annotations have been found + """ + defs = anno.getanno(node, anno.Static.ORIG_DEFINITIONS, ()) + if not defs: + return default + + arg_values_found = [] + for def_ in defs: + if (directive in def_.directives and arg in def_.directives[directive]): + arg_values_found.append(def_.directives[directive][arg]) + + if not arg_values_found: + return default + + if len(arg_values_found) == 1: + return arg_values_found[0] + + # If multiple annotations reach the symbol, they must all match. If they do, + # return any of them. + first_value = arg_values_found[0] + for other_value in arg_values_found[1:]: + if not ast_util.matches(first_value, other_value): + qn = anno.getanno(node, anno.Basic.QN) + raise ValueError( + '%s has ambiguous annotations for %s(%s): %s, %s' % + (qn, directive.__name__, arg, parser.unparse(other_value).strip(), + parser.unparse(first_value).strip())) + return first_value + + def visit(self, node): + if not self._ast_depth: + if self._used: + raise ValueError('converter objects cannot be reused') + self._used = True + + self._ast_depth += 1 + try: + return super(Base, self).visit(node) + finally: + self._ast_depth -= 1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/converter_testing.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/converter_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..4778f94c034c6dca40df97826c322d60ef971212 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/converter_testing.py @@ -0,0 +1,126 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Base class for tests in this module.""" + +import contextlib +import imp +import inspect +import io +import sys + +from tensorflow.python.autograph.core import config +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.impl import api +from tensorflow.python.framework import ops +from tensorflow.python.platform import test + + +def allowlist(f): + """Helper that marks a callable as whtelitisted.""" + if 'allowlisted_module_for_testing' not in sys.modules: + allowlisted_mod = imp.new_module('allowlisted_module_for_testing') + sys.modules['allowlisted_module_for_testing'] = allowlisted_mod + config.CONVERSION_RULES = ( + (config.DoNotConvert('allowlisted_module_for_testing'),) + + config.CONVERSION_RULES) + + f.__module__ = 'allowlisted_module_for_testing' + + +def is_inside_generated_code(): + """Tests whether the caller is generated code. Implementation-specific.""" + frame = inspect.currentframe() + try: + frame = frame.f_back + + internal_stack_functions = ('converted_call', '_call_unconverted') + # Walk up the stack until we're out of the internal functions. + while (frame is not None and + frame.f_code.co_name in internal_stack_functions): + frame = frame.f_back + if frame is None: + return False + + return 'ag__' in frame.f_locals + finally: + del frame + + +class TestingTranspiler(api.PyToTF): + """Testing version that only applies given transformations.""" + + def __init__(self, converters, ag_overrides): + super(TestingTranspiler, self).__init__() + if isinstance(converters, (list, tuple)): + self._converters = converters + else: + self._converters = (converters,) + self.transformed_ast = None + self._ag_overrides = ag_overrides + + def get_extra_locals(self): + retval = super(TestingTranspiler, self).get_extra_locals() + if self._ag_overrides: + modified_ag = imp.new_module('fake_autograph') + modified_ag.__dict__.update(retval['ag__'].__dict__) + modified_ag.__dict__.update(self._ag_overrides) + retval['ag__'] = modified_ag + return retval + + def transform_ast(self, node, ctx): + node = self.initial_analysis(node, ctx) + + for c in self._converters: + node = c.transform(node, ctx) + + self.transformed_ast = node + self.transform_ctx = ctx + return node + + +class TestCase(test.TestCase): + """Base class for unit tests in this module. Contains relevant utilities.""" + + def setUp(self): + # AutoGraph tests must run in graph mode to properly test control flow. + self.graph = ops.Graph().as_default() + self.graph.__enter__() + + def tearDown(self): + self.graph.__exit__(None, None, None) + + @contextlib.contextmanager + def assertPrints(self, expected_result): + try: + out_capturer = io.StringIO() + sys.stdout = out_capturer + yield + self.assertEqual(out_capturer.getvalue(), expected_result) + finally: + sys.stdout = sys.__stdout__ + + def transform( + self, f, converter_module, include_ast=False, ag_overrides=None): + program_ctx = converter.ProgramContext( + options=converter.ConversionOptions(recursive=True), + autograph_module=api) + + tr = TestingTranspiler(converter_module, ag_overrides) + transformed, _, _ = tr.transform_function(f, program_ctx) + + if include_ast: + return transformed, tr.transformed_ast, tr.transform_ctx + + return transformed diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/function_wrappers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/function_wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..0e1f1da2c0f3c5d1cb34251ecc63bde1b536274a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/function_wrappers.py @@ -0,0 +1,113 @@ +# 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. +# ============================================================================== +"""Support for wrapping converted functions bodies with auxiliary logic.""" + +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.operators import variables +from tensorflow.python.framework import auto_control_deps +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.util import nest + + +# TODO(mdan): Move this into operators - it represents a function definition. + + +class FunctionScope(object): + """Context manager that wraps the body of a converted function. + + This context manager handles various operations related to the scope of a + function: + * optional TF name scopes - these name scopes match the name of the + function, for easy visualization in tensorBoard; + * optional automatic control dependencies - this adds the same mechanism + for control dependencies that is used by `@tf.function`; it can be + optionally enabled when using `tf.autograph.to_graph`; + * tracking of autograph conversion state (whether it's enabled by the user, + conversion options; + """ + + def __init__(self, function_name, scope_name, options): + self.name = scope_name + self.options = options + + if options.user_requested: + self.autograph_ctx = ag_ctx.ControlStatusCtx(ag_ctx.Status.ENABLED, + options) + self.callopts = options.call_options() + + use_name_scope = options.uses(converter.Feature.NAME_SCOPES) + self.use_name_scope = use_name_scope + if use_name_scope: + self.name_scope = ops.name_scope(self._sanitize(function_name)) + + use_auto_deps = self.options.uses(converter.Feature.AUTO_CONTROL_DEPS) + self.use_auto_deps = use_auto_deps + if use_auto_deps: + self.autodeps_scope = auto_control_deps.AutomaticControlDependencies() + self._return_value_marked = False + + def _sanitize(self, name): + """See https://www.tensorflow.org/api_docs/python/tf/Graph#name_scope.""" + # TensorFlow doesn't like leading underscores at the top level. + if name and name.startswith('_'): + name = 'fn' + name + return name + + def __enter__(self): + if self.options.user_requested: + self.autograph_ctx.__enter__() + if self.use_name_scope: + self.name_scope.__enter__() + if self.use_auto_deps: + self.autodeps_scope.__enter__() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.options.user_requested: + self.autograph_ctx.__exit__(exc_type, exc_val, exc_tb) + if self.use_name_scope: + self.name_scope.__exit__(exc_type, exc_val, exc_tb) + if self.use_auto_deps: + self.autodeps_scope.__exit__(exc_type, exc_val, exc_tb) + + def ret(self, value, did_return): + """Marks a value as returned from the function guarded by the scope.""" + del did_return + + if isinstance(value, variables.UndefinedReturnValue): + return None + + if self.use_auto_deps: + self._return_value_marked = True + if value is None: + # We don't create dummy returns, to preserve Python semantics. The user + # is responsible for adding a return value to the top-level function. + return None + + def _mark_return_if_tensor(t): + if tensor_util.is_tf_type(t): + return self.autodeps_scope.mark_as_return(t) + return t + + value = nest.map_structure(_mark_return_if_tensor, value) + return value + + +def with_function_scope(thunk, scope_name, options): + """Inline version of the FunctionScope context manager.""" + with FunctionScope('lambda_', scope_name, options) as scope: + return thunk(scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/unsupported_features_checker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/unsupported_features_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..7fad7eb728c255033e75957ba71a95f568d0747d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/core/unsupported_features_checker.py @@ -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. +# ============================================================================== +"""Checkers for detecting unsupported Python features.""" + +import gast + +from tensorflow.python.autograph.pyct import errors + + +class UnsupportedFeaturesChecker(gast.NodeVisitor): + """Quick check for Python features we know we don't support. + + Any features detected will cause AutoGraph to not compile a function. + """ + + def visit_Attribute(self, node): + if (node.attr is not None + and node.attr.startswith('__') and not node.attr.endswith('__')): + raise errors.UnsupportedLanguageElementError( + 'mangled names are not yet supported') + self.generic_visit(node) + + def visit_For(self, node): + if node.orelse: + raise errors.UnsupportedLanguageElementError( + 'for/else statement not yet supported') + self.generic_visit(node) + + def visit_While(self, node): + if node.orelse: + raise errors.UnsupportedLanguageElementError( + 'while/else statement not yet supported') + self.generic_visit(node) + + # These checks could potentially be replaced with inspect.isgeneratorfunction + # to avoid a getsource/parse/ast-walk round trip. + def visit_Yield(self, node): + raise errors.UnsupportedLanguageElementError('generators are not supported') + + def visit_YieldFrom(self, node): + raise errors.UnsupportedLanguageElementError('generators are not supported') + + +def verify(node): + UnsupportedFeaturesChecker().visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/api.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/api.py new file mode 100644 index 0000000000000000000000000000000000000000..b60c457599e71726fa984a6bbf4e5d62b0fe2d8f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/api.py @@ -0,0 +1,949 @@ +# 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. +# ============================================================================== +"""This module contains the user- and codegen-facing API for AutoGraph.""" + +import functools +import importlib +import inspect +import os +import sys +import textwrap +import traceback + +from tensorflow.python.autograph import operators +from tensorflow.python.autograph import utils +from tensorflow.python.autograph.converters import asserts +from tensorflow.python.autograph.converters import break_statements +from tensorflow.python.autograph.converters import call_trees +from tensorflow.python.autograph.converters import conditional_expressions +from tensorflow.python.autograph.converters import continue_statements +from tensorflow.python.autograph.converters import control_flow +from tensorflow.python.autograph.converters import directives +from tensorflow.python.autograph.converters import functions +from tensorflow.python.autograph.converters import lists +from tensorflow.python.autograph.converters import logical_expressions +from tensorflow.python.autograph.converters import return_statements +from tensorflow.python.autograph.converters import slices +from tensorflow.python.autograph.converters import variables +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.core import function_wrappers +from tensorflow.python.autograph.core import unsupported_features_checker +from tensorflow.python.autograph.impl import conversion +from tensorflow.python.autograph.lang import special_functions +from tensorflow.python.autograph.operators import py_builtins +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import cfg +from tensorflow.python.autograph.pyct import error_utils +from tensorflow.python.autograph.pyct import errors +from tensorflow.python.autograph.pyct import inspect_utils +from tensorflow.python.autograph.pyct import origin_info +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import transpiler +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis import reaching_definitions +from tensorflow.python.autograph.utils import ag_logging as logging +from tensorflow.python.eager.polymorphic_function import tf_method_target +from tensorflow.python.framework import errors_impl +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import tf_stack +from tensorflow.python.util.tf_export import tf_export + + +def is_autograph_strict_conversion_mode(): + return int(os.environ.get('AUTOGRAPH_STRICT_CONVERSION', '0')) > 0 + + +# +# Error handling +# + + +# TODO(mdan): Export this symbol. +class AutoGraphError(errors.PyCTError): + """Base class for all AutoGraph exceptions.""" + pass + + +class ConversionError(AutoGraphError): + """Raised during the conversion process.""" + pass + + +class StagingError(AutoGraphError): + """Raised during the staging (i.e. Python execution) of converted code.""" + pass + + +class _ErrorMetadata(error_utils.ErrorMetadataBase): + """AutoGraph-specific error metadata. See base class.""" + + def create_exception(self, source_error): + preferred_type = type(source_error) + if issubclass(preferred_type, errors_impl.OpError): + # Best-effort unpacking of OpError exceptions. + # TODO(mdan): Use a mechanism that is more future-proof. + init_argspec = tf_inspect.getfullargspec(preferred_type.__init__) + message = self.get_message() + init_args = tuple(init_argspec.args) + # At the time of this writing, TF errors either take 3 or 4 arguments, + # the argument '*args' may or may not be used. + if init_args == ('self', 'node_def', 'op', 'message'): + return preferred_type(source_error.node_def, source_error.op, message, + source_error.experimental_payloads) + + elif preferred_type in (errors.PyCTError, AutoGraphError, ConversionError, + StagingError, errors_impl.InaccessibleTensorError, + errors_impl.OperatorNotAllowedInGraphError): + return preferred_type(self.get_message()) + + exc = super(_ErrorMetadata, self).create_exception(source_error) + if exc is not None: + return exc + + # Note: While changing an error's message property to change the message it + # displays will probably work a lot of times, there is no standard way in + # Python to do that. The safest way is therefore to create a new exception. + # For user defined exceptions, we could define an interface that allowed + # them to work under this mechanism. + return StagingError(self.get_message()) + + +def _attach_error_metadata(e, f): + """Augments an error with the metadata necessary for rewrite.""" + if hasattr(e, 'ag_pass_through'): + return + + metadata = getattr(e, 'ag_error_metadata', None) + source_map = f.ag_source_map + + if metadata is None: + logging.log(1, 'Caught error in user callable %s', f, exc_info=True) + message = '{}: {}'.format(e.__class__.__name__, e) + else: + message = None + + cause_tb = traceback.extract_tb(sys.exc_info()[2])[1:] + + e.ag_error_metadata = _ErrorMetadata(cause_tb, metadata, message, source_map, + __file__) + + +class StackTraceMapper(tf_stack.StackTraceMapper): + """Remaps generated code to code it originated from.""" + + def __init__(self, converted_fn): + super().__init__() + self._source_map = converted_fn.ag_source_map + # This may be called repeatedly: once on entry, by the superclass, then by + # each child context manager. + self._cached_map = None + + def get_effective_source_map(self): + if self._cached_map is not None: + return self._cached_map + + parent_map = self.parent.get_effective_source_map() + + effective_source_map = {} + for loc, origin in self._source_map.items(): + effective_source_map[(loc.filename, loc.lineno)] = (origin.loc.filename, + origin.loc.lineno, + origin.function_name) + + for key, value in parent_map.items(): + filename, lineno, _ = value + value_loc = origin_info.LineLocation(filename=filename, lineno=lineno) + if value_loc in self._source_map: + origin = self._source_map[value_loc] + effective_source_map[key] = (origin.loc.filename, origin.loc.lineno, + origin.function_name) + else: + effective_source_map[key] = value + + self._cached_map = effective_source_map + return effective_source_map + + +# +# Actual source code transformation +# + + +class PyToTF(transpiler.PyToPy): + """The TensorFlow AutoGraph transformer.""" + + def __init__(self): + super(PyToTF, self).__init__() + self._extra_locals = None + + def get_transformed_name(self, node): + return 'tf__' + super(PyToTF, self).get_transformed_name(node) + + def get_extra_locals(self): + if self._extra_locals is None: + # TODO(mdan): Move into core or replace with an actual importable module. + # Craft a module that exposes the external API as well as certain + # internal modules. + module_spec = importlib.machinery.ModuleSpec('autograph', None) + ag_internal = importlib.util.module_from_spec(module_spec) + ag_internal.__dict__.update(inspect.getmodule(PyToTF).__dict__) + ag_internal.ConversionOptions = converter.ConversionOptions + ag_internal.STD = converter.STANDARD_OPTIONS + ag_internal.Feature = converter.Feature + ag_internal.utils = utils + ag_internal.FunctionScope = function_wrappers.FunctionScope + ag_internal.with_function_scope = function_wrappers.with_function_scope + # TODO(mdan): Add safeguards against name clashes. + # We don't want to create a submodule because we want the operators to be + # accessible as ag__. + ag_internal.__dict__.update(special_functions.__dict__) + ag_internal.__dict__.update(operators.__dict__) + + self._extra_locals = {'ag__': ag_internal} + return self._extra_locals + + def get_caching_key(self, ctx): + return ctx.options + + def initial_analysis(self, node, ctx): + graphs = cfg.build(node) + node = qual_names.resolve(node) + node = activity.resolve(node, ctx, None) + node = reaching_definitions.resolve(node, ctx, graphs) + anno.dup( + node, + { + anno.Static.DEFINITIONS: anno.Static.ORIG_DEFINITIONS, + }, + ) + return node + + def transform_ast(self, node, ctx): + unsupported_features_checker.verify(node) + node = self.initial_analysis(node, ctx) + + node = functions.transform(node, ctx) + node = directives.transform(node, ctx) + node = break_statements.transform(node, ctx) + if ctx.user.options.uses(converter.Feature.ASSERT_STATEMENTS): + node = asserts.transform(node, ctx) + # Note: sequencing continue canonicalization before for loop one avoids + # dealing with the extra loop increment operation that the for + # canonicalization creates. + node = continue_statements.transform(node, ctx) + node = return_statements.transform(node, ctx) + if ctx.user.options.uses(converter.Feature.LISTS): + node = lists.transform(node, ctx) + node = slices.transform(node, ctx) + node = call_trees.transform(node, ctx) + node = control_flow.transform(node, ctx) + node = conditional_expressions.transform(node, ctx) + node = logical_expressions.transform(node, ctx) + node = variables.transform(node, ctx) + return node + + +def _convert_actual(entity, program_ctx): + """Applies AutoGraph to entity.""" + + # TODO(mdan): Put these extra fields inside __autograph_info__. + if not hasattr(entity, '__code__'): + raise ValueError('Cannot apply autograph to a function that doesn\'t ' + 'expose a __code__ object. If this is a @tf.function,' + ' try passing f.python_function instead.') + + transformed, module, source_map = _TRANSPILER.transform(entity, program_ctx) + + assert not hasattr(transformed, 'ag_module') + assert not hasattr(transformed, 'ag_source_map') + transformed.ag_module = module + transformed.ag_source_map = source_map + return transformed + + +# +# Generated code support +# + + +def autograph_artifact(entity, extras=None): + if inspect.ismethod(entity): + setattr(entity.__func__, 'autograph_info__', extras) + else: + setattr(entity, 'autograph_info__', extras) + return entity + + +def is_autograph_artifact(entity): + return hasattr(entity, 'autograph_info__') + + +def converted_call(f, args, kwargs, caller_fn_scope=None, options=None): + """Converts a function call inline. + + For internal use only. + + Note: The argument list is optimized for readability of generated code, which + may look like this: + + ag__.converted_call(f, (arg1, arg2), None, fscope) + ag__.converted_call(f, (), dict(arg1=val1, **kwargs), fscope) + ag__.converted_call(f, (arg1, arg2) + varargs, dict(**kwargs), lscope) + + Args: + f: The function to convert. + args: Tuple, the original positional arguments of f + kwargs: Optional[Dict], the original keyword arguments of f + caller_fn_scope: Optional[function_wrappers.FunctionScope], the function + scope of the converted function in which this call was originally made. + options: Optional[converter.ConversionOptions], conversion options. If not + specified, the value of caller_fn_scope.callopts is used. Either options + or caller_fn_scope must be present. + + Returns: + Any, the result of executing a possibly-converted `f` with the given + arguments. + """ + logging.log(1, 'Converted call: %s\n args: %s\n kwargs: %s\n', f, args, + kwargs) + + if options is None: + if caller_fn_scope is None: + raise ValueError('either caller_fn_scope or options must have a value') + options = caller_fn_scope.callopts + + if conversion.is_in_allowlist_cache(f, options): + logging.log(2, 'Allowlisted %s: from cache', f) + return _call_unconverted(f, args, kwargs, options, False) + + if ag_ctx.control_status_ctx().status == ag_ctx.Status.DISABLED: + logging.log(2, 'Allowlisted: %s: AutoGraph is disabled in context', f) + return _call_unconverted(f, args, kwargs, options, False) + + if is_autograph_artifact(f): + logging.log(2, 'Permanently allowed: %s: AutoGraph artifact', f) + return _call_unconverted(f, args, kwargs, options) + + # If this is a partial, unwrap it and redo all the checks. + if isinstance(f, functools.partial): + new_kwargs = {} + if f.keywords is not None: + # Use copy to avoid mutating the underlying keywords. + new_kwargs = f.keywords.copy() + if kwargs is not None: + new_kwargs.update(kwargs) + new_args = f.args + args + logging.log(3, 'Forwarding call of partial %s with\n%s\n%s\n', f, new_args, + new_kwargs) + return converted_call( + f.func, + new_args, + new_kwargs, + caller_fn_scope=caller_fn_scope, + options=options) + + if inspect_utils.isbuiltin(f): + if f is eval: + return py_builtins.eval_in_original_context(f, args, caller_fn_scope) + if f is super: + return py_builtins.super_in_original_context(f, args, caller_fn_scope) + if f is globals: + return py_builtins.globals_in_original_context(caller_fn_scope) + if f is locals: + return py_builtins.locals_in_original_context(caller_fn_scope) + if kwargs: + return py_builtins.overload_of(f)(*args, **kwargs) + else: + return py_builtins.overload_of(f)(*args) + + if conversion.is_unsupported(f): + return _call_unconverted(f, args, kwargs, options) + + if not options.user_requested and conversion.is_allowlisted(f): + return _call_unconverted(f, args, kwargs, options) + + # internal_convert_user_code is for example turned off when issuing a dynamic + # call conversion from generated code while in nonrecursive mode. In that + # case we evidently don't want to recurse, but we still have to convert + # things like builtins. + if not options.internal_convert_user_code: + return _call_unconverted(f, args, kwargs, options) + + try: + if inspect.ismethod(f) or inspect.isfunction(f): + target_entity = f + effective_args = args + + f_self = getattr(f, '__self__', None) + if f_self is not None: + if isinstance(f_self, tf_method_target.TfMethodTarget): + f_self = f_self.target + effective_args = (f_self,) + effective_args + + elif hasattr(f, '__class__') and hasattr(f.__class__, '__call__'): + # Callable objects. Dunder methods have special lookup rules, see: + # https://docs.python.org/3/reference/datamodel.html#specialnames + # TODO(mdan): Recurse into converted_call to simplify other verifications. + # This should be handled in the same way as partials. + target_entity = f.__class__.__call__ + effective_args = (f,) + args + + else: + target_entity = f + raise NotImplementedError('unknown callable type "%s"' % type(f)) + + except Exception as e: # pylint:disable=broad-except + logging.log(1, 'Error transforming entity %s', target_entity, exc_info=True) + if is_autograph_strict_conversion_mode(): + raise + return _fall_back_unconverted(f, args, kwargs, options, e) + + if not hasattr(target_entity, '__code__'): + logging.log(2, 'Permanently allowed: %s: native binding', target_entity) + return _call_unconverted(f, args, kwargs, options) + elif (hasattr(target_entity.__code__, 'co_filename') and + target_entity.__code__.co_filename == ''): + # TODO(mdan): __globals__['txt'] might work in Py3. + logging.log(2, 'Permanently allowed: %s: dynamic code (exec?)', + target_entity) + return _call_unconverted(f, args, kwargs, options) + + try: + program_ctx = converter.ProgramContext(options=options) + converted_f = _convert_actual(target_entity, program_ctx) + if logging.has_verbosity(2): + _log_callargs(converted_f, effective_args, kwargs) + except Exception as e: # pylint:disable=broad-except + logging.log(1, 'Error transforming entity %s', target_entity, exc_info=True) + if is_autograph_strict_conversion_mode(): + raise + return _fall_back_unconverted(f, args, kwargs, options, e) + + with StackTraceMapper(converted_f), tf_stack.CurrentModuleFilter(): + try: + if kwargs is not None: + result = converted_f(*effective_args, **kwargs) + else: + result = converted_f(*effective_args) + except Exception as e: + _attach_error_metadata(e, converted_f) + raise + + return result + + +def _call_unconverted(f, args, kwargs, options, update_cache=True): + """Calls the original function without converting with AutoGraph.""" + if update_cache: + conversion.cache_allowlisted(f, options) + + if (inspect.ismethod(f) and + isinstance(f.__self__, tf_method_target.TfMethodTarget)): + return f.__self__.call(args, kwargs) + + if kwargs is not None: + return f(*args, **kwargs) + return f(*args) + + +def _fall_back_unconverted(f, args, kwargs, options, exc): + """Falls back to calling the function unconverted, in case of error.""" + # TODO(mdan): Consider adding an internal metric. + warning_template = ( + 'AutoGraph could not transform %s and will run it as-is.\n' + '%s' + 'Cause: %s\n' + 'To silence this warning, decorate the function with' + ' @tf.autograph.experimental.do_not_convert') + if isinstance(exc, errors.InaccessibleSourceCodeError): + if ag_ctx.INSPECT_SOURCE_SUPPORTED: + logging.warning(warning_template, f, '', exc) + elif isinstance(exc, errors.UnsupportedLanguageElementError): + if not conversion.is_in_allowlist_cache(f, options): + logging.warning(warning_template, f, '', exc) + else: + file_bug_message = ( + 'Please report this to the TensorFlow team. When filing the bug, set' + ' the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and' + ' attach the full output.\n') + logging.warning(warning_template, f, file_bug_message, exc) + + return _call_unconverted(f, args, kwargs, options) + + +# +# TensorFlow integration +# + + +@tf_export('__internal__.autograph.tf_convert', v1=[]) +def tf_convert(f, ctx, convert_by_default=True, user_requested=False): + """Decorator that applies AutoGraph to a function. + + Use in internal APIs. + + This API is suitable for high order functions internal to the TensorFlow API, + and more generally any function to which AutoGraph is not applied. + + Guidance: `convert` was a decorator meant for use directly by developers, but + most of today's uses go through `tf.function`. `tf_convert` is to be called + from high order functions internal to TF. By default, all the internal + TensorFlow functions are skipped when AutoGraph processes the code. This may + lead to user-supplied functions to be incorrectly skipped as well. + `tf_convert` helps avoid that. See the following example for more details. + + ``` + =====tf_internal_module.py===== + + def unconverted(input_fn): + return input_fn() + + def converted(input_fn): + return tf.__internal__.autograph.tf_convert( + input_fn, ctx=tf.__internal__.autograph.control_status_ctx())() + + ======user_module.py====== + + @tf.function + def foo(input_fn) + return unconverted(input_fn) + + @tf.function + def bar(input_fn) + return converted(input_fn) + + @tf.function(autograph=False) + def baz(input_fn) + return converted(input_fn) + ``` + + The `foo` method above will execute the `input_fn` without autograph + conversion, while the `bar` method will run an autographed `input_fn`. The + `baz` method will run an unconverted `input_fn`, since `tf_convert` respect + the control status context. + + Note that both methods in `tf_internal_module` are skipped by autograph when + tracing the `tf.function`. The configuration of whether a module/package + should be skipped by autograph is controlled in + tensorflow/python/autograph/core/config.py. + + Args: + f: Callable. + ctx: ag_ctx.ControlStatusCtx, the Autograph context in which `f` is used. + convert_by_default: bool, whether to use AutoGraph when the context doesn't + specify. + user_requested: bool, whether to ignore the conversion allowlist. See + ConversionOptions.user_requested. + + Returns: + Either `f or the converted version of `f`. + """ + + if is_autograph_artifact(f): + return f + f_wrapper = f + decorators, f = tf_decorator.unwrap(f) + + # TODO(mdan): Grab features from context. + # Note: we pass the original context through to convert to properly handle the + # following scenario, which can be used inside TF implementations: + # + # ctx = ag_ctx.control_status_ctx() + # @function(autograph=False) # Low-level graph code + # def inner_fn(): + # # The context is disabled here, but should be enabled in user user_fn + # tf_convert(user_fn, ctx=ctx) + if ctx.status == ag_ctx.Status.ENABLED: + wrapper_factory = convert( + recursive=True, user_requested=user_requested, conversion_ctx=ctx) + elif ctx.status == ag_ctx.Status.DISABLED: + wrapper_factory = do_not_convert + elif ctx.status == ag_ctx.Status.UNSPECIFIED: + if convert_by_default: + wrapper_factory = convert( + recursive=True, user_requested=user_requested, conversion_ctx=ctx) + else: + wrapper_factory = call_with_unspecified_conversion_status + else: + assert False, 'This switch contains all possible cases!' + wrapper = wrapper_factory(f) + + if decorators: + wrapper = tf_decorator.rewrap(f_wrapper, f, wrapper) + + return autograph_artifact(wrapper) + + +def call_with_unspecified_conversion_status(func): + """Decorator that resets the conversion context to the unspecified status.""" + + def wrapper(*args, **kwargs): + with ag_ctx.ControlStatusCtx(status=ag_ctx.Status.UNSPECIFIED): + return func(*args, **kwargs) + + if inspect.isfunction(func) or inspect.ismethod(func): + wrapper = functools.update_wrapper(wrapper, func) + + return autograph_artifact(wrapper) + + +def _log_callargs(f, args, kwargs): + """Logging helper.""" + logging.log(2, 'Defaults of %s : %s', f, f.__defaults__) + logging.log(2, 'KW defaults of %s : %s', f, f.__kwdefaults__) + + if kwargs is not None: + callargs = tf_inspect.getcallargs(f, *args, **kwargs) + else: + callargs = tf_inspect.getcallargs(f, *args) + + formatted_callargs = '\n'.join( + ' {}: {}'.format(k, v) for k, v in callargs.items()) + logging.log(2, 'Calling %s with\n%s\n', f, formatted_callargs) + + +# +# Public API +# + + +@tf_export('autograph.experimental.do_not_convert') +def do_not_convert(func=None): + """Decorator that suppresses the conversion of a function. + + Args: + func: function to decorate. + + Returns: + If `func` is not None, returns a `Callable` which is equivalent to + `func`, but is not converted by AutoGraph. + If `func` is None, returns a decorator that, when invoked with a + single `func` argument, returns a `Callable` equivalent to the + above case. + """ + if func is None: + return do_not_convert + + def wrapper(*args, **kwargs): + with ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED): + return func(*args, **kwargs) + + if inspect.isfunction(func) or inspect.ismethod(func): + wrapper = functools.update_wrapper(wrapper, func) + + return autograph_artifact(wrapper) + + +# TODO(mdan): Make private. +def convert(recursive=False, + optional_features=None, + user_requested=True, + conversion_ctx=ag_ctx.NullCtx()): + """Decorator that compiles a function to use TensorFlow ops. + + The decorator is dynamic - it recompiles the target whenever the decorated + function is called. This means the parameter values are known at conversion. + It also means that repeated calls with different types of parameters will be + correctly processed. + + Args: + recursive: bool, whether to recursively convert any functions or classes + that the converted function may use. + optional_features: converted.Feature, allows toggling optional or + experimental features. When set to None, only the core features are + enabled. + user_requested: bool, whether this is a function that the user explicitly + asked to be converted. See ConversionOptions.user_requested. + conversion_ctx: Optional ag_ctx.ControlStatusCtx, the Autograph context in + which `f` is used. + + Returns: + Callable, a decorator that converts the given function into an equivalent + function that uses TensorFlow ops. + """ + + def decorator(f): + """Decorator implementation.""" + + def wrapper(*args, **kwargs): + """Wrapper that calls the converted version of f.""" + options = converter.ConversionOptions( + recursive=recursive, + user_requested=user_requested, + optional_features=optional_features) + try: + with conversion_ctx: + return converted_call(f, args, kwargs, options=options) + except Exception as e: # pylint:disable=broad-except + if hasattr(e, 'ag_error_metadata'): + raise e.ag_error_metadata.to_exception(e) + else: + raise + + if inspect.isfunction(f) or inspect.ismethod(f): + wrapper = functools.update_wrapper(wrapper, f) + + decorated_wrapper = tf_decorator.make_decorator(f, wrapper) + return autograph_artifact(decorated_wrapper) + + return decorator + + +# pylint:disable=line-too-long +@tf_export('autograph.to_graph', v1=[]) +def to_graph(entity, recursive=True, experimental_optional_features=None): + """Converts a Python entity into a TensorFlow graph. + + Also see: `tf.autograph.to_code`, `tf.function`. + + Unlike `tf.function`, `to_graph` is a low-level transpiler that converts + Python code to TensorFlow graph code. It does not implement any caching, + variable management or create any actual ops, and is best used where greater + control over the generated TensorFlow graph is desired. Another difference + from `tf.function` is that `to_graph` will not wrap the graph into a + TensorFlow function or a Python callable. Internally, `tf.function` uses + `to_graph`. + + Example usage: + + >>> def f(x): + ... if x > 0: + ... y = x * x + ... else: + ... y = -x + ... return y + ... + >>> converted_f = to_graph(f) + >>> x = tf.constant(2) + >>> converted_f(x) # converted_foo is like a TensorFlow Op. + + + Supported Python entities include: + * functions + * classes + * object methods + + Functions are converted into new functions with converted code. + + Classes are converted by generating a new class whose methods use converted + code. + + Methods are converted into unbound function that have an additional first + argument called `self`. + + For a tutorial, see the + [tf.function and AutoGraph guide](https://www.tensorflow.org/guide/function). + For more detailed information, see the + [AutoGraph reference documentation](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/index.md). + + Args: + entity: Python callable or class to convert. + recursive: Whether to recursively convert any functions that the converted + function may call. + experimental_optional_features: `None`, a tuple of, or a single + `tf.autograph.experimental.Feature` value. + + Returns: + Same as `entity`, the converted Python function or class. + + Raises: + ValueError: If the entity could not be converted. + """ + try: + program_ctx = converter.ProgramContext( + options=converter.ConversionOptions( + recursive=recursive, + user_requested=True, + optional_features=experimental_optional_features)) + return autograph_artifact(_convert_actual(entity, program_ctx)) + except (ValueError, AttributeError, KeyError, NameError, AssertionError) as e: + logging.error(1, 'Error converting %s', entity, exc_info=True) + raise ConversionError('converting {}: {}: {}'.format( + entity, e.__class__.__name__, str(e))) + + +@tf_export(v1=['autograph.to_graph']) +def to_graph_v1(entity, + recursive=True, + arg_values=None, + arg_types=None, + experimental_optional_features=None): + """Converts a Python entity into a TensorFlow graph. + + Also see: `tf.autograph.to_code`, `tf.function`. + + Unlike `tf.function`, `to_graph` is a low-level transpiler that converts + Python code to TensorFlow graph code. It does not implement any caching, + variable management or create any actual ops, and is best used where greater + control over the generated TensorFlow graph is desired. Another difference + from `tf.function` is that `to_graph` will not wrap the graph into a + TensorFlow function or a Python callable. Internally, `tf.function` uses + `to_graph`. + + _Example Usage_ + + ```python + def foo(x): + if x > 0: + y = x * x + else: + y = -x + return y + + converted_foo = to_graph(foo) + + x = tf.constant(1) + y = converted_foo(x) # converted_foo is a TensorFlow Op-like. + assert is_tensor(y) + ``` + + Supported Python entities include: + * functions + * classes + * object methods + + Functions are converted into new functions with converted code. + + Classes are converted by generating a new class whose methods use converted + code. + + Methods are converted into unbound function that have an additional first + argument called `self`. + + Args: + entity: Python callable or class to convert. + recursive: Whether to recursively convert any functions that the converted + function may call. + arg_values: Deprecated. + arg_types: Deprecated. + experimental_optional_features: `None`, a tuple of, or a single + `tf.autograph.experimental.Feature` value. + + Returns: + Same as `entity`, the converted Python function or class. + + Raises: + ValueError: If the entity could not be converted. + """ + del arg_types + del arg_values + return to_graph( + entity, + recursive=recursive, + experimental_optional_features=experimental_optional_features) + + +@tf_export(v1=['autograph.to_code']) +def to_code_v1(entity, + recursive=True, + arg_values=None, + arg_types=None, + indentation=' ', + experimental_optional_features=None): + """Returns the source code generated by AutoGraph, as a string. + + Example usage: + + >>> def f(x): + ... if x < 0: + ... x = -x + ... return x + >>> tf.autograph.to_code(f) + "...def tf__f(x):..." + + Also see: `tf.autograph.to_graph`. + + Note: If a function has been decorated with `tf.function`, pass its + underlying Python function, rather than the callable that `tf.function + creates: + + >>> @tf.function + ... def f(x): + ... if x < 0: + ... x = -x + ... return x + >>> tf.autograph.to_code(f.python_function) + "...def tf__f(x):..." + + Args: + entity: Python callable or class. + recursive: Whether to recursively convert any functions that the converted + function may call. + arg_values: Deprecated. + arg_types: Deprecated. + indentation: Deprecated. + experimental_optional_features: `None`, a tuple of, or a single + `tf.autograph.experimental.Feature` value. + + Returns: + The converted code as string. + """ + del arg_values + del arg_types + del indentation + return to_code( + entity, + recursive=recursive, + experimental_optional_features=experimental_optional_features) + + +@tf_export('autograph.to_code', v1=[]) +def to_code(entity, recursive=True, experimental_optional_features=None): + """Returns the source code generated by AutoGraph, as a string. + + Example usage: + + >>> def f(x): + ... if x < 0: + ... x = -x + ... return x + >>> tf.autograph.to_code(f) + "...def tf__f(x):..." + + Also see: `tf.autograph.to_graph`. + + Note: If a function has been decorated with `tf.function`, pass its + underlying Python function, rather than the callable that `tf.function + creates: + + >>> @tf.function + ... def f(x): + ... if x < 0: + ... x = -x + ... return x + >>> tf.autograph.to_code(f.python_function) + "...def tf__f(x):..." + + Args: + entity: Python callable or class to convert. + recursive: Whether to recursively convert any functions that the converted + function may call. + experimental_optional_features: `None`, a tuple of, or a single + `tf.autograph.experimental.Feature` value. + + Returns: + The converted code as string. + """ + source = tf_inspect.getsource( + to_graph( + entity, + recursive=recursive, + experimental_optional_features=experimental_optional_features)) + return textwrap.dedent(source) + + +_TRANSPILER = PyToTF() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/conversion.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..b2dd4c678c4c631d4bb9774cc8eec91ba436ce77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/conversion.py @@ -0,0 +1,227 @@ +# 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. +# ============================================================================== +"""Core conversion logic, serves as main point of access.""" + +import functools +import inspect +import sys +import unittest + +from tensorflow.python.autograph.core import config +from tensorflow.python.autograph.pyct import cache +from tensorflow.python.autograph.pyct import inspect_utils +from tensorflow.python.autograph.utils import ag_logging as logging +from tensorflow.python.eager.polymorphic_function import tf_method_target +from tensorflow.python.util import tf_inspect + + +_ALLOWLIST_CACHE = cache.UnboundInstanceCache() + + +def _is_of_known_loaded_module(f, module_name): + mod = sys.modules.get(module_name, None) + if mod is None: + return False + if any(v is not None for v in mod.__dict__.values() if f is v): + return True + return False + + +def _is_known_loaded_type(f, module_name, entity_name): + """Tests whether the function or method is an instance of a known type.""" + if (module_name not in sys.modules or + not hasattr(sys.modules[module_name], entity_name)): + return False + type_entity = getattr(sys.modules[module_name], entity_name) + if isinstance(f, type_entity): + # The method if of this type. Example: + # + # o = ClassType() + # function(o.method)() + return True + # Note: inspect is required here, to avoid unpacking tf.function decorators. + if inspect.ismethod(f): + # The unbound method if of this type. Example: + # + # class ClassType: + # @function + # def method(self): + # ... + # o = ClassType() + # o.method() + if isinstance(f.__func__, type_entity): + return True + return False + + +def is_unsupported(o): + """Checks whether an entity is supported by AutoGraph at all.""" + + # TODO(b/122265385): Remove this bypass. + if (_is_known_loaded_type(o, 'wrapt', 'FunctionWrapper') or + _is_known_loaded_type(o, 'wrapt', 'BoundFunctionWrapper')): + logging.warning( + '{} appears to be decorated by wrapt, which is not yet supported' + ' by AutoGraph. The function will run as-is.' + ' You may still apply AutoGraph before the wrapt decorator.'.format(o)) + logging.log(2, 'Permanently allowed: %s: wrapt decorated', o) + return True + + if _is_known_loaded_type(o, 'functools', '_lru_cache_wrapper'): + logging.log(2, 'Permanently allowed: %s: lru_cache', o) + return True + + # Constructors are permanently allowed. + # TODO(mdan): Toggle as experimental feature instead. + # TODO(b/124016764): Remove this limitation. + if inspect_utils.isconstructor(o): + logging.log(2, 'Permanently allowed: %s: constructor', o) + return True + + # Other built-in modules are permanently allowed. + # TODO(mdan): Figure out how to do this consistently for all stdlib modules. + if any( + _is_of_known_loaded_module(o, m) + for m in ('collections', 'pdb', 'copy', 'inspect', 're')): + logging.log(2, 'Permanently allowed: %s: part of builtin module', o) + return True + + # Custom ops and kernels are also permanently allowed. + # See tensorflow.framework.load_library. + if (hasattr(o, '__module__') and + hasattr(o.__module__, '_IS_TENSORFLOW_PLUGIN')): + logging.log(2, 'Permanently allowed: %s: TensorFlow plugin', o) + return True + + return False + + +# TODO(mdan): allow_namedtuple_subclass should be hardcoded to True. +def is_allowlisted( + o, check_call_override=True, allow_namedtuple_subclass=False): + """Checks whether an entity is allowed for use in graph mode. + + Examples of allowed entities include all members of the tensorflow + package. + + Args: + o: A Python entity. + check_call_override: Reserved for internal use. When set to `False`, it + disables the rule according to which classes are allowed if their + __call__ method is allowed. + allow_namedtuple_subclass: Reserved for internal use. When `True`, + namedtuple subclasses are not allowed. + + Returns: + Boolean + """ + # TODO(b/120224672): Fix this. + if isinstance(o, functools.partial): + # tf_inspect.getmodule(functools.partial(...)) otherwise returns None since + # functools.partial objects do not have a __module__ attribute. + m = functools + else: + m = tf_inspect.getmodule(o) + + # Examples of callables that lack a __module__ property include builtins. + if hasattr(m, '__name__'): + for rule in config.CONVERSION_RULES: + action = rule.get_action(m) + if action == config.Action.CONVERT: + logging.log(2, 'Not allowed: %s: %s', o, rule) + return False + elif action == config.Action.DO_NOT_CONVERT: + logging.log(2, 'Allowlisted: %s: %s', o, rule) + return True + + # The check for __code__ below is because isgeneratorfunction crashes + # without one. + if hasattr(o, '__code__') and tf_inspect.isgeneratorfunction(o): + logging.log(2, 'Allowlisted: %s: generator functions are not converted', o) + return True + + if (check_call_override and not tf_inspect.isclass(o) and + hasattr(o, '__call__')): + # Callable objects: allowed if their __call__ method is. + # The type check avoids infinite recursion around the __call__ method + # of function objects. + if (type(o) != type(o.__call__)) and is_allowlisted(o.__call__): # pylint: disable=unidiomatic-typecheck + logging.log(2, 'Allowlisted: %s: object __call__ allowed', o) + return True + + owner_class = None + if tf_inspect.ismethod(o): + # Methods of allowed classes are also allowed, even if they are + # bound via user subclasses. + # + # For example, suppose `tf.Foo` has a method called `bar`, and `baz` is + # defined as below. `tf.Foo` is allowed. Then `baz.bar` is also + # allowed. + # + # class Custom(tf.Foo): + # pass + # + # baz = Custom() + # + # For the example above, if `Custom` did overload `bar`, then it would no + # longer be allowed. + + owner_class = inspect_utils.getmethodclass(o) + if owner_class is tf_method_target.TfMethodTarget: + owner_class = o.__self__.target_class + if owner_class is not None: + if issubclass(owner_class, unittest.TestCase): + logging.log(2, 'Allowlisted: %s: method of TestCase subclass', o) + return True + + owner_class = inspect_utils.getdefiningclass(o, owner_class) + if is_allowlisted( + owner_class, + check_call_override=False, + allow_namedtuple_subclass=True): + logging.log(2, 'Allowlisted: %s: owner is allowed %s', o, + owner_class) + return True + + if inspect_utils.isnamedtuple(o): + # Due to the way they're constructed, namedtuple types cannot be converted + # because they don't expose source code. But we assume they are safe for + # graph mode since they are just containers. + if allow_namedtuple_subclass: + if not any(inspect_utils.isnamedtuple(base) for base in o.__bases__): + logging.log(2, 'Allowlisted: %s: named tuple', o) + return True + else: + logging.log(2, 'Allowlisted: %s: named tuple or subclass', o) + return True + + logging.log(2, 'Not allowed: %s: default rule', o) + return False + + +def is_in_allowlist_cache(entity, options): + try: + return _ALLOWLIST_CACHE.has(entity, options) + except TypeError: + # Catch-all for entities that are unhashable or don't allow weakrefs. + return False + + +def cache_allowlisted(entity, options): + try: + _ALLOWLIST_CACHE[entity][options] = True + except TypeError: + # Catch-all for entities that are unhashable or don't allow weakrefs. + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/testing/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/testing/pybind_for_testing.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/testing/pybind_for_testing.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ec051f113b7b79232a800ec015ff606dfcdc16a5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/impl/testing/pybind_for_testing.pyi @@ -0,0 +1,18 @@ +# 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. +# ============================================================================== + +class TestClassDef: + def __init__(self) -> None: ... + def method(self) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/directives.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/directives.py new file mode 100644 index 0000000000000000000000000000000000000000..c3647fc849e0dd36ad1aabdc09d232706c7b0390 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/directives.py @@ -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. +# ============================================================================== +"""Directives are special no-op functions that serve as compilation markers. + +They provide static information like type hints, compilation and TensorFlow +overrides. + +These serve as annotations in the compiled code, allowing the user some control +over the compilation process. They have no functional role at runtime. +""" + +from tensorflow.python.util.tf_export import tf_export + +UNSPECIFIED = object() + + +def set_element_type(entity, dtype, shape=UNSPECIFIED): + """Indicates that the entity is expected hold items of specified type/shape. + + The staged TensorFlow ops will reflect and assert this data type. Ignored + otherwise. + + Args: + entity: The entity to annotate. + dtype: TensorFlow dtype value to assert for entity. + shape: Optional shape to assert for entity. + """ + del entity + del dtype + del shape + + +@tf_export('autograph.experimental.set_loop_options') +def set_loop_options( + parallel_iterations=UNSPECIFIED, + swap_memory=UNSPECIFIED, + maximum_iterations=UNSPECIFIED, + shape_invariants=UNSPECIFIED): + """Specifies additional arguments to be passed to the enclosing while_loop. + + The parameters apply to and only to the immediately enclosing loop. It only + has effect if the loop is staged as a TF while_loop; otherwise the parameters + have no effect. + + Usage: + + >>> @tf.function(autograph=True) + ... def f(): + ... n = 0 + ... for i in tf.range(10): + ... tf.autograph.experimental.set_loop_options(maximum_iterations=3) + ... n += 1 + ... return n + + >>> @tf.function(autograph=True) + ... def f(): + ... v = tf.constant((0,)) + ... for i in tf.range(3): + ... tf.autograph.experimental.set_loop_options( + ... shape_invariants=[(v, tf.TensorShape([None]))] + ... ) + ... v = tf.concat((v, [i]), 0) + ... return v + + Also see tf.while_loop. + + Args: + parallel_iterations: The maximum number of iterations allowed to run in + parallel at any given time. Note that this does not guarantee parallel + execution. + swap_memory: Whether to store intermediate values needed for + gradients on the CPU instead of GPU. + maximum_iterations: Allows limiting the total number of iterations executed + by the loop. + shape_invariants: Allows controlling the argument with the same name passed + to tf.while_loop. Unlike tf.while_loop, this is a list of + `(tensor, shape)` pairs. + """ + del parallel_iterations + del swap_memory + del maximum_iterations + del shape_invariants diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/special_functions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/special_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..a2fa91ef6cdd2938992e7a4febf8ec5f61bd5e13 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/lang/special_functions.py @@ -0,0 +1,118 @@ +# 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. +# ============================================================================== +"""Special functions that only make sense for AutoGraph. + +These functions are meant to ensure feature parity between Python and AutoGraph, +so that the exact same code works in both modes. In general, AutoGraph will +replace these calls. +""" + +from tensorflow.python.autograph.operators import data_structures +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import tensor_util + + +def _validate_list_constructor(elements, element_dtype, element_shape): + """Validates the inputs of tensor_list.""" + if element_dtype is not None and element_shape is not None: + return + if tensor_util.is_tf_type(elements): + return + if isinstance(elements, (list, tuple)): + if elements: + return + else: + raise ValueError( + 'element_dtype and element_shape are required when elements are' + ' empty') + + raise ValueError( + 'unknown type for elements: {}; only Tensor, list and tuple are' + ' allowed'.format(type(elements))) + + +def match_staging_level(value, like_value): + """Casts a value to be staged at the same level as another.""" + if tensor_util.is_tf_type(like_value): + return constant_op.constant(value) + return value + + +def tensor_list(elements, + element_dtype=None, + element_shape=None, + use_tensor_array=False): + """Creates an tensor list and populates it with the given elements. + + This function provides a more uniform access to tensor lists and tensor + arrays, and allows optional initialization. + + Note: this function is a simplified wrapper. If you need greater control, + it is recommended to use the underlying implementation directly. + + Args: + elements: Iterable[tf.Tensor, ...], the elements to initially fill the list + with + element_dtype: Optional[tf.DType], data type for the elements in the list; + required if the list is empty + element_shape: Optional[tf.TensorShape], shape for the elements in the list; + required if the list is empty + use_tensor_array: bool, whether to use the more compatible but restrictive + tf.TensorArray implementation + Returns: + Union[tf.Tensor, tf.TensorArray], the new list. + Raises: + ValueError: for invalid arguments + """ + _validate_list_constructor(elements, element_dtype, element_shape) + if use_tensor_array: + return data_structures.tf_tensor_array_new(elements, element_dtype, + element_shape) + else: + return data_structures.tf_tensor_list_new(elements, element_dtype, + element_shape) + + +def stack(list_or_tensor, element_dtype=None, strict=True): + """Stacks the input, if it admits the notion of stacking. + + For example, a list of tensors can be stacked into a larger tensor. This + function is similar to tf.stack, but it accepts non-lists and lists of + non-tensors as arguments. In the latter case, the function does nothing. + + Args: + list_or_tensor: Any + element_dtype: tf.DType, optional dtypedtype for the elements in the list. + Required if the input is stackable, and the list is untyped. + strict: bool, if True an error is raised if the input is not stackable. + Otherwise the function is a no-op. + + Returns: + Any, if the input is stackable, the result will be a tf.Tensor. Otherwise, + if strict=False, the result will be list_or_tensor. + + Raises: + ValueError: if strict=True and the input is not stackable. + """ + if strict: + def raise_error(x): + raise ValueError('%s must be stackable when strict=True' % x) + original_call = raise_error + else: + original_call = lambda x: x + return data_structures.list_stack( + list_or_tensor, + data_structures.ListStackOpts( + element_dtype=element_dtype, original_call=original_call)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db275e6ed9dc9220f2dae1ade04434d9c86d410e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/__init__.py @@ -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. +# ============================================================================== +"""This module implements operators that AutoGraph overloads. + +Note that "operator" is used loosely here, and includes control structures like +conditionals and loops, implemented in functional form, using for example +closures for the body. +""" + +# Naming conventions: +# * operator names match the name usually used for the respective Python +# idiom; examples: for_stmt, list_append +# * operator arguments match either of: +# - the corresponding Python AST attribute (e.g. the condition of an if +# statement is called test) if the operator represents an AST construct +# - the names used in the Python docs, if the operator is a function (e.g. +# list_ and x for append, see +# https://docs.python.org/3.7/tutorial/datastructures.html) +# +# All operators may accept a final argument named "opts", of a type that +# subclasses namedtuple and contains any arguments that are only required +# for some specializations of the operator. + +from tensorflow.python.autograph.operators.conditional_expressions import if_exp +from tensorflow.python.autograph.operators.control_flow import for_stmt +from tensorflow.python.autograph.operators.control_flow import if_stmt +from tensorflow.python.autograph.operators.control_flow import while_stmt +from tensorflow.python.autograph.operators.data_structures import list_append +from tensorflow.python.autograph.operators.data_structures import list_pop +from tensorflow.python.autograph.operators.data_structures import list_stack +from tensorflow.python.autograph.operators.data_structures import ListPopOpts +from tensorflow.python.autograph.operators.data_structures import ListStackOpts +from tensorflow.python.autograph.operators.data_structures import new_list +from tensorflow.python.autograph.operators.exceptions import assert_stmt +from tensorflow.python.autograph.operators.logical import and_ +from tensorflow.python.autograph.operators.logical import eq +from tensorflow.python.autograph.operators.logical import not_ +from tensorflow.python.autograph.operators.logical import not_eq +from tensorflow.python.autograph.operators.logical import or_ +from tensorflow.python.autograph.operators.py_builtins import float_ +from tensorflow.python.autograph.operators.py_builtins import int_ +from tensorflow.python.autograph.operators.py_builtins import len_ +from tensorflow.python.autograph.operators.py_builtins import print_ +from tensorflow.python.autograph.operators.py_builtins import range_ +from tensorflow.python.autograph.operators.slices import get_item +from tensorflow.python.autograph.operators.slices import GetItemOpts +from tensorflow.python.autograph.operators.slices import set_item +from tensorflow.python.autograph.operators.variables import ld +from tensorflow.python.autograph.operators.variables import ldu +from tensorflow.python.autograph.operators.variables import Undefined +from tensorflow.python.autograph.operators.variables import UndefinedReturnValue diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/conditional_expressions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/conditional_expressions.py new file mode 100644 index 0000000000000000000000000000000000000000..28fd328834c65bf1fed10793bbdb9fdcde167276 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/conditional_expressions.py @@ -0,0 +1,52 @@ +# 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. +# ============================================================================== +"""Conditional expressions (e.g. the ternary if statement).""" + + +from tensorflow.python.autograph.operators import control_flow +from tensorflow.python.autograph.utils import tensors +from tensorflow.python.ops import cond as tf_cond + + +def if_exp(cond, if_true, if_false, expr_repr): + if tensors.is_dense_tensor(cond): + return _tf_if_exp(cond, if_true, if_false, expr_repr) + else: + return _py_if_exp(cond, if_true, if_false) + + +def _tf_if_exp(cond, if_true, if_false, expr_repr): + """Overload of if_exp that stages a TF cond.""" + # TODO(mdan): Use nonlocal once we no longer need to support py2. + true_val = [] + false_val = [] + + def true_fn(): + true_val.append(if_true()) + if true_val and false_val: + control_flow.verify_single_cond_var(expr_repr, true_val[0], false_val[0]) + return true_val[0] + + def false_fn(): + false_val.append(if_false()) + if true_val and false_val: + control_flow.verify_single_cond_var(expr_repr, true_val[0], false_val[0]) + return false_val[0] + + return tf_cond.cond(cond, true_fn, false_fn) + + +def _py_if_exp(cond, if_true, if_false): + return if_true() if cond else if_false() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/control_flow.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/control_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..8386c0c9edac54a2489999b0588fdc6c48761a61 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/control_flow.py @@ -0,0 +1,1270 @@ +# 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. +# ============================================================================== +"""Control flow statements: loops, conditionals, etc. + +Note: most of these operators accept pairs of get_state/set_state functions, to +capture mutations that the corresponding code blocks might make. These +mutations only need to be captured when staging the control flow, and they just +work when reverting to Python behavior. + +__Examples__ + +``` +while cond: + self.x += i +``` + +When the functionalized version is executed as a Python loop, it just works: + +``` +def loop_body(): + self.x += i # works as expected for Python loops +``` + +But it won't work for TF loops: + +``` +def loop_body(): + self.x += i # self.x has the wrong value! +``` + +get_state/set_state allow piping the mutations through the loop variables as +well, in effect changing the loop body: + +``` +def loop_body(self_x): + self.x = self_x # self.x now has the proper value + self.x += i # the original block + self_x = self.x # write self.x back into the loop vars + return self_x + +self_x = tf.while_loop(...) +self.x = self_x # the result is not properly captured +``` +""" + +import functools +import sys +import traceback + +import numpy as np + +from tensorflow.python.autograph.operators import py_builtins +from tensorflow.python.autograph.operators import variables +from tensorflow.python.autograph.utils import ag_logging +from tensorflow.python.autograph.utils import misc +from tensorflow.python.autograph.utils import tensors +from tensorflow.python.autograph.utils import type_registry +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.types import distribute +from tensorflow.python.util import nest +from tensorflow.python.util import variable_utils + + +PYTHON_MAX_ITERATIONS = 100000000 # Fails in about one minute for empty loops. +WARN_INEFFICIENT_UNROLL = True +INEFFICIENT_UNROLL_MIN_ITERATIONS = 50000 +INEFFICIENT_UNROLL_MIN_OPS = 1 + + +# TODO(mdan): Use the custom operator pattern instead of type dispatch. +# An example of this pattern is found in the implementation of distributed +# datasets. Before it can be used though, we need to standardize the interface. + +for_loop_registry = type_registry.TypeRegistry() + + +def _is_none_or_undef(value): + """Tests whether a value is None or undefined. + + AutoGraph represents undefined symbols using special objects of type Undefined + or UndefinedReturnValue. + + Args: + value: value to test + + Returns: + Boolean + """ + return ((value is None) + or isinstance(value, variables.UndefinedReturnValue) + or isinstance(value, variables.Undefined)) + + +def _verify_tf_condition(cond, tag): + """Ensures that the condition can be used in a TF control flow.""" + extra_hint = 'to check for None, use `is not None`' + cond = tensor_conversion.convert_to_tensor_v2(cond) + + if cond.dtype != dtypes.bool: + raise ValueError( + 'condition of {} expected to be `tf.bool` scalar, got {}' + '; to use as boolean Tensor, use `tf.cast`' + '; {}'.format(tag, cond, extra_hint)) + + if cond.shape is None or cond.shape.ndims is None: + # TODO(mdan): Consider a explicit size check, if not too slow. + cond = array_ops.reshape(cond, ()) + + elif cond.shape.ndims > 0: + known_dims = [d for d in cond.shape.as_list() if d is not None] + if np.prod(known_dims) > 1: + raise ValueError( + 'condition of {} expected to be `tf.bool` scalar, got {}' + '; {}'.format(tag, cond, extra_hint)) + else: + cond = array_ops.reshape(cond, ()) + + return cond + + +def verify_loop_init_vars( + init_vars, symbol_names, first_iter_vars=None, extra_message=None +): + """Ensures that all values in the state are valid to use in a TF loop. + + The init_vars may contain placeholder values derived from first_iter_vars. + + Args: + init_vars: initial loop variables (as taken before entering the loop) + symbol_names: corresponding names of the initial loop variables + first_iter_vars: loop variables after one iteration of the loop + extra_message: an extra string to append to the error message, in case of + "undefined variable" errors (see variables.Undefined) + """ + if not symbol_names: + return + if first_iter_vars is None: + first_iter_vars = (None,) * len(symbol_names) + + assert len(symbol_names) == len(init_vars) + assert len(symbol_names) == len(first_iter_vars) + for name, val, fi_val in zip(symbol_names, init_vars, first_iter_vars): + if isinstance(val, variables.UndefinedReturnValue): + if fi_val: + raise ValueError( + 'the return value from a TensorFlow loop may only be a {}; got {}' + .format(LEGAL_LOOP_TYPES, type(fi_val))) + else: + # TODO(mdan): This can be handled by removing the return value. + raise NotImplementedError( + 'a return statement cannot be placed inside this TensorFlow loop;' + ' this may happen if a return statement depends on a' + ' static Python condition such as a hyperparameter') + + error_msg = None + if val is None: + error_msg = "'{}' is not allowed to be None before the loop".format(name) + elif isinstance(val, variables.Undefined): + error_msg = "'{}' must be defined before the loop".format(name) + if extra_message: + error_msg += '\n' + extra_message + + if error_msg is not None: + raise ValueError(error_msg) + + +def _is_subshape(left, right): + """Returns True if left shape is at least as specific as right shape.""" + # TODO(mdan): This code should be in TensorShape. + # Note: this is not the same as TensorShape.is_compatible_with, which is + # symmetric. + # This code also duplicates _ShapeLessThanOrEqual from control_flow_ops.py. + if right.dims is None: + return True + if left.ndims != right.ndims: + return False + for ldim, rdim in zip(left.dims, right.dims): + if rdim.value is not None and ldim.value != rdim.value: + return False + return True + + +# TODO(mdan): Remove these verifications once TF ops can properly report names. +def _verify_single_loop_var( + name, check_shape, init, entry, exit_, shape_invariant): + """Verifies whether the initial, entry and exit values are consistent.""" + assert entry is not None, "no TF op should set '{}' to None?".format(name) + if exit_ is None: + raise ValueError("'{}' is None at the end of the iteration.".format(name)) + + if isinstance(init, (bool, int, float, str, np.ndarray)): + init = tensor_conversion.convert_to_tensor_v2(init) + if isinstance(entry, (bool, int, float, str, np.ndarray)): + entry = tensor_conversion.convert_to_tensor_v2(entry) + if isinstance(exit_, (bool, int, float, str, np.ndarray)): + exit_ = tensor_conversion.convert_to_tensor_v2(exit_) + + if (not tensor_util.is_tf_type(entry) or + not tensor_util.is_tf_type(exit_)): + return + + # TODO(mdan): Properly account for CompositeTensors. + if (not hasattr(entry, 'dtype') or + not hasattr(exit_, 'dtype')): + return + if (not hasattr(entry, 'shape') or + not hasattr(exit_, 'shape')): + return + + if entry.dtype != exit_.dtype: + raise TypeError( + "'{}' has dtype {} before the loop, but dtype {} after one" + ' iteration'.format( + name, + entry.dtype.name, + exit_.dtype.name, + )) + if check_shape: + exit_shape = exit_.shape + if shape_invariant is None: + entry_shape = entry.shape + if not _is_subshape(exit_shape, entry_shape): + raise ValueError( + "'{}' has shape {} before the loop, but shape {} after one" + ' iteration. Use tf.autograph.experimental.set_loop_options to set' + ' shape invariants.'.format(name, entry_shape, exit_shape)) + else: + init_shape = init.shape + if not _is_subshape(init_shape, shape_invariant): + raise ValueError( + "'{}' has shape {} before the loop, which does not conform with" + ' the shape invariant {}.'.format(name, init_shape, + shape_invariant)) + if not _is_subshape(exit_shape, shape_invariant): + raise ValueError( + "'{}' has shape {} after one iteration, which does not conform with" + ' the shape invariant {}.'.format(name, exit_shape, shape_invariant) + ) + + +def verify_tf_loop_vars( + init_vars, + iter_entry_vars, + iter_exit_vars, + symbol_names, + opts, + check_shapes=True, +): + """Verifies loop variables for consistency.""" + if check_shapes and 'shape_invariants' in opts: + shape_invariants = opts['shape_invariants'] + else: + shape_invariants = nest.map_structure(lambda _: None, iter_entry_vars) + + assert len(symbol_names) == len(shape_invariants) + assert len(symbol_names) == len(init_vars) + assert len(symbol_names) == len(iter_entry_vars) + assert len(symbol_names) == len(iter_exit_vars) + + for i in range(len(symbol_names)): + name = symbol_names[i] + init = init_vars[i] + entry = iter_entry_vars[i] + exit_ = iter_exit_vars[i] + invariant = shape_invariants[i] + + try: + nest.assert_same_structure(init, entry, expand_composites=True) + except (ValueError, TypeError): + # `Variable`s in `init` may be implicitly converted to `Tensor`s. Convert + # `ResourceVariable`s to Tensors so tf.nest.assert_same_structure + # won't break due to type spec mismatches between `ResourceVariable`s and + # `Tensor`s. + try: + init_tensors = variable_utils.convert_variables_to_tensors(init) + nest.assert_same_structure(init_tensors, entry, expand_composites=True) + except (ValueError, TypeError) as e: + raise TypeError("'{}' does not have the same nested structure after one" + ' iteration.\n\n{}'.format(name, e)) from e + + try: + nest.assert_same_structure(entry, exit_, expand_composites=True) + except (ValueError, TypeError) as e: + raise TypeError("'{}' does not have the same nested structure after one" + ' iteration.\n\n{}'.format(name, e)) from e + if invariant is not None: + try: + nest.assert_same_structure(init, invariant, expand_composites=False) + except (ValueError, TypeError) as e: + raise TypeError("'{}' does not have the same nested structure as its" + ' corresponding shape invariant.\n\n{}'.format( + name, e)) from e + + nest.map_structure( + functools.partial(_verify_single_loop_var, name, check_shapes), init, + entry, exit_, invariant) + + +def verify_single_cond_var(name, body_var, orelse_var): + """Verifies whether body_var and orelse_var are consistent.""" + if body_var is None: + raise ValueError("'{}' is None at the end of the main branch.".format(name)) + if orelse_var is None: + raise ValueError( + "'{}' is None at the end of the else branch.".format(name)) + + if isinstance(body_var, (bool, int, float, str, np.ndarray)): + body_var = tensor_conversion.convert_to_tensor_v2(body_var) + + if isinstance(orelse_var, (bool, int, float, str, np.ndarray)): + orelse_var = tensor_conversion.convert_to_tensor_v2(orelse_var) + + if (not tensor_util.is_tf_type(body_var) or + not tensor_util.is_tf_type(orelse_var)): + return + + # TODO(mdan): Properly account for CompositeTensors. + if (not hasattr(body_var, 'dtype') or + not hasattr(orelse_var, 'dtype')): + return + + if body_var.dtype != orelse_var.dtype: + raise TypeError( + "'{}' has dtype {} in the main branch, but dtype {} in the else" + ' branch'.format(name, body_var.dtype.name, + orelse_var.dtype.name)) + + +def _verify_tf_cond_branch_vars(vars_, symbol_names, branch_name): + """Verifies variables output by a conditional branch for consistency.""" + for name, var_ in zip(symbol_names, vars_): + if isinstance(var_, variables.Undefined): + raise ValueError( + "'{}' must also be initialized in the {} branch".format( + name, branch_name)) + if isinstance(var_, variables.UndefinedReturnValue): + raise ValueError( + 'the {} branch must also have a return statement.'.format( + branch_name)) + + +def _verify_tf_cond_vars(body_vars, orelse_vars, symbol_names): + """Verifies variables manipulated by a conditional for consistency.""" + named_vars = zip(symbol_names, body_vars, orelse_vars) + + for name, body_var, orelse_var in named_vars: + try: + nest.assert_same_structure(body_var, orelse_var, expand_composites=True) + except (ValueError, TypeError): + # One branch of cond could be a `Tensor`, while the other branch could be + # a `ResourceVariable`. Convert `ResourceVariable`s to `Tensor`s so + # assert_same_structure won't fail. + try: + body_var_tensors = variable_utils.convert_variables_to_tensors(body_var) + orelse_var_tensors = variable_utils.convert_variables_to_tensors( + orelse_var) + nest.assert_same_structure(body_var_tensors, orelse_var_tensors, + expand_composites=True) + except (ValueError, TypeError) as e: + raise TypeError( + "'{}' must have the same nested structure in the main and else" + ' branches:\n\n{}'.format(name, str(e))) from e + nest.map_structure( + functools.partial(verify_single_cond_var, name), body_var, orelse_var) + + +def for_stmt(iter_, extra_test, body, get_state, set_state, symbol_names, opts): + """Functional form of a for statement. + + The loop operates on a state, which includes all symbols that are + variant across loop iterations, excluding the variables local to the loop. + + For example, given the loop below that calculates the geometric and + arithmetic means or some numbers: + + ``` + geo_mean = 1 + arith_mean = 0 + for i in range(n): + a = numbers[i] + geo_mean *= a + arith_mean += a + ``` + + The state is represented by the variables named geo_mean and arith_mean. The + `extra_test`, `body`, `get_state` and `set_state` functions must bind to the + original `geo_mean` and `arith_mean` symbols, using `nonlocal`. + + The inputs and outputs of the callables representing the loop blocks are not + explicit - instead, these functions must use nonlocal/global for side effects. + The inputs and outputs are instead controlled by the set_state/get_state + functions. + + Args: + iter_: The entity being iterated over. + extra_test: Callable with boolean return type. An additional loop condition. + body: Callable representing the actual loop body. + get_state: Additional callable which can capture additional state (such as + the values of composite symbols). This is only useful when staging the + loop. + set_state: Additional callable which save values captured by get_state back + into the Python environment. This is only useful when staging the loop. + symbol_names: Tuple containing names of the loop variables returned by + get_state. + opts: Optional dict of extra loop parameters. + """ + + try: + for_fn = for_loop_registry.lookup(iter_) + except LookupError: + for_fn = _py_for_stmt + + if tensor_util.is_tf_type(iter_): + if tensors.is_range_tensor(iter_): + for_fn = _tf_range_for_stmt + else: + for_fn = _known_len_tf_for_stmt + elif isinstance(iter_, distribute.Iterator): + for_fn = _tf_iterator_for_stmt + elif isinstance(iter_, distribute.Iterable): + # TODO(b/162250181): Use _tf_iterator_for_stmt(iter(iter_)... + for_fn = _tf_distributed_iterable_for_stmt + + for_fn(iter_, extra_test, body, get_state, set_state, symbol_names, opts) + + +def _py_for_stmt( + iter_, extra_test, body, get_state, set_state, symbol_names, opts +): + """Overload of for_stmt that executes a Python for loop.""" + del get_state, set_state, symbol_names, opts + + if __debug__: + checker = _PythonLoopChecker() + before_iteration = checker.before_iteration + after_iteration = checker.after_iteration + before_iteration() + + original_body = body + def protected_body(protected_iter): + original_body(protected_iter) + after_iteration() + before_iteration() + body = protected_body + + if extra_test is not None: + def guarded_extra_test(): + extra_test_result = extra_test() + try: + # Note: Using try/except and not tensor_util.is_tf_type to avoid + # performance degradation. + return bool(extra_test_result) + except errors_impl.OperatorNotAllowedInGraphError as e: + ag_logging.log( + 1, + 'Caught error while evaluating loop stop condition', + exc_info=True) + # TODO(mdan): We can pass the location of extra_test and show it here. + raise NotImplementedError( + 'break and return statements which depend on a TF condition are not' + ' supported in Python for loops. Did you intend to make it a TF' + ' loop?\nSee ' + 'https://github.com/tensorflow/tensorflow/blob/master/tensorflow/' + 'python/autograph/g3doc/reference/limitations.md' + '#consistency-of-control-flow-types for more info.') from e + + if guarded_extra_test(): + for target in iter_: + body(target) + if not guarded_extra_test(): + break + + else: + for target in iter_: + body(target) + + +def _add_max_iterations_hint(opts, n): + # TODO(b/159186914): Remove the safeguard, and always set maximum_iterations. + if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()): + opts['maximum_iterations'] = n + + +def _known_len_tf_for_stmt( + iter_, extra_test, body, get_state, set_state, symbol_names, opts): + """Overload of for_stmt that iterates over TF entities that admit a length.""" + n = py_builtins.len_(iter_) + + # TODO(b/117628877): Revisit performance once XLA has the necessary support. + # Note: using a TensorArray creates an extra copy, but can calculate + # gradients more efficiently than StridedSlice. + ta = tensor_array_ops.TensorArray(iter_.dtype, size=n) + iter_ = ta.unstack(iter_) + + iterate_index = 0 + + def aug_get_state(): + return (iterate_index,) + get_state() + + def aug_set_state(aug_loop_vars): + nonlocal iterate_index + # TODO(b/171479293): Drop the lint override. + iterate_index, *loop_vars = aug_loop_vars # pylint:disable=unused-variable + # The iteration index is not "output" by the for loop. If the iteration index + # is used outside the loop, it will appear in the loop vars separately. + set_state(loop_vars) + + def aug_body(): + nonlocal iterate_index + body(iter_.read(iterate_index)) + iterate_index += 1 + + def aug_test(): + main_test = iterate_index < n + if extra_test is not None: + return tf_cond.cond(main_test, extra_test, lambda: False) + return main_test + + _add_max_iterations_hint(opts, n) + + _tf_while_stmt( + aug_test, + aug_body, + aug_get_state, + aug_set_state, + ('',) + symbol_names, + opts, + ) + + +def _tf_range_for_stmt( + iter_, extra_test, body, get_state, set_state, symbol_names, opts): + """Overload of for_stmt that iterates over a TF range (and elides it).""" + start, limit, delta = iter_.op.inputs + + iterate = start + + def _value_or(name, var, default): + if (name == opts['iterate_names'] and isinstance(var, variables.Undefined)): + return default + return var + + def aug_get_state(): + state_vars = get_state() + state_vars = tuple( + _value_or(name, var, iterate) + for name, var in zip(symbol_names, state_vars)) + return (iterate,) + state_vars + + def aug_set_state(aug_loop_vars): + nonlocal iterate + # TODO(b/171479293): Drop the lint override. + iterate, *loop_vars = aug_loop_vars # pylint:disable=unused-variable + # The iteration index is not "output" by the for loop. If the iterate + # is used outside the loop, it will appear in the loop vars separately. + set_state(loop_vars) + + def aug_body(): + nonlocal iterate + body(iterate) + iterate += delta + + def aug_test(): + # TODO(b/159713842): Remove once constant folding works. + const_delta = tensor_util.constant_value(delta) + if const_delta is not None: + if const_delta >= 0: + main_test = iterate < limit + else: + main_test = iterate > limit + else: + main_test = math_ops.logical_or( + math_ops.logical_and(delta >= 0, iterate < limit), + math_ops.logical_and(delta < 0, iterate > limit)) + + if extra_test is not None: + main_test = tf_cond.cond(main_test, extra_test, lambda: False) + return main_test + + _add_max_iterations_hint( + opts, + math_ops.cast(misc.get_range_len(start, limit, delta), dtypes.int32)) + + _tf_while_stmt( + aug_test, + aug_body, + aug_get_state, + aug_set_state, + ('',) + symbol_names, + opts) + + +def _tf_iterator_for_stmt( + iter_, extra_test, body, get_state, set_state, symbol_names, opts): + """Overload of for_stmt that iterates over TF Iterators. See for_loop.""" + symbol_names = ('',) + symbol_names + has_next = True + + def aug_get_state(): + return (has_next,) + get_state() + + def aug_set_state(aug_loop_vars): + nonlocal has_next + # TODO(b/171479293): Drop the lint override. + has_next, *loop_vars = aug_loop_vars # pylint:disable=unused-variable + set_state(loop_vars) + + init_vars = aug_get_state() + verify_loop_init_vars(init_vars, symbol_names) + + def aug_body(): + """Main body passed to _tf_while_stmt.""" + nonlocal has_next + opt_iterate = iter_.get_next_as_optional() + has_next = opt_iterate.has_value() + loop_vars = aug_get_state() # updated by set_state() in _tf_while_loop. + + def main_path(): + body(opt_iterate.get_value()) + new_loop_vars = aug_get_state() + # Note: this verification duplicates the one performed in tf_while_stmt, + # but needs to be done earlier to prevent the tf.cond from blowing up + # first. + verify_tf_loop_vars( + init_vars, loop_vars, new_loop_vars, symbol_names, opts) + return new_loop_vars + + def noop_path(): + return loop_vars + + # TODO(mdan): If tf.while_loop supported Optional, this could be avoided. + # Calling set_state so that get_state() _tf_while_loop sees the conditional + # tensors. + aug_set_state( + tf_cond.cond(has_next, main_path, noop_path)) + + def aug_test(): + # This value takes a complicated path to get here: + # prev_iteration_body -> get_state -> tf.while_loop (as loop var) + # -> current_iteration_body -> set_state -> has_next + main_test = has_next + if extra_test is not None: + return tf_cond.cond(main_test, extra_test, lambda: False) + return main_test + + _tf_while_stmt( + aug_test, + aug_body, + aug_get_state, + aug_set_state, + symbol_names, + opts) + + +def _tf_distributed_iterable_for_stmt( + iter_, extra_test, body, get_state, set_state, symbol_names, opts): + """Overload of for_stmt that iterates over TF distributed datasets.""" + + if extra_test is not None: + raise NotImplementedError( + 'break and return statements are not yet supported in ' + 'for ... in distributed input loops.') + + init_vars = get_state() + verify_loop_init_vars(init_vars, symbol_names) + + if 'shape_invariants' in opts: + opts['shape_invariants'] = _shape_invariants_mapping_to_positional_list( + opts['shape_invariants'], init_vars) + + def reduce_body(loop_vars, iterate): + set_state(loop_vars) + body(iterate) + new_loop_vars = get_state() + verify_tf_loop_vars( + init_vars, loop_vars, new_loop_vars, symbol_names, opts) + return new_loop_vars + + set_state(iter_.reduce(init_vars, reduce_body)) + + +def while_stmt(test, body, get_state, set_state, symbol_names, opts): + """Functional form of a while statement. + + The loop operates on a so-called state, which includes all symbols that are + variant across loop iterations. In what follows we refer to state as either + a tuple of entities that represent an actual state, or a list of arguments + of the corresponding types. + + The inputs and outputs of the callables representing the loop blocks are not + explicit - instead, these functions must use nonlocal/global for side effects. + The inputs and outputs are instead controlled by the set_state/get_state + functions. + + Args: + test: Callable with boolean return type. The loop condition. + body: Callable representing the actual loop body. + get_state: Additional callable which can capture additional state (such as + the values of composite symbols). This is only useful when staging the + loop. + set_state: Additional callable which save values captured by get_state back + into the Python environment. This is only useful when staging the loop. + symbol_names: Tuple containing the names of all loop variables. + opts: Optional dict of extra loop parameters. + + Returns: + Tuple containing the final state. + """ + + # Evaluate the initial test once in order to do the dispatch. The evaluation + # is isolated to minimize unwanted side effects. + # TODO(mdan): Do a full iteration - some state types might lower to Tensor. + with func_graph.FuncGraph('tmp').as_default(): + init_test = test() + + # TensorFlow: Multiple evaluations are acceptable in this case, so we're fine + # with the re-evaluation of `test` that `_tf_while_stmt` will make. + if tensors.is_dense_tensor(init_test): + _tf_while_stmt(test, body, get_state, set_state, symbol_names, opts) + return + + # Normal Python: We already consumed one evaluation of `test`; consistently, + # unroll one iteration before dispatching to a normal loop. + # TODO(mdan): Push the "init_test" value via opts into _py_while_stmt? + if not init_test: + return + body() + + _py_while_stmt(test, body, get_state, set_state, opts) + + +class _PythonLoopChecker(object): + """Verifies Python loops for TF-specific limits.""" + + __slots__ = ( + 'iterations', + 'check_inefficient_unroll', + 'check_op_count_after_iteration', + 'ops_before_iteration', + ) + + def __init__(self): + self.iterations = 1 + self.check_inefficient_unroll = WARN_INEFFICIENT_UNROLL + + # Triggered when we decided to test the op counts. + self.check_op_count_after_iteration = False + + def _get_ops(self): + return set(ops.get_default_graph().get_operations()) + + def _check_unroll_limits(self): + if self.iterations > PYTHON_MAX_ITERATIONS: + raise ValueError('iteration limit exceeded') + + def _stop_checking_inefficient_unroll(self): + self.check_inefficient_unroll = False + self.check_op_count_after_iteration = False + self.ops_before_iteration = None + + def _verify_inefficient_unroll(self): + """Checks for possibly-inefficient creation of ops in a Python loop.""" + assert self.ops_before_iteration is not None + ops_after_iteration = self._get_ops() + new_ops = tuple( + op for op in ops_after_iteration if op not in self.ops_before_iteration) + + if len(new_ops) < INEFFICIENT_UNROLL_MIN_OPS: + return False + + ag_logging.warning( + 'Large unrolled loop detected. Did you mean to use a TF loop?' + ' The following ops were created after iteration %s: %s' + '\nSee' + ' https://github.com/tensorflow/tensorflow/blob/master/' + 'tensorflow/python/autograph/g3doc/reference/common_errors.md' + '#warning-large-unrolled-loop-detected' + '\n' + 'Location:' + '\n%s' + '', self.iterations, new_ops, '\n'.join(traceback.format_stack())) + return True + + def before_iteration(self): + """Called before each iteration in a Python loop.""" + if (self.check_inefficient_unroll and + self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS): + self.ops_before_iteration = self._get_ops() + self.check_op_count_after_iteration = True + + def after_iteration(self): + """Called after each iteration in a Python loop.""" + self.iterations += 1 + + self._check_unroll_limits() + + if self.check_op_count_after_iteration: + did_warn = self._verify_inefficient_unroll() + if did_warn: + self._stop_checking_inefficient_unroll() # Only warn once. + elif self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS + 3: + # Once deciding to check the op counts, only do it for a few iterations. + self._stop_checking_inefficient_unroll() + + +def _py_while_stmt(test, body, get_state, set_state, opts): + """Overload of while_stmt that executes a Python while loop.""" + del opts, get_state, set_state + + if __debug__: + checker = _PythonLoopChecker() + before_iteration = checker.before_iteration + after_iteration = checker.after_iteration + before_iteration() + + original_body = body + def protected_body(): + original_body() + after_iteration() + before_iteration() + body = protected_body + + def guarded_test(): + test_result = test() + try: + # Note: Using try/except and not tensor_util.is_tf_type to avoid + # performance degradation. + return bool(test_result) + except errors_impl.OperatorNotAllowedInGraphError as e: + ag_logging.log( + 1, + 'Caught error while evaluating while loop condition', + exc_info=True) + # TODO(mdan): distinguish beteen these two cases. + raise NotImplementedError( + 'The condition of while loop started as non-Tensor, then changed to' + ' Tensor. This may happen either because variables changed type, or' + ' when a break or return statement inside the loop depends on a' + ' Tensor condition. In both cases, changing to a TF loop should' + ' remove the error.\nSee ' + 'https://github.com/tensorflow/tensorflow/blob/master/tensorflow/' + 'python/autograph/g3doc/reference/limitations.md' + '#consistency-of-control-flow-types for more info.') from e + while guarded_test(): + body() + + +def _shape_invariants_mapping_to_positional_list(mapping, keys): + # The keys are not expected to be hashable. + mapping = {id(k): (k, v) for k, v in mapping} + result = [] + for k in keys: + map_key, map_val = mapping.get(id(k), (None, None)) + result.append( + map_val if map_key is k else nest.map_structure(lambda _: None, k)) + return tuple(result) + + +# Textual description of what a legal TF loop variable is. This description +# summarizes types that _placeholder_value below can handle. Keep the two +# together and in sync. +LEGAL_LOOP_TYPES = 'Tensor, int, float, bool or a list, tuple or dict thereof' + + +def _placeholder_value(like, shape_invariant, original=None): + """Constructs a (dummy) placeholder value for a loop-initialized variable. + + Args: + like: Any object. The value created by the first iteration of the loop. If a + Python scalar, the placeholder will be the zero value of that type. If a + Tensor, the placeholder will be a zero tensor of matching shape and dtype. + If a list, dict or tuple, the placeholder will be an identical structure + of placeholders. + shape_invariant: The shape invariant specified by the user (or None, if + nothing was specified) for the respective variable. + original: Any object. The value of the variable prior to entering the loop. + Typically, this is one of the special "Undefined" value, because that's + when a placeholder is needed. + + Returns: + Either a zero value of structure, shape and dtype mathing 'like', or + 'original', if no such zero value could be created. + """ + if like is None: + return original, None + + elif isinstance(like, (variables.Undefined, variables.UndefinedReturnValue)): + return original, None + + elif isinstance(like, (int, float, bool)): + return type(like)(0), None + + elif tensor_util.is_tf_type(like): + + like_shape = shape_invariant if shape_invariant is not None else like.shape + if like_shape is None or like_shape.rank is None: + return array_ops.zeros((), like.dtype), like_shape + + # If the shape contains dynamic values, set the corresponding starting + # dimension to either zero or what the shape invariant specified. + placeholder_shape = [] + has_dynamic_dims = False + for s, i in zip(like.shape, like_shape): + if i is None: + like_dim = 0 + elif isinstance(i, tensor_shape.Dimension): + if i.value is None: + like_dim = 0 + else: + like_dim = i.value + else: + like_dim = i + + if s is None: + placeholder_shape.append(like_dim) + has_dynamic_dims = True + elif isinstance(s, tensor_shape.Dimension): + if s.value is None: + placeholder_shape.append(like_dim) + has_dynamic_dims = True + else: + placeholder_shape.append(s.value) + else: + placeholder_shape.append(s) + + if has_dynamic_dims: + invariant = like_shape + else: + invariant = None + + return array_ops.zeros(placeholder_shape, like.dtype), invariant + + elif isinstance(like, (list, tuple, dict)): + if shape_invariant is None: + zipped = nest.map_structure(lambda v: _placeholder_value(v, None), + nest.flatten(like)) + else: + zipped = nest.map_structure(_placeholder_value, nest.flatten(like), + nest.flatten(shape_invariant)) + vals, invars = zip(*zipped) + return (nest.pack_sequence_as(like, + vals), nest.pack_sequence_as(like, invars)) + + # This is to be caught by _try_handling_undefineds, to give more context. + raise TypeError( + "Found an unsupported type '{}' while creating placeholder for {}." + ' Supported types include Tensor, int, float, bool, list, tuple or dict.' + .format(type(like).__name__, like)) + + +def _try_handling_undefineds(body, get_state, set_state, init_vars, nulls, + shape_invariants, symbol_names): + """Makes a best-effort attempt to substitute undefineds with placeholders. + + Note: this substitution requires two things to happen: + 1. the types of loop variables could be inferred (usually by staging one + iteration) + 2. these types could be replaced by placeholders (e.g. zero values, for + tensors). + + Args: + body: a function representing the loop body. See while_stmt. + get_state: state getter for the loop statement. See while_stmt. + set_state: state getter for the loop statement. See while_stmt. + init_vars: loop variables before entering the loop. See while_stmt. + nulls: list of boolean flags indicating whether the corresponding loop var + is None or undefined. + shape_invariants: user-specified shape invariant for each loop variable. + symbol_names: list of loop variable names. See while_stmt. + + Returns: + A tuple (success, new_init_vars, extra_shape_invariants, failure_message): + * success is a boolean flag indicating + whether types could be successfully inferred (step 1 above) + * new_init_vars contains the loop vars, with None or undefined values + replaced by default values, where possible (step 2 above) + * extra_shape_invariants contains shape invariants that would be needed + by while_stmt, for instance if the placeholder values had a shape + different from the corresponding loop outputs + """ + state_modified = False + first_iter_vars = None + failure_message = None + + try: + # Stage an iteration of the loop body in a temporary graph. + with func_graph.FuncGraph('tmp').as_default(): + # This call to set_state helps report nicer error messages when symbols + # are inconsistently used. + # Another complication is that non_tensor values will be autocast to + # Tensor by while_loop, and their static value lost. So we need to account + # that here. + def autocast_to_tensor(v): + if isinstance( + v, (int, float, bool, str, list, tuple, np.ndarray, np.generic)): + init_val = tensor_conversion.convert_to_tensor_v2(v) + return array_ops.placeholder(init_val.dtype, init_val.shape) + return v + autocast_init_vars = nest.map_structure(autocast_to_tensor, init_vars) + set_state(autocast_init_vars) + state_modified = True + + body() + first_iter_vars = get_state() + + # Note: the actual placeholder value doesn't matter, because as the + # staging proved, it will be replaced by an actual value before being + # read. + inits_and_invariants = tuple( + (_placeholder_value(iv, i, v) if n else (v, None)) + for v, n, iv, i in zip(init_vars, nulls, first_iter_vars, + shape_invariants)) + init_vars, extra_shape_invariants = zip(*inits_and_invariants) + success = True + + except (UnboundLocalError, TypeError, ValueError, KeyError): + ag_logging.log(1, 'Caught error while staging loop body', exc_info=True) + # Fall back to the old functionality. It will likely result in an input + # validation failure. + exc = sys.exc_info() + failure_message = ( + 'Note: AutoGraph tried to define it automatically, but ran into a' + ' {}: {}'.format(exc[0].__name__, exc[1])) + + finally: + if state_modified: + set_state(init_vars) + + # This check runs regardless, in case we captured non-Tensor inputs. + verify_loop_init_vars( + init_vars, symbol_names, first_iter_vars, extra_message=failure_message) + + return success, init_vars, extra_shape_invariants + + +def _runtime_zero_iterations_errmsg(symbol_names, nulls, init_vars): + """Creates an error message asking for the loop to iterate at least once.""" + var_names = [] + for sn, n, v in zip(symbol_names, nulls, init_vars): + if not n: + continue + if isinstance(v, variables.UndefinedReturnValue): + var_names.append('the function return value') + else: + var_names.append(sn) + var_names = ', '.join(var_names) + return 'loop must iterate at least once to initialize {}'.format(var_names) + + +def _tf_while_stmt(test, body, get_state, set_state, symbol_names, opts): + """Overload of while_stmt that stages a TF while_stmt.""" + init_vars = get_state() + orig_init_vars = init_vars + + nulls = tuple(_is_none_or_undef(v) for v in init_vars) + if any(nulls): + shape_invars_by_init_vals = { + id(v): i for v, i in opts.get('shape_invariants', ()) + } + shape_invariants = tuple( + shape_invars_by_init_vals.get(id(v), None) for v in orig_init_vars) + (require_one_iteration, init_vars, + extra_shape_invariants) = _try_handling_undefineds(body, get_state, + set_state, init_vars, + nulls, shape_invariants, + symbol_names) + else: + require_one_iteration = False + + if require_one_iteration: + merged_shape_invariants = dict(shape_invars_by_init_vals) + # This has two roles: + # 1. Shape invariants are remapped from the old init vars to the new ones. + # 2. Any new shape invariants created by the init vars are kept, but only + # if the user didn't already specify some. + for v, nv, ni in zip(orig_init_vars, init_vars, extra_shape_invariants): + merged_invariant = merged_shape_invariants.get(id(v), ni) + if merged_invariant is not None: + merged_shape_invariants[id(nv)] = merged_invariant + merged_shape_invariants = tuple((nv, merged_shape_invariants[id(nv)]) + for nv in init_vars + if id(nv) in merged_shape_invariants) + if merged_shape_invariants: + opts = dict(**opts) + opts['shape_invariants'] = merged_shape_invariants + + def aug_test(*loop_vars): + if require_one_iteration: + loop_vars = loop_vars[1:] + + set_state(loop_vars) + return _verify_tf_condition(test(), 'while loop') + + def aug_body(*loop_vars): + if require_one_iteration: + loop_vars = loop_vars[1:] + + set_state(loop_vars) + body() + new_loop_vars = get_state() + verify_tf_loop_vars( + init_vars, loop_vars, new_loop_vars, symbol_names, opts) + + if require_one_iteration: + new_loop_vars = (True,) + new_loop_vars + + return new_loop_vars + + if 'shape_invariants' in opts: + opts['shape_invariants'] = _shape_invariants_mapping_to_positional_list( + opts['shape_invariants'], init_vars) + + while_loop_opts = dict(opts) + while_loop_opts.pop('iterate_names', None) + + # Non-v2 while_loop unpacks the results when there is only one return value. + # This enforces consistency across versions. + while_loop_opts['return_same_structure'] = True + + if require_one_iteration: + aug_init_vars = (False,) + init_vars + if 'shape_invariants' in while_loop_opts: + while_loop_opts['shape_invariants'] = ( + (None,) + while_loop_opts['shape_invariants']) + else: + aug_init_vars = init_vars + + final_loop_vars = while_loop.while_loop(aug_test, aug_body, aug_init_vars, + **while_loop_opts) + + if require_one_iteration: + with ops.control_dependencies([ + control_flow_assert.Assert(final_loop_vars[0], [ + _runtime_zero_iterations_errmsg(symbol_names, nulls, orig_init_vars) + ]) + ]): + final_loop_vars = nest.map_structure( + lambda v: (array_ops.identity(v) if tensor_util.is_tf_type(v) else v), + final_loop_vars[1:], + ) + + set_state(final_loop_vars) + + +def if_stmt(cond, body, orelse, get_state, set_state, symbol_names, nouts): + """Functional form of an if statement. + + The conditional operates on a state, which includes all symbols whose values + are a function of the branch taken. + + For example, given the code below that calculates the abs function: + + ``` + x = 1 + if x > 0: + x = -x + ``` + + The state is represented by the variable `x`. The `body, `orelse` and + `set_state` functions must bind to the original `x` symbol, using `nonlocal`. + + The inputs and outputs of the callables representing the loop blocks are not + explicit - instead, these functions must use nonlocal/global for side effects. + The inputs and outputs are instead controlled by the set_state/get_state + functions. + + Args: + cond: Boolean. + body: Callable representing the main block of the conditional. + orelse: Callable representing the else block of the conditional. + get_state: Function that returns a tuple containing the values of all + composite symbols modified within the conditional. This allows access to + state that branches may mutate through side effects. This function is not + needed and should not be called when dispatching to code matching Python's + default semantics. This is useful for checkpointing to avoid unintended + side-effects when staging requires evaluating all code-paths. + set_state: Function to set the values of all composite symbols modified + within the conditional. This is the complement to get_state, used to + restore checkpointed values. The single argument a tuple containing values + for each composite symbol that may be modified in a branch of the + conditional. The is usually the result of a call to get_state. + symbol_names: Tuple containing basic loop var names. + nouts: Number of variables output by the statement. Vars which are not + outputs will not be passed through staged control flow such as tf.cond. + This includes variables that are defined before the conditional, but are + not used after it. + """ + # Note: tf.cond doesn't support SparseTensor. + if tensors.is_dense_tensor(cond): + _tf_if_stmt(cond, body, orelse, get_state, set_state, symbol_names, nouts) + else: + _py_if_stmt(cond, body, orelse) + + +def _tf_if_stmt( + cond, body, orelse, get_state, set_state, symbol_names, nouts): + """Overload of if_stmt that stages a TF cond.""" + cond = _verify_tf_condition(cond, 'if statement') + + if not nouts: + prev_get_state, prev_set_state = get_state, set_state + # Control flow V1 wants at least one output. + get_state = lambda: (0,) + prev_get_state() + set_state = lambda v: prev_set_state(v[1:]) + symbol_names += ('',) + nouts = 1 + + init_vars = get_state() + + # TODO(mdan): Use nonlocal once we no longer need to support py2. + new_body_vars_ = [None] + new_orelse_vars_ = [None] + + def aug_body(): + set_state(init_vars) + body() + new_body_vars = get_state() + new_body_vars = new_body_vars[:nouts] + new_body_vars_[0] = new_body_vars + _verify_tf_cond_branch_vars(new_body_vars, symbol_names, 'main') + if new_orelse_vars_[0] is not None: + _verify_tf_cond_vars(new_body_vars, new_orelse_vars_[0], symbol_names) + return new_body_vars + + def aug_orelse(): + set_state(init_vars) + orelse() + new_orelse_vars = get_state() + new_orelse_vars = new_orelse_vars[:nouts] + new_orelse_vars_[0] = new_orelse_vars + _verify_tf_cond_branch_vars(new_orelse_vars, symbol_names, 'else') + if new_body_vars_[0] is not None: + _verify_tf_cond_vars(new_body_vars_[0], new_orelse_vars, symbol_names) + return new_orelse_vars + + final_cond_vars = tf_cond.cond( + cond, aug_body, aug_orelse, strict=True) + final_cond_vars = final_cond_vars + init_vars[nouts:] + + set_state(final_cond_vars) + + +def _py_if_stmt(cond, body, orelse): + """Overload of if_stmt that executes a Python if statement.""" + return body() if cond else orelse() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/data_structures.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/data_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..375d3179ab7291a4ef2ce1aacfc6b005c1113d3a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/data_structures.py @@ -0,0 +1,347 @@ +# 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. +# ============================================================================== +"""Operators specific to data structures: list append, subscripts, etc.""" + +import collections + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import tensor_array_ops + + +# TODO(mdan): Once control flow supports objects, repackage as a class. + + +def new_list(iterable=None): + """The list constructor. + + Args: + iterable: Optional elements to fill the list with. + + Returns: + A list-like object. The exact return value depends on the initial elements. + """ + if iterable: + elements = tuple(iterable) + else: + elements = () + + if elements: + # When the list contains elements, it is assumed to be a "Python" lvalue + # list. + return _py_list_new(elements) + return tf_tensor_list_new(elements) + + +def tf_tensor_array_new(elements, element_dtype=None, element_shape=None): + """Overload of new_list that stages a Tensor list creation.""" + elements = tuple(ops.convert_to_tensor(el) for el in elements) + + all_dtypes = set(el.dtype for el in elements) + if len(all_dtypes) == 1: + inferred_dtype, = tuple(all_dtypes) + if element_dtype is not None and element_dtype != inferred_dtype: + raise ValueError( + 'incompatible dtype; specified: {}, inferred from {}: {}'.format( + element_dtype, elements, inferred_dtype)) + elif len(all_dtypes) > 1: + raise ValueError( + 'TensorArray requires all elements to have the same dtype:' + ' {}'.format(elements)) + else: + if element_dtype is None: + raise ValueError('dtype is required to create an empty TensorArray') + + all_shapes = set(tuple(el.shape.as_list()) for el in elements) + if len(all_shapes) == 1: + inferred_shape, = tuple(all_shapes) + if element_shape is not None and element_shape != inferred_shape: + raise ValueError( + 'incompatible shape; specified: {}, inferred from {}: {}'.format( + element_shape, elements, inferred_shape)) + elif len(all_shapes) > 1: + raise ValueError( + 'TensorArray requires all elements to have the same shape:' + ' {}'.format(elements)) + # TODO(mdan): We may want to allow different shapes with infer_shape=False. + else: + inferred_shape = None + + if element_dtype is None: + element_dtype = inferred_dtype + if element_shape is None: + element_shape = inferred_shape + + l = tensor_array_ops.TensorArray( + dtype=element_dtype, + size=len(elements), + dynamic_size=True, + infer_shape=(element_shape is None), + element_shape=element_shape) + for i, el in enumerate(elements): + l = l.write(i, el) + return l + + +def tf_tensor_list_new(elements, element_dtype=None, element_shape=None): + """Overload of new_list that stages a Tensor list creation.""" + if tensor_util.is_tf_type(elements): + if element_shape is not None: + raise ValueError( + 'element shape may not be specified when creating list from tensor') + element_shape = array_ops.shape(elements)[1:] + l = list_ops.tensor_list_from_tensor(elements, element_shape=element_shape) + return l + + elements = tuple(ops.convert_to_tensor(el) for el in elements) + + all_dtypes = set(el.dtype for el in elements) + if len(all_dtypes) == 1: + inferred_dtype = tuple(all_dtypes)[0] + if element_dtype is not None and element_dtype != inferred_dtype: + raise ValueError( + 'incompatible dtype; specified: {}, inferred from {}: {}'.format( + element_dtype, elements, inferred_dtype)) + elif all_dtypes: + # Heterogeneous lists are ok. + if element_dtype is not None: + raise ValueError( + 'specified dtype {} is inconsistent with that of elements {}'.format( + element_dtype, elements)) + inferred_dtype = dtypes.variant + else: + inferred_dtype = dtypes.variant + + all_shapes = set(tuple(el.shape.as_list()) for el in elements) + if len(all_shapes) == 1: + inferred_shape = array_ops.shape(elements[0]) + if element_shape is not None and element_shape != inferred_shape: + raise ValueError( + 'incompatible shape; specified: {}, inferred from {}: {}'.format( + element_shape, elements, inferred_shape)) + elif all_shapes: + # Heterogeneous lists are ok. + if element_shape is not None: + raise ValueError( + 'specified shape {} is inconsistent with that of elements {}'.format( + element_shape, elements)) + inferred_shape = constant_op.constant(-1) # unknown shape, by convention + else: + inferred_shape = constant_op.constant(-1) # unknown shape, by convention + + if element_dtype is None: + element_dtype = inferred_dtype + if element_shape is None: + element_shape = inferred_shape + + element_shape = ops.convert_to_tensor(element_shape, dtype=dtypes.int32) + l = list_ops.empty_tensor_list( + element_shape=element_shape, element_dtype=element_dtype) + for el in elements: + l = list_ops.tensor_list_push_back(l, el) + return l + + +def _py_list_new(elements): + """Overload of new_list that creates a Python list.""" + return list(elements) + + +def list_append(list_, x): + """The list append function. + + Note: it is unspecified where list_ will be mutated or not. If list_ is + a TensorFlow entity, it will not be typically mutated. If list_ is a plain + list, it will be. In general, if the list is mutated then the return value + should point to the original entity. + + Args: + list_: An entity that supports append semantics. + x: The element to append. + + Returns: + Same as list_, after the append was performed. + + Raises: + ValueError: if list_ is not of a known list-like type. + """ + if isinstance(list_, tensor_array_ops.TensorArray): + return _tf_tensorarray_append(list_, x) + elif tensor_util.is_tf_type(list_): + if list_.dtype == dtypes.variant: + return _tf_tensor_list_append(list_, x) + else: + raise ValueError( + 'tensor lists are expected to be Tensors with dtype=tf.variant,' + ' instead found %s' % list_) + else: + return _py_list_append(list_, x) + + +def _tf_tensor_list_append(list_, x): + """Overload of list_append that stages a Tensor list write.""" + def empty_list_of_elements_like_x(): + tensor_x = ops.convert_to_tensor(x) + return list_ops.empty_tensor_list( + element_shape=array_ops.shape(tensor_x), + element_dtype=tensor_x.dtype) + + list_ = cond.cond( + list_ops.tensor_list_length(list_) > 0, + lambda: list_, + empty_list_of_elements_like_x, + ) + return list_ops.tensor_list_push_back(list_, x) + + +def _tf_tensorarray_append(list_, x): + """Overload of list_append that stages a TensorArray write.""" + return list_.write(list_.size(), x) + + +def _py_list_append(list_, x): + """Overload of list_append that executes a Python list append.""" + # Revert to the original call. + list_.append(x) + return list_ + + +class ListPopOpts( + collections.namedtuple('ListPopOpts', ('element_dtype', 'element_shape'))): + pass + + +def list_pop(list_, i, opts): + """The list pop function. + + Note: it is unspecified where list_ will be mutated or not. If list_ is + a TensorFlow entity, it will not be typically mutated. If list_ is a plain + list, it will be. In general, if the list is mutated then the return value + should point to the original entity. + + Args: + list_: An entity that supports pop semantics. + i: Optional index to pop from. May be None. + opts: A ListPopOpts. + + Returns: + Tuple (x, out_list_): + out_list_: same as list_, after the removal was performed. + x: the removed element value. + + Raises: + ValueError: if list_ is not of a known list-like type or the operation is + not supported for that type. + """ + assert isinstance(opts, ListPopOpts) + + if isinstance(list_, tensor_array_ops.TensorArray): + raise ValueError('TensorArray does not support item removal') + elif tensor_util.is_tf_type(list_): + if list_.dtype == dtypes.variant: + return _tf_tensor_list_pop(list_, i, opts) + else: + raise ValueError( + 'tensor lists are expected to be Tensors with dtype=tf.variant,' + ' instead found %s' % list_) + else: + return _py_list_pop(list_, i) + + +def _tf_tensor_list_pop(list_, i, opts): + """Overload of list_pop that stages a Tensor list pop.""" + if i is not None: + raise NotImplementedError('tensor lists only support removing from the end') + + if opts.element_dtype is None: + raise ValueError('cannot pop from a list without knowing its element ' + 'type; use set_element_type to annotate it') + if opts.element_shape is None: + raise ValueError('cannot pop from a list without knowing its element ' + 'shape; use set_element_type to annotate it') + list_out, x = list_ops.tensor_list_pop_back( + list_, element_dtype=opts.element_dtype) + x.set_shape(opts.element_shape) + return list_out, x + + +def _py_list_pop(list_, i): + """Overload of list_pop that executes a Python list append.""" + if i is None: + x = list_.pop() + else: + x = list_.pop(i) + return list_, x + + +# TODO(mdan): Look into reducing duplication between all these containers. +class ListStackOpts( + collections.namedtuple('ListStackOpts', + ('element_dtype', 'original_call'))): + pass + + +def list_stack(list_, opts): + """The list stack function. + + This does not have a direct correspondent in Python. The closest idiom to + this is tf.append or np.stack. It's different from those in the sense that it + accepts a Tensor list, rather than a list of tensors. It can also accept + TensorArray. When the target is anything else, the dispatcher will rely on + ctx.original_call for fallback. + + Args: + list_: An entity that supports append semantics. + opts: A ListStackOpts object. + + Returns: + The output of the stack operation, typically a Tensor. + """ + assert isinstance(opts, ListStackOpts) + + if isinstance(list_, tensor_array_ops.TensorArray): + return _tf_tensorarray_stack(list_) + elif tensor_util.is_tf_type(list_): + if list_.dtype == dtypes.variant: + return _tf_tensor_list_stack(list_, opts) + else: + # No-op for primitive Tensor arguments. + return list_ + else: + return _py_list_stack(list_, opts) + + +def _tf_tensorarray_stack(list_): + """Overload of list_stack that stages a TensorArray stack.""" + return list_.stack() + + +def _tf_tensor_list_stack(list_, opts): + """Overload of list_stack that stages a Tensor list write.""" + if opts.element_dtype is None: + raise ValueError('cannot stack a list without knowing its element type;' + ' use set_element_type to annotate it') + return list_ops.tensor_list_stack(list_, element_dtype=opts.element_dtype) + + +def _py_list_stack(list_, opts): + """Overload of list_stack that executes a Python list append.""" + # Revert to the original call. + return opts.original_call(list_) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/exceptions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..763a6da90127159cb907cbe361daf4c5ab35ab32 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/exceptions.py @@ -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. +# ============================================================================== +"""Exception handling statements: assert, etc.""" + +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.util import tf_inspect + + +def assert_stmt(expression1, expression2): + """Functional form of an assert statement. + + This follows the semantics of the Python assert statement, however the + concrete implementations may deviate from it. See the respective + implementation for details. + + In general, the assert statement should not be used for control flow. + Furthermore, it is encouraged that the assertion expressions should not have + side effects. + + Args: + expression1: Any + expression2: Callable[[], Any], returns the expression to include in the + error message when expression1 evaluates to False. When expression1 is + True, the result of expression2 will not be evaluated, however, + expression2 itself may be evaluated in some implementations. + + Returns: + Any, implementation-dependent. + + Raises: + ValueError: if any arguments are illegal. + """ + if not callable(expression2): + raise ValueError('{} must be a callable'.format(expression2)) + args, _, keywords, _ = tf_inspect.getargspec(expression2) + if args or keywords: + raise ValueError('{} may not have any arguments'.format(expression2)) + + if tensor_util.is_tf_type(expression1): + return _tf_assert_stmt(expression1, expression2) + else: + return _py_assert_stmt(expression1, expression2) + + +def _tf_assert_stmt(expression1, expression2): + """Overload of assert_stmt that stages a TF Assert. + + This implementation deviates from Python semantics as follows: + (1) the assertion is verified regardless of the state of __debug__ + (2) on assertion failure, the graph execution will fail with + tensorflow.errors.ValueError, rather than AssertionError. + + Args: + expression1: tensorflow.Tensor, must evaluate to a tf.bool scalar + expression2: Callable[[], Union[tensorflow.Tensor, List[tensorflow.Tensor]]] + + Returns: + tensorflow.Operation + """ + expression2_tensors = expression2() + if not isinstance(expression2_tensors, list): + expression2_tensors = [expression2_tensors] + return control_flow_assert.Assert(expression1, expression2_tensors) + + +def _py_assert_stmt(expression1, expression2): + """Overload of assert_stmt that executes a Python assert statement.""" + assert expression1, expression2() + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/logical.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/logical.py new file mode 100644 index 0000000000000000000000000000000000000000..73608807223ef093b28de839fb8a6db6b5f4d47a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/logical.py @@ -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. +# ============================================================================== +"""Logical boolean operators: not, and, or.""" + +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import gen_math_ops + + +def not_(a): + """Functional form of "not".""" + if tensor_util.is_tf_type(a): + return _tf_not(a) + return _py_not(a) + + +def _tf_not(a): + """Implementation of the "not_" operator for TensorFlow.""" + return gen_math_ops.logical_not(a) + + +def _py_not(a): + """Default Python implementation of the "not_" operator.""" + return not a + + +def and_(a, b): + """Functional form of "and". Uses lazy evaluation semantics.""" + a_val = a() + if tensor_util.is_tf_type(a_val): + return _tf_lazy_and(a_val, b) + return _py_lazy_and(a_val, b) + + +def _tf_lazy_and(cond, b): + """Lazy-eval equivalent of "and" for Tensors.""" + # TODO(mdan): Enforce cond is scalar here? + return tf_cond.cond(cond, b, lambda: cond) + + +def _py_lazy_and(cond, b): + """Lazy-eval equivalent of "and" in Python.""" + return cond and b() + + +def or_(a, b): + """Functional form of "or". Uses lazy evaluation semantics.""" + a_val = a() + if tensor_util.is_tf_type(a_val): + return _tf_lazy_or(a_val, b) + return _py_lazy_or(a_val, b) + + +def _tf_lazy_or(cond, b): + """Lazy-eval equivalent of "or" for Tensors.""" + # TODO(mdan): Enforce cond is scalar here? + return tf_cond.cond(cond, lambda: cond, b) + + +def _py_lazy_or(cond, b): + """Lazy-eval equivalent of "or" in Python.""" + return cond or b() + + +def eq(a, b): + """Functional form of "equal".""" + if tensor_util.is_tf_type(a) or tensor_util.is_tf_type(b): + return _tf_equal(a, b) + return _py_equal(a, b) + + +def _tf_equal(a, b): + """Overload of "equal" for Tensors.""" + return gen_math_ops.equal(a, b) + + +def _py_equal(a, b): + """Overload of "equal" that falls back to Python's default implementation.""" + return a == b + + +def not_eq(a, b): + """Functional form of "not-equal".""" + return not_(eq(a, b)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/py_builtins.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/py_builtins.py new file mode 100644 index 0000000000000000000000000000000000000000..96ee2d53a92bc5c937dcca9c309740ecb1f5068c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/py_builtins.py @@ -0,0 +1,533 @@ +# 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. +# ============================================================================== +"""Operators corresponding to Python builtin functions. + +List of built-in functions: https://docs.python.org/3/library/functions.html +""" + +import inspect + +from tensorflow.python.autograph.utils import tensors +from tensorflow.python.autograph.utils import type_registry +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import gen_parsing_ops +from tensorflow.python.ops import gen_string_ops +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import math_ops + + +UNSPECIFIED = object() + +abs_registry = type_registry.TypeRegistry() +len_registry = type_registry.TypeRegistry() +print_registry = type_registry.TypeRegistry() +enumerate_registry = type_registry.TypeRegistry() +zip_registry = type_registry.TypeRegistry() +map_registry = type_registry.TypeRegistry() +filter_registry = type_registry.TypeRegistry() +any_registry = type_registry.TypeRegistry() +all_registry = type_registry.TypeRegistry() +sorted_registry = type_registry.TypeRegistry() +next_registry = type_registry.TypeRegistry() + + +def registry_lookup(reg, obj): + try: + return reg.lookup(obj) + except LookupError: + pass + return None + + +def overload_of(f): + if f in SUPPORTED_BUILTINS: + return BUILTIN_FUNCTIONS_MAP[f.__name__] + return f + + +def _find_originating_frame(caller_fn_scope, innermost=True): + """Locates the frame in which `caller_fn_scope` was defined.""" + ctx_frame = inspect.currentframe() + result = None + while ctx_frame is not None: + # Note it should not be normally possible to get false positives this way + # because the function scope object is not accessible to user code (barring + # call stack introspection). + if ctx_frame.f_locals.get(caller_fn_scope.name, None) is caller_fn_scope: + result = ctx_frame + if innermost: + break + ctx_frame = ctx_frame.f_back + + assert result is not None, ( + 'the conversion process should ensure the caller_fn_scope is always' + ' found somewhere on the call stack') + + return result + + +def locals_in_original_context(caller_fn_scope): + """Executes the locals function in the context of a specified function.""" + return _find_originating_frame(caller_fn_scope, innermost=True).f_locals + + +def globals_in_original_context(caller_fn_scope): + """Executes the locals function in the context of a specified function.""" + return _find_originating_frame(caller_fn_scope, innermost=True).f_globals + + +def eval_in_original_context(f, args, caller_fn_scope): + """Executes the eval function in the context of a specified function.""" + # When control flow is rewritten using functions, eval should use the + # variables found in the same block where it was called. That is equivalent + # to the innermost function call. + ctx_frame = _find_originating_frame(caller_fn_scope, innermost=True) + + args = ( + args[0], + ctx_frame.f_globals if len(args) < 2 else args[1], + ctx_frame.f_locals if len(args) < 3 else args[2], + ) + return f(*args) + + +def super_in_original_context(f, args, caller_fn_scope): + """Executes the super function in the context of a specified function. + + See https://docs.python.org/3/library/functions.html#super for the exact + details + + Args: + f: Callable, typically the super builtin + args: List[Any], the original call arguments + caller_fn_scope: Optional[function_wrappers.FunctionScope], the function + scope of the converted function in which this call was originally made + + Returns: + The result of calling `f` as if it was called in the frame indicated by + `caller_fn_scope`. + """ + + # Only the no-arg call is desugared. + if args: + return f(*args) + + # Inner functions seem to include their closure in f_locals, so we need + # to find the outermost frame. + ctx_frame = _find_originating_frame(caller_fn_scope, innermost=False) + + # When super(..) is called without arguments, it looks for __class__ cell + # variable and the first argument passed in the enclosing function according + # to the spec https://www.python.org/dev/peps/pep-3135/ . + # + # We couldn't verify if `inspect.currentframe().f_code.co_varnames[0]` is + # guaranteed to be the first argument from an official doc or PEP, however, + # it's fairly stable and well established: + # - An unofficial community doc mentions it. + # https://python-reference.readthedocs.io/en/latest/docs/code/varnames.html + # - CPython has tests checking that order, which was merged in 2008, and + # unchanged since then. + # https://github.com/python/cpython/blame/2f224a077a83ac9de8a12bb7dcc516642b8176d8/Lib/lib2to3/tests/data/py2_test_grammar.py#L157 + # https://github.com/python/cpython/blame/2f224a077a83ac9de8a12bb7dcc516642b8176d8/Lib/lib2to3/tests/data/py3_test_grammar.py#L192 + # + # Note: the name can be more reliably obtained by inspecting the calling + # function's argspec. + # + # Even though methods can be declared using *args (def method(*args)), + # that pattern is disallowed by super() -- it raises super() no arguments. + # Method definitions using **kwargs are not allowed at all. + # In other words, we can always assume that self is on the first positional + # argument (for correct code). + # + # TODO(mdan): Consider additional checks in case the input code is incorrect. + # For example, the error might be cryptic compared to what super() regularly + # raises. + + type_arg = ctx_frame.f_locals['__class__'] + self_arg_name = ctx_frame.f_code.co_varnames[0] + self_arg = ctx_frame.f_locals[self_arg_name] + return f(type_arg, self_arg) + + +def abs_(x): + abs_override = registry_lookup(abs_registry, x) + if abs_override is not None: + return abs_override(x) + if tensor_util.is_tf_type(x): + return _tf_abs(x) + return _py_abs(x) + + +def _tf_abs(x): + return math_ops.abs(x) + + +def _py_abs(x): + return abs(x) + + +def float_(x=0): + if tensor_util.is_tf_type(x): + return _tf_float(x) + return _py_float(x) + + +def _tf_float(x): + # TODO(mdan): We shouldn't assume float32. + if x.dtype == dtypes.string: + return gen_parsing_ops.string_to_number(x, out_type=dtypes.float32) + return math_ops.cast(x, dtype=dtypes.float32) + + +def _py_float(x): + return float(x) + + +def int_(x=0, base=UNSPECIFIED): + if tensor_util.is_tf_type(x): + return _tf_int(x, base) + return _py_int(x, base) + + +def _tf_int(x, base): + if base not in (10, UNSPECIFIED): + raise NotImplementedError('base {} not supported for int'.format(base)) + + # TODO(mdan): We shouldn't assume int32. + if x.dtype == dtypes.string: + return gen_parsing_ops.string_to_number(x, out_type=dtypes.int32) + return math_ops.cast(x, dtype=dtypes.int32) + + +def _py_int(x, base): + if base is UNSPECIFIED: + return int(x) + return int(x, base) + + +def len_(s): + len_override = registry_lookup(len_registry, s) + if len_override is not None: + return len_override(s) + if tensors.is_tensor_array(s): + return _tf_tensor_array_len(s) + elif tensors.is_tensor_list(s): + return _tf_tensor_list_len(s) + elif tensor_util.is_tf_type(s): + return _tf_tensor_len(s) + return _py_len(s) + + +def _tf_tensor_array_len(s): + return s.size() + + +def _tf_tensor_list_len(s): + return list_ops.tensor_list_length(s) + + +def _tf_tensor_len(s): + """Overload of len_ for Tensor arguments.""" + # Statically shaped tensors: length is known ahead of time. + if s.shape.ndims and s.shape.dims[0].value is not None: + return s.shape.dims[0].value + + # Static shape of unknown dimensions: use dynamic shape but statically + # check that it's a scalar. + shape = array_ops.shape(s) + + assert shape.shape, 'shape tensor of zero size? {}'.format(shape) + + if shape.shape[0] == 0: + raise ValueError( + 'len requires a non-scalar tensor, got one of shape {}'.format(shape)) + + if shape.shape.dims[0].value is not None: + return array_ops.shape(s)[0] + + # Fully dynamic shape: use ops. + rank = array_ops.rank(s) + + def raise_zero_rank_error(): + msg = gen_string_ops.string_join( + ['len requires non-zero rank, got ', + gen_string_ops.as_string(rank)]) + with ops.control_dependencies([control_flow_assert.Assert(False, [msg])]): + return constant_op.constant(0, dtype=dtypes.int32) + + return cond.cond(rank > 0, lambda: array_ops.shape(s)[0], + raise_zero_rank_error) + + +def _py_len(s): + return len(s) + + +def print_(*objects, **kwargs): + """Overload of the print builtin.""" + # Note: Python 2.6 doesn't support explicit keywords after starargs. + unknown_kwargs = tuple( + set(kwargs.keys()) - set(('sep', 'end', 'file', 'flush'))) + if unknown_kwargs: + raise ValueError('invalid keyword arguments: {}'.format(unknown_kwargs)) + + print_fn = _py_print + for x in objects: + print_override = registry_lookup(print_registry, x) + if print_override is not None: # pylint: disable=comparison-with-callable + print_fn = print_override + break + + if print_fn is _py_print: + # If this fails, ops/autograph_ops.py hasn't been imported. + assert not any(tensor_util.is_tf_type(s) for s in objects) + + return print_fn(*objects, **kwargs) + + +def _py_print(*objects, **kwargs): + print(*objects, **kwargs) + + +def min_(*args, **kwargs): + if any(tensor_util.is_tf_type(s) for s in args): + return _tf_min(*args, **kwargs) + return _py_min(*args, **kwargs) + + +def _tf_min(*args, **kwargs): + if len(kwargs): + kwargs_tuple = tuple(set(kwargs.keys())) + raise ValueError('These keyword arguments are ' + 'currently not supported: {}'.format(kwargs_tuple)) + if len(args) == 1: + rank = args[0].shape.rank + if rank == 0: + return args[0] + if rank == 1: + return math_ops.reduce_min(*args, axis=0) + raise ValueError('min(arg) currently support only tensor with rank 1, ' + 'but got a tensor with rank {}'.format(rank)) + for arg in args: + rank = arg.shape.rank + if rank != 0: + raise ValueError('min(arg1, arg2, *args) currently support ' + 'only scalar tensor, but got a tensor ' + 'with shape {}'.format(rank)) + return math_ops.reduce_min(args, axis=0) + + +def _py_min(*args, **kwargs): + return min(*args, **kwargs) + + +def max_(*args, **kwargs): + if any(tensor_util.is_tf_type(s) for s in args): + return _tf_max(*args, **kwargs) + return _py_max(*args, **kwargs) + + +def _tf_max(*args, **kwargs): + if len(kwargs): + kwargs_tuple = tuple(set(kwargs.keys())) + raise ValueError('These keyword arguments are ' + 'currently not supported: {}'.format(kwargs_tuple)) + if len(args) == 1: + rank = args[0].shape.rank + if rank == 0: + return args[0] + if rank == 1: + return math_ops.reduce_max(*args, axis=0) + raise ValueError('max(arg) currently support only tensor with rank 1, ' + 'but got a tensor with rank {}'.format(rank)) + for arg in args: + rank = arg.shape.rank + if rank != 0: + raise ValueError('max(arg1, arg2, *args) currently support ' + 'only scalar tensor, but got a tensor ' + 'with shape {}'.format(rank)) + return math_ops.reduce_max(args, axis=0) + + +def _py_max(*args, **kwargs): + return max(*args, **kwargs) + + +def range_(start_or_stop, stop=UNSPECIFIED, step=UNSPECIFIED): + if any(tensor_util.is_tf_type(s) for s in (start_or_stop, stop, step)): + return _tf_range(start_or_stop, stop, step) + return _py_range(start_or_stop, stop, step) + + +def _tf_range(start_or_stop, stop, step): + """Overload of range_ that generates a TF range tensor.""" + # Note: for static inputs (e.g. constants), tf.range errors out at graph + # construction time, instead of returning an empty tensor. Preventing the + # graph construction error aligns the semantics with Python. + + # TODO(mdan): We should optimize this when a full tensor is not required. + if step is not UNSPECIFIED: + # TODO(mdan): Add argument coercion similar to other cases. + return math_ops.range(start_or_stop, stop, step) + if stop is not UNSPECIFIED: + stop = math_ops.maximum(start_or_stop, stop) + return math_ops.range(start_or_stop, stop) + start_or_stop = math_ops.maximum(start_or_stop, 0) + return math_ops.range(start_or_stop) + + +def _py_range(start_or_stop, stop, step): + if step is not UNSPECIFIED: + return range(start_or_stop, stop, step) + if stop is not UNSPECIFIED: + return range(start_or_stop, stop) + return range(start_or_stop) + + +def enumerate_(s, start=0): + enumerate_override = registry_lookup(enumerate_registry, s) + if enumerate_override is not None: + return enumerate_override(s, start) + return _py_enumerate(s, start) + + +def _py_enumerate(s, start=0): + return enumerate(s, start) + + +def zip_(*iterables, strict=False): + zip_fn = _py_zip + # If the overridden function is not the same across all iterables, use _py_zip + for x in iterables: + zip_override = registry_lookup(zip_registry, x) + if zip_override is None or (zip_fn != _py_zip and zip_override != zip_fn): # pylint: disable=comparison-with-callable + zip_fn = _py_zip + break + zip_fn = zip_override + return zip_fn(*iterables, strict=strict) + + +def _py_zip(*iterables, strict=False): + if strict: + return zip(*iterables, strict=True) + else: + # Python < 3.10 doesn't have `strict` kwarg. + return zip(*iterables) + + +def map_(fn, *iterables): + map_fn = _py_map + # If the overridden function is not the same across all iterables, use _py_map + for x in iterables: + map_override = registry_lookup(map_registry, x) + if map_override is None or (map_fn != _py_map and map_override != map_fn): # pylint: disable=comparison-with-callable + map_fn = _py_map + break + map_fn = map_override + return map_fn(fn, *iterables) + + +def _py_map(fn, *iterables): + return map(fn, *iterables) + + +def next_(iterator, default=UNSPECIFIED): + next_override = registry_lookup(next_registry, iterator) + if next_override is not None: + return next_override(iterator, default) + return next_py(iterator, default) + + +def next_py(iterator, default=UNSPECIFIED): + if default is UNSPECIFIED: + return next(iterator) + return next(iterator, default) + + +def filter_(function, iterable): + filter_override = registry_lookup(filter_registry, iterable) + if filter_override is not None: + return filter_override(function, iterable) + return _py_filter(function, iterable) + + +def _py_filter(function, iterable): + return filter(function, iterable) + + +def any_(iterable): + any_override = registry_lookup(any_registry, iterable) + if any_override is not None: + return any_override(iterable) + return _py_any(iterable) + + +def _py_any(iterable): + return any(iterable) + + +def all_(iterable): + all_override = registry_lookup(all_registry, iterable) + if all_override is not None: + return all_override(iterable) + return _py_all(iterable) + + +def _py_all(iterable): + return all(iterable) + + +def sorted_(iterable, key=UNSPECIFIED, reverse=UNSPECIFIED): + sorted_override = registry_lookup(sorted_registry, iterable) + if sorted_override is not None: + return sorted_override(iterable, key, reverse) + return _py_sorted(iterable, key, reverse) + + +def _py_sorted(iterable, key, reverse): + if key is not UNSPECIFIED and reverse is UNSPECIFIED: + return sorted(iterable, key=key) + if key is UNSPECIFIED and reverse is not UNSPECIFIED: + return sorted(iterable, reverse=reverse) + if key is not UNSPECIFIED and reverse is not UNSPECIFIED: + return sorted(iterable, key=key, reverse=reverse) + return sorted(iterable) + + +SUPPORTED_BUILTINS = (abs, float, int, len, print, range, enumerate, zip, map, + filter, any, all, sorted) + +BUILTIN_FUNCTIONS_MAP = { + 'abs': abs_, + 'any': any_, + 'all': all_, + 'enumerate': enumerate_, + 'filter': filter_, + 'float': float_, + 'int': int_, + 'len': len_, + 'map': map_, + 'next': next_, + 'print': print_, + 'range': range_, + 'sorted': sorted_, + 'zip': zip_, +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/slices.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/slices.py new file mode 100644 index 0000000000000000000000000000000000000000..fde5afdc6037c0668973fcb80a0d18ef44612009 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/slices.py @@ -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. +# ============================================================================== +"""Operators specific to slicing operations.""" + +import collections + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_string_ops +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import tensor_array_ops + + +# TODO(mdan): Support extended slices. + + +class GetItemOpts(collections.namedtuple('GetItemOpts', ('element_dtype',))): + pass + + +def get_item(target, i, opts): + """The slice read operator (i.e. __getitem__). + + Note: it is unspecified whether target will be mutated or not. In general, + if target is mutable (like Python lists), it will be mutated. + + Args: + target: An entity that supports getitem semantics. + i: Index to read from. + opts: A GetItemOpts object. + + Returns: + The read element. + + Raises: + ValueError: if target is not of a supported type. + """ + assert isinstance(opts, GetItemOpts) + + if isinstance(target, tensor_array_ops.TensorArray): + return _tf_tensorarray_get_item(target, i) + elif tensor_util.is_tf_type(target): + if target.dtype == dtypes.variant: + return _tf_tensor_list_get_item(target, i, opts) + elif target.dtype == dtypes.string and target.shape.ndims == 0: + return _tf_tensor_string_get_item(target, i) + else: + return _tf_tensor_get_item(target, i) + else: + return _py_get_item(target, i) + + +def _tf_tensorarray_get_item(target, i): + """Overload of get_item that stages a TensorArray read.""" + return target.read(i) + + +def _tf_tensor_list_get_item(target, i, opts): + """Overload of get_item that stages a Tensor list read.""" + if opts.element_dtype is None: + raise ValueError('cannot retrieve from a list without knowing its ' + 'element type; use set_element_type to annotate it') + x = list_ops.tensor_list_get_item(target, i, element_dtype=opts.element_dtype) + return x + + +def _tf_tensor_get_item(target, i): + """Overload of get_item that stages a Tensor (not Tensor list) read.""" + return target[i] + + +def _tf_tensor_string_get_item(target, i): + """Overload of get_item that stages a Tensor string read.""" + x = gen_string_ops.substr(target, i, 1) + return x + + +def _py_get_item(target, i): + """Overload of get_item that executes a Python list modification.""" + return target[i] + + +def set_item(target, i, x): + """The slice write operator (i.e. __setitem__). + + Note: it is unspecified whether target will be mutated or not. In general, + if target is mutable (like Python lists), it will be mutated. + + Args: + target: An entity that supports setitem semantics. + i: Index to modify. + x: The new element value. + + Returns: + Same as target, after the update was performed. + + Raises: + ValueError: if target is not of a supported type. + """ + if isinstance(target, tensor_array_ops.TensorArray): + return _tf_tensorarray_set_item(target, i, x) + elif tensor_util.is_tf_type(target): + if target.dtype == dtypes.variant: + return _tf_tensor_list_set_item(target, i, x) + else: + return _tf_tensor_set_item(target, i, x) + else: + return _py_set_item(target, i, x) + + +def _tf_tensorarray_set_item(target, i, x): + """Overload of set_item that stages a TensorArray write.""" + return target.write(i, x) + + +def _tf_tensor_list_set_item(target, i, x): + """Overload of set_item that stages a Tensor list update.""" + return list_ops.tensor_list_set_item(target, i, x) + + +def _tf_tensor_set_item(target, i, x): + """Overload of set_item that stages a Tensor scatter update.""" + return gen_array_ops.tensor_scatter_update(target, ((i,),), (x,)) + + +def _py_set_item(target, i, x): + """Overload of set_item that executes a Python list modification.""" + target[i] = x + return target diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/variables.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/variables.py new file mode 100644 index 0000000000000000000000000000000000000000..115c44701741e9c92a52f3fd3f6f2e59a3bc7ec7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/operators/variables.py @@ -0,0 +1,104 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities used to capture Python idioms.""" + + +def ld(v): + """Load variable operator.""" + if isinstance(v, Undefined): + return v.read() + return v + + +def ldu(load_v, name): + """Load variable operator that returns Undefined when failing to evaluate. + + Note: the name ("load or return undefined") is abbreviated to minimize + the amount of clutter in generated code. + + This variant of `ld` is useful when loading symbols that may be undefined at + runtime, such as composite symbols, and whether they are defined or not cannot + be determined statically. For example `d['a']` is undefined when `d` is an + empty dict. + + Args: + load_v: Lambda that executes the actual read. + name: Human-readable name of the symbol being read. + Returns: + Either the value of the symbol, or Undefined, if the symbol is not fully + defined. + """ + try: + # TODO(mdan): Use locals()/globals() here. + return load_v() + except (KeyError, AttributeError, NameError): + return Undefined(name) + + +class Undefined(object): + """Represents an undefined symbol in Python. + + This is used to reify undefined symbols, which is required to use the + functional form of loops. + Example: + + while n > 0: + n = n - 1 + s = n + return s # Runtime error if n == 0 + + This is valid Python code and will not result in an error as long as n + is positive. The use of this class is to stay as close to Python semantics + as possible for staged code of this nature. + + Converted version of the above showing the possible usage of this class: + + s = Undefined('s') + init_state = (s,) + s = while_loop(cond, body, init_state) + return s # s is an instance of Undefined if the loop never runs + + Attributes: + symbol_name: Text, identifier for the undefined symbol + """ + + __slots__ = ('symbol_name',) + + def __init__(self, symbol_name): + self.symbol_name = symbol_name + + def read(self): + raise UnboundLocalError("'{}' is used before assignment".format( + self.symbol_name)) + + def __repr__(self): + return self.symbol_name + + def __getattribute__(self, name): + try: + # If it's an existing attribute, return it. + return object.__getattribute__(self, name) + except AttributeError: + # Otherwise return Undefined. + return self + + def __getitem__(self, i): + return self + + +# TODO(mdan): Refactor as a RetVal object, aggregating the value and do_return. +class UndefinedReturnValue(object): + """Represents a return value that is undefined.""" + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/anno.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/anno.py new file mode 100644 index 0000000000000000000000000000000000000000..59ff703587cbb1fefd81a83008381d87b82499d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/anno.py @@ -0,0 +1,174 @@ +# 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. +# ============================================================================== +"""AST node annotation support. + +Adapted from Tangent. +""" + +import enum + +# pylint:disable=g-bad-import-order + +import gast +# pylint:enable=g-bad-import-order + + +# TODO(mdan): Shorten the names. +# These names are heavily used, and anno.blaa +# TODO(mdan): Replace the attr-dict mechanism with a more typed solution. + + +class NoValue(enum.Enum): + """Base class for different types of AST annotations.""" + + def of(self, node, default=None): + return getanno(node, self, default=default) + + def add_to(self, node, value): + setanno(node, self, value) + + def exists(self, node): + return hasanno(node, self) + + def __repr__(self): + return str(self.name) + + +class Basic(NoValue): + """Container for basic annotation keys. + + The enum values are used strictly for documentation purposes. + """ + + QN = 'Qualified name, as it appeared in the code. See qual_names.py.' + SKIP_PROCESSING = ( + 'This node should be preserved as is and not processed any further.') + INDENT_BLOCK_REMAINDER = ( + 'When a node is annotated with this, the remainder of the block should' + ' be indented below it. The annotation contains a tuple' + ' (new_body, name_map), where `new_body` is the new indented block and' + ' `name_map` allows renaming symbols.') + ORIGIN = ('Information about the source code that converted code originated' + ' from. See origin_information.py.') + DIRECTIVES = ('User directives associated with a statement or a variable.' + ' Typically, they affect the immediately-enclosing statement.') + + EXTRA_LOOP_TEST = ( + 'A special annotation containing additional test code to be executed in' + ' for loops.') + + +class Static(NoValue): + """Container for static analysis annotation keys. + + The enum values are used strictly for documentation purposes. + """ + + # Symbols + # These flags are boolean. + IS_PARAM = 'Symbol is a parameter to the function being analyzed.' + + # Scopes + # Scopes are represented by objects of type activity.Scope. + SCOPE = 'The scope for the annotated node. See activity.py.' + # TODO(mdan): Drop these in favor of accessing the child's SCOPE. + ARGS_SCOPE = 'The scope for the argument list of a function call.' + COND_SCOPE = 'The scope for the test node of a conditional statement.' + BODY_SCOPE = ( + 'The scope for the main body of a statement (True branch for if ' + 'statements, main body for loops).') + ORELSE_SCOPE = ( + 'The scope for the orelse body of a statement (False branch for if ' + 'statements, orelse body for loops).') + + # Static analysis annotations. + DEFINITIONS = ( + 'Reaching definition information. See reaching_definitions.py.') + ORIG_DEFINITIONS = ( + 'The value of DEFINITIONS that applied to the original code before any' + ' conversion.') + DEFINED_FNS_IN = ( + 'Local function definitions that may exist when exiting the node. See' + ' reaching_fndefs.py') + DEFINED_VARS_IN = ( + 'Symbols defined when entering the node. See reaching_definitions.py.') + LIVE_VARS_OUT = ('Symbols live when exiting the node. See liveness.py.') + LIVE_VARS_IN = ('Symbols live when entering the node. See liveness.py.') + TYPES = 'Static type information. See type_inference.py.' + CLOSURE_TYPES = 'Types of closure symbols at each detected call site.' + VALUE = 'Static value information. See type_inference.py.' + + +FAIL = object() + + +def keys(node, field_name='___pyct_anno'): + if not hasattr(node, field_name): + return frozenset() + return frozenset(getattr(node, field_name).keys()) + + +def getanno(node, key, default=FAIL, field_name='___pyct_anno'): + if (default is FAIL or (hasattr(node, field_name) and + (key in getattr(node, field_name)))): + return getattr(node, field_name)[key] + return default + + +def hasanno(node, key, field_name='___pyct_anno'): + return hasattr(node, field_name) and key in getattr(node, field_name) + + +def setanno(node, key, value, field_name='___pyct_anno'): + annotations = getattr(node, field_name, {}) + setattr(node, field_name, annotations) + annotations[key] = value + + # So that the annotations survive gast_to_ast() and ast_to_gast() + if field_name not in node._fields: + node._fields += (field_name,) + + +def delanno(node, key, field_name='___pyct_anno'): + annotations = getattr(node, field_name) + del annotations[key] + if not annotations: + delattr(node, field_name) + node._fields = tuple(f for f in node._fields if f != field_name) + + +def copyanno(from_node, to_node, key, field_name='___pyct_anno'): + if hasanno(from_node, key, field_name=field_name): + setanno( + to_node, + key, + getanno(from_node, key, field_name=field_name), + field_name=field_name) + + +def dup(node, copy_map, field_name='___pyct_anno'): + """Recursively copies annotations in an AST tree. + + Args: + node: ast.AST + copy_map: Dict[Hashable, Hashable], maps a source anno key to a destination + key. All annotations with the source key will be copied to identical + annotations with the destination key. + field_name: str + """ + for n in gast.walk(node): + for k in copy_map: + if hasanno(n, k, field_name): + setanno(n, copy_map[k], getanno(n, k, field_name), field_name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/ast_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/ast_util.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf13fad82827d3508e13d2f43c54d45b81c9c39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/ast_util.py @@ -0,0 +1,344 @@ +# 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. +# ============================================================================== +"""AST manipulation utilities.""" + +import ast + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names + + +class CleanCopier(object): + """NodeTransformer-like visitor that copies an AST.""" + + def __init__(self, preserve_annos): + super(CleanCopier, self).__init__() + self.preserve_annos = preserve_annos + + def copy(self, node): + """Returns a deep copy of node (excluding some fields, see copy_clean).""" + + if isinstance(node, list): + return [self.copy(n) for n in node] + elif isinstance(node, tuple): + return tuple(self.copy(n) for n in node) + elif not isinstance(node, (gast.AST, ast.AST)): + # Assuming everything that's not an AST, list or tuple is a value type + # and may simply be assigned. + return node + + assert isinstance(node, (gast.AST, ast.AST)) + + new_fields = {} + for f in node._fields: + if not f.startswith('__') and hasattr(node, f): + new_fields[f] = self.copy(getattr(node, f)) + new_node = type(node)(**new_fields) + + if self.preserve_annos: + for k in self.preserve_annos: + anno.copyanno(node, new_node, k) + return new_node + + +def copy_clean(node, preserve_annos=None): + """Creates a deep copy of an AST. + + The copy will not include fields that are prefixed by '__', with the + exception of user-specified annotations. + + Args: + node: ast.AST + preserve_annos: Optional[Set[Hashable]], annotation keys to include in the + copy + Returns: + ast.AST + """ + return CleanCopier(preserve_annos).copy(node) + + +class SymbolRenamer(gast.NodeTransformer): + """Transformer that can rename symbols to a simple names.""" + + def __init__(self, name_map): + self.name_map = name_map + + def _process_name_node(self, node): + qn = anno.getanno(node, anno.Basic.QN) + if qn in self.name_map: + new_node = gast.Name( + str(self.name_map[qn]), + ctx=node.ctx, + annotation=None, + type_comment=None) + # All annotations get carried over. + for k in anno.keys(node): + anno.copyanno(node, new_node, k) + return new_node + return self.generic_visit(node) + + def _process_list_of_strings(self, names): + for i in range(len(names)): + qn = qual_names.QN(names[i]) + if qn in self.name_map: + names[i] = str(self.name_map[qn]) + return names + + def visit_Nonlocal(self, node): + node.names = self._process_list_of_strings(node.names) + return node + + def visit_Global(self, node): + node.names = self._process_list_of_strings(node.names) + return node + + def visit_Name(self, node): + return self._process_name_node(node) + + def visit_Attribute(self, node): + if anno.hasanno(node, anno.Basic.QN): + return self._process_name_node(node) + # Renaming attributes is not supported. + return self.generic_visit(node) + + def visit_FunctionDef(self, node): + qn = qual_names.QN(node.name) + if qn in self.name_map: + node.name = str(self.name_map[qn]) + return self.generic_visit(node) + + +def rename_symbols(node, name_map): + """Renames symbols in an AST. Requires qual_names annotations.""" + renamer = SymbolRenamer(name_map) + if isinstance(node, list): + return [renamer.visit(n) for n in node] + elif isinstance(node, tuple): + return tuple(renamer.visit(n) for n in node) + return renamer.visit(node) + + +def keywords_to_dict(keywords): + """Converts a list of ast.keyword objects to a dict.""" + keys = [] + values = [] + for kw in keywords: + keys.append(gast.Constant(kw.arg, kind=None)) + values.append(kw.value) + return gast.Dict(keys=keys, values=values) + + +class PatternMatcher(gast.NodeVisitor): + """Matches a node against a pattern represented by a node.""" + + def __init__(self, pattern): + self.pattern = pattern + self.pattern_stack = [] + self.matches = True + + def compare_and_visit(self, node, pattern): + self.pattern_stack.append(self.pattern) + self.pattern = pattern + self.generic_visit(node) + self.pattern = self.pattern_stack.pop() + + def no_match(self): + self.matches = False + return False + + def is_wildcard(self, p): + if isinstance(p, (list, tuple)) and len(p) == 1: + p, = p + if isinstance(p, gast.Name) and p.id == '_': + return True + if p == '_': + return True + return False + + def generic_visit(self, node): + if not self.matches: + return + + pattern = self.pattern + for f in node._fields: + if f.startswith('__'): + continue + + if not hasattr(node, f): + if hasattr(pattern, f) and getattr(pattern, f): + return self.no_match() + else: + continue + if not hasattr(pattern, f): + return self.no_match() + + v = getattr(node, f) + p = getattr(pattern, f) + + if self.is_wildcard(p): + continue + if isinstance(v, (list, tuple)): + if not isinstance(p, (list, tuple)) or len(v) != len(p): + return self.no_match() + for v_item, p_item in zip(v, p): + self.compare_and_visit(v_item, p_item) + elif isinstance(v, (gast.AST, ast.AST)): + if not isinstance(v, type(p)) and not isinstance(p, type(v)): + return self.no_match() + self.compare_and_visit(v, p) + else: + # Assume everything else is a value type. + if v != p: + return self.no_match() + + +def matches(node, pattern): + """Basic pattern matcher for AST. + + The pattern may contain wildcards represented by the symbol '_'. A node + matches a pattern if for every node in the tree, either there is a node of + the same type in pattern, or a Name node with id='_'. + + Args: + node: ast.AST + pattern: ast.AST + Returns: + bool + """ + if isinstance(pattern, str): + pattern = parser.parse_str(pattern) + + matcher = PatternMatcher(pattern) + matcher.visit(node) + return matcher.matches + + +# TODO(mdan): Once we have error tracing, we may be able to just go to SSA. +def apply_to_single_assignments(targets, values, apply_fn): + """Applies a function to each individual assignment. + + This function can process a possibly-unpacked (e.g. a, b = c, d) assignment. + It tries to break down the unpacking if possible. In effect, it has the same + effect as passing the assigned values in SSA form to apply_fn. + + Examples: + + The following will result in apply_fn(a, c), apply_fn(b, d): + + a, b = c, d + + The following will result in apply_fn(a, c[0]), apply_fn(b, c[1]): + + a, b = c + + The following will result in apply_fn(a, (b, c)): + + a = b, c + + It uses the visitor pattern to allow subclasses to process single + assignments individually. + + Args: + targets: Union[List[ast.AST, ...], Tuple[ast.AST, ...], ast.AST, should be + used with the targets field of an ast.Assign node + values: ast.AST + apply_fn: Callable[[ast.AST, ast.AST], None], called with the + respective nodes of each single assignment + """ + if not isinstance(targets, (list, tuple)): + targets = (targets,) + for target in targets: + if isinstance(target, (gast.Tuple, gast.List)): + for i in range(len(target.elts)): + target_el = target.elts[i] + if isinstance(values, (gast.Tuple, gast.List)): + value_el = values.elts[i] + else: + idx = parser.parse_expression(str(i)) + value_el = gast.Subscript(values, idx, ctx=gast.Load()) + apply_to_single_assignments(target_el, value_el, apply_fn) + else: + apply_fn(target, values) + + +def parallel_walk(node, other): + """Walks two ASTs in parallel. + + The two trees must have identical structure. + + Args: + node: Union[ast.AST, Iterable[ast.AST]] + other: Union[ast.AST, Iterable[ast.AST]] + Yields: + Tuple[ast.AST, ast.AST] + Raises: + ValueError: if the two trees don't have identical structure. + """ + if isinstance(node, (list, tuple)): + node_stack = list(node) + else: + node_stack = [node] + + if isinstance(other, (list, tuple)): + other_stack = list(other) + else: + other_stack = [other] + + while node_stack and other_stack: + assert len(node_stack) == len(other_stack) + n = node_stack.pop() + o = other_stack.pop() + + if ((not isinstance(n, (ast.AST, gast.AST, str)) and n is not None) or + (not isinstance(o, (ast.AST, gast.AST, str)) and n is not None) or + n.__class__.__name__ != o.__class__.__name__): + raise ValueError('inconsistent nodes: {} ({}) and {} ({})'.format( + n, n.__class__.__name__, o, o.__class__.__name__)) + + yield n, o + + if isinstance(n, str): + assert isinstance(o, str), 'The check above should have ensured this' + continue + if n is None: + assert o is None, 'The check above should have ensured this' + continue + + for f in n._fields: + n_child = getattr(n, f, None) + o_child = getattr(o, f, None) + if f.startswith('__') or n_child is None or o_child is None: + continue + + if isinstance(n_child, (list, tuple)): + if (not isinstance(o_child, (list, tuple)) or + len(n_child) != len(o_child)): + raise ValueError( + 'inconsistent values for field {}: {} and {}'.format( + f, n_child, o_child)) + node_stack.extend(n_child) + other_stack.extend(o_child) + + elif isinstance(n_child, (gast.AST, ast.AST)): + node_stack.append(n_child) + other_stack.append(o_child) + + elif n_child != o_child: + raise ValueError( + 'inconsistent values for field {}: {} and {}'.format( + f, n_child, o_child)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/cache.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..2d125e687ef842394d4117bc03276a69064d528f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/cache.py @@ -0,0 +1,93 @@ +# 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. +# ============================================================================== +"""Caching utilities.""" + +import inspect +import weakref + + +# TODO(mdan): Add a garbage collection hook for cleaning up modules. +class _TransformedFnCache(object): + """Generic hierarchical cache for transformed functions. + + The keys are soft references (i.e. they are discarded when the key is + destroyed) created from the source function by `_get_key`. The subkeys are + strong references and can be any value. Typically they identify different + kinds of transformation. + """ + + __slots__ = ('_cache',) + + def __init__(self): + self._cache = weakref.WeakKeyDictionary() + + def _get_key(self, entity): + raise NotImplementedError('subclasses must override') + + def has(self, entity, subkey): + key = self._get_key(entity) + parent = self._cache.get(key, None) + if parent is None: + return False + return subkey in parent + + def __getitem__(self, entity): + key = self._get_key(entity) + parent = self._cache.get(key, None) + if parent is None: + # The bucket is initialized to support this usage: + # cache[key][subkey] = value + self._cache[key] = parent = {} + return parent + + def __len__(self): + return len(self._cache) + + +class CodeObjectCache(_TransformedFnCache): + """A function cache based on code objects. + + Code objects are good proxies for the source code of a function. + + This cache efficiently handles functions that share code objects, such as + functions defined in a loop, bound methods, etc. + + The cache falls back to the function object, if it doesn't have a code object. + """ + + def _get_key(self, entity): + if hasattr(entity, '__code__'): + return entity.__code__ + else: + return entity + + +class UnboundInstanceCache(_TransformedFnCache): + """A function cache based on unbound function objects. + + Using the function for the cache key allows efficient handling of object + methods. + + Unlike the _CodeObjectCache, this discriminates between different functions + even if they have the same code. This is needed for decorators that may + masquerade as another function. + """ + + def _get_key(self, entity): + if inspect.ismethod(entity): + return entity.__func__ + return entity + + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/cfg.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..fd8ddf046d29e9b4acf92a9ad5ee4dd936d89798 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/cfg.py @@ -0,0 +1,971 @@ +# 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. +# ============================================================================== +"""Control flow graph (CFG) structure for Python AST representation. + +The CFG is a digraph with edges representing valid control flow. Each +node is associated with exactly one AST node, but not all AST nodes may have +a corresponding CFG counterpart. + +Once built, the CFG itself is immutable, but the values it holds need not be; +they are usually annotated with information extracted by walking the graph. + +Tip: Use `Graph.as_dot` to visualize the CFG using any DOT viewer. + +Note: the CFG tries to include all code paths that MAY be taken, with a single +notable exception: + * function calls do not generate edges corresponding to exceptions they may + raise (i.e. a function call in the middle of a block does not return or jump + to any except or finally block) +TODO(mdan): Consider adding the edges above. They'd only add ~O(n) edges. +TODO(mdan): Alternatively, consider adding an edge from try to all its excepts. +""" + +# TODO(mdan): The notion of 'statements' below is inaccurate. +# They should rather be called 'block statements', because they include +# statements that may have a body, e.g. if and while. + +import collections +import enum +import weakref + +import astunparse +import gast + +from tensorflow.python.autograph.pyct import anno + + +class Node(object): + """A node in the CFG. + + Although new instances of this class are mutable, the objects that a user + finds in the CFG are typically not. + + The nodes represent edges in the CFG graph, and maintain pointers to allow + efficient walking in both forward and reverse order. The following property + holds for all nodes: "child in node.next" iff "node in child.prev". + + Attributes: + next: FrozenSet[Node, ...], the nodes that follow this node, in control flow + order + prev: FrozenSet[Node, ...], the nodes that precede this node, in reverse + control flow order + ast_node: ast.AST, the AST node corresponding to this CFG node + """ + + def __init__(self, next_, prev, ast_node): + self.next = next_ + self.prev = prev + self.ast_node = ast_node + + def freeze(self): + self.next = frozenset(self.next) + # Assumption: All CFG nodes have identical life spans, because the graph + # owns them. Nodes should never be used outside the context of an existing + # graph. + self.prev = weakref.WeakSet(self.prev) + + def __repr__(self): + if isinstance(self.ast_node, gast.FunctionDef): + return 'def %s' % self.ast_node.name + elif isinstance(self.ast_node, gast.ClassDef): + return 'class %s' % self.ast_node.name + elif isinstance(self.ast_node, gast.withitem): + # TODO(xjun): remove use of astunparse + return astunparse.unparse(self.ast_node.context_expr).strip() + return astunparse.unparse(self.ast_node).strip() + + +class Graph( + collections.namedtuple( + 'Graph', + ['entry', 'exit', 'error', 'index', 'stmt_prev', 'stmt_next'])): + """A Control Flow Graph. + + The CFG maintains an index to allow looking up a CFG node by the AST node to + which it is associated. The index can also be enumerated in top-down, depth + first order. + + Walking the graph in forward or reverse order is supported by double + parent-child links. + + Note: the error nodes are not wired to their corresponding finally guards, + because these are shared, and wiring them would create a reverse path from + normal control flow into the error nodes, which we want to avoid. + + The graph also maintains edges corresponding to higher level statements + like for-else loops. A node is considered successor of a statement if there + is an edge from a node that is lexically a child of that statement to a node + that is not. Statement predecessors are analogously defined. + + Attributes: + entry: Node, the entry node + exit: FrozenSet[Node, ...], the exit nodes + error: FrozenSet[Node, ...], nodes that exit due to an explicitly raised + error (errors propagated from function calls are not accounted) + index: Dict[ast.Node, Node], mapping AST nodes to the respective CFG node + stmt_prev: Dict[ast.Node, FrozenSet[Node, ...]], mapping statement AST nodes + to their predecessor CFG nodes + stmt_next: Dict[ast.Node, FrozenSet[Node, ...]], mapping statement AST nodes + to their successor CFG nodes + """ + + def __repr__(self): + return self.as_dot() + + def as_dot(self): + """Print CFG in DOT format.""" + result = 'digraph CFG {\n' + for node in self.index.values(): + result += ' %s [label="%s"];\n' % (id(node), node) + for node in self.index.values(): + for next_ in node.next: + result += ' %s -> %s;\n' % (id(node), id(next_)) + result += '}' + return result + + +class _WalkMode(enum.Enum): + FORWARD = 1 + REVERSE = 2 + + +# TODO(mdan): Rename to DataFlowAnalyzer. +# TODO(mdan): Consider specializations that use gen/kill/transfer abstractions. +class GraphVisitor(object): + """Base class for a CFG visitors. + + This implementation is not thread safe. + + The visitor has some facilities to simplify dataflow analyses. In particular, + it allows revisiting the nodes at the decision of the subclass. This can be + used to visit the graph until the state reaches a fixed point. + + For more details on dataflow analysis, see + https://www.seas.harvard.edu/courses/cs252/2011sp/slides/Lec02-Dataflow.pdf + + Note: the literature generally suggests visiting successor nodes only when the + state of the current node changed, regardless of whether that successor has + ever been visited. This implementation visits every successor at least once. + + Attributes: + graph: Graph + in_: Dict[Node, Any], stores node-keyed state during a visit + out: Dict[Node, Any], stores node-keyed state during a visit + """ + + def __init__(self, graph): + self.graph = graph + self.reset() + + def init_state(self, node): + """State initialization function. + + Optional to overload. + + An in/out state slot will be created for each node in the graph. Subclasses + must overload this to control what that is initialized to. + + Args: + node: Node + """ + raise NotImplementedError('Subclasses must implement this.') + + # TODO(mdan): Rename to flow? + def visit_node(self, node): + """Visitor function. + + Args: + node: Node + + Returns: + bool, whether the node should be revisited; subclasses can visit every + reachable node exactly once by always returning False + """ + raise NotImplementedError('Subclasses must implement this.') + + def reset(self): + self.in_ = { + node: self.init_state(node) for node in self.graph.index.values() + } + self.out = { + node: self.init_state(node) for node in self.graph.index.values() + } + + def can_ignore(self, node): + """Returns True if the node can safely be assumed not to touch variables.""" + ast_node = node.ast_node + if anno.hasanno(ast_node, anno.Basic.SKIP_PROCESSING): + return True + return isinstance(ast_node, + (gast.Break, gast.Continue, gast.Raise, gast.Pass)) + + def _visit_internal(self, mode): + """Visits the CFG, breadth-first.""" + assert mode in (_WalkMode.FORWARD, _WalkMode.REVERSE) + if mode == _WalkMode.FORWARD: + open_ = [self.graph.entry] + elif mode == _WalkMode.REVERSE: + open_ = list(self.graph.exit) + closed = set() + + while open_: + node = open_.pop(0) + closed.add(node) + + should_revisit = self.visit_node(node) + + if mode == _WalkMode.FORWARD: + children = node.next + elif mode == _WalkMode.REVERSE: + children = node.prev + + for next_ in children: + if should_revisit or next_ not in closed: + open_.append(next_) + + def visit_forward(self): + self._visit_internal(_WalkMode.FORWARD) + + def visit_reverse(self): + self._visit_internal(_WalkMode.REVERSE) + + +class GraphBuilder(object): + """Builder that constructs a CFG from a given AST. + + This GraphBuilder facilitates constructing the DAG that forms the CFG when + nodes + are supplied in lexical order (i.e., top-down, depth first). Under these + conditions, it supports building patterns found in typical structured + programs. + + This builder ignores the flow generated by exceptions, which are assumed to + always be catastrophic and present purely for diagnostic purposes (e.g. to + print debug information). Statements like raise and try/catch sections are + allowed and will generate control flow edges, but ordinary statements are + assumed not to raise exceptions. + + Finally sections are also correctly interleaved between break/continue/return + nodes and their subsequent statements. + + Important concepts: + * nodes - nodes refer to CFG nodes; AST nodes are qualified explicitly + * leaf set - since the graph is constructed gradually, a leaf set maintains + the CFG nodes that will precede the node that the builder expects to + receive next; when an ordinary node is added, it is connected to the + existing leaves and it in turn becomes the new leaf + * jump nodes - nodes that should generate edges other than what + ordinary nodes would; these correspond to break, continue and return + statements + * sections - logical delimiters for subgraphs that require special + edges; there are various types of nodes, each admitting various + types of jump nodes; sections are identified by their corresponding AST + node + """ + + # TODO(mdan): Perhaps detail this in a markdown doc. + # TODO(mdan): Add exception support. + + def __init__(self, parent_ast_node): + self.reset() + self.parent = parent_ast_node + + def reset(self): + """Resets the state of this factory.""" + self.head = None + self.errors = set() + self.node_index = {} + + # TODO(mdan): Too many primitives. Use classes. + self.leaves = set() + + # Note: This mechanism requires that nodes are added in lexical order (top + # to bottom, depth first). + self.active_stmts = set() + self.owners = {} # type: Set[any] + self.forward_edges = set() # type: Tuple[Node, Node] # (from, to) + + self.finally_sections = {} + # Dict values represent (entry, exits) + self.finally_section_subgraphs = { + } # type: Dict[ast.AST, Tuple[Node, Set[Node]]] + # Whether the guard section can be reached from the statement that precedes + # it. + self.finally_section_has_direct_flow = {} + # Finally sections that await their first node. + self.pending_finally_sections = set() + + # Exit jumps keyed by the section they affect. + self.exits = {} + + # The entry of loop sections, keyed by the section. + self.section_entry = {} + # Continue jumps keyed by the section they affect. + self.continues = {} + + # Raise jumps keyed by the except section guarding them. + self.raises = {} + + # The entry of conditional sections, keyed by the section. + self.cond_entry = {} + # Lists of leaf nodes corresponding to each branch in the section. + self.cond_leaves = {} + + def _connect_nodes(self, first, second): + """Connects nodes to signify that control flows from first to second. + + Args: + first: Union[Set[Node, ...], Node] + second: Node + """ + if isinstance(first, Node): + first.next.add(second) + second.prev.add(first) + self.forward_edges.add((first, second)) + else: + for node in first: + self._connect_nodes(node, second) + + def _add_new_node(self, ast_node): + """Grows the graph by adding a CFG node following the current leaves.""" + if ast_node in self.node_index: + raise ValueError('%s added twice' % ast_node) + # Assumption: All CFG nodes have identical life spans, because the graph + # owns them. Nodes should never be used outside the context of an existing + # graph. + node = Node(next_=set(), prev=weakref.WeakSet(), ast_node=ast_node) + self.node_index[ast_node] = node + self.owners[node] = frozenset(self.active_stmts) + + if self.head is None: + self.head = node + + for leaf in self.leaves: + self._connect_nodes(leaf, node) + + # If any finally section awaits its first node, populate it. + for section_id in self.pending_finally_sections: + self.finally_section_subgraphs[section_id][0] = node + self.pending_finally_sections = set() + + return node + + def begin_statement(self, stmt): + """Marks the beginning of a statement. + + Args: + stmt: Hashable, a key by which the statement can be identified in the + CFG's stmt_prev and stmt_next attributes + """ + self.active_stmts.add(stmt) + + def end_statement(self, stmt): + """Marks the end of a statement. + + Args: + stmt: Hashable, a key by which the statement can be identified in the + CFG's stmt_prev and stmt_next attributes; must match a key previously + passed to begin_statement. + """ + self.active_stmts.remove(stmt) + + def add_ordinary_node(self, ast_node): + """Grows the graph by adding an ordinary CFG node. + + Ordinary nodes are followed by the next node, in lexical order, that is, + they become the new leaf set. + + Args: + ast_node: ast.AST + + Returns: + Node + """ + node = self._add_new_node(ast_node) + self.leaves = set((node,)) + return node + + def _add_jump_node(self, ast_node, guards): + """Grows the graph by adding a jump node. + + Jump nodes are added to the current leaf set, and the leaf set becomes + empty. If the jump node is the last in a cond section, then it may be added + back to the leaf set by a separate mechanism. + + Args: + ast_node: ast.AST + guards: Tuple[ast.AST, ...], the finally sections active for this node + + Returns: + Node + """ + node = self._add_new_node(ast_node) + self.leaves = set() + # The guards themselves may not yet be complete, and will be wired later. + self.finally_sections[node] = guards + return node + + def _connect_jump_to_finally_sections(self, node): + """Connects a jump node to the finally sections protecting it.""" + cursor = set((node,)) + if node not in self.finally_sections: + return cursor + for guard_section_id in self.finally_sections[node]: + guard_begin, guard_ends = self.finally_section_subgraphs[guard_section_id] + self._connect_nodes(cursor, guard_begin) + cursor = guard_ends + del self.finally_sections[node] + # TODO(mdan): Should garbage-collect finally_section_subgraphs. + return cursor + + def add_exit_node(self, ast_node, section_id, guards): + """Grows the graph by adding an exit node. + + This node becomes an exit for the current section. + + Args: + ast_node: ast.AST + section_id: Hashable, the node for which ast_node should be considered to + be an exit node + guards: Tuple[ast.AST, ...], the finally sections that guard ast_node + + Returns: + Node + """ + node = self._add_jump_node(ast_node, guards) + self.exits[section_id].add(node) + return node + + def add_continue_node(self, ast_node, section_id, guards): + """Grows the graph by adding a reentry node. + + This node causes control flow to go back to the loop section's entry. + + Args: + ast_node: ast.AST + section_id: Hashable, the node for which ast_node should be considered to + be an exit node + guards: Tuple[ast.AST, ...], the finally sections that guard ast_node + """ + node = self._add_jump_node(ast_node, guards) + self.continues[section_id].add(node) + + def connect_raise_node(self, node, except_guards): + """Adds extra connection between a raise node and containing except guards. + + The node is a graph node, not an ast node. + + Args: + node: Node + except_guards: Tuple[ast.AST, ...], the except sections that guard node + """ + for guard in except_guards: + if guard in self.raises: + self.raises[guard].append(node) + else: + self.raises[guard] = [node] + + def enter_section(self, section_id): + """Enters a regular section. + + Regular sections admit exit jumps, which end the section. + + Args: + section_id: Hashable, the same node that will be used in calls to the + ast_node arg passed to add_exit_node + """ + assert section_id not in self.exits + self.exits[section_id] = set() + + def exit_section(self, section_id): + """Exits a regular section.""" + + # Exits are jump nodes, which may be protected. + for exit_ in self.exits[section_id]: + self.leaves |= self._connect_jump_to_finally_sections(exit_) + + del self.exits[section_id] + + def enter_loop_section(self, section_id, entry_node): + """Enters a loop section. + + Loop sections define an entry node. The end of the section always flows back + to the entry node. These admit continue jump nodes which also flow to the + entry node. + + Args: + section_id: Hashable, the same node that will be used in calls to the + ast_node arg passed to add_continue_node + entry_node: ast.AST, the entry node into the loop (e.g. the test node for + while loops) + """ + assert section_id not in self.section_entry + assert section_id not in self.continues + self.continues[section_id] = set() + node = self.add_ordinary_node(entry_node) + self.section_entry[section_id] = node + + def exit_loop_section(self, section_id): + """Exits a loop section.""" + self._connect_nodes(self.leaves, self.section_entry[section_id]) + + # continues are jump nodes, which may be protected. + for reentry in self.continues[section_id]: + guard_ends = self._connect_jump_to_finally_sections(reentry) + self._connect_nodes(guard_ends, self.section_entry[section_id]) + + # Loop nodes always loop back. + self.leaves = set((self.section_entry[section_id],)) + + del self.continues[section_id] + del self.section_entry[section_id] + + def enter_cond_section(self, section_id): + """Enters a conditional section. + + Conditional sections define an entry node, and one or more branches. + + Args: + section_id: Hashable, the same node that will be used in calls to the + section_id arg passed to new_cond_branch + """ + + assert section_id not in self.cond_entry + assert section_id not in self.cond_leaves + self.cond_leaves[section_id] = [] + + def new_cond_branch(self, section_id): + """Begins a new branch in a cond section.""" + assert section_id in self.cond_leaves + + if section_id in self.cond_entry: + # Subsequent splits move back to the split point, and memorize the + # current leaves. + self.cond_leaves[section_id].append(self.leaves) + self.leaves = self.cond_entry[section_id] + else: + # If this is the first time we split a section, just remember the split + # point. + self.cond_entry[section_id] = self.leaves + + def exit_cond_section(self, section_id): + """Exits a conditional section.""" + for split in self.cond_leaves[section_id]: + self.leaves |= split + del self.cond_entry[section_id] + del self.cond_leaves[section_id] + + def enter_except_section(self, section_id): + """Enters an except section.""" + if section_id in self.raises: + self.leaves.update(self.raises[section_id]) + + def enter_finally_section(self, section_id): + """Enters a finally section.""" + # TODO(mdan): This, not the caller, should track the active sections. + self.finally_section_subgraphs[section_id] = [None, None] + if self.leaves: + self.finally_section_has_direct_flow[section_id] = True + else: + self.finally_section_has_direct_flow[section_id] = False + self.pending_finally_sections.add(section_id) + + def exit_finally_section(self, section_id): + """Exits a finally section.""" + assert section_id not in self.pending_finally_sections, 'Empty finally?' + self.finally_section_subgraphs[section_id][1] = self.leaves + # If the guard can only be reached by a jump, then it will not flow + # into the statement that follows it. + if not self.finally_section_has_direct_flow[section_id]: + self.leaves = set() + del self.finally_section_has_direct_flow[section_id] + + def build(self): + """Returns the CFG accumulated so far and resets the builder. + + Returns: + Graph + """ + # Freeze the nodes. + for node in self.node_index.values(): + node.freeze() + + # Build the statement edges. + stmt_next = {} + stmt_prev = {} + + for node in self.node_index.values(): + for stmt in self.owners[node]: + if stmt not in stmt_prev: + stmt_prev[stmt] = set() + if stmt not in stmt_next: + stmt_next[stmt] = set() + + for first, second in self.forward_edges: + stmts_exited = self.owners[first] - self.owners[second] + for stmt in stmts_exited: + stmt_next[stmt].add(second) + stmts_entered = self.owners[second] - self.owners[first] + for stmt in stmts_entered: + stmt_prev[stmt].add(first) + for stmt in stmt_next: + stmt_next[stmt] = frozenset(stmt_next[stmt]) + for stmt in stmt_prev: + stmt_prev[stmt] = frozenset(stmt_prev[stmt]) + + # Construct the final graph object. + result = Graph( + entry=self.head, + exit=self.leaves, + error=self.errors, + index=self.node_index, + stmt_prev=stmt_prev, + stmt_next=stmt_next) + + # Reset the state. + self.reset() + + return result + + +class AstToCfg(gast.NodeVisitor): + """Converts an AST to CFGs. + + A separate CFG will be constructed for each function. + """ + + def __init__(self): + super(AstToCfg, self).__init__() + + self.builder_stack = [] + self.builder = None + self.cfgs = {} + + self.lexical_scopes = [] + + def _enter_lexical_scope(self, node): + self.lexical_scopes.append(node) + + def _exit_lexical_scope(self, node): + leaving_node = self.lexical_scopes.pop() + assert node == leaving_node + + def _get_enclosing_finally_scopes(self, stop_at): + included = [] + for node in reversed(self.lexical_scopes): + if isinstance(node, gast.Try) and node.finalbody: + included.append(node) + if isinstance(node, stop_at): + return node, included + return None, included + + def _get_enclosing_except_scopes(self, stop_at): + included = [] + for node in reversed(self.lexical_scopes): + if isinstance(node, gast.Try) and node.handlers: + included.extend(node.handlers) + if isinstance(node, stop_at): + break + return included + + def _process_basic_statement(self, node): + self.generic_visit(node) + self.builder.add_ordinary_node(node) + + def _process_exit_statement(self, + node, + exits_nodes_of_type, + may_exit_via_except=False): + self.generic_visit(node) + # Note: this is safe because we process functions separately. + try_node, guards = self._get_enclosing_finally_scopes(exits_nodes_of_type) + assert try_node is not None, '{} that is not enclosed by any of {}'.format( + node, exits_nodes_of_type) + + node = self.builder.add_exit_node(node, try_node, guards) + + if may_exit_via_except: + except_guards = self._get_enclosing_except_scopes(exits_nodes_of_type) + self.builder.connect_raise_node(node, except_guards) + + def _process_continue_statement(self, node, *loops_to_nodes_of_type): + # Note: this is safe because we process functions separately. + try_node, guards = self._get_enclosing_finally_scopes( + tuple(loops_to_nodes_of_type)) + if try_node is None: + raise ValueError('%s that is not enclosed by any of %s' % + (node, loops_to_nodes_of_type)) + self.builder.add_continue_node(node, try_node, guards) + + def visit_ClassDef(self, node): + # We also keep the ClassDef node in the CFG, since it technically is a + # statement. + # For example, this is legal and allows executing user code: + # + # class Foo(bar()): + # pass + # + # It also has a scope: + # + # class Bar(object): + # a = 1 + if self.builder is None: + self.generic_visit(node) + return + + self.builder.add_ordinary_node(node) + + self.builder_stack.append(self.builder) + self.builder = GraphBuilder(node) + self._enter_lexical_scope(node) + + self._process_basic_statement(node) + + self._exit_lexical_scope(node) + # TODO(mdan): Track the CFG local to the class definition as well? + self.builder = self.builder_stack.pop() + + def _process_function_def(self, node, is_lambda): + # The function body is stored in a separate graph, because function + # definitions have effects very different from function calls. + if self.builder is not None: + self.builder.add_ordinary_node(node) + + self.builder_stack.append(self.builder) + self.builder = GraphBuilder(node) + + self._enter_lexical_scope(node) + self.builder.enter_section(node) + + self._process_basic_statement(node.args) + if is_lambda: + self._process_exit_statement(node.body, (gast.Lambda,)) + else: + for stmt in node.body: + self.visit(stmt) + + self.builder.exit_section(node) + self._exit_lexical_scope(node) + + self.cfgs[node] = self.builder.build() + self.builder = self.builder_stack.pop() + + def visit_FunctionDef(self, node): + self._process_function_def(node, is_lambda=False) + + def visit_Lambda(self, node): + self._process_function_def(node, is_lambda=True) + + def visit_Return(self, node): + self._process_exit_statement(node, (gast.FunctionDef,)) + + def visit_Import(self, node): + self._process_basic_statement(node) + + def visit_ImportFrom(self, node): + self._process_basic_statement(node) + + def visit_Expr(self, node): + self._process_basic_statement(node) + + def visit_Assign(self, node): + self._process_basic_statement(node) + + def visit_AnnAssign(self, node): + self._process_basic_statement(node) + + def visit_AugAssign(self, node): + self._process_basic_statement(node) + + def visit_Pass(self, node): + self._process_basic_statement(node) + + def visit_Global(self, node): + self._process_basic_statement(node) + + def visit_Nonlocal(self, node): + self._process_basic_statement(node) + + def visit_Print(self, node): + self._process_basic_statement(node) + + def visit_Raise(self, node): + self._process_exit_statement( + node, (gast.FunctionDef,), may_exit_via_except=True) + self.builder.errors.add(node) + + def visit_Assert(self, node): + # Ignoring the effect of exceptions. + self._process_basic_statement(node) + + def visit_Delete(self, node): + self._process_basic_statement(node) + + def visit_If(self, node): + # No need to track ifs as lexical scopes, for now. + # Lexical scopes are generally tracked in order to be able to resolve the + # targets of jump statements like break/continue/etc. Since there is no + # statement that can interrupt a conditional, we don't need to track their + # lexical scope. That may change in the future. + self.builder.begin_statement(node) + + self.builder.enter_cond_section(node) + self._process_basic_statement(node.test) + + self.builder.new_cond_branch(node) + for stmt in node.body: + self.visit(stmt) + + self.builder.new_cond_branch(node) + for stmt in node.orelse: + self.visit(stmt) + + self.builder.exit_cond_section(node) + self.builder.end_statement(node) + + def visit_While(self, node): + self.builder.begin_statement(node) + self._enter_lexical_scope(node) + + self.builder.enter_section(node) + + self.generic_visit(node.test) + self.builder.enter_loop_section(node, node.test) + for stmt in node.body: + self.visit(stmt) + self.builder.exit_loop_section(node) + + # Note: although the orelse is technically part of the loop node, + # the statements inside it don't affect the loop itself. For example, a + # break in the loop's orelse will not affect the loop itself. + self._exit_lexical_scope(node) + + for stmt in node.orelse: + self.visit(stmt) + + self.builder.exit_section(node) + self.builder.end_statement(node) + + def visit_For(self, node): + self.builder.begin_statement(node) + self._enter_lexical_scope(node) + + self.builder.enter_section(node) + + # Note: Strictly speaking, this should be node.target + node.iter. + # However, the activity analysis accounts for this inconsistency, + # so dataflow analysis produces the correct values. + self.generic_visit(node.iter) + self.builder.enter_loop_section(node, node.iter) + # Also include the "extra loop test" annotation, to capture things like the + # control variable for return and break in for loops. + if anno.hasanno(node, anno.Basic.EXTRA_LOOP_TEST): + self._process_basic_statement( + anno.getanno(node, anno.Basic.EXTRA_LOOP_TEST)) + for stmt in node.body: + self.visit(stmt) + self.builder.exit_loop_section(node) + + # Note: although the orelse is technically part of the loop node, + # they don't count as loop bodies. For example, a break in the loop's + # orelse will affect the parent loop, not the current one. + self._exit_lexical_scope(node) + + for stmt in node.orelse: + self.visit(stmt) + + self.builder.exit_section(node) + self.builder.end_statement(node) + + def visit_Break(self, node): + self._process_exit_statement(node, ( + gast.While, + gast.For, + )) + + def visit_Continue(self, node): + self._process_continue_statement(node, ( + gast.While, + gast.For, + )) + + def visit_ExceptHandler(self, node): + self.builder.begin_statement(node) + self.builder.enter_except_section(node) + + if node.type is not None: + self.visit(node.type) + if node.name is not None: + self.visit(node.name) + + for stmt in node.body: + self.visit(stmt) + + self.builder.end_statement(node) + + def visit_Try(self, node): + self.builder.begin_statement(node) + self._enter_lexical_scope(node) + + # Note: the current simplification is that the try block fully executes + # regardless of whether an exception triggers or not. This is consistent + # with blocks free of try/except, which also don't account for the + # possibility of an exception being raised mid-block. + + for stmt in node.body: + self.visit(stmt) + # The orelse is an optional continuation of the body. + if node.orelse: + block_representative = node.orelse[0] + self.builder.enter_cond_section(block_representative) + self.builder.new_cond_branch(block_representative) + for stmt in node.orelse: + self.visit(stmt) + self.builder.new_cond_branch(block_representative) + self.builder.exit_cond_section(block_representative) + + self._exit_lexical_scope(node) + + if node.handlers: + # Using node would be inconsistent. Using the first handler node is also + # inconsistent, but less so. + block_representative = node.handlers[0] + self.builder.enter_cond_section(block_representative) + for block in node.handlers: + self.builder.new_cond_branch(block_representative) + self.visit(block) + self.builder.new_cond_branch(block_representative) + self.builder.exit_cond_section(block_representative) + + if node.finalbody: + self.builder.enter_finally_section(node) + for stmt in node.finalbody: + self.visit(stmt) + self.builder.exit_finally_section(node) + + self.builder.end_statement(node) + + def visit_With(self, node): + # TODO(mdan): Mark the context manager's exit call as exit guard. + for item in node.items: + self._process_basic_statement(item) + for stmt in node.body: + self.visit(stmt) + + +def build(node): + visitor = AstToCfg() + visitor.visit(node) + return visitor.cfgs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/common_transformers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/common_transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/common_transformers/anf.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/common_transformers/anf.py new file mode 100644 index 0000000000000000000000000000000000000000..71ba9f35d7847e359a7c207ac9f89e86ec8e6639 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/common_transformers/anf.py @@ -0,0 +1,620 @@ +# 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. +# ============================================================================== +"""Conversion to A-normal form. + +The general idea of A-normal form is that every intermediate value is +explicitly named with a variable. For more, see +https://en.wikipedia.org/wiki/A-normal_form. + +The specific converters used here are based on Python AST semantics as +documented at https://greentreesnakes.readthedocs.io/en/latest/. +""" + +import collections + +import gast + +from tensorflow.python.autograph.pyct import gast_util +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct import transformer + + +# TODO(mdan): Replace with naming.Namer. +class DummyGensym: + """A dumb gensym that suffixes a stem by sequential numbers from 1000.""" + + def __init__(self): + # A proper implementation needs to account for: + # * ctx.info.namespace + # * all the symbols defined in the AST + # * the symbols generated so far + self._idx = 0 + + def new_name(self, stem='tmp'): + self._idx += 1 + return stem + '_' + str(1000 + self._idx) + + +REPLACE = lambda _1, _2, _3: True +LEAVE = lambda _1, _2, _3: False +ANY = object() + + +class ASTEdgePattern(collections.namedtuple( + 'ASTEdgePattern', ['parent', 'field', 'child'])): + """A pattern defining a type of AST edge. + + This consists of three components: + - The type of the parent node, checked with isinstance, + - The name of the field, checked with string equality, and + - The type of the child node, also checked with isinstance. + If all three match, the whole pattern is considered to match. + + In all three slots, the special value `anf.ANY` is treated as "match + anything". The internal nodes are produced from the `gast` library rather + than the standard `ast` module, which may affect `isinstance` checks. + """ + __slots__ = () + + def matches(self, parent, field, child): + """Computes whether this pattern matches the given edge.""" + if self.parent is ANY or isinstance(parent, self.parent): + pass # OK + else: + return False + if self.field is ANY or field == self.field: + pass # OK + else: + return False + return self.child is ANY or isinstance(child, self.child) + + +class AnfTransformer(transformer.Base): + """Performs the conversion to A-normal form (ANF).""" + + # The algorithm is a postorder recursive tree walk. Any given node A may, in + # general, require creation of a series B of Assign statements, which compute + # and explicitly name the intermediate values needed to compute the value of + # A. If A was already a statement, it can be replaced with the sequence B + + # [A]. If A was an expression, B needs to be propagated up the tree until a + # statement is encountered. Since the `ast.NodeTransformer` framework makes + # no provision for subtraversals returning side information, this class + # accumulates the sequence B in an instance variable. + + # The only other subtlety is that some Python statements (like `if`) have both + # expression fields (`test`) and statement list fields (`body` and `orelse`). + # Any additional assignments needed to name all the intermediate values in the + # `test` can be prepended to the `if` node, but assignments produced by + # processing the `body` and the `orelse` need to be kept together with them, + # and not accidentally lifted out of the `if`. + + def __init__(self, ctx, config): + """Creates an ANF transformer. + + Args: + ctx: transformer.Context + config: Configuration + """ + super(AnfTransformer, self).__init__(ctx) + if config is None: + # These could be pulled out, but are generally considered to already be in + # A-normal form. Thus they are left in by default, but could be pulled + # out if the configuration calls for it. + if gast_util.GAST2: + literal_node_types = ( + gast.Num, gast.Str, gast.Bytes, gast.NameConstant, + gast.Name # Name is here to cover True, False, and None in Python 2 + ) + elif gast_util.GAST3: + literal_node_types = ( + gast.Constant, + gast.Name # Name is here to cover True, False, and None in Python 2 + ) + else: + assert False + + self._overrides = [ + (ASTEdgePattern(ANY, ANY, literal_node_types), LEAVE), + (ASTEdgePattern(ANY, ANY, gast.expr), REPLACE)] + else: + self._overrides = config + self._gensym = DummyGensym() + self._pending_statements = [] + + def _consume_pending_statements(self): + ans = self._pending_statements + self._pending_statements = [] + return ans + + def _add_pending_statement(self, stmt): + self._pending_statements.append(stmt) + + def _match(self, pattern, parent, field, child): + if pattern is ANY: + return True + else: + return pattern.matches(parent, field, child) + + def _should_transform(self, parent, field, child): + for pat, result in self._overrides: + if self._match(pat, parent, field, child): + return result(parent, field, child) + # Fell off the end of the pattern list: do not transform + return False + + def _do_transform_node(self, node): + temp_name = self._gensym.new_name() + temp_assign = templates.replace( + 'temp_name = expr', temp_name=temp_name, expr=node)[0] + self._add_pending_statement(temp_assign) + answer = templates.replace('temp_name', temp_name=temp_name)[0] + return answer + + def _ensure_node_in_anf(self, parent, field, node): + """Puts `node` in A-normal form, by replacing it with a variable if needed. + + The exact definition of A-normal form is given by the configuration. The + parent and the incoming field name are only needed because the configuration + may be context-dependent. + + Args: + parent: An AST node, the parent of `node`. + field: The field name under which `node` is the child of `parent`. + node: An AST node, potentially to be replaced with a variable reference. + + Returns: + node: An AST node; the argument if transformation was not necessary, + or the new variable reference if it was. + """ + if node is None: + return node + if _is_trivial(node): + return node + if isinstance(node, list): + # If something's field was actually a list, e.g., variadic arguments. + return [self._ensure_node_in_anf(parent, field, n) for n in node] + if isinstance(node, gast.keyword): + node.value = self._ensure_node_in_anf(parent, field, node.value) + return node + if isinstance(node, (gast.Starred, gast.withitem, gast.slice)): + # These nodes aren't really extractable in their own right, but their + # subnodes might be. Propagate the parent and field name to the child + # nodes, instead of querying the configuration for children of, e.g., + # gast.Starred. + return self._ensure_fields_in_anf(node, parent, field) + if self._should_transform(parent, field, node): + return self._do_transform_node(node) + else: + return node + + def _ensure_fields_in_anf(self, node, parent=None, super_field=None): + for field in node._fields: + if field.startswith('__'): + continue + parent_supplied = node if parent is None else parent + field_supplied = field if super_field is None else super_field + setattr(node, field, self._ensure_node_in_anf( + parent_supplied, field_supplied, getattr(node, field))) + return node + + def _visit_strict_statement(self, node, children_ok_to_transform=True): + assert not self._pending_statements + node = self.generic_visit(node) + if children_ok_to_transform: + self._ensure_fields_in_anf(node) + results = self._consume_pending_statements() + results.append(node) + return results + + def _visit_trivial_only_statement(self, node, msg): + assert not self._pending_statements + node = self.generic_visit(node) + self._ensure_fields_in_anf(node) + if self._pending_statements: + raise ValueError(msg) + else: + return node + + def _visit_strict_expression(self, node): + node = self.generic_visit(node) + self._ensure_fields_in_anf(node) + return node + + def _visit_trivial_only_expression(self, node, msg): + k = len(self._pending_statements) + node = self.generic_visit(node) + self._ensure_fields_in_anf(node) + # This check relies on there being no opportunities to consume pending + # statements while traversing children of an expression. + if len(self._pending_statements) != k: + raise ValueError(msg) + else: + return node + + # Note on code order: These are listed in the same order as the grammar + # elements on https://github.com/serge-sans-paille/gast + + # FunctionDef, AsyncFunctionDef, and ClassDef should be correct by default. + + def visit_Return(self, node): + return self._visit_strict_statement(node) + + def visit_Delete(self, node): + return self._visit_strict_statement(node, children_ok_to_transform=False) + + def visit_Assign(self, node): + return self._visit_strict_statement(node, children_ok_to_transform=False) + + def visit_AugAssign(self, node): + return self._visit_strict_statement(node, children_ok_to_transform=False) + + def visit_Print(self, node): + return self._visit_strict_statement(node) + + def visit_For(self, node): + assert not self._pending_statements + # It's important to visit node.iter first, because any statements created + # thereby need to live outside the body. + self.visit(node.iter) + node.iter = self._ensure_node_in_anf(node, 'iter', node.iter) + iter_stmts = self._consume_pending_statements() + # This generic_visit will revisit node.iter, but that is correct because by + # this point the node.iter link has been checked. It may be somewhat + # expensive if the configuration didn't call for transforming node.iter, as + # then it may be large and will be uselessly transformed again. This + # behavior is what causes the documented effect that configuration callables + # may be invoked more than once of the same links; if the code is rewritten + # not to do that (anywhere), the docstring of `transform` should be updated. + node = self.generic_visit(node) + assert not self._pending_statements + iter_stmts.append(node) + return iter_stmts + + def visit_AsyncFor(self, node): + msg = ('Nontrivial AsyncFor nodes not supported yet ' + '(need to think through the semantics).') + return self._visit_trivial_only_statement(node, msg) + + def visit_While(self, node): + assert not self._pending_statements + self.visit(node.test) + node.test = self._ensure_node_in_anf(node, 'test', node.test) + if self._pending_statements: + msg = ('While with nontrivial test not supported yet ' + '(need to avoid precomputing the test).') + raise ValueError(msg) + # If traversing node.test yielded no statements extracted, the generic visit + # will do the right thing. + return self.generic_visit(node) + + def visit_If(self, node): + assert not self._pending_statements + # It's important to visit node.test first, because any statements created + # thereby need to live outside the body. + self.visit(node.test) + node.test = self._ensure_node_in_anf(node, 'test', node.test) + condition_stmts = self._consume_pending_statements() + # This generic_visit will revisit node.test, but that is correct because by + # this point the node.test link has been checked. It may be somewhat + # expensive if the configuration didn't call for transforming node.test, as + # then it may be large and will be uselessly transformed again. This + # happens in several places. + node = self.generic_visit(node) + assert not self._pending_statements + condition_stmts.append(node) + return condition_stmts + + def visit_With(self, node): + assert not self._pending_statements + # It's important to visit node.items first, because any statements created + # thereby need to live outside the body. + for item in node.items: + self.visit(item) + node.items = [self._ensure_node_in_anf(node, 'items', n) + for n in node.items] + contexts_stmts = self._consume_pending_statements() + # This generic_visit will revisit node.items, but that is correct because by + # this point the node.items link has been checked. It may be somewhat + # expensive if the configuration didn't call for transforming node.items, as + # then it may be large and will be uselessly transformed again. This + # happens in several places. + node = self.generic_visit(node) + assert not self._pending_statements + contexts_stmts.append(node) + return contexts_stmts + + def visit_AsyncWith(self, node): + msg = ('Nontrivial AsyncWith nodes not supported yet ' + '(need to think through the semantics).') + return self._visit_trivial_only_statement(node, msg) + + def visit_Raise(self, node): + return self._visit_strict_statement(node) + + # Try should be correct by default. + + def visit_Assert(self, node): + msg = ('Nontrivial Assert nodes not supported yet ' + '(need to avoid computing the test when assertions are off, and ' + 'avoid computing the irritant when the assertion does not fire).') + return self._visit_trivial_only_statement(node, msg) + + # Import and ImportFrom should be correct by default. + + def visit_Exec(self, node): + return self._visit_strict_statement(node) + + # Global and Nonlocal should be correct by default. + + def visit_Expr(self, node): + return self._visit_strict_statement(node, children_ok_to_transform=False) + + # Pass, Break, and Continue should be correct by default. + + def visit_BoolOp(self, node): + msg = ('Nontrivial BoolOp nodes not supported yet ' + '(need to preserve short-circuiting semantics).') + return self._visit_trivial_only_expression(node, msg) + + def visit_BinOp(self, node): + return self._visit_strict_expression(node) + + def visit_UnaryOp(self, node): + return self._visit_strict_expression(node) + + def visit_Lambda(self, node): + msg = ('Nontrivial Lambda nodes not supported ' + '(cannot insert statements into lambda bodies).') + return self._visit_trivial_only_expression(node, msg) + + def visit_IfExp(self, node): + msg = ('Nontrivial IfExp nodes not supported yet ' + '(need to convert to If statement, to evaluate branches lazily ' + 'and insert statements into them).') + return self._visit_trivial_only_expression(node, msg) + + def visit_Dict(self, node): + return self._visit_strict_expression(node) + + def visit_Set(self, node): + return self._visit_strict_expression(node) + + def visit_ListComp(self, node): + msg = ('ListComp nodes not supported ' + '(need to convert to a form that tolerates ' + 'assignment statements in clause bodies).') + raise ValueError(msg) + + def visit_SetComp(self, node): + msg = ('SetComp nodes not supported ' + '(need to convert to a form that tolerates ' + 'assignment statements in clause bodies).') + raise ValueError(msg) + + def visit_DictComp(self, node): + msg = ('DictComp nodes not supported ' + '(need to convert to a form that tolerates ' + 'assignment statements in clause bodies).') + raise ValueError(msg) + + def visit_GeneratorExp(self, node): + msg = ('GeneratorExp nodes not supported ' + '(need to convert to a form that tolerates ' + 'assignment statements in clause bodies).') + raise ValueError(msg) + + def visit_Await(self, node): + msg = ('Nontrivial Await nodes not supported yet ' + '(need to think through the semantics).') + return self._visit_trivial_only_expression(node, msg) + + def visit_Yield(self, node): + return self._visit_strict_expression(node) + + def visit_YieldFrom(self, node): + msg = ('Nontrivial YieldFrom nodes not supported yet ' + '(need to unit-test them in Python 2).') + return self._visit_trivial_only_expression(node, msg) + + def visit_Compare(self, node): + if len(node.ops) > 1: + msg = ('Multi-ary compare nodes not supported yet ' + '(need to preserve short-circuiting semantics).') + raise ValueError(msg) + return self._visit_strict_expression(node) + + def visit_Call(self, node): + return self._visit_strict_expression(node) + + def visit_Repr(self, node): + msg = ('Nontrivial Repr nodes not supported yet ' + '(need to research their syntax and semantics).') + return self._visit_trivial_only_expression(node, msg) + + def visit_FormattedValue(self, node): + msg = ('Nontrivial FormattedValue nodes not supported yet ' + '(need to unit-test them in Python 2).') + return self._visit_trivial_only_expression(node, msg) + + def visit_JoinedStr(self, node): + msg = ('Nontrivial JoinedStr nodes not supported yet ' + '(need to unit-test them in Python 2).') + return self._visit_trivial_only_expression(node, msg) + + def visit_Attribute(self, node): + return self._visit_strict_expression(node) + + def visit_Subscript(self, node): + return self._visit_strict_expression(node) + + # Starred and Name are correct by default, because the right thing to do is to + # just recur. + + def visit_List(self, node): + node = self.generic_visit(node) + if not isinstance(node.ctx, gast.Store): + self._ensure_fields_in_anf(node) + return node + + def visit_Tuple(self, node): + node = self.generic_visit(node) + if not isinstance(node.ctx, gast.Store): + self._ensure_fields_in_anf(node) + return node + + +def _is_py2_name_constant(node): + return isinstance(node, gast.Name) and node.id in ['True', 'False', 'None'] + + +def _is_trivial(node): + """Returns whether to consider the given node 'trivial'. + + The definition of 'trivial' is a node that can't meaningfully be pulled out + into its own assignment statement. + + This is surprisingly difficult to do robustly across versions of Python and + gast, as the parsing of constants has changed, if I may, constantly. + + Args: + node: An AST node to check for triviality + + Returns: + trivial: A Python `bool` indicating whether the node is trivial. + """ + trivial_node_types = ( + # Variable names + gast.Name, + # Non-nodes that show up as AST fields + bool, + str, + # Binary operators + gast.Add, + gast.Sub, + gast.Mult, + gast.Div, + gast.Mod, + gast.Pow, + gast.LShift, + gast.RShift, + gast.BitOr, + gast.BitXor, + gast.BitAnd, + gast.FloorDiv, + # Unary operators + gast.Invert, + gast.Not, + gast.UAdd, + gast.USub, + # Comparison operators + gast.Eq, + gast.NotEq, + gast.Lt, + gast.LtE, + gast.Gt, + gast.GtE, + gast.Is, + gast.IsNot, + gast.In, + gast.NotIn, + # Other leaf nodes that don't make sense standalone. + gast.expr_context, + ) + if isinstance(node, trivial_node_types) and not _is_py2_name_constant(node): + return True + if gast_util.is_ellipsis(node): + return True + + return False + + +def transform(node, ctx, config=None): + """Converts the given node to A-normal form (ANF). + + The general idea of A-normal form: https://en.wikipedia.org/wiki/A-normal_form + + The specific converters used here are based on Python AST semantics as + documented at https://greentreesnakes.readthedocs.io/en/latest/. + + What exactly should be considered A-normal form for any given programming + language is not completely obvious. The transformation defined here is + therefore configurable as to which syntax to replace with a fresh variable and + which to leave be. The configuration is intentionally flexible enough to + define very precise variable insertion transformations, should that be + desired. + + The configuration is a list of syntax rules, each of which is a 2-tuple: + - An `ASTEdgePattern` (which see) defining a type of AST edge, and + - Whether to transform children of such edges. + The special object `anf.ANY` may be used as a pattern that matches all edges. + + Each replacement directive is one of three possible things: + - The object `anf.REPLACE`, meaning "Replace this child node with a variable", + - The object `anf.LEAVE`, meaning "Do not replace this child node with a + variable", or + - A Python callable. If a callable, it is called with the parent node, the + field name, and the child node, and must compute a boolean indicating + whether to transform the child node or not. The callable is free to use + whatever context information it chooses. The callable may be invoked more + than once on the same link, and must produce the same answer each time. + + The syntax rules are tested in order, and the first match governs. If no rule + matches, the node is not transformed. + + The above rules notwithstanding, + - Variable references are never replaced with (fresh) variables, as that would + accomplish nothing. + - The left-hand children of Assign and AugAssign nodes, and the children of + Del nodes, are never replaced with variables, as that would break their + semantics. + - The right-hand children of Assign nodes are never replaced with variables, + as the original assignment would still have to be present in the result + to define the new variable. (That is, there's no point in transforming + `x = sin(y)` into `tmp = sin(y); x = tmp`.) + - The right-hand children of AugAssign nodes are never replaced with variables + either, but only because the difference from Assign was considered a + potential source of confusion (and it would have been slightly awkward in + the code to treat the RHS differently than the LHS). + - Various special-purpose AST nodes are not exposed to the configuration, lest + the transform produce invalid syntax like, e.g., `tmp = +; x = 1 tmp 2`. + + For example, the configuration + ```python + [(anf.ASTEdgePattern(anf.ANY, anf.ANY, gast.expr), anf.REPLACE)] + ``` + gives explicit fresh names to all expressions regardless of context (except as + outlined above), whereas + ```python + [(anf.ASTEdgePattern(gast.If, "test", anf.ANY), anf.REPLACE)] + ``` + only transforms the conditionals of `if` statements (but not, e.g., `while`). + + If no configuration is supplied, the default behavior is to transform all + expressions except literal constants, which is defined as a configuration as + ```python + # For Python 3, and gast library versions before 0.3 + literals = (gast.Num, gast.Str, gast.Bytes, gast.NameConstant) + [(anf.ASTEdgePattern(anf.ANY, anf.ANY, literals), anf.LEAVE), + (anf.ASTEdgePattern(anf.ANY, anf.ANY, gast.expr), anf.REPLACE)] + ``` + + Args: + node: The node to transform. + ctx: transformer.EntityInfo. TODO(mdan): What information does this + argument provide? + config: Optional ANF configuration. If omitted, ANF replaces all expression + expect literal constants. + """ + return AnfTransformer(ctx, config).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/error_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/error_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..95fe2d78324ec1f71061923234e09b85075e73a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/error_utils.py @@ -0,0 +1,230 @@ +# 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. +# ============================================================================== +"""Code transformation exceptions.""" + +import collections + +from tensorflow.python.autograph.pyct import origin_info +from tensorflow.python.util import traceback_utils + + +class FrameInfo( + collections.namedtuple('FrameInfo', + ('filename', 'lineno', 'function_name', 'code', + 'is_converted', 'is_allowlisted'))): + + __slots__ = () + + +def _stack_trace_inside_mapped_code(tb, source_map, converter_filename): + """Summarizes inner traceback frames up to the call to a given function. + + This functions locates the innermost (i.e. most recent) frame that corresponds + to code that can be mapped by source_map originated from, and returns a + translated stack trace ending at that frame. If no such frame is found, the + entire stack trace is summarized. + + For example, the following code: + + def f(): + for i in tf.range(1): + z = y + i # z only defined here + + Would generate this traceback: + + + ag__.for_stmt(...) + + return _known_len_tf_for_stmt(iter_, extra_test, body, init_state) + <_known_len_tf_for_stmt> + _disallow_undefs_into_loop(*init_state) + <_disallow_undefs_into_loop> + raise ... + + Which is then processed into: + + + for i in tf.range(1): + + return _known_len_tf_for_stmt(iter_, extra_test, body, init_state) + <_known_len_tf_for_stmt> + _disallow_undefs_into_loop(*init_state) + <_disallow_undefs_into_loop> + raise ... + + Args: + tb: traceback.FrameSummary, The traceback corresponding to an error. + Typically, the output of traceback.Summary.extract(capture_locals=True). + source_map: Dict[LineLocation, OriginInfo], a source map as created by + origin_info.create_source_map. + converter_filename: str, the file path of the converted module. Call frames + corresponding to this module are elided and their preceding frames are + marked as allowlisted. Note that frames enclosing converted code are + dropped using a different mechanism. + + Returns: + List[FrameInfo] + """ + result_frames = [] + for filename, line_number, function_name, text in reversed(tb): + + loc = origin_info.LineLocation(filename=filename, lineno=line_number) + if loc in source_map: + origin = source_map[loc] + fi = FrameInfo( + filename=origin.loc.filename, + lineno=origin.loc.lineno, + function_name=origin.function_name, + code=origin.source_code_line, + is_converted=True, + is_allowlisted=False) + result_frames.append(fi) + break + + if filename == converter_filename: + if result_frames: + prev = result_frames[-1] + assert not prev.is_converted # See the if above. + fi = FrameInfo( + filename=prev.filename, + lineno=prev.lineno, + function_name=prev.function_name, + code=prev.code, + is_converted=False, + is_allowlisted=True) + result_frames[-1] = fi + continue + + fi = FrameInfo( + filename=filename, + lineno=line_number, + function_name=function_name, + code=text, + is_converted=False, + is_allowlisted=False) + result_frames.append(fi) + + return tuple(result_frames) + + +KNOWN_STRING_CONSTRUCTOR_ERRORS = ( + AssertionError, + AttributeError, + NameError, + NotImplementedError, + RuntimeError, + StopIteration, + TypeError, + UnboundLocalError, + ValueError, +) + + +# KeyError escapes newlines in strings. We create a special subclass +# that doesn't do that. Overriding the name for display purposes; hopefully +# that won't create too many surprises. +class MultilineMessageKeyError(KeyError): + + def __init__(self, message, original_key): + super(MultilineMessageKeyError, self).__init__(original_key) + self.__message = message + + def __str__(self): + return self.__message + +MultilineMessageKeyError.__name__ = KeyError.__name__ + + +class ErrorMetadataBase(object): + """Container objects attached to exceptions raised in user code. + + This metadata allows re-raising exceptions that occur in generated code, with + a custom error message that includes a stack trace relative to user-readable + code from which the generated code originated. + """ + + __slots__ = ('translated_stack', 'cause_message') + + def __init__(self, callsite_tb, cause_metadata, cause_message, source_map, + converter_filename): + translated_stack = _stack_trace_inside_mapped_code( + callsite_tb, source_map, converter_filename) + + if cause_metadata is None: + self.translated_stack = translated_stack + self.cause_message = cause_message + else: + # Daisy chain the translated stacks. + self.translated_stack = ( + cause_metadata.translated_stack + (translated_stack[-1],)) + self.cause_message = cause_metadata.cause_message + + def get_message(self): + """Returns the message for the underlying exception.""" + lines = [] + + lines.append('in user code:') + lines.append('') + + for frame_info in reversed(self.translated_stack): + if (traceback_utils.is_traceback_filtering_enabled() and + not traceback_utils.include_frame(frame_info.filename)): + continue + + # Same format with Python traceback. + formatted_line = (f' File "{frame_info.filename}", line ' + f'{frame_info.lineno}, in {frame_info.function_name}') + if frame_info.is_converted: + formatted_line += ' *' + elif frame_info.is_allowlisted: + formatted_line += ' **' + lines.append(formatted_line) + + if frame_info.code is None: + code_snippet = '' + else: + code_snippet = frame_info.code.strip() + lines.append(' {}'.format(code_snippet)) + + lines.append('') + + message_lines = self.cause_message.split('\n') + for i in range(len(message_lines)): + message_lines[i] = ' ' + message_lines[i] + lines.extend(message_lines) + + lines.append('') + + return '\n'.join(lines) + + def create_exception(self, source_error): + """Creates exception from source_error.""" + preferred_type = type(source_error) + to_ret = None + if preferred_type.__init__ is Exception.__init__: + to_ret = preferred_type(self.get_message()) + if preferred_type in KNOWN_STRING_CONSTRUCTOR_ERRORS: + to_ret = preferred_type(self.get_message()) + elif preferred_type is KeyError: + to_ret = MultilineMessageKeyError(self.get_message(), self.cause_message) + + if to_ret is not None: + return to_ret.with_traceback(source_error.__traceback__) + + def to_exception(self, source_error): + exc = self.create_exception(source_error) + exc.__suppress_context__ = True + exc.ag_error_metadata = self + return exc diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/errors.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..781480133793cdbd0d913f95fb91c94dc403d2c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/errors.py @@ -0,0 +1,27 @@ +# 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. +# ============================================================================== +"""Code transformation exceptions.""" + + +class PyCTError(Exception): + """Base class for all exceptions.""" + + +class UnsupportedLanguageElementError(PyCTError, NotImplementedError): + """Raised for code patterns that AutoGraph does not support.""" + + +class InaccessibleSourceCodeError(PyCTError, ValueError): + """Raised when inspect can not access source code.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/gast_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/gast_util.py new file mode 100644 index 0000000000000000000000000000000000000000..bdbe50075516819051ae258c941004ed2bd779d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/gast_util.py @@ -0,0 +1,74 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gast compatibility library. Supports 0.2.2 and 0.3.2.""" +# TODO(mdan): Remove this file once it's safe to break compatibility. + +import functools + +import gast + + +GAST2 = hasattr(gast, 'Str') +GAST3 = not GAST2 + + +def _is_constant_gast_2(node): + return isinstance(node, (gast.Num, gast.Str, gast.Bytes, gast.Ellipsis, + gast.NameConstant)) + + +def _is_constant_gast_3(node): + return isinstance(node, gast.Constant) + + +def is_literal(node): + """Tests whether node represents a Python literal.""" + # Normal literals, True/False/None/Etc. in Python3 + if is_constant(node): + return True + + # True/False/None/Etc. in Python2 + if isinstance(node, gast.Name) and node.id in ['True', 'False', 'None']: + return True + + return False + + +def _is_ellipsis_gast_2(node): + return isinstance(node, gast.Ellipsis) + + +def _is_ellipsis_gast_3(node): + return isinstance(node, gast.Constant) and node.value == Ellipsis + + +if GAST2: + is_constant = _is_constant_gast_2 + is_ellipsis = _is_ellipsis_gast_2 + + Module = gast.Module + Name = gast.Name + Str = gast.Str + +elif GAST3: + is_constant = _is_constant_gast_3 + is_ellipsis = _is_ellipsis_gast_3 + + Module = functools.partial(gast.Module, type_ignores=None) # pylint:disable=invalid-name + Name = functools.partial(gast.Name, type_comment=None) # pylint:disable=invalid-name + Str = functools.partial(gast.Constant, kind=None) # pylint:disable=invalid-name + +else: + assert False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/inspect_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/inspect_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a1d8fdb927ab719c94cba8f0cf98ea18f3a25b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/inspect_utils.py @@ -0,0 +1,321 @@ +# 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. +# ============================================================================== +"""Live entity inspection utilities. + +This module contains whatever inspect doesn't offer out of the box. +""" + +import builtins +import inspect +import itertools +import linecache +import sys +import threading +import types + +from tensorflow.python.util import tf_inspect + +# This lock seems to help avoid linecache concurrency errors. +_linecache_lock = threading.Lock() + +# Cache all the builtin elements in a frozen set for faster lookup. +_BUILTIN_FUNCTION_IDS = frozenset(id(v) for v in builtins.__dict__.values()) + + +def islambda(f): + if not tf_inspect.isfunction(f): + return False + # TODO(mdan): Look into checking the only the code object. + if not (hasattr(f, '__name__') and hasattr(f, '__code__')): + return False + # Some wrappers can rename the function, but changing the name of the + # code object is harder. + return ((f.__name__ == '') or (f.__code__.co_name == '')) + + +def isnamedtuple(f): + """Returns True if the argument is a namedtuple-like.""" + if not (tf_inspect.isclass(f) and issubclass(f, tuple)): + return False + if not hasattr(f, '_fields'): + return False + fields = getattr(f, '_fields') + if not isinstance(fields, tuple): + return False + if not all(isinstance(f, str) for f in fields): + return False + return True + + +def isbuiltin(f): + """Returns True if the argument is a built-in function.""" + if id(f) in _BUILTIN_FUNCTION_IDS: + return True + elif isinstance(f, types.BuiltinFunctionType): + return True + elif inspect.isbuiltin(f): + return True + elif f is eval: + return True + else: + return False + + +def isconstructor(cls): + """Returns True if the argument is an object constructor. + + In general, any object of type class is a constructor, with the exception + of classes created using a callable metaclass. + See below for why a callable metaclass is not a trivial combination: + https://docs.python.org/2.7/reference/datamodel.html#customizing-class-creation + + Args: + cls: Any + + Returns: + Bool + """ + return (inspect.isclass(cls) and + not (issubclass(cls.__class__, type) and + hasattr(cls.__class__, '__call__') and + cls.__class__.__call__ is not type.__call__)) + + +def _fix_linecache_record(obj): + """Fixes potential corruption of linecache in the presence of functools.wraps. + + functools.wraps modifies the target object's __module__ field, which seems + to confuse linecache in special instances, for example when the source is + loaded from a .par file (see https://google.github.io/subpar/subpar.html). + + This function simply triggers a call to linecache.updatecache when a mismatch + was detected between the object's __module__ property and the object's source + file. + + Args: + obj: Any + """ + if hasattr(obj, '__module__'): + obj_file = inspect.getfile(obj) + obj_module = obj.__module__ + + # A snapshot of the loaded modules helps avoid "dict changed size during + # iteration" errors. + loaded_modules = tuple(sys.modules.values()) + for m in loaded_modules: + if hasattr(m, '__file__') and m.__file__ == obj_file: + if obj_module is not m: + linecache.updatecache(obj_file, m.__dict__) + + +def getimmediatesource(obj): + """A variant of inspect.getsource that ignores the __wrapped__ property.""" + with _linecache_lock: + _fix_linecache_record(obj) + lines, lnum = inspect.findsource(obj) + return ''.join(inspect.getblock(lines[lnum:])) + + +def getnamespace(f): + """Returns the complete namespace of a function. + + Namespace is defined here as the mapping of all non-local variables to values. + This includes the globals and the closure variables. Note that this captures + the entire globals collection of the function, and may contain extra symbols + that it does not actually use. + + Args: + f: User defined function. + + Returns: + A dict mapping symbol names to values. + """ + namespace = dict(f.__globals__) + closure = f.__closure__ + freevars = f.__code__.co_freevars + if freevars and closure: + for name, cell in zip(freevars, closure): + try: + namespace[name] = cell.cell_contents + except ValueError: + # Cell contains undefined variable, omit it from the namespace. + pass + return namespace + + +def getqualifiedname(namespace, object_, max_depth=5, visited=None): + """Returns the name by which a value can be referred to in a given namespace. + + If the object defines a parent module, the function attempts to use it to + locate the object. + + This function will recurse inside modules, but it will not search objects for + attributes. The recursion depth is controlled by max_depth. + + Args: + namespace: Dict[str, Any], the namespace to search into. + object_: Any, the value to search. + max_depth: Optional[int], a limit to the recursion depth when searching + inside modules. + visited: Optional[Set[int]], ID of modules to avoid visiting. + Returns: Union[str, None], the fully-qualified name that resolves to the value + o, or None if it couldn't be found. + """ + if visited is None: + visited = set() + + # Copy the dict to avoid "changed size error" during concurrent invocations. + # TODO(mdan): This is on the hot path. Can we avoid the copy? + namespace = dict(namespace) + + for name in namespace: + # The value may be referenced by more than one symbol, case in which + # any symbol will be fine. If the program contains symbol aliases that + # change over time, this may capture a symbol that will later point to + # something else. + # TODO(mdan): Prefer the symbol that matches the value type name. + if object_ is namespace[name]: + return name + + # If an object is not found, try to search its parent modules. + parent = tf_inspect.getmodule(object_) + if (parent is not None and parent is not object_ and parent is not namespace): + # No limit to recursion depth because of the guard above. + parent_name = getqualifiedname( + namespace, parent, max_depth=0, visited=visited) + if parent_name is not None: + name_in_parent = getqualifiedname( + parent.__dict__, object_, max_depth=0, visited=visited) + assert name_in_parent is not None, ( + 'An object should always be found in its owner module') + return '{}.{}'.format(parent_name, name_in_parent) + + if max_depth: + # Iterating over a copy prevents "changed size due to iteration" errors. + # It's unclear why those occur - suspecting new modules may load during + # iteration. + for name in namespace.keys(): + value = namespace[name] + if tf_inspect.ismodule(value) and id(value) not in visited: + visited.add(id(value)) + name_in_module = getqualifiedname(value.__dict__, object_, + max_depth - 1, visited) + if name_in_module is not None: + return '{}.{}'.format(name, name_in_module) + return None + + +def getdefiningclass(m, owner_class): + """Resolves the class (e.g. one of the superclasses) that defined a method.""" + method_name = m.__name__ + for super_class in inspect.getmro(owner_class): + if ((hasattr(super_class, '__dict__') and + method_name in super_class.__dict__) or + (hasattr(super_class, '__slots__') and + method_name in super_class.__slots__)): + return super_class + return owner_class + + +def getmethodclass(m): + """Resolves a function's owner, e.g. + + a method's class. + + Note that this returns the object that the function was retrieved from, not + necessarily the class where it was defined. + + This function relies on Python stack frame support in the interpreter, and + has the same limitations that inspect.currentframe. + + Limitations. This function will only work correctly if the owned class is + visible in the caller's global or local variables. + + Args: + m: A user defined function + + Returns: + The class that this function was retrieved from, or None if the function + is not an object or class method, or the class that owns the object or + method is not visible to m. + + Raises: + ValueError: if the class could not be resolved for any unexpected reason. + """ + + # Callable objects: return their own class. + if (not hasattr(m, '__name__') and hasattr(m, '__class__') and + hasattr(m, '__call__')): + if isinstance(m.__class__, type): + return m.__class__ + + # Instance and class: return the class of "self". + m_self = getattr(m, '__self__', None) + if m_self is not None: + if inspect.isclass(m_self): + return m_self + return m_self.__class__ + + # Class, static and unbound methods: search all defined classes in any + # namespace. This is inefficient but more robust a method. + owners = [] + caller_frame = tf_inspect.currentframe().f_back + try: + # TODO(mdan): This doesn't consider cell variables. + # TODO(mdan): This won't work if the owner is hidden inside a container. + # Cell variables may be pulled using co_freevars and the closure. + for v in itertools.chain(caller_frame.f_locals.values(), + caller_frame.f_globals.values()): + if hasattr(v, m.__name__): + candidate = getattr(v, m.__name__) + # Py2 methods may be bound or unbound, extract im_func to get the + # underlying function. + if hasattr(candidate, 'im_func'): + candidate = candidate.im_func + if hasattr(m, 'im_func'): + m = m.im_func + if candidate is m: + owners.append(v) + finally: + del caller_frame + + if owners: + if len(owners) == 1: + return owners[0] + + # If multiple owners are found, and are not subclasses, raise an error. + owner_types = tuple(o if tf_inspect.isclass(o) else type(o) for o in owners) + for o in owner_types: + if tf_inspect.isclass(o) and issubclass(o, tuple(owner_types)): + return o + raise ValueError('Found too many owners of %s: %s' % (m, owners)) + + return None + + +def getfutureimports(entity): + """Detects what future imports are necessary to safely execute entity source. + + Args: + entity: Any object + + Returns: + A tuple of future strings + """ + if not (tf_inspect.isfunction(entity) or tf_inspect.ismethod(entity)): + return tuple() + return tuple( + sorted(name for name, value in entity.__globals__.items() + if getattr(value, '__module__', None) == '__future__')) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/loader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..600ddd2707dc00cea8d5334b625e7d02ab256dd7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/loader.py @@ -0,0 +1,102 @@ +# 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. +# ============================================================================== +"""Converting AST to code and Python entities. + +Adapted from Tangent. +""" + +import atexit +import errno +import importlib +import os +import sys +import tempfile + +from tensorflow.python.autograph.pyct import origin_info +from tensorflow.python.autograph.pyct import parser + + +def _remove_file(file_name): + """Remove a file, if it exists.""" + try: + os.remove(file_name) + except OSError as e: + if e.errno == errno.ENOENT: + # The file disappeared. Ignore this. Temporary files might get + # cleaned up, especially if they reside in /tmp. + pass + else: + raise + + +def load_source(source, delete_on_exit): + """Loads the given source code as a Python module.""" + with tempfile.NamedTemporaryFile( + mode='w', + suffix='.py', + prefix='__autograph_generated_file', + delete=False, + encoding='utf-8') as f: + module_name = os.path.basename(f.name[:-3]) + file_name = f.name + f.write(source) + + if delete_on_exit: + atexit.register(lambda: _remove_file(file_name)) + + spec = importlib.util.spec_from_file_location(module_name, file_name) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + # TODO(mdan): Use our own garbage-collected cache instead of sys.modules. + sys.modules[module_name] = module + return module, file_name + + +def load_ast(nodes, + indentation=' ', + include_source_map=False, + delete_on_exit=True): + """Loads the given AST as a Python module. + + Compiling the AST code this way ensures that the source code is readable by + e.g. `pdb` or `inspect`. + + Args: + nodes: Union[ast.AST, Iterable[ast.AST]], the code to compile, as an AST + object. + indentation: Text, the string to use for indentation. + include_source_map: bool, whether return a source map. + delete_on_exit: bool, whether to delete the temporary file used for + compilation on exit. + + Returns: + Tuple[module, Text, Dict[LineLocation, OriginInfo]], containing: + the module containing the unparsed nodes, the source code corresponding to + nodes, and the source map. Is include_source_map is False, the source map + will be None. + """ + if not isinstance(nodes, (list, tuple)): + nodes = (nodes,) + + source = parser.unparse(nodes, indentation=indentation) + module, _ = load_source(source, delete_on_exit) + + if include_source_map: + source_map = origin_info.create_source_map(nodes, source, module.__file__) + else: + source_map = None + + # TODO(mdan): Return a structured object. + return module, source, source_map diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/naming.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/naming.py new file mode 100644 index 0000000000000000000000000000000000000000..d9bfbe7fc3bf39c2196cfd9fb74c1f180b69586d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/naming.py @@ -0,0 +1,53 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Symbol naming utilities.""" + +from tensorflow.python.autograph.pyct import qual_names + + +class Namer(object): + """Symbol name generator.""" + + def __init__(self, global_namespace): + self.global_namespace = global_namespace + self.generated_names = set() + + def new_symbol(self, name_root, reserved_locals): + """See control_flow.SymbolNamer.new_symbol.""" + # reserved_locals may contain QNs. + all_reserved_locals = set() + for s in reserved_locals: + if isinstance(s, qual_names.QN): + all_reserved_locals.update(s.qn) + elif isinstance(s, str): + all_reserved_locals.add(s) + else: + raise ValueError('Unexpected symbol type "%s"' % type(s)) + + pieces = name_root.split('_') + if pieces[-1].isdigit(): + name_root = '_'.join(pieces[:-1]) + n = int(pieces[-1]) + else: + n = 0 + new_name = name_root + + while (new_name in self.global_namespace or + new_name in all_reserved_locals or new_name in self.generated_names): + n += 1 + new_name = '%s_%d' % (name_root, n) + + self.generated_names.add(new_name) + return new_name diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/origin_info.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/origin_info.py new file mode 100644 index 0000000000000000000000000000000000000000..08f73422667de16776af2f2550841e5917f53cd9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/origin_info.py @@ -0,0 +1,296 @@ +# 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. +# ============================================================================== +"""Container for origin source code information before AutoGraph compilation.""" +import collections +import difflib +import io +import os +import tokenize + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import ast_util +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import pretty_printer +from tensorflow.python.util import tf_inspect + + +class LineLocation( + collections.namedtuple('LineLocation', ('filename', 'lineno'))): + """Similar to Location, but without column information. + + Attributes: + filename: Text + lineno: int, 1-based + """ + pass + + +class Location( + collections.namedtuple('Location', ('filename', 'lineno', 'col_offset'))): + """Encodes code location information. + + Attributes: + filename: Text + lineno: int, 1-based + col_offset: int + line_loc: LineLocation + """ + + @property + def line_loc(self): + return LineLocation(self.filename, self.lineno) + + +class OriginInfo( + collections.namedtuple( + 'OriginInfo', + ('loc', 'function_name', 'source_code_line', 'comment'))): + """Container for information about the source code before conversion. + + Attributes: + loc: Location + function_name: Optional[Text] + source_code_line: Text + comment: Optional[Text] + """ + + def as_frame(self): + """Returns a 4-tuple consistent with the return of traceback.extract_tb.""" + return (self.loc.filename, self.loc.lineno, self.function_name, + self.source_code_line) + + def __repr__(self): + if self.loc.filename: + return '{}:{}:{}'.format( + os.path.split(self.loc.filename)[1], self.loc.lineno, + self.loc.col_offset) + return ':{}:{}'.format(self.loc.lineno, self.loc.col_offset) + + +# TODO(mdan): This source map should be a class - easier to refer to. +def create_source_map(nodes, code, filepath): + """Creates a source map between an annotated AST and the code it compiles to. + + Note: this function assumes nodes nodes, code and filepath correspond to the + same code. + + Args: + nodes: Iterable[ast.AST, ...], one or more AST modes. + code: Text, the source code in which nodes are found. + filepath: Text + + Returns: + Dict[LineLocation, OriginInfo], mapping locations in code to locations + indicated by origin annotations in node. + """ + reparsed_nodes = parser.parse(code, preamble_len=0, single_node=False) + for node in reparsed_nodes: + resolve(node, code, filepath, node.lineno, node.col_offset) + + source_map = {} + + try: + for before, after in ast_util.parallel_walk(nodes, reparsed_nodes): + # Note: generated code might not be mapped back to its origin. + # TODO(mdan): Generated code should always be mapped to something. + origin_info = anno.getanno(before, anno.Basic.ORIGIN, default=None) + final_info = anno.getanno(after, anno.Basic.ORIGIN, default=None) + if origin_info is None or final_info is None: + continue + + # Note: the keys are by line only, excluding the column offset. + line_loc = LineLocation(final_info.loc.filename, final_info.loc.lineno) + + existing_origin = source_map.get(line_loc) + if existing_origin is not None: + # Overlaps may exist because of child nodes, but almost never to + # different line locations. Exception make decorated functions, where + # both lines are mapped to the same line in the AST. + + # Line overlaps: keep bottom node. + if existing_origin.loc.line_loc == origin_info.loc.line_loc: + if existing_origin.loc.lineno >= origin_info.loc.lineno: + continue + + # In case of column overlaps, keep the leftmost node. + if existing_origin.loc.col_offset <= origin_info.loc.col_offset: + continue + + source_map[line_loc] = origin_info + + except ValueError as err: + new_msg = 'Inconsistent ASTs detected. This is a bug. Cause: \n' + new_msg += str(err) + new_msg += 'Diff:\n' + + for n, rn in zip(nodes, reparsed_nodes): + nodes_str = pretty_printer.fmt(n, color=False, noanno=True) + reparsed_nodes_str = pretty_printer.fmt(rn, color=False, noanno=True) + diff = difflib.context_diff( + nodes_str.split('\n'), + reparsed_nodes_str.split('\n'), + fromfile='Original nodes', + tofile='Reparsed nodes', + n=7) + diff = '\n'.join(diff) + new_msg += diff + '\n' + raise ValueError(new_msg) + + return source_map + + +class _Function: + + def __init__(self, name): + self.name = name + + +class OriginResolver(gast.NodeVisitor): + """Annotates an AST with additional source information like file name.""" + + def __init__(self, root_node, source_lines, comments_map, + context_lineno, context_col_offset, + filepath): + self._source_lines = source_lines + self._comments_map = comments_map + + if (hasattr(root_node, 'decorator_list') and root_node.decorator_list and + hasattr(root_node.decorator_list[0], 'lineno')): + # Typical case: functions. The line number of the first decorator + # is more accurate than the line number of the function itself in + # 3.8+. In earier versions they coincide. + self._lineno_offset = context_lineno - root_node.decorator_list[0].lineno + else: + # Fall back to the line number of the root node. + self._lineno_offset = context_lineno - root_node.lineno + + self._col_offset = context_col_offset - root_node.col_offset + + self._filepath = filepath + + self._function_stack = [] + + def _absolute_lineno(self, lineno): + return lineno + self._lineno_offset + + def _absolute_col_offset(self, col_offset): + if col_offset is None: + return 0 + return col_offset + self._col_offset + + def _attach_origin_info(self, node): + lineno = getattr(node, 'lineno', None) + col_offset = getattr(node, 'col_offset', None) + + if lineno is None: + return + + if self._function_stack: + function_name = self._function_stack[-1].name + else: + function_name = None + + source_code_line = self._source_lines[lineno - 1] + comment = self._comments_map.get(lineno) + + loc = Location(self._filepath, self._absolute_lineno(lineno), + self._absolute_col_offset(col_offset)) + origin = OriginInfo(loc, function_name, source_code_line, comment) + anno.setanno(node, 'lineno', lineno) + anno.setanno(node, anno.Basic.ORIGIN, origin) + + def visit(self, node): + entered_function = False + if isinstance(node, gast.FunctionDef): + entered_function = True + self._function_stack.append(_Function(node.name)) + + self._attach_origin_info(node) + self.generic_visit(node) + + if entered_function: + self._function_stack.pop() + + +def resolve(node, source, context_filepath, context_lineno, context_col_offset): + """Adds origin information to an AST, based on the source it was loaded from. + + This allows us to map the original source code line numbers to generated + source code. + + Note: the AST may be a part of a larger context (e.g. a function is part of + a module that may contain other things). However, this function does not + assume the source argument contains the entire context, nor that it contains + only code corresponding to node itself. However, it assumes that node was + parsed from the given source code. + For this reason, two extra arguments are required, and they indicate the + location of the node in the original context. + + Args: + node: gast.AST, the AST to annotate. + source: Text, the source code representing node. + context_filepath: Text + context_lineno: int + context_col_offset: int + """ + # TODO(mdan): Pull this to a separate utility. + code_reader = io.StringIO(source) + comments_map = {} + try: + for token in tokenize.generate_tokens(code_reader.readline): + tok_type, tok_string, loc, _, _ = token + srow, _ = loc + if tok_type == tokenize.COMMENT: + comments_map[srow] = tok_string.strip()[1:].strip() + except tokenize.TokenError: + if isinstance(node, gast.Lambda): + # Source code resolution in older Python versions is brittle for + # lambda functions, and may contain garbage. + pass + else: + raise + + source_lines = source.split('\n') + visitor = OriginResolver(node, source_lines, comments_map, + context_lineno, context_col_offset, + context_filepath) + visitor.visit(node) + + +def resolve_entity(node, source, entity): + """Like resolve, but extracts the context information from an entity.""" + lines, lineno = tf_inspect.getsourcelines(entity) + filepath = tf_inspect.getsourcefile(entity) + + # Poor man's attempt at guessing the column offset: count the leading + # whitespace. This might not work well with tabs. + definition_line = lines[0] + col_offset = len(definition_line) - len(definition_line.lstrip()) + + resolve(node, source, filepath, lineno, col_offset) + + +def copy_origin(from_node, to_node): + """Copies the origin info from a node to another, recursively.""" + origin = anno.Basic.ORIGIN.of(from_node, default=None) + if origin is None: + return + if not isinstance(to_node, (list, tuple)): + to_node = (to_node,) + for node in to_node: + for n in gast.walk(node): + anno.setanno(n, anno.Basic.ORIGIN, origin) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/parser.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9c2181f8e66262b5e85b65ac3af4b97bed38a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/parser.py @@ -0,0 +1,396 @@ +# 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. +# ============================================================================== +"""Converting code to AST. + +Adapted from Tangent. +""" + +import ast +import inspect +import io +import linecache +import re +import sys +import textwrap +import tokenize + +import astunparse +import gast + +from tensorflow.python.autograph.pyct import errors +from tensorflow.python.autograph.pyct import inspect_utils +from tensorflow.python.util import tf_inspect + + +PY2_PREAMBLE = textwrap.dedent(""" +""") +PY3_PREAMBLE = '' +MAX_SIZE = 0 + +if sys.version_info >= (3, 9): + astunparse = ast + +if sys.version_info >= (3,): + STANDARD_PREAMBLE = PY3_PREAMBLE + MAX_SIZE = sys.maxsize +else: + STANDARD_PREAMBLE = PY2_PREAMBLE + MAX_SIZE = sys.maxint + +STANDARD_PREAMBLE_LEN = STANDARD_PREAMBLE.count('__future__') + + +_LEADING_WHITESPACE = re.compile(r'\s*') + + +def _unfold_continuations(code_string): + """Removes any backslash line continuations from the code.""" + return code_string.replace('\\\n', '') + + +def dedent_block(code_string): + """Dedents a code so that its first line starts at row zero.""" + + code_string = _unfold_continuations(code_string) + + token_gen = tokenize.generate_tokens(io.StringIO(code_string).readline) + + block_indentation = None + tokens = [] + try: + for tok in token_gen: + tokens.append(tok) + except tokenize.TokenError: + # Resolution of lambda functions may yield incomplete code, which can + # in turn generate this error. We silently ignore this error because the + # parser may still be able to deal with it. + pass + + for tok in tokens: + tok_type, tok_string, _, _, _ = tok + if tok_type == tokenize.INDENT: + block_indentation = tok_string + block_level = len(block_indentation) + break + elif tok_type not in ( + tokenize.NL, tokenize.NEWLINE, tokenize.STRING, tokenize.COMMENT): + block_indentation = '' + break + + if not block_indentation: + return code_string + + block_level = len(block_indentation) + first_indent_uses_tabs = '\t' in block_indentation + for i, tok in enumerate(tokens): + tok_type, tok_string, _, _, _ = tok + if tok_type == tokenize.INDENT: + if ((' ' in tok_string and first_indent_uses_tabs) + or ('\t' in tok_string and not first_indent_uses_tabs)): + # TODO(mdan): We could attempt to convert tabs to spaces by unix rule. + # See: + # https://docs.python.org/3/reference/lexical_analysis.html#indentation + raise errors.UnsupportedLanguageElementError( + 'code mixing tabs and spaces for indentation is not allowed') + if len(tok_string) >= block_level: + tok_string = tok_string[block_level:] + tokens[i] = (tok_type, tok_string) + + new_code = tokenize.untokenize(tokens) + + # Note: untokenize respects the line structure, but not the whitespace within + # lines. For example, `def foo()` may be untokenized as `def foo ()` + # So instead of using the output of dedent, we match the leading whitespace + # on each line. + dedented_code = [] + for line, new_line in zip(code_string.split('\n'), new_code.split('\n')): + original_indent = re.match(_LEADING_WHITESPACE, line).group() + new_indent = re.match(_LEADING_WHITESPACE, new_line).group() + if len(original_indent) > len(new_indent): + dedented_line = line[len(original_indent) - len(new_indent):] + else: + dedented_line = line + dedented_code.append(dedented_line) + new_code = '\n'.join(dedented_code) + + return new_code + + +def parse_entity(entity, future_features): + """Returns the AST and source code of given entity. + + Args: + entity: Any, Python function/method/class + future_features: Iterable[Text], future features to use (e.g. + 'print_statement'). See + https://docs.python.org/2/reference/simple_stmts.html#future + + Returns: + gast.AST, Text: the parsed AST node; the source code that was parsed to + generate the AST (including any prefixes that this function may have added). + """ + if inspect_utils.islambda(entity): + return _parse_lambda(entity) + + try: + original_source = inspect_utils.getimmediatesource(entity) + except OSError as e: + raise errors.InaccessibleSourceCodeError( + f'Unable to locate the source code of {entity}. Note that functions' + ' defined in certain environments, like the interactive Python shell,' + ' do not expose their source code. If that is the case, you should' + ' define them in a .py source file. If you are certain the code is' + ' graph-compatible, wrap the call using' + f' @tf.autograph.experimental.do_not_convert. Original error: {e}') + + source = dedent_block(original_source) + + future_statements = tuple( + 'from __future__ import {}'.format(name) for name in future_features) + source = '\n'.join(future_statements + (source,)) + + return parse(source, preamble_len=len(future_features)), source + + +def _without_context(node, lines, minl, maxl): + """Returns a clean node and source code without indenting and context.""" + for n in gast.walk(node): + lineno = getattr(n, 'lineno', None) + if lineno is not None: + n.lineno = lineno - minl + end_lineno = getattr(n, 'end_lineno', None) + if end_lineno is not None: + n.end_lineno = end_lineno - minl + + code_lines = lines[minl - 1:maxl] + + # Attempt to clean up surrounding context code. + + end_col_offset = getattr(node, 'end_col_offset', None) + if end_col_offset is not None: + # This is only available in 3.8. + code_lines[-1] = code_lines[-1][:end_col_offset] + + col_offset = getattr(node, 'col_offset', None) + if col_offset is None: + # Older Python: try to find the "lambda" token. This is brittle. + match = re.search(r'(?' % f))) + continue + v = getattr(node, f) + if isinstance(v, list): + if v: + self._print('%s%s=[' % (self._indent(), self._field(f))) + self.indent_lvl += 1 + for n in v: + if n is not None: + self.generic_visit(n) + else: + self._print('%sNone' % (self._indent())) + self.indent_lvl -= 1 + self._print('%s]' % (self._indent())) + else: + self._print('%s%s=[]' % (self._indent(), self._field(f))) + elif isinstance(v, tuple): + if v: + self._print('%s%s=(' % (self._indent(), self._field(f))) + self.indent_lvl += 1 + for n in v: + if n is not None: + self.generic_visit(n) + else: + self._print('%sNone' % (self._indent())) + self.indent_lvl -= 1 + self._print('%s)' % (self._indent())) + else: + self._print('%s%s=()' % (self._indent(), self._field(f))) + elif isinstance(v, gast.AST): + self.generic_visit(v, f) + elif isinstance(v, bytes): + self._print('%s%s=%s' % (self._indent(), self._field(f), + self._value('b"%s"' % v))) + elif isinstance(v, str): + self._print('%s%s=%s' % (self._indent(), self._field(f), + self._value('u"%s"' % v))) + else: + self._print('%s%s=%s' % (self._indent(), self._field(f), + self._value(v))) + self.indent_lvl -= 1 + + +def fmt(node, color=True, noanno=False): + printer = PrettyPrinter(color, noanno) + if isinstance(node, (list, tuple)): + for n in node: + printer.visit(n) + else: + printer.visit(node) + return printer.result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/qual_names.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/qual_names.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7d1ce46bed83b2032ec46ecd409a95cce340f7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/qual_names.py @@ -0,0 +1,266 @@ +# 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 manipulating qualified names. + +A qualified name is a uniform way to refer to simple (e.g. 'foo') and composite +(e.g. 'foo.bar') syntactic symbols. + +This is *not* related to the __qualname__ attribute used by inspect, which +refers to scopes. +""" + +import collections + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser + + +class CallerMustSetThis(object): + pass + + +class Symbol(collections.namedtuple('Symbol', ['name'])): + """Represents a Python symbol.""" + + +class Literal(collections.namedtuple('Literal', ['value'])): + """Represents a Python numeric literal.""" + + def __str__(self): + if isinstance(self.value, str): + return "'{}'".format(self.value) + return str(self.value) + + def __repr__(self): + return str(self) + + +# TODO(mdan): Use subclasses to remove the has_attr has_subscript booleans. +class QN(object): + """Represents a qualified name.""" + + def __init__(self, base, attr=None, subscript=None): + if attr is not None and subscript is not None: + raise ValueError('A QN can only be either an attr or a subscript, not ' + 'both: attr={}, subscript={}.'.format(attr, subscript)) + self._has_attr = False + self._has_subscript = False + + if attr is not None: + if not isinstance(base, QN): + raise ValueError( + 'for attribute QNs, base must be a QN; got instead "%s"' % base) + if not isinstance(attr, str): + raise ValueError('attr may only be a string; got instead "%s"' % attr) + self._parent = base + # TODO(mdan): Get rid of the tuple - it can only have 1 or 2 elements now. + self.qn = (base, attr) + self._has_attr = True + + elif subscript is not None: + if not isinstance(base, QN): + raise ValueError('For subscript QNs, base must be a QN.') + self._parent = base + self.qn = (base, subscript) + self._has_subscript = True + + else: + if not isinstance(base, (str, Literal)): + # TODO(mdan): Require Symbol instead of string. + raise ValueError( + 'for simple QNs, base must be a string or a Literal object;' + ' got instead "%s"' % type(base)) + assert '.' not in base and '[' not in base and ']' not in base + self._parent = None + self.qn = (base,) + + def is_symbol(self): + return isinstance(self.qn[0], str) + + def is_simple(self): + return len(self.qn) <= 1 + + def is_composite(self): + return len(self.qn) > 1 + + def has_subscript(self): + return self._has_subscript + + def has_attr(self): + return self._has_attr + + @property + def attr(self): + if not self._has_attr: + raise ValueError('Cannot get attr of non-attribute "%s".' % self) + return self.qn[1] + + @property + def parent(self): + if self._parent is None: + raise ValueError('Cannot get parent of simple name "%s".' % self.qn[0]) + return self._parent + + @property + def owner_set(self): + """Returns all the symbols (simple or composite) that own this QN. + + In other words, if this symbol was modified, the symbols in the owner set + may also be affected. + + Examples: + 'a.b[c.d]' has two owners, 'a' and 'a.b' + """ + owners = set() + if self.has_attr() or self.has_subscript(): + owners.add(self.parent) + owners.update(self.parent.owner_set) + return owners + + @property + def support_set(self): + """Returns the set of simple symbols that this QN relies on. + + This would be the smallest set of symbols necessary for the QN to + statically resolve (assuming properties and index ranges are verified + at runtime). + + Examples: + 'a.b' has only one support symbol, 'a' + 'a[i]' has two support symbols, 'a' and 'i' + """ + # TODO(mdan): This might be the set of Name nodes in the AST. Track those? + roots = set() + if self.has_attr(): + roots.update(self.parent.support_set) + elif self.has_subscript(): + roots.update(self.parent.support_set) + roots.update(self.qn[1].support_set) + else: + roots.add(self) + return roots + + def __hash__(self): + return hash(self.qn + (self._has_attr, self._has_subscript)) + + def __eq__(self, other): + return (isinstance(other, QN) and self.qn == other.qn and + self.has_subscript() == other.has_subscript() and + self.has_attr() == other.has_attr()) + + def __lt__(self, other): + return str(self) < str(other) + + def __gt__(self, other): + return str(self) > str(other) + + def __str__(self): + root = self.qn[0] + if self.has_subscript(): + return '{}[{}]'.format(root, self.qn[1]) + if self.has_attr(): + return '.'.join(map(str, self.qn)) + else: + return str(root) + + def __repr__(self): + return str(self) + + def ssf(self): + """Simple symbol form.""" + ssfs = [n.ssf() if isinstance(n, QN) else n for n in self.qn] + ssf_string = '' + for i in range(0, len(self.qn) - 1): + if self.has_subscript(): + delimiter = '_sub_' + else: + delimiter = '_' + ssf_string += ssfs[i] + delimiter + return ssf_string + ssfs[-1] + + def ast(self): + """AST representation.""" + # The caller must adjust the context appropriately. + if self.has_subscript(): + return gast.Subscript( + value=self.parent.ast(), + slice=self.qn[-1].ast(), + ctx=CallerMustSetThis) + if self.has_attr(): + return gast.Attribute( + value=self.parent.ast(), attr=self.qn[-1], ctx=CallerMustSetThis) + + base = self.qn[0] + if isinstance(base, str): + return gast.Name( + base, ctx=CallerMustSetThis, annotation=None, type_comment=None) + elif isinstance(base, Literal): + return gast.Constant(base.value, kind=None) + else: + assert False, ('the constructor should prevent types other than ' + 'str and Literal') + + +class QnResolver(gast.NodeTransformer): + """Annotates nodes with QN information. + + Note: Not using NodeAnnos to avoid circular dependencies. + """ + + def visit_Name(self, node): + node = self.generic_visit(node) + anno.setanno(node, anno.Basic.QN, QN(node.id)) + return node + + def visit_Attribute(self, node): + node = self.generic_visit(node) + if anno.hasanno(node.value, anno.Basic.QN): + anno.setanno(node, anno.Basic.QN, + QN(anno.getanno(node.value, anno.Basic.QN), attr=node.attr)) + return node + + def visit_Subscript(self, node): + # TODO(mdan): This may no longer apply if we overload getitem. + node = self.generic_visit(node) + s = node.slice + if isinstance(s, (gast.Tuple, gast.Slice)): + # TODO(mdan): Support range and multi-dimensional indices. + # Continuing silently because some demos use these. + return node + if isinstance(s, gast.Constant) and s.value != Ellipsis: + subscript = QN(Literal(s.value)) + else: + # The index may be an expression, case in which a name doesn't make sense. + if anno.hasanno(s, anno.Basic.QN): + subscript = anno.getanno(s, anno.Basic.QN) + else: + return node + if anno.hasanno(node.value, anno.Basic.QN): + anno.setanno(node, anno.Basic.QN, + QN(anno.getanno(node.value, anno.Basic.QN), + subscript=subscript)) + return node + + +def resolve(node): + return QnResolver().visit(node) + + +def from_str(qn_str): + node = parser.parse_expression(qn_str) + node = resolve(node) + return anno.getanno(node, anno.Basic.QN) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/activity.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/activity.py new file mode 100644 index 0000000000000000000000000000000000000000..8af0f7ae9477d0d46d865fcfd8894e6dfa07f693 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/activity.py @@ -0,0 +1,706 @@ +# 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. +# ============================================================================== +"""Activity analysis. + +Requires qualified name annotations (see qual_names.py). +""" + +import copy +import weakref + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import transformer +from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno + + +class Scope(object): + """Encloses local symbol definition and usage information. + + This can track for instance whether a symbol is modified in the current scope. + Note that scopes do not necessarily align with Python's scopes. For example, + the body of an if statement may be considered a separate scope. + + Caution - the AST references held by this object are weak. + + Scope objects are mutable during construction only, and must be frozen using + `Scope.finalize()` before use. Furthermore, a scope is consistent only after + all its children have been frozen. While analysing code blocks, scopes are + being gradually built, from the innermost scope outward. Freezing indicates + that the analysis of a code block is complete. Once frozen, mutation is no + longer allowed. `is_final` tracks whether the scope is frozen or not. Certain + properties, like `referenced`, are only accurate when called on frozen scopes. + + Attributes: + parent: Optional[Scope], the parent scope, if any. + isolated: bool, whether the scope is a true Python scope (e.g. the scope of + a function), or just a surrogate tracking an ordinary code block. Using + the terminology of the Python 3 reference documentation, True roughly + represents an actual scope, whereas False represents an ordinary code + block. + function_name: Optional[str], name of the function owning this scope. + isolated_names: Set[qual_names.QN], identifiers that are isolated to this + scope (even if the scope is not isolated). + annotations: Set[qual_names.QN], identifiers used as type annotations + in this scope. + read: Set[qual_names.QN], identifiers read in this scope. + modified: Set[qual_names.QN], identifiers modified in this scope. + deleted: Set[qual_names.QN], identifiers deleted in this scope. + bound: Set[qual_names.QN], names that are bound to this scope. See + https://docs.python.org/3/reference/executionmodel.html#binding-of-names + for a precise definition. + globals: Set[qual_names.QN], names that are explicitly marked as global in + this scope. Note that this doesn't include free read-only vars bound to + global symbols. + nonlocals: Set[qual_names.QN], names that are explicitly marked as nonlocal + in this scope. Note that this doesn't include free read-only vars bound to + global symbols. + free_vars: Set[qual_names.QN], the free variables in this scope. See + https://docs.python.org/3/reference/executionmodel.html for a precise + definition. + params: WeakValueDictionary[qual_names.QN, ast.Node], function arguments + visible in this scope, mapped to the function node that defines them. + enclosing_scope: Scope, the innermost isolated scope that is a transitive + parent of this scope. May be the scope itself. + referenced: Set[qual_names.QN], the totality of the symbols used by this + scope and its parents. + is_final: bool, whether the scope is frozen or not. + + Note - simple statements may never delete and modify a symbol at the same + time. However, compound ones like if statements can. In that latter case, it's + undefined whether the symbol is actually modified or deleted upon statement + exit. Certain analyses like reaching definitions need to be careful about + this. + """ + + # Note: this mutable-immutable pattern is used because using a builder would + # have taken a lot more boilerplate. + + def __init__(self, parent, isolated=True, function_name=None): + """Create a new scope. + + Args: + parent: A Scope or None. + isolated: Whether the scope is isolated, that is, whether variables + modified in this scope should be considered modified in the parent + scope. + function_name: Name of the function owning this scope. + """ + self.parent = parent + self.isolated = isolated + self.function_name = function_name + + self.isolated_names = set() + + self.read = set() + self.modified = set() + self.deleted = set() + + self.bound = set() + self.globals = set() + self.nonlocals = set() + self.annotations = set() + + self.params = weakref.WeakValueDictionary() + + # Certain fields can only be accessed after the scope and all its parent + # scopes have been fully built. This field guards that. + self.is_final = False + + @property + def enclosing_scope(self): + assert self.is_final + if self.parent is not None and not self.isolated: + return self.parent + return self + + @property + def referenced(self): + if self.parent is not None: + return self.read | self.parent.referenced + return self.read + + @property + def free_vars(self): + enclosing_scope = self.enclosing_scope + return enclosing_scope.read - enclosing_scope.bound + + def copy_from(self, other): + """Recursively copies the contents of this scope from another scope.""" + assert not self.is_final + if self.parent is not None: + assert other.parent is not None + self.parent.copy_from(other.parent) + self.isolated_names = copy.copy(other.isolated_names) + self.modified = copy.copy(other.modified) + self.read = copy.copy(other.read) + self.deleted = copy.copy(other.deleted) + self.bound = copy.copy(other.bound) + self.annotations = copy.copy(other.annotations) + self.params = copy.copy(other.params) + + @classmethod + def copy_of(cls, other): + if other.parent is not None: + assert other.parent is not None + parent = cls.copy_of(other.parent) + else: + parent = None + new_copy = cls(parent) + new_copy.copy_from(other) + return new_copy + + def merge_from(self, other): + """Adds all activity from another scope to this scope.""" + assert not self.is_final + if self.parent is not None: + assert other.parent is not None + self.parent.merge_from(other.parent) + self.isolated_names.update(other.isolated_names) + self.read.update(other.read) + self.modified.update(other.modified) + self.bound.update(other.bound) + self.deleted.update(other.deleted) + self.annotations.update(other.annotations) + self.params.update(other.params) + + def finalize(self): + """Freezes this scope.""" + assert not self.is_final + # TODO(mdan): freeze read, modified, bound. + if self.parent is not None: + assert not self.parent.is_final + if not self.isolated: + self.parent.read.update(self.read - self.isolated_names) + self.parent.modified.update(self.modified - self.isolated_names) + self.parent.bound.update(self.bound - self.isolated_names) + self.parent.globals.update(self.globals) + self.parent.nonlocals.update(self.nonlocals) + self.parent.annotations.update(self.annotations) + else: + # TODO(mdan): This is not accurate. + self.parent.read.update(self.read - self.bound) + self.parent.annotations.update(self.annotations - self.bound) + self.is_final = True + + def __repr__(self): + return 'Scope{r=%s, w=%s}' % (tuple(self.read), tuple(self.modified)) + + def mark_param(self, name, owner): + # Assumption: all AST nodes have the same life span. This lets us use + # a weak reference to mark the connection between a symbol node and the + # function node whose argument that symbol is. + self.params[name] = owner + + +class _Comprehension(object): + + no_root = True + + def __init__(self): + # TODO(mdan): Consider using an enum. + self.is_list_comp = False + self.targets = set() + + +class _FunctionOrClass(object): + + def __init__(self): + self.node = None + + +class ActivityAnalyzer(transformer.Base): + """Annotates nodes with local scope information. + + See Scope. + + The use of this class requires that qual_names.resolve() has been called on + the node. This class will ignore nodes have not been + annotated with their qualified names. + """ + + def __init__(self, context, parent_scope=None): + super(ActivityAnalyzer, self).__init__(context) + self.allow_skips = False + self.scope = Scope(parent_scope, isolated=True) + + # Note: all these flags crucially rely on the respective nodes are + # leaves in the AST, that is, they cannot contain other statements. + self._in_aug_assign = False + self._in_annotation = False + self._track_annotations_only = False + + @property + def _in_constructor(self): + context = self.state[_FunctionOrClass] + if context.level > 2: + innermost = context.stack[-1].node + parent = context.stack[-2].node + return (isinstance(parent, gast.ClassDef) and + (isinstance(innermost, gast.FunctionDef) and + innermost.name == '__init__')) + return False + + def _node_sets_self_attribute(self, node): + if anno.hasanno(node, anno.Basic.QN): + qn = anno.getanno(node, anno.Basic.QN) + # TODO(mdan): The 'self' argument is not guaranteed to be called 'self'. + if qn.has_attr and qn.parent.qn == ('self',): + return True + return False + + def _track_symbol(self, node, composite_writes_alter_parent=False): + if self._track_annotations_only and not self._in_annotation: + return + + # A QN may be missing when we have an attribute (or subscript) on a function + # call. Example: a().b + if not anno.hasanno(node, anno.Basic.QN): + return + qn = anno.getanno(node, anno.Basic.QN) + + # When inside a comprehension, ignore reads to any of the comprehensions's + # targets. This includes attributes or slices of those arguments. + for l in self.state[_Comprehension]: + if qn in l.targets: + return + if qn.owner_set & set(l.targets): + return + + if isinstance(node.ctx, gast.Store): + # In comprehensions, modified symbols are the comprehension targets. + if self.state[_Comprehension].level > 0: + self.state[_Comprehension].targets.add(qn) + return + + self.scope.modified.add(qn) + self.scope.bound.add(qn) + if qn.is_composite and composite_writes_alter_parent: + self.scope.modified.add(qn.parent) + if self._in_aug_assign: + self.scope.read.add(qn) + + elif isinstance(node.ctx, gast.Load): + self.scope.read.add(qn) + if self._in_annotation: + self.scope.annotations.add(qn) + + elif isinstance(node.ctx, gast.Param): + self.scope.bound.add(qn) + self.scope.mark_param(qn, self.state[_FunctionOrClass].node) + + elif isinstance(node.ctx, gast.Del): + # The read matches the Python semantics - attempting to delete an + # undefined symbol is illegal. + self.scope.read.add(qn) + # Targets of del are considered bound: + # https://docs.python.org/3/reference/executionmodel.html#binding-of-names + self.scope.bound.add(qn) + self.scope.deleted.add(qn) + + else: + raise ValueError('Unknown context {} for node "{}".'.format( + type(node.ctx), qn)) + + def _enter_scope(self, isolated, f_name=None): + self.scope = Scope(self.scope, isolated=isolated, function_name=f_name) + + def _exit_scope(self): + exited_scope = self.scope + exited_scope.finalize() + self.scope = exited_scope.parent + return exited_scope + + def _exit_and_record_scope(self, node, tag=anno.Static.SCOPE): + node_scope = self._exit_scope() + anno.setanno(node, tag, node_scope) + return node_scope + + def _process_statement(self, node): + self._enter_scope(False) + node = self.generic_visit(node) + self._exit_and_record_scope(node) + return node + + def _process_annotation(self, node): + self._in_annotation = True + node = self.visit(node) + self._in_annotation = False + return node + + def visit_Import(self, node): + return self._process_statement(node) + + def visit_ImportFrom(self, node): + return self._process_statement(node) + + def visit_Global(self, node): + self._enter_scope(False) + for name in node.names: + qn = qual_names.QN(name) + self.scope.read.add(qn) + self.scope.globals.add(qn) + self._exit_and_record_scope(node) + return node + + def visit_Nonlocal(self, node): + self._enter_scope(False) + for name in node.names: + qn = qual_names.QN(name) + self.scope.read.add(qn) + self.scope.bound.add(qn) + self.scope.nonlocals.add(qn) + self._exit_and_record_scope(node) + return node + + def visit_Expr(self, node): + return self._process_statement(node) + + def visit_Raise(self, node): + return self._process_statement(node) + + def visit_Return(self, node): + return self._process_statement(node) + + def visit_Assign(self, node): + return self._process_statement(node) + + def visit_AnnAssign(self, node): + self._enter_scope(False) + node.target = self.visit(node.target) + if node.value is not None: + # Can be None for pure declarations, e.g. `n: int`. This is a new thing + # enabled by type annotations, but does not influence static analysis + # (declarations are not definitions). + node.value = self.visit(node.value) + if node.annotation: + node.annotation = self._process_annotation(node.annotation) + self._exit_and_record_scope(node) + return node + + def visit_AugAssign(self, node): + # Special rules for AugAssign. Here, the AST only shows the target as + # written, when it is in fact also read. + self._enter_scope(False) + + self._in_aug_assign = True + node.target = self.visit(node.target) + self._in_aug_assign = False + + node.op = self.visit(node.op) + node.value = self.visit(node.value) + self._exit_and_record_scope(node) + return node + + def visit_Delete(self, node): + return self._process_statement(node) + + def visit_Name(self, node): + if node.annotation: + node.annotation = self._process_annotation(node.annotation) + self._track_symbol(node) + return node + + def visit_alias(self, node): + node = self.generic_visit(node) + + if node.asname is None: + # Only the root name is a real symbol operation. + qn = qual_names.QN(node.name.split('.')[0]) + else: + qn = qual_names.QN(node.asname) + + self.scope.modified.add(qn) + self.scope.bound.add(qn) + return node + + def visit_Attribute(self, node): + node = self.generic_visit(node) + if self._in_constructor and self._node_sets_self_attribute(node): + self._track_symbol(node, composite_writes_alter_parent=True) + else: + self._track_symbol(node) + return node + + def visit_Subscript(self, node): + node = self.generic_visit(node) + # Subscript writes (e.g. a[b] = "value") are considered to modify + # both the element itself (a[b]) and its parent (a). + self._track_symbol(node) + return node + + def visit_Print(self, node): + self._enter_scope(False) + node.values = self.visit_block(node.values) + node_scope = self._exit_and_record_scope(node) + anno.setanno(node, NodeAnno.ARGS_SCOPE, node_scope) + return node + + def visit_Assert(self, node): + return self._process_statement(node) + + def visit_Call(self, node): + self._enter_scope(False) + node.args = self.visit_block(node.args) + node.keywords = self.visit_block(node.keywords) + # TODO(mdan): Account starargs, kwargs + self._exit_and_record_scope(node, tag=NodeAnno.ARGS_SCOPE) + + node.func = self.visit(node.func) + return node + + def _process_block_node(self, node, block, scope_name): + self._enter_scope(False) + block = self.visit_block(block) + self._exit_and_record_scope(node, tag=scope_name) + return node + + def _process_parallel_blocks(self, parent, children): + # Because the scopes are not isolated, processing any child block + # modifies the parent state causing the other child blocks to be + # processed incorrectly. So we need to checkpoint the parent scope so that + # each child sees the same context. + before_parent = Scope.copy_of(self.scope) + after_children = [] + for child, scope_name in children: + self.scope.copy_from(before_parent) + parent = self._process_block_node(parent, child, scope_name) + after_child = Scope.copy_of(self.scope) + after_children.append(after_child) + for after_child in after_children: + self.scope.merge_from(after_child) + return parent + + def _process_comprehension(self, + node, + is_list_comp=False, + is_dict_comp=False): + with self.state[_Comprehension] as comprehension_: + comprehension_.is_list_comp = is_list_comp + # Note: it's important to visit the generators first to properly account + # for the variables local to these generators. Example: `x` is local to + # the expression `z for x in y for z in x`. + node.generators = self.visit_block(node.generators) + if is_dict_comp: + node.key = self.visit(node.key) + node.value = self.visit(node.value) + else: + node.elt = self.visit(node.elt) + return node + + def visit_comprehension(self, node): + # It is important to visit children in this order so that the reads to + # the target name are appropriately ignored. + node.iter = self.visit(node.iter) + node.target = self.visit(node.target) + return self.generic_visit(node) + + def visit_DictComp(self, node): + return self._process_comprehension(node, is_dict_comp=True) + + def visit_ListComp(self, node): + return self._process_comprehension(node, is_list_comp=True) + + def visit_SetComp(self, node): + return self._process_comprehension(node) + + def visit_GeneratorExp(self, node): + return self._process_comprehension(node) + + def visit_ClassDef(self, node): + with self.state[_FunctionOrClass] as fn: + fn.node = node + # The ClassDef node itself has a Scope object that tracks the creation + # of its name, along with the usage of any decorator accompanying it. + self._enter_scope(False) + node.decorator_list = self.visit_block(node.decorator_list) + self.scope.modified.add(qual_names.QN(node.name)) + self.scope.bound.add(qual_names.QN(node.name)) + node.bases = self.visit_block(node.bases) + node.keywords = self.visit_block(node.keywords) + self._exit_and_record_scope(node) + + # A separate Scope tracks the actual class definition. + self._enter_scope(True) + node = self.generic_visit(node) + self._exit_scope() + return node + + def _visit_node_list(self, nodes): + return [(None if n is None else self.visit(n)) for n in nodes] + + def _visit_arg_annotations(self, node): + node.args.kw_defaults = self._visit_node_list(node.args.kw_defaults) + node.args.defaults = self._visit_node_list(node.args.defaults) + self._track_annotations_only = True + node = self._visit_arg_declarations(node) + self._track_annotations_only = False + return node + + def _visit_arg_declarations(self, node): + node.args.posonlyargs = self._visit_node_list(node.args.posonlyargs) + node.args.args = self._visit_node_list(node.args.args) + if node.args.vararg is not None: + node.args.vararg = self.visit(node.args.vararg) + node.args.kwonlyargs = self._visit_node_list(node.args.kwonlyargs) + if node.args.kwarg is not None: + node.args.kwarg = self.visit(node.args.kwarg) + return node + + def visit_FunctionDef(self, node): + with self.state[_FunctionOrClass] as fn: + fn.node = node + # The FunctionDef node itself has a Scope object that tracks the creation + # of its name, along with the usage of any decorator accompanying it. + self._enter_scope(False) + node.decorator_list = self.visit_block(node.decorator_list) + if node.returns: + node.returns = self._process_annotation(node.returns) + # Argument annotartions (includeing defaults) affect the defining context. + node = self._visit_arg_annotations(node) + + function_name = qual_names.QN(node.name) + self.scope.modified.add(function_name) + self.scope.bound.add(function_name) + self._exit_and_record_scope(node) + + # A separate Scope tracks the actual function definition. + self._enter_scope(True, node.name) + + # Keep a separate scope for the arguments node, which is used in the CFG. + self._enter_scope(False, node.name) + + # Arg declarations only affect the function itself, and have no effect + # in the defining context whatsoever. + node = self._visit_arg_declarations(node) + + self._exit_and_record_scope(node.args) + + # Track the body separately. This is for compatibility reasons, it may not + # be strictly needed. + self._enter_scope(False, node.name) + node.body = self.visit_block(node.body) + self._exit_and_record_scope(node, NodeAnno.BODY_SCOPE) + + self._exit_and_record_scope(node, NodeAnno.ARGS_AND_BODY_SCOPE) + return node + + def visit_Lambda(self, node): + # Lambda nodes are treated in roughly the same way as FunctionDef nodes. + with self.state[_FunctionOrClass] as fn: + fn.node = node + # The Lambda node itself has a Scope object that tracks the creation + # of its name, along with the usage of any decorator accompanying it. + self._enter_scope(False) + node = self._visit_arg_annotations(node) + self._exit_and_record_scope(node) + + # A separate Scope tracks the actual function definition. + self._enter_scope(True) + + # Keep a separate scope for the arguments node, which is used in the CFG. + self._enter_scope(False) + node = self._visit_arg_declarations(node) + self._exit_and_record_scope(node.args) + + # Track the body separately. This is for compatibility reasons, it may not + # be strictly needed. + # TODO(mdan): Do remove it, it's confusing. + self._enter_scope(False) + node.body = self.visit(node.body) + + # The lambda body can contain nodes of types normally not found as + # statements, and may not have the SCOPE annotation needed by the CFG. + # So we attach one if necessary. + if not anno.hasanno(node.body, anno.Static.SCOPE): + anno.setanno(node.body, anno.Static.SCOPE, self.scope) + + self._exit_and_record_scope(node, NodeAnno.BODY_SCOPE) + + lambda_scope = self.scope + self._exit_and_record_scope(node, NodeAnno.ARGS_AND_BODY_SCOPE) + + # TODO(bhack:) https://github.com/tensorflow/tensorflow/issues/56089 + # remove after deprecation + # Exception: lambdas are assumed to be used in the place where + # they are defined. Therefore, their activity is passed on to the + # calling statement. + self.scope.read.update(lambda_scope.read - lambda_scope.bound) + + return node + + def visit_With(self, node): + self._enter_scope(False) + node = self.generic_visit(node) + self._exit_and_record_scope(node, NodeAnno.BODY_SCOPE) + return node + + def visit_withitem(self, node): + return self._process_statement(node) + + def visit_If(self, node): + self._enter_scope(False) + node.test = self.visit(node.test) + node_scope = self._exit_and_record_scope(node.test) + anno.setanno(node, NodeAnno.COND_SCOPE, node_scope) + + node = self._process_parallel_blocks(node, + ((node.body, NodeAnno.BODY_SCOPE), + (node.orelse, NodeAnno.ORELSE_SCOPE))) + return node + + def visit_For(self, node): + self._enter_scope(False) + node.target = self.visit(node.target) + node.iter = self.visit(node.iter) + self._exit_and_record_scope(node.iter) + + self._enter_scope(False) + self.visit(node.target) + if anno.hasanno(node, anno.Basic.EXTRA_LOOP_TEST): + self._process_statement(anno.getanno(node, anno.Basic.EXTRA_LOOP_TEST)) + self._exit_and_record_scope(node, tag=NodeAnno.ITERATE_SCOPE) + + node = self._process_parallel_blocks(node, + ((node.body, NodeAnno.BODY_SCOPE), + (node.orelse, NodeAnno.ORELSE_SCOPE))) + return node + + def visit_While(self, node): + self._enter_scope(False) + node.test = self.visit(node.test) + node_scope = self._exit_and_record_scope(node.test) + anno.setanno(node, NodeAnno.COND_SCOPE, node_scope) + + node = self._process_parallel_blocks(node, + ((node.body, NodeAnno.BODY_SCOPE), + (node.orelse, NodeAnno.ORELSE_SCOPE))) + return node + + def visit_ExceptHandler(self, node): + self._enter_scope(False) + # try/except oddity: as expected, it leaks any names you defined inside the + # except block, but not the name of the exception variable. + if node.name is not None: + self.scope.isolated_names.add(anno.getanno(node.name, anno.Basic.QN)) + node = self.generic_visit(node) + self._exit_scope() + return node + + +def resolve(node, context, parent_scope=None): + return ActivityAnalyzer(context, parent_scope).visit(node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/annos.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/annos.py new file mode 100644 index 0000000000000000000000000000000000000000..54d85cc3d72253f3e3f141619e260a74c6954d1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/annos.py @@ -0,0 +1,55 @@ +# 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. +# ============================================================================== +"""Annotations used by the static analyzer.""" + +from enum import Enum + + +# TODO(mdan): Remove. + + +class NoValue(Enum): + + def __repr__(self): # pylint: disable=invalid-repr-returned + return self.name + + +class NodeAnno(NoValue): + """Additional annotations used by the static analyzer. + + These are in addition to the basic annotations declared in anno.py. + """ + + # Symbols + # These flags are boolean. + IS_LOCAL = 'Symbol is local to the function scope being analyzed.' + IS_PARAM = 'Symbol is a parameter to the function being analyzed.' + IS_MODIFIED_SINCE_ENTRY = ( + 'Symbol has been explicitly replaced in the current function scope.') + + # Scopes + # Scopes are represented by objects of type activity.Scope. + ARGS_SCOPE = 'The scope for the argument list of a function call.' + COND_SCOPE = 'The scope for the test node of a conditional statement.' + ITERATE_SCOPE = 'The scope for the iterate assignment of a for loop.' + ARGS_AND_BODY_SCOPE = ( + 'The scope for the main body of a function or lambda, including its' + ' arguments.') + BODY_SCOPE = ( + 'The scope for the main body of a statement (True branch for if ' + 'statements, main body for loops).') + ORELSE_SCOPE = ( + 'The scope for the orelse body of a statement (False branch for if ' + 'statements, orelse body for loops).') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/liveness.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/liveness.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1eae04998d57b3edcf728ac168addf6c3a5842 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/liveness.py @@ -0,0 +1,220 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Live variable analysis. + +See https://en.wikipedia.org/wiki/Live_variable_analysis for a definition of +the following idioms: live variable, live in, live out, which are used +throughout this file. + +This analysis attaches the following: + * symbols that are live at the exit of control flow statements + * symbols that are live at the entry of control flow statements + +Requires activity analysis. +""" + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import cfg +from tensorflow.python.autograph.pyct import transformer +from tensorflow.python.autograph.pyct.static_analysis import annos + + +class Analyzer(cfg.GraphVisitor): + """CFG visitor that performs liveness analysis at statement level.""" + + def __init__(self, graph, include_annotations): + super(Analyzer, self).__init__(graph) + self.include_annotations = include_annotations + + def init_state(self, _): + return set() + + def lamba_check(self, fn_ast_node): + if isinstance(fn_ast_node, gast.Lambda): + # Exception: lambda functions are assumed to be used only in the + # place where they are defined, and not later. + return True + return False + + def visit_node(self, node): + prev_live_in = self.in_[node] + + if anno.hasanno(node.ast_node, anno.Static.SCOPE): + node_scope = anno.getanno(node.ast_node, anno.Static.SCOPE) + + gen = node_scope.read + if not self.include_annotations: + gen -= node_scope.annotations + # TODO(mdan): verify whether composites' parents need to be added. + # E.g. whether x needs to be added if x.y is live. Theoretically the + # activity analysis should have both so that wouldn't be needed. + kill = node_scope.modified | node_scope.deleted + + live_out = set() + for n in node.next: + live_out |= self.in_[n] + live_in = gen | (live_out - kill) + + reaching_functions = anno.getanno( + node.ast_node, anno.Static.DEFINED_FNS_IN) + for fn_ast_node in reaching_functions: + if self.lamba_check(fn_ast_node): + continue + fn_scope = anno.getanno(fn_ast_node, annos.NodeAnno.ARGS_AND_BODY_SCOPE) + # Any closure of a reaching function definition is conservatively + # considered live. + live_in |= (fn_scope.read - fn_scope.bound) + + else: + assert self.can_ignore(node), (node.ast_node, node) + + live_out = set() + for n in node.next: + live_out |= self.in_[n] + live_in = live_out + + self.in_[node] = live_in + self.out[node] = live_out + + # TODO(mdan): Move this to the superclass? + return prev_live_in != live_in + + +class TreeAnnotator(transformer.Base): + """Runs liveness analysis on each of the functions defined in the AST. + + If a function defined other local functions, those will have separate CFGs. + However, dataflow analysis needs to tie up these CFGs to properly emulate the + effect of closures. In the case of liveness, the parent function's live + variables must account for the variables that are live at the entry of each + subfunction. For example: + + def foo(): + # baz is live from here on + def bar(): + print(baz) + + This analyzer runs liveness analysis on each individual function, accounting + for the effect above. + """ + + def __init__(self, source_info, graphs, include_annotations): + super(TreeAnnotator, self).__init__(source_info) + self.include_annotations = include_annotations + self.allow_skips = False + self.graphs = graphs + self.current_analyzer = None + + def visit(self, node): + node = super(TreeAnnotator, self).visit(node) + if (self.current_analyzer is not None and + isinstance(node, gast.stmt) and + node in self.current_analyzer.graph.index): + cfg_node = self.current_analyzer.graph.index[node] + anno.setanno(node, anno.Static.LIVE_VARS_IN, + frozenset(self.current_analyzer.in_[cfg_node])) + return node + + def _analyze_function(self, node, is_lambda): + parent_analyzer = self.current_analyzer + + analyzer = Analyzer(self.graphs[node], self.include_annotations) + analyzer.visit_reverse() + self.current_analyzer = analyzer + node = self.generic_visit(node) + + self.current_analyzer = parent_analyzer + return node + + def visit_Lambda(self, node): + return self._analyze_function(node, is_lambda=True) + + def visit_FunctionDef(self, node): + return self._analyze_function(node, is_lambda=False) + + def _block_statement_live_out(self, node): + successors = self.current_analyzer.graph.stmt_next[node] + stmt_live_out = set() + for s in successors: + stmt_live_out.update(self.current_analyzer.in_[s]) + anno.setanno(node, anno.Static.LIVE_VARS_OUT, frozenset(stmt_live_out)) + return node + + def _block_statement_live_in(self, node, entry_node): + if entry_node in self.current_analyzer.graph.index: + cfg_node = self.current_analyzer.graph.index[entry_node] + stmt_live_in = frozenset(self.current_analyzer.in_[cfg_node]) + else: + assert anno.hasanno(entry_node, anno.Static.LIVE_VARS_IN), ( + 'If not matching a CFG node, must be a block statement:' + ' {}'.format(entry_node)) + stmt_live_in = anno.getanno(entry_node, anno.Static.LIVE_VARS_IN) + anno.setanno(node, anno.Static.LIVE_VARS_IN, stmt_live_in) + return node + + def visit_If(self, node): + node = self.generic_visit(node) + node = self._block_statement_live_out(node) + return self._block_statement_live_in(node, node.test) + + def visit_For(self, node): + node = self.generic_visit(node) + node = self._block_statement_live_out(node) + return self._block_statement_live_in(node, node.iter) + + def visit_While(self, node): + node = self.generic_visit(node) + node = self._block_statement_live_out(node) + return self._block_statement_live_in(node, node.test) + + def visit_Try(self, node): + node = self.generic_visit(node) + node = self._block_statement_live_out(node) + return self._block_statement_live_in(node, node.body[0]) + + def visit_ExceptHandler(self, node): + node = self.generic_visit(node) + node = self._block_statement_live_out(node) + return self._block_statement_live_in(node, node.body[0]) + + def visit_With(self, node): + node = self.generic_visit(node) + return self._block_statement_live_in(node, node.items[0]) + + def visit_Expr(self, node): + node = self.generic_visit(node) + cfg_node = self.current_analyzer.graph.index[node] + anno.setanno(node, anno.Static.LIVE_VARS_OUT, + frozenset(self.current_analyzer.out[cfg_node])) + return node + + +# TODO(mdan): Investigate the possibility of removing include_annotations. +def resolve(node, source_info, graphs, include_annotations=True): + """Resolves the live symbols at the exit of control flow statements. + + Args: + node: ast.AST + source_info: transformer.SourceInfo + graphs: Dict[ast.FunctionDef, cfg.Graph] + include_annotations: Bool, whether type annotations should be included in + the analysis. + Returns: + ast.AST + """ + node = TreeAnnotator(source_info, graphs, include_annotations).visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..aa07142528ee0129b99fe6f49ffc189ca9bcea58 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/reaching_definitions.py @@ -0,0 +1,288 @@ +# 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. +# ============================================================================== +"""Reaching definition analysis. + +This analysis attaches a set of a Definition objects to each symbol, one +for each distinct definition that may reach it. The Definition objects are +mutable and may be used by subsequent analyses to further annotate data like +static type and value information. +The analysis also attaches the set of the symbols defined at the entry of +control flow statements. + +Requires activity analysis. +""" + +import weakref + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import cfg +from tensorflow.python.autograph.pyct import transformer + + +class Definition(object): + """Definition objects describe a unique definition of a variable. + + Subclasses of this may be used by passing an appropriate factory function to + resolve. + + Attributes: + param_of: Optional[ast.AST] + directives: Dict, optional definition annotations + """ + + def __init__(self): + self.param_of = None + self.directives = {} + + def __repr__(self): + return '%s[%d]' % (self.__class__.__name__, id(self)) + + +class _NodeState(object): + """Abstraction for the state of the CFG walk for reaching definition analysis. + + This is a value type. Only implements the strictly necessary operators. + + Attributes: + value: Dict[qual_names.QN, Set[Definition, ...]], the defined symbols and + their possible definitions + """ + + def __init__(self, init_from=None): + if init_from: + if isinstance(init_from, _NodeState): + self.value = { + s: set(other_infos) for s, other_infos in init_from.value.items() + } + elif isinstance(init_from, dict): + self.value = {s: set((init_from[s],)) for s in init_from} + else: + assert False, init_from + else: + self.value = {} + + def __eq__(self, other): + if frozenset(self.value.keys()) != frozenset(other.value.keys()): + return False + ret = all(self.value[s] == other.value[s] for s in self.value) + return ret + + def __ne__(self, other): + return not self.__eq__(other) + + def __or__(self, other): + assert isinstance(other, _NodeState) + result = _NodeState(self) + for s, other_infos in other.value.items(): + if s in result.value: + result.value[s].update(other_infos) + else: + result.value[s] = set(other_infos) + return result + + def __sub__(self, other): + assert isinstance(other, set) + result = _NodeState(self) + for s in other: + result.value.pop(s, None) + return result + + def __repr__(self): + return 'NodeState[%s]=%s' % (id(self), repr(self.value)) + + +class Analyzer(cfg.GraphVisitor): + """CFG visitor that determines reaching definitions at statement level.""" + + def __init__(self, graph, definition_factory): + self._definition_factory = definition_factory + super(Analyzer, self).__init__(graph) + self.gen_map = {} + + def init_state(self, _): + return _NodeState() + + def visit_node(self, node): + prev_defs_out = self.out[node] + + defs_in = _NodeState() + for n in node.prev: + defs_in |= self.out[n] + + if anno.hasanno(node.ast_node, anno.Static.SCOPE): + node_scope = anno.getanno(node.ast_node, anno.Static.SCOPE) + # The definition objects created by each node must be singletons because + # their ids are used in equality checks. + if node not in self.gen_map: + node_symbols = {} + # Every binding operation (assign, nonlocal, global, etc.) counts as a + # definition, with the exception of del, which only deletes without + # creating a new variable. + newly_defined = ((node_scope.bound | node_scope.globals) - + node_scope.deleted) + for s in newly_defined: + def_ = self._definition_factory() + node_symbols[s] = def_ + # Every param receives a definition. Params are not necessarily + # considered as "modified". + for s, p in node_scope.params.items(): + def_ = self._definition_factory() + def_.param_of = weakref.ref(p) + node_symbols[s] = def_ + self.gen_map[node] = _NodeState(node_symbols) + + gen = self.gen_map[node] + kill = node_scope.modified | node_scope.deleted + defs_out = gen | (defs_in - kill) + + gen = self.gen_map[node] + defs_out = gen | (defs_in - kill) + + else: + assert self.can_ignore(node), (node.ast_node, node) + defs_out = defs_in + + self.in_[node] = defs_in + self.out[node] = defs_out + + return prev_defs_out != defs_out + + +class TreeAnnotator(transformer.Base): + """AST visitor that annotates each symbol name with its reaching definitions. + + Simultaneously, the visitor runs the dataflow analysis on each function node, + accounting for the effect of closures. For example: + + def foo(): + bar = 1 + def baz(): + # bar = 1 reaches here + """ + + def __init__(self, source_info, graphs, definition_factory): + super(TreeAnnotator, self).__init__(source_info) + self.allow_skips = False + self.definition_factory = definition_factory + self.graphs = graphs + self.current_analyzer = None + self.current_cfg_node = None + + def visit_FunctionDef(self, node): + parent_analyzer = self.current_analyzer + subgraph = self.graphs[node] + + analyzer = Analyzer(subgraph, self.definition_factory) + analyzer.visit_forward() + + # Recursively process any remaining subfunctions. + self.current_analyzer = analyzer + node.args = self.visit(node.args) + node.body = self.visit_block(node.body) + self.current_analyzer = parent_analyzer + + return node + + def visit_Name(self, node): + if self.current_analyzer is None: + # Names may appear outside function defs - for example in class + # definitions. + return node + + analyzer = self.current_analyzer + cfg_node = self.current_cfg_node + + assert cfg_node is not None, ('name node, %s, outside of any statement?' + % node.id) + + qn = anno.getanno(node, anno.Basic.QN) + if isinstance(node.ctx, gast.Load): + anno.setanno(node, anno.Static.DEFINITIONS, + tuple(analyzer.in_[cfg_node].value.get(qn, ()))) + else: + anno.setanno(node, anno.Static.DEFINITIONS, + tuple(analyzer.out[cfg_node].value.get(qn, ()))) + + return node + + def _aggregate_predecessors_defined_in(self, node): + preds = self.current_analyzer.graph.stmt_prev[node] + node_defined_in = set() + for p in preds: + node_defined_in |= set(self.current_analyzer.out[p].value.keys()) + anno.setanno(node, anno.Static.DEFINED_VARS_IN, frozenset(node_defined_in)) + + def visit_If(self, node): + self._aggregate_predecessors_defined_in(node) + return self.generic_visit(node) + + def visit_For(self, node): + self._aggregate_predecessors_defined_in(node) + + # Manually accounting for the shortcoming described in + # cfg.AstToCfg.visit_For. + parent = self.current_cfg_node + self.current_cfg_node = self.current_analyzer.graph.index[node.iter] + node.target = self.visit(node.target) + self.current_cfg_node = parent + + node.iter = self.visit(node.iter) + node.body = self.visit_block(node.body) + node.orelse = self.visit_block(node.orelse) + + return node + + def visit_While(self, node): + self._aggregate_predecessors_defined_in(node) + return self.generic_visit(node) + + def visit_Try(self, node): + self._aggregate_predecessors_defined_in(node) + return self.generic_visit(node) + + def visit_ExceptHandler(self, node): + self._aggregate_predecessors_defined_in(node) + # TODO(mdan): Also track the exception type / name symbols. + node.body = self.visit_block(node.body) + return node + + def visit(self, node): + parent = self.current_cfg_node + + if (self.current_analyzer is not None and + node in self.current_analyzer.graph.index): + self.current_cfg_node = self.current_analyzer.graph.index[node] + node = super(TreeAnnotator, self).visit(node) + + self.current_cfg_node = parent + return node + + +def resolve(node, source_info, graphs, definition_factory=Definition): + """Resolves reaching definitions for each symbol. + + Args: + node: ast.AST + source_info: transformer.SourceInfo + graphs: Dict[ast.FunctionDef, cfg.Graph] + definition_factory: Callable[[], Definition] + Returns: + ast.AST + """ + visitor = TreeAnnotator(source_info, graphs, definition_factory) + node = visitor.visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/reaching_fndefs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/reaching_fndefs.py new file mode 100644 index 0000000000000000000000000000000000000000..2ef592edf5f13a353a7dc1d42962d21927a28ea7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/reaching_fndefs.py @@ -0,0 +1,178 @@ +# 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. +# ============================================================================== +"""An analysis that determines the reach of a function definition. + +A function definition is said to reach a statement if that function may exist +(and therefore may be called) when that statement executes. +""" + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import cfg +from tensorflow.python.autograph.pyct import transformer + + +class Definition(object): + """Definition objects describe a unique definition of a function.""" + + def __init__(self, def_node): + self.def_node = def_node + + +class _NodeState(object): + """Abstraction for the state of the CFG walk for reaching definition analysis. + + This is a value type. Only implements the strictly necessary operators. + + Attributes: + value: Dict[qual_names.QN, Set[Definition, ...]], the defined symbols and + their possible definitions + """ + + def __init__(self, init_from=None): + if init_from: + self.value = set(init_from) + else: + self.value = set() + + def __eq__(self, other): + return self.value == other.value + + def __ne__(self, other): + return self.value != other.value + + def __or__(self, other): + assert isinstance(other, _NodeState) + result = _NodeState(self.value) + result.value.update(other.value) + return result + + def __add__(self, value): + result = _NodeState(self.value) + result.value.add(value) + return result + + def __repr__(self): + return 'NodeState[%s]=%s' % (id(self), repr(self.value)) + + +class Analyzer(cfg.GraphVisitor): + """CFG visitor that determines reaching definitions at statement level.""" + + def __init__(self, graph, external_defs): + super(Analyzer, self).__init__(graph) + # This allows communicating that nodes have extra reaching definitions, + # e.g. those that a function closes over. + self.external_defs = external_defs + + def init_state(self, _): + return _NodeState() + + def visit_node(self, node): + prev_defs_out = self.out[node] + + if node is self.graph.entry: + defs_in = _NodeState(self.external_defs) + else: + defs_in = prev_defs_out + + for n in node.prev: + defs_in |= self.out[n] + + defs_out = defs_in + if isinstance(node.ast_node, (gast.Lambda, gast.FunctionDef)): + defs_out += node.ast_node + + self.in_[node] = defs_in + self.out[node] = defs_out + + return prev_defs_out != defs_out + + +class TreeAnnotator(transformer.Base): + """AST visitor that annotates each symbol name with its reaching definitions. + + Simultaneously, the visitor runs the dataflow analysis on each function node, + accounting for the effect of closures. For example: + + def foo(): + def f(): + pass + def g(): + # `def f` reaches here + """ + + def __init__(self, source_info, graphs): + super(TreeAnnotator, self).__init__(source_info) + self.graphs = graphs + self.allow_skips = False + self.current_analyzer = None + + def _proces_function(self, node): + parent_analyzer = self.current_analyzer + subgraph = self.graphs[node] + + if (self.current_analyzer is not None + and node in self.current_analyzer.graph.index): + cfg_node = self.current_analyzer.graph.index[node] + defined_in = self.current_analyzer.in_[cfg_node].value + else: + defined_in = () + + analyzer = Analyzer(subgraph, defined_in) + analyzer.visit_forward() + + self.current_analyzer = analyzer + node = self.generic_visit(node) + self.current_analyzer = parent_analyzer + return node + + def visit_FunctionDef(self, node): + return self._proces_function(node) + + def visit_Lambda(self, node): + return self._proces_function(node) + + def visit(self, node): + # This can happen before entering the top level function + if (self.current_analyzer is not None + and node in self.current_analyzer.graph.index): + cfg_node = self.current_analyzer.graph.index[node] + anno.setanno(node, anno.Static.DEFINED_FNS_IN, + self.current_analyzer.in_[cfg_node].value) + + extra_node = anno.getanno(node, anno.Basic.EXTRA_LOOP_TEST, default=None) + if extra_node is not None: + cfg_node = self.current_analyzer.graph.index[extra_node] + anno.setanno(extra_node, anno.Static.DEFINED_FNS_IN, + self.current_analyzer.in_[cfg_node].value) + + return super(TreeAnnotator, self).visit(node) + + +def resolve(node, source_info, graphs): + """Resolves reaching definitions for each symbol. + + Args: + node: ast.AST + source_info: transformer.SourceInfo + graphs: Dict[ast.FunctionDef, cfg.Graph] + Returns: + ast.AST + """ + visitor = TreeAnnotator(source_info, graphs) + node = visitor.visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/type_inference.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/type_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..5b59a5a18f5edf166f4098cdc43ad1bc7c646511 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/static_analysis/type_inference.py @@ -0,0 +1,624 @@ +# 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. +# ============================================================================== +"""Type inference. + +This analysis annotates all symbols nodes of an AST with type information +extracted from static sources: + * type annotations + * global and local symbols visible to the function at analysis time + * literals + +Important: This analysis is static, and does not detect dynamic type changes. +The analysis attempts to use the values of external symbols, if available. These +values are also considered static for the purpose of analysis. + +Requires reaching function definitions analysis. +""" + +import itertools + +from typing import Any, Callable, Dict, Set + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import cfg +from tensorflow.python.autograph.pyct import qual_names +from tensorflow.python.autograph.pyct import transformer +from tensorflow.python.autograph.pyct.static_analysis import activity +from tensorflow.python.autograph.pyct.static_analysis import annos + + +class Resolver(object): + """Resolver objects handle the process of looking up actual names and types. + + Unless noted otherwise, all resolve_* methods: + * have a first namespace argument, mapping string to actual values + * have a second types_namespace argument, mapping string to actual inferred + types + * specify names as QN objects + * specify types as a Set of inferred types + + Unless noted otherwise, all resolve_* methods must return either: + * a set of `type` objects + * None + """ + + def res_name(self, ns, types_ns, name): + """Resolves the type/value an external (e.g. closure, global) variable. + + Args: + ns: namespace + types_ns: types namespace + name: symbol name + Returns: + Tuple (type, static_value). The first element is the type to use for + inferrence. The second is the static value to use. Return None to treat it + as unknown. + """ + raise NotImplementedError('subclasses must implement') + + def res_value(self, ns, value): + """Resolves the type a literal or static value.""" + raise NotImplementedError('subclasses must implement') + + def res_arg(self, ns, types_ns, f_name, name, type_anno, f_is_local): + """Resolves the type of a (possibly annotated) function argument. + + Args: + ns: namespace + types_ns: types namespace + f_name: str, the function name + name: str, the argument name + type_anno: the type annotating the argument, if any + f_is_local: bool, whether the function is a local function + Returns: + Set of the argument types. + """ + raise NotImplementedError('subclasses must implement') + + def res_call(self, ns, types_ns, node, f_type, args, keywords): + """Resolves the return type an external function or method call. + + Args: + ns: namespace + types_ns: types namespace + node: str, the function name + f_type: types of the actual function being called, if known + args: types of each respective argument in node.args + keywords: types of each respective argument in node.keywords + + Returns: + Tuple (return_type, side_effect_types). The first element is just the + return types of the function. The second element is a map from + argument names to sets of types, and allow modelling side effects of + functions (for example via global or nonlocal). + """ + raise NotImplementedError('subclasses must implement') + + # TODO(mdan): Clean this up. + def res_slice(self, ns, types_ns, node_or_slice, value, slice_): + """Resolves the return type of slice operation.""" + raise NotImplementedError('subclasses must implement') + + def res_compare(self, ns, types_ns, node, left, right): + """Resolves the return type of a unary operation.""" + raise NotImplementedError('subclasses must implement') + + def res_unop(self, ns, types_ns, node, opnd): + """Resolves the return type of a unary operation.""" + raise NotImplementedError('subclasses must implement') + + def res_binop(self, ns, types_ns, node, left, right): + """Resolves the return type of a binary operation.""" + raise NotImplementedError('subclasses must implement') + + def res_list_literal(self, ns, elt_types): + """Resolves the type of a list literal from its elements.""" + raise NotImplementedError('subclasses must implement') + + +class _TypeMap(object): + """Abstraction for the state of the CFG walk for type inference. + + This is a value type. Only implements the strictly necessary operators. + + Attributes: + types: Dict[qual_names.QN, Set[Type]], mapping symbols to the set of + possible types. + """ + + def __init__(self, init_from=None): + if init_from: + assert isinstance(init_from, _TypeMap) + self.types = { + s: set(other_types) for s, other_types in init_from.types.items() + } + else: + self.types = {} + + def __eq__(self, other): + if frozenset(self.types.keys()) != frozenset(other.types.keys()): + return False + ret = all(self.types[s] == other.types[s] for s in self.types) + return ret + + def __ne__(self, other): + return not self.__eq__(other) + + def __or__(self, other): + assert isinstance(other, _TypeMap) + result = _TypeMap(self) + for s, other_types in other.types.items(): + if s not in result.types: + self_types = set() + result.types[s] = self_types + else: + self_types = result.types[s] + self_types.update(other_types) + return result + + def __repr__(self): + return 'SymbolTable {}'.format(self.types) + + +NO_VALUE = object() + + +class StmtInferrer(gast.NodeVisitor): + """Runs type inference on a single AST statement. + + This visitor annotates most nodes with type information. It also sets types + for the symbols modified by this statement in its types_out property. + + Note: this inferrer is able to capture side effects of functions, however, + these side effects will not be applied to the current expression. Doing so + would create too much of a dependence on the runtime's internal rules about + execution order. + Example: + + def f(): + nonlocal a + a = 1 + return a + + a = 0.0 + b = f() + a # a = float; side effect of f() ignored + print(a) # a = int; side effect of f() accounted for + """ + + def __init__(self, + resolver: Resolver, + scope: activity.Scope, + namespace: Dict[qual_names.QN, Any], + closure_types: Dict[qual_names.QN, Set[Any]], + types_in: _TypeMap): + self.resolver = resolver + self.scope = scope + self.namespace = namespace + self.closure_types = closure_types + self.types_in = types_in + self.new_symbols = {} + + # rvalue type. This property is set when encountering an assign operation, + # so that visiting nodes with Store ctx (typically found on left side of + # assignments) can infer the type they should receive. + self.rtype = None + + def visit(self, node): + types = super().visit(node) + if __debug__: + self._check_set(types) + if types is not None: + # TODO(mdan): Normalize by removing subtypes. + anno.setanno(node, anno.Static.TYPES, tuple(types)) + return types + + def _check_set(self, value): + if value is not None and not isinstance(value, set): + raise ValueError('{} method expected to return set, got {}'.format( + self.resolver, value)) + + def visit_Constant(self, node): + types = self.resolver.res_value(self.namespace, node.value) + if __debug__: + self._check_set(types) + return types + + def _apply_unpacking(self, node): + assert isinstance(node.ctx, gast.Store) + if self.rtype is not None: + original_stype = self.rtype + # TODO(mdan): Find a better way to express unpacking. + i_type = self.resolver.res_value(self.namespace, 0) + for i, elt in enumerate(node.elts): + self.rtype = self.resolver.res_slice( + self.namespace, self.types_in.types, i, original_stype, i_type) + self.visit(elt) + self.rtype = original_stype + return original_stype + return None + + def visit_Tuple(self, node): + if isinstance(node.ctx, gast.Load): + elt_types = () + for elt in node.elts: + types_ = self.visit(elt) + if types_ is None: + return None + elt_types += (types_,) + return set(itertools.product(*elt_types)) + return self._apply_unpacking(node) + + def visit_List(self, node): + if isinstance(node.ctx, gast.Load): + elt_types = tuple(self.visit(elt) for elt in node.elts) + return self.resolver.res_list_literal(self.namespace, elt_types) + return self._apply_unpacking(node) + + def visit_Set(self, node): + raise NotImplementedError() + + def visit_Name(self, node): + name = anno.getanno(node, anno.Basic.QN) + + if isinstance(node.ctx, gast.Load): + types = self.types_in.types.get(name, None) + if types is None: + if (name not in self.scope.bound) or (name in self.scope.nonlocals): + # TODO(mdan): Test with global variables. + if name in self.closure_types: + types = self.closure_types[name] + else: + types, value = self.resolver.res_name( + self.namespace, self.types_in.types, name) + if value is not None: + anno.setanno(node, anno.Static.VALUE, value) + + elif isinstance(node.ctx, gast.Param): + # The direct parent it the whole function scope. See activity.py. + f_is_local = self.scope.parent.parent is not None + + type_name = anno.getanno(node.annotation, anno.Basic.QN, None) + types = self.resolver.res_arg(self.namespace, self.types_in.types, + self.scope.function_name, name, type_name, + f_is_local) + if types is not None: + self.new_symbols[name] = types + + elif isinstance(node.ctx, gast.Store): + if self.rtype is not None: + self.new_symbols[name] = self.rtype + types = self.rtype + + else: + assert False, 'unknown ctx' + + if __debug__: + self._check_set(types) + + return types + + def visit_Attribute(self, node): + parent_types = self.visit(node.value) + + # Attempt to use the static value if known. + parent_value = anno.Static.VALUE.of(node.value, None) + if parent_value is not None: + static_value = getattr(parent_value, node.attr, NO_VALUE) + + if static_value is NO_VALUE: + # Unexpected failure to resolve attribute. Ask the resolver about the + # full name instead. + types, static_value = self.resolver.res_name( + self.namespace, self.types_in, anno.Basic.QN.of(node)) + anno.setanno(node, anno.Static.VALUE, static_value) + if __debug__: + self._check_set(types) + return types + + else: + # Fall back to the type if that is known. + if parent_types is None: + return None + + inferred_values = [getattr(t, node.attr, None) for t in parent_types] + if not inferred_values: + return None + + static_value = inferred_values[0] + if static_value is None: + return None + + if any(v is not static_value for v in inferred_values[1:]): + # Static value not stable, assume it's dynamic. + return None + + types = self.resolver.res_value(self.namespace, static_value) + anno.setanno(node, anno.Static.VALUE, static_value) + + if __debug__: + self._check_set(types) + + return types + + def visit_FunctionDef(self, node): + f_name = qual_names.QN(node.name) + + if node.decorator_list: + raise NotImplementedError('decorators: {}'.format(node.decorator_list)) + + ret_types = None + if node.returns: + ret_types, _ = self.resolver.res_name( + self.namespace, self.types_in.types, anno.Basic.QN.of(node.returns)) + if __debug__: + self._check_set(ret_types) + + if ret_types is None: + ret_types = {Any} + + f_types = set() + for rt in ret_types: + f_types.add(Callable[[Any], rt]) + + self.new_symbols[f_name] = f_types + # The definition of a function is an expression, hence has no return value. + return None + + def _resolve_typed_callable(self, f_types, arg_types, keyword_types): + ret_types = set() + for t in f_types: + + if isinstance(t, Callable): + # Note: these are undocummented - may be version-specific! + # Callable[[x], y]: __args__ are (x, y) + args = t.__args__ + if args: + ret_types.add(args[-1]) + else: + ret_types.add(Any) + else: + raise NotImplementedError('callable type {}'.format(type(t))) + + # Side effects can not be inferred based on type alone. + side_effects = None + return ret_types, side_effects + + def visit_Call(self, node): + self.visit(node.func) + + f_name = anno.Basic.QN.of(node.func) + arg_types = [self.visit(a) for a in node.args] + keyword_types = [self.visit(kw.value) for kw in node.keywords] + + if f_name in self.scope.bound: + # Local function, use local type definitions, if available. + f_type = self.types_in.types.get(f_name, None) + if f_type is None: + # No static type info available, nothing more to do. + ret_type, side_effects = None, None + else: + ret_type, side_effects = self._resolve_typed_callable( + f_type, arg_types, keyword_types) + + else: + # Nonlocal function, resolve externally. + f_type = anno.Static.TYPES.of(node.func, None) + ret_type, side_effects = self.resolver.res_call(self.namespace, + self.types_in.types, node, + f_type, arg_types, + keyword_types) + + if __debug__: + self._check_set(ret_type) + if side_effects: + if not isinstance(side_effects, dict): + raise ValueError( + 'side effects must be dict, got {}'.format(side_effects)) + for k, v in side_effects.items(): + if not isinstance(k, qual_names.QN): + raise ValueError('side effect keys must be QNs, got {}'.format(k)) + self._check_set(v) + + if side_effects: + self.new_symbols.update(side_effects) + return ret_type + + def visit_Expr(self, node): + return self.visit(node.value) + + def visit_Assign(self, node): + self.rtype = self.visit(node.value) + + for t in node.targets: + self.visit(t) + + self.rtype = None + + def visit_Subscript(self, node): + val_types = self.visit(node.value) + slice_types = self.visit(node.slice) + + if val_types is None or slice_types is None: + return None + + types = self.resolver.res_slice( + self.namespace, self.types_in.types, node, val_types, slice_types) + + if __debug__: + self._check_set(types) + + return types + + def visit_Compare(self, node): + left_types = self.visit(node.left) + right_types = [self.visit(c) for c in node.comparators] + + if left_types is None or any(t is None for t in right_types): + return None + + types = self.resolver.res_compare( + self.namespace, self.types_in.types, node, left_types, right_types) + + if __debug__: + self._check_set(types) + + return types + + def visit_BinOp(self, node): + left_types = self.visit(node.left) + right_types = self.visit(node.right) + + if left_types is None or right_types is None: + return None + + types = self.resolver.res_binop( + self.namespace, self.types_in.types, node, left_types, right_types) + + if __debug__: + self._check_set(types) + + return types + + def visit_UnaryOp(self, node): + opnd_types = self.visit(node.operand) + + if opnd_types is None: + return None + + types = self.resolver.res_unop( + self.namespace, self.types_in.types, node, opnd_types) + + if __debug__: + self._check_set(types) + + return types + + +class Analyzer(cfg.GraphVisitor): + """CFG visitor that propagates type information across statements.""" + + def __init__(self, graph, resolver, namespace, scope, closure_types): + """Creates a new analyzer. + + Args: + graph: cfg.Graph + resolver: Resolver + namespace: Dict[str, Any] + scope: activity.Scope + closure_types: Dict[QN, Set] + """ + super(Analyzer, self).__init__(graph) + self.resolver = resolver + self.namespace = namespace + self.scope = scope + self.closure_types = closure_types + + context_types = { + n: t for n, t in closure_types.items() if n not in scope.bound + } + if context_types: + self.context_types = _TypeMap() + self.context_types.types = context_types + else: + self.context_types = None + + def init_state(self, _): + return _TypeMap() + + def _update_closure_types(self, ast_node, types): + existing_types = anno.Static.CLOSURE_TYPES.of(ast_node, None) + + if existing_types is None: + existing_types = {} + anno.Static.CLOSURE_TYPES.add_to(ast_node, existing_types) + + for k, v in types.types.items(): + if k in existing_types: + existing_types[k].update(v) + else: + existing_types[k] = set(v) + + def visit_node(self, node): + prev_types_out = self.out[node] + + types_in = _TypeMap() + for n in node.prev: + types_in |= self.out[n] + if (self.context_types is not None) and (node is self.graph.entry): + types_in |= self.context_types + + types_out = _TypeMap(types_in) + ast_node = node.ast_node + + inferrer = StmtInferrer(self.resolver, self.scope, self.namespace, + self.closure_types, types_in) + inferrer.visit(ast_node) + types_out.types.update(inferrer.new_symbols) + + reaching_fndefs = anno.Static.DEFINED_FNS_IN.of(ast_node) + node_scope = anno.Static.SCOPE.of(ast_node, None) + if node_scope is not None: + # TODO(mdan): Check that it's actually safe to skip nodes without scope. + reads = {str(qn) for qn in node_scope.read} + for def_node in reaching_fndefs: + if def_node.name in reads: + self._update_closure_types(def_node, types_out) + + self.in_[node] = types_in + self.out[node] = types_out + + return prev_types_out != types_out + + +class FunctionVisitor(transformer.Base): + """AST visitor that applies type inference to each function separately.""" + + def __init__(self, source_info, graphs, resolver): + super(FunctionVisitor, self).__init__(source_info) + self.graphs = graphs + self.resolver = resolver + + def visit_FunctionDef(self, node): + subgraph = self.graphs[node] + scope = anno.getanno(node, annos.NodeAnno.ARGS_AND_BODY_SCOPE) + closure_types = anno.getanno(node, anno.Static.CLOSURE_TYPES, {}) + + analyzer = Analyzer(subgraph, self.resolver, self.ctx.info.namespace, scope, + closure_types) + analyzer.visit_forward() + + # Recursively process any remaining subfunctions. + node.body = self.visit_block(node.body) + + return node + + +def resolve(node, source_info, graphs, resolver): + """Performs type inference. + + Args: + node: ast.AST + source_info: transformer.SourceInfo + graphs: Dict[ast.FunctionDef, cfg.Graph] + resolver: Resolver + + Returns: + ast.AST + """ + visitor = FunctionVisitor(source_info, graphs, resolver) + node = visitor.visit(node) + return node diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/templates.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/templates.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4b589102254fe2f70a00140c40b0e683ecd6dd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/templates.py @@ -0,0 +1,290 @@ +# 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. +# ============================================================================== +"""AST conversion templates. + +Adapted from Tangent. +""" + +import ast +import textwrap + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import ast_util +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import qual_names + + +class ContextAdjuster(gast.NodeTransformer): + """Adjusts the ctx field of nodes to ensure consistency. + + This transformer can change the ctx fields of a variable, tuple and other + AST elements that allow one, based on whether the element is being read or + written. + """ + + def __init__(self, override_value): + self._ctx_override = override_value + + def visit(self, node): + original_override = self._ctx_override + node = super(ContextAdjuster, self).visit(node) + if hasattr(node, 'ctx'): + assert node.ctx is not None, 'node {} has ctx unset'.format(node) + self._ctx_override = original_override + return node + + def _apply_override(self, node): + if self._ctx_override is not None: + node.ctx = self._ctx_override() + + def visit_Attribute(self, node): + self._apply_override(node) + self._ctx_override = gast.Load + node = self.generic_visit(node) + return node + + def visit_Tuple(self, node): + self._apply_override(node) + return self.generic_visit(node) + + def visit_List(self, node): + self._apply_override(node) + return self.generic_visit(node) + + def visit_Name(self, node): + self._apply_override(node) + return self.generic_visit(node) + + def visit_Call(self, node): + self._apply_override(node) + # We may be able to override these to Load(), but for now it's simpler + # to just assert that they're set. + self._ctx_override = None + return self.generic_visit(node) + + def visit_Dict(self, node): + # We may be able to override these to Load(), but for now it's simpler + # to just assert that they're set. + self._ctx_override = None + return self.generic_visit(node) + + def visit_Subscript(self, node): + self._apply_override(node) + self._ctx_override = gast.Load + node.value = self.visit(node.value) + return self.generic_visit(node) + + def visit_comprehension(self, node): + # We may be able to override some of these, but for now it's simpler + # to just assert that they're set. + self._ctx_override = None + return self.generic_visit(node) + + def visit_Lambda(self, node): + # We may be able to override some of these, but for now it's simpler + # to just assert that they're set. + self._ctx_override = None + return self.generic_visit(node) + + +class ReplaceTransformer(gast.NodeTransformer): + """Replace AST nodes.""" + + def __init__(self, replacements): + """Create a new ReplaceTransformer. + + Args: + replacements: A mapping from placeholder names to (lists of) AST nodes + that these placeholders will be replaced by. + """ + self.replacements = replacements + self.in_replacements = False + self.preserved_annos = { + anno.Basic.DIRECTIVES, + anno.Basic.EXTRA_LOOP_TEST, + anno.Basic.ORIGIN, + anno.Basic.SKIP_PROCESSING, + anno.Static.ORIG_DEFINITIONS, + 'function_context_name', + } + + def _prepare_replacement(self, replaced, key): + """Prepares a replacement AST that's safe to swap in for a node. + + Args: + replaced: ast.AST, the node being replaced + key: Hashable, the key of the replacement AST + Returns: + ast.AST, the replacement AST + """ + repl = self.replacements[key] + + new_nodes = ast_util.copy_clean(repl, preserve_annos=self.preserved_annos) + if isinstance(new_nodes, gast.AST): + new_nodes = [new_nodes] + + return new_nodes + + def visit_Expr(self, node): + # When replacing a placeholder with an entire statement, the replacement + # must stand on its own and not be wrapped in an Expr. + new_value = self.visit(node.value) + if new_value is node.value: + return node + return new_value + + def visit_keyword(self, node): + if node.arg not in self.replacements: + return self.generic_visit(node) + + repl = self._prepare_replacement(node, node.arg) + if isinstance(repl, gast.keyword): + return repl + elif (repl and isinstance(repl, (list, tuple)) and + all(isinstance(r, gast.keyword) for r in repl)): + return repl + # TODO(mdan): We may allow replacing with a string as well. + # For example, if one wanted to replace foo with bar in foo=baz, then + # we could allow changing just node arg, so that we end up with bar=baz. + raise ValueError( + 'a keyword argument may only be replaced by another keyword or a ' + 'non-empty list of keywords. Found: {} for keyword {}'.format( + repl, node.arg)) + + def visit_FunctionDef(self, node): + node = self.generic_visit(node) + if node.name not in self.replacements: + return node + + repl = self.replacements[node.name] + if not isinstance(repl, (gast.Name, ast.Name)): + raise ValueError( + 'a function name can only be replaced by a Name node. Found: %s' % + repl) + node.name = repl.id + return node + + def visit_Attribute(self, node): + node = self.generic_visit(node) + if node.attr not in self.replacements: + return node + + repl = self.replacements[node.attr] + if not isinstance(repl, gast.Name): + raise ValueError( + 'An attribute can only be replaced by a Name node. Found: %s' % repl) + node.attr = repl.id + return node + + def visit_Name(self, node): + if node.id not in self.replacements: + return node + + new_nodes = self._prepare_replacement(node, node.id) + + if not new_nodes: + return new_nodes + + # Preserve the target context. + adjuster = ContextAdjuster(type(node.ctx)) + for n in new_nodes: + if hasattr(n, 'ctx'): + adjuster.visit(n) + + if len(new_nodes) == 1: + new_nodes, = new_nodes + + return new_nodes + + +def _convert_to_ast(n): + """Converts from a known data type to AST.""" + # Note: When generating AST nodes from strings/QNs in isolation, ctx is + # unknown. ctx must be filled in according to the template being used. + # See ReplaceTransformer.visit_Name. + if isinstance(n, str): + return gast.Name(id=n, ctx=None, annotation=None, type_comment=None) + if isinstance(n, qual_names.QN): + return n.ast() + if isinstance(n, list): + return [_convert_to_ast(e) for e in n] + if isinstance(n, tuple): + return tuple(_convert_to_ast(e) for e in n) + return n + + +def replace(template, **replacements): + """Replaces placeholders in a Python template. + + AST Name and Tuple nodes always receive the context that inferred from + the template. However, when replacing more complex nodes (that can potentially + contain Name children), then the caller is responsible for setting the + appropriate context. + + Args: + template: A string representing Python code. Any symbol name can be used + that appears in the template code can be used as placeholder. + **replacements: A mapping from placeholder names to (lists of) AST nodes + that these placeholders will be replaced by. String values are also + supported as a shorthand for AST Name nodes with the respective ID. + + Returns: + An AST node or list of AST nodes with the replacements made. If the + template was a function, a list will be returned. If the template was a + node, the same node will be returned. If the template was a string, an + AST node will be returned (a `Module` node in the case of a multi-line + string, an `Expr` node otherwise). + + Raises: + ValueError: if the arguments are incorrect. + """ + if not isinstance(template, str): + raise ValueError('Expected string template, got %s' % type(template)) + for k in replacements: + replacements[k] = _convert_to_ast(replacements[k]) + template_str = parser.STANDARD_PREAMBLE + textwrap.dedent(template) + nodes = parser.parse( + template_str, + preamble_len=parser.STANDARD_PREAMBLE_LEN, + single_node=False) + results = [] + for node in nodes: + node = ReplaceTransformer(replacements).visit(node) + if isinstance(node, (list, tuple)): + results.extend(node) + else: + results.append(node) + results = [qual_names.resolve(r) for r in results] + return results + + +def replace_as_expression(template, **replacements): + """Variant of replace that generates expressions, instead of code blocks.""" + replacement = replace(template, **replacements) + if len(replacement) != 1: + raise ValueError( + 'single expression expected; for more general templates use replace') + node, = replacement + + if isinstance(node, gast.Expr): + return node.value + elif isinstance(node, gast.Name): + return node + + raise ValueError( + 'the template is expected to generate an expression or a name node;' + ' instead found %s' % node) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/basic_definitions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/basic_definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..333b56ee889acfea889c11d55da2480938cd5b0d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/basic_definitions.py @@ -0,0 +1,65 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Module with basic entity definitions for testing.""" + + +def simple_function(x): + """Docstring.""" + return x # comment + + +def nested_functions(x): + """Docstring.""" + + def inner_fn(y): + return y + + return inner_fn(x) + + +def function_with_print(): + print('foo') + + +simple_lambda = lambda: None + + +class SimpleClass(object): + + def simple_method(self): + return self + + def method_with_print(self): + print('foo') + + +def function_with_multiline_call(x): + """Docstring.""" + return range( + x, + x + 1, + ) + + +def basic_decorator(f): + return f + + +@basic_decorator +@basic_decorator +def decorated_function(x): + if x > 0: + return 1 + return 2 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/decorators.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..332686aed472fc7a45c5879c226d51385bc90403 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/testing/decorators.py @@ -0,0 +1,46 @@ +# 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. +# ============================================================================== +"""Module with test decorators.""" + +import functools + + +def wrapping_decorator(f): + + @functools.wraps(f) + def wrapper(*args, **kwargs): + return f(*args, **kwargs) + + return wrapper + + +def standalone_decorator(f): + + def standalone_wrapper(*args, **kwargs): + return f(*args, **kwargs) + + return standalone_wrapper + + +def functional_decorator(): + + def decorator(f): + + def functional_wrapper(*args, **kwargs): + return f(*args, **kwargs) + + return functional_wrapper + + return decorator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/transformer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..c19009784a562031c30ae272bb0201b0b2cf73a1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/transformer.py @@ -0,0 +1,538 @@ +# 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 node transformer that includes utilities for SCT.""" + +import collections +import enum + +import gast + +from tensorflow.python.autograph.pyct import anno +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import pretty_printer +from tensorflow.python.autograph.pyct import templates + + +class AnalysisLevel(enum.IntEnum): + + NONE = 0 + ACTIVITY = 1 + DEFINEDNESS = 2 + LIVENESS = 3 + + +# TODO(znado): Use namedtuple. +class Context(object): + """Contains information about a source code transformation. + + This object is mutable, and is updated during conversion. Not thread safe. + + Attributes: + info: EntityInfo, immutable. + namer: naming.Namer. + current_origin: origin_info.OriginInfo, holds the OriginInfo of the last + AST node to be processed successfully. Useful for error handling. + user: An user-supplied context object. The object is opaque to the + infrastructure, but will pe passed through to all custom transformations. + """ + + def __init__(self, info, namer, user_context): + self.info = info + self.namer = namer + self.current_origin = None + self.user = user_context + + +# TODO(mdan): Move to a standalone file. +class EntityInfo( + collections.namedtuple( + 'EntityInfo', + ('name', 'source_code', 'source_file', 'future_features', 'namespace')) +): + """Contains information about a Python entity. + + Immutable. + + Examples of entities include functions and classes. + + Attributes: + name: The name that identifies this entity. + source_code: The entity's source code. + source_file: The entity's source file. + future_features: Tuple[Text], the future features that this entity was + compiled with. See + https://docs.python.org/2/reference/simple_stmts.html#future. + namespace: Dict[str, ], containing symbols visible to the entity (excluding + parameters). + """ + pass + + +class _StateStack(object): + """Templated context manager. + + This class provides syntactic sugar for a stack of objects of known + type. It allows accessing attributes of the object at the top of the stack + directly against this object, which allows for very terse syntax. + + For example, this code: + + stack = _StateStack(Foo) + stack.enter() + stack.bar + + Is equivalent to: + + stack = [] + stack.append(Foo()) + foo = stack[-1] + foo.bar + + See _State for more on how this is used. + + Attributes: + type: Any, the type of objects that this stack holds + level: int, the current stack depth + stack: List[Any], the actual stack + value: Any, the instance of the object at the top of the stack + """ + + def __init__(self, type_): + # Because we override __setattr__, we need to attach these attributes using + # the superclass' setattr. + object.__setattr__(self, 'type', type_) + object.__setattr__(self, '_stack', []) + if not hasattr(type_, 'no_root'): + self.enter() + + def __enter__(self): + self.enter() + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.exit() + + def enter(self): + self._stack.append(self.type()) + + def exit(self): + self._stack.pop() + + @property + def stack(self): + return self._stack + + @property + def level(self): + return len(self._stack) + + @property + def value(self): + return self._stack[-1] + + def __iter__(self): + return iter(self._stack) + + def __getattr__(self, key): + return getattr(self._stack[-1], key) + + def __setattr__(self, key, value): + setattr(self._stack[-1], key, value) + + +class _State(object): + """Syntactic sugar for accessing an instance of a StateStack context manager. + + This structure offers syntactic sugar over a dict of stacks of objects + of known type. These structures are useful to keep state during AST walks. + Multiple different scopes can be tracked in parallel. For example: + + s = _State() + + s[foo].enter() + s[bar].enter() # this will not affect s[foo] + + Element access has special semantics: + * keys are a data type + * element values are _StateStack(type=key) objects + * missing elements are automatically added, similarly to defaultdict + + For example, the following block : + + _State s + s[Foo] + + Is equivalent to: + + s = {} + if Foo not in s: + s[Foo] = Foo() + s[Foo] + + See Base for how it's used. + """ + + def __init__(self): + self._value = {} + + def __getitem__(self, key): + if key not in self._value: + self._value[key] = _StateStack(key) + return self._value[key] + + +class NodeStateTracker(object): + """Base class for general-purpose Python code transformation. + + This abstract class provides helpful functions, like state tracking within + the scope of arbitrary node, helpers for processing code blocks, debugging, + mapping of transformed code to original code, and others. + + Scope-local state tracking: to keep state across nodes, at the level of + (possibly nested) scopes, use enter/exit_local_scope and set/get_local. + You must call enter/exit_local_scope manually, but the transformer detects + when they are not properly paired. + + The transformer allows keeping state across calls that is local + to arbitrary nodes and their descendants, using the self.state attribute. + Multiple independent scopes are allowed and automatically constructed. + + For example, to keep track of the `If` node that encloses any `Name` node, + one can write: + + ``` + class FooType(object): + + def __init__(self): + self.foo_property = None + + class DummyTransformer(NodeStateTracker, ast.NodeTransformer): + + def visit_If(self, node): + self.state[FooType].enter() + self.state[FooType].foo_property = node + node = self.veneric_visit(node) + self.state[FooType].exit() + return node + + def visit_Name(self, node): + self.state[FooType].foo_property # will hold the innermost enclosing if + ``` + + Alternatively, the `enter()`/`exit()` calls can be managed by a `with` + statement: + + ``` + def visit_If(self, node): + with self.state[FooType] as foo: + foo.foo_property = node + return self.generic_visit(node) + ``` + """ + + # TODO(mdan): Document all extra features. + + def __init__(self, ctx): + """Initialize the transformer. + + Subclasses should call this. + + Args: + ctx: A Context object. + """ + self._lineno = 0 + self._col_offset = 0 + self.ctx = ctx + + # Allows scoping of local variables to keep state across calls to visit_* + # methods. Multiple scope hierarchies may exist and are keyed by tag. A + # scope is valid at one or more nodes and all its children. Scopes created + # in child nodes supersede their parent. Scopes are isolated from one + # another. + self.state = _State() + + def debug_print(self, node): + """Helper method useful for debugging. Prints the AST.""" + if __debug__: + print(pretty_printer.fmt(node)) + return node + + def debug_print_src(self, node): + """Helper method useful for debugging. Prints the AST as code.""" + if __debug__: + print(parser.unparse(node)) + return node + + def visit_block(self, nodes, before_visit=None, after_visit=None): + """A more powerful version of generic_visit for statement blocks. + + An example of a block is the body of an if statement. + + This function allows specifying a postprocessing callback (the + after_visit argument) argument which can be used to move nodes to a new + destination. This is done by after_visit by returning a non-null + second return value, e.g. return new_node, new_destination. + + For example, a transformer could perform the following move: + + foo() + bar() + baz() + + foo() + if cond: + bar() + baz() + + The above could be done with a postprocessor of this kind: + + def after_visit(node): + if node_is_function_call(bar): + new_container_node = build_cond() + new_container_node.body.append(node) + return new_container_node, new_container_node.body + else: + # Once we set a new destination, all subsequent items will be + # moved to it, so we don't need to explicitly handle baz. + return node, None + + Args: + nodes: enumerable of AST node objects. If None, the function returns None. + before_visit: optional callable that is called before visiting each item + in nodes + after_visit: optional callable that takes in an AST node and returns a + tuple (new_node, new_destination). It is called after visiting each item + in nodes. Is used in the same was as the + visit_* methods: new_node will replace the node; if not None, + new_destination must be a list, and subsequent nodes will be placed + in this list instead of the list returned by visit_block. + + Returns: + A list of AST node objects containing the transformed items fron nodes, + except those nodes that have been relocated using after_visit. + """ + if nodes is None: + return None + + results = [] + node_destination = results + for node in nodes: + if before_visit: + # TODO(mdan): We can modify node here too, if ever needed. + before_visit() + + replacement = self.visit(node) + + if after_visit and replacement: + replacement, new_destination = after_visit(replacement) + else: + new_destination = None + + if replacement: + if isinstance(replacement, (list, tuple)): + node_destination.extend(replacement) + else: + node_destination.append(replacement) + + # Allow the postprocessor to reroute the remaining nodes to a new list. + if new_destination is not None: + node_destination = new_destination + return results + + +# TODO(mdan): Rename to PythonCodeTransformer. +class Base(NodeStateTracker, gast.NodeTransformer): + """Base class for general-purpose Python-to-Python code transformation. + + This is an extension of ast.NodeTransformer that provides the additional + functions offered by NodeStateTracker. + """ + + def create_assignment(self, target, expression): + template = """ + target = expression + """ + return templates.replace(template, target=target, expression=expression) + + # TODO(mdan): Remove. + def apply_to_single_assignments(self, targets, values, apply_fn): + """Applies a function to each individual assignment. + + This function can process a possibly-unpacked (e.g. a, b = c, d) assignment. + It tries to break down the unpacking if possible. In effect, it has the same + effect as passing the assigned values in SSA form to apply_fn. + + Examples: + + The following will result in apply_fn(a, c), apply_fn(b, d): + + a, b = c, d + + The following will result in apply_fn(a, c[0]), apply_fn(b, c[1]): + + a, b = c + + The following will result in apply_fn(a, (b, c)): + + a = b, c + + It uses the visitor pattern to allow subclasses to process single + assignments individually. + + Args: + targets: list, tuple of or individual AST node. Should be used with the + targets field of an ast.Assign node. + values: an AST node. + apply_fn: a function of a single argument, which will be called with the + respective nodes of each single assignment. The signature is + apply_fn(target, value), no return value. + """ + if not isinstance(targets, (list, tuple)): + targets = (targets,) + for target in targets: + if isinstance(target, (gast.Tuple, gast.List)): + for i in range(len(target.elts)): + target_el = target.elts[i] + if isinstance(values, (gast.Tuple, gast.List)): + value_el = values.elts[i] + else: + value_el = gast.Subscript(values, i, ctx=gast.Store()) + self.apply_to_single_assignments(target_el, value_el, apply_fn) + else: + # TODO(mdan): Look into allowing to rewrite the AST here. + apply_fn(target, values) + + def visit(self, node): + if not isinstance(node, gast.AST): + # This is not that uncommon a mistake: various node bodies are lists, for + # example, posing a land mine for transformers that need to recursively + # call `visit`. The error needs to be raised before the exception handler + # below is installed, because said handler will mess up if `node` is not, + # in fact, a node. + msg = ('invalid value for "node": expected "ast.AST", got "{}"; to' + ' visit lists of nodes, use "visit_block" instead').format( + type(node)) + raise ValueError(msg) + + if anno.hasanno(node, anno.Basic.SKIP_PROCESSING): + return node + + parent_origin = self.ctx.current_origin + if anno.hasanno(node, anno.Basic.ORIGIN): + self.ctx.current_origin = anno.getanno(node, anno.Basic.ORIGIN) + + try: + processing_expr_node = isinstance(node, gast.Expr) + if processing_expr_node: + entry_expr_value = node.value + + result = super(Base, self).visit(node) + + # Adjust for consistency: replacing the value of an Expr with + # an Assign node removes the need for the Expr node. + if (processing_expr_node and isinstance(result, gast.Expr) and + (result.value is not entry_expr_value)): + # When the replacement is a list, it is assumed that the list came + # from a template that contained a number of statements, which + # themselves are standalone and don't require an enclosing Expr. + if isinstance(result.value, + (list, tuple, gast.Assign, gast.AugAssign)): + result = result.value + + # By default, all replacements receive the origin info of the replaced + # node. + if result is not node and result is not None: + inherited_origin = anno.getanno( + node, anno.Basic.ORIGIN, default=parent_origin) + if inherited_origin is not None: + nodes_to_adjust = result + if isinstance(result, (list, tuple)): + nodes_to_adjust = result + else: + nodes_to_adjust = (result,) + for n in nodes_to_adjust: + if not anno.hasanno(n, anno.Basic.ORIGIN): + anno.setanno(n, anno.Basic.ORIGIN, inherited_origin) + finally: + self.ctx.current_origin = parent_origin + + return result + + +class CodeGenerator(NodeStateTracker, gast.NodeVisitor): + """Base class for general-purpose Python-to-string code transformation. + + Similar to Base, but outputs arbitrary strings instead of a Python AST. + + This uses the same visitor mechanism that the standard NodeVisitor uses, + meaning that subclasses write handlers for the different kinds of nodes. + New code is generated using the emit method, which appends to a code buffer + that can be afterwards obtained from code_buffer. + + Example: + + class SimpleCodeGen(CodeGenerator): + + def visitIf(self, node): + self.emit('if ') + self.visit(node.test) + self.emit(' { ') + self.visit(node.body) + self.emit(' } else { ') + self.visit(node.orelse) + self.emit(' } ') + + node = ast.parse(...) + gen = SimpleCodeGen() + gen.visit(node) + # gen.code_buffer contains the resulting code + """ + + def __init__(self, ctx): + super(CodeGenerator, self).__init__(ctx) + + self._output_code = '' + self.source_map = {} + + def emit(self, code): + self._output_code += code + + @property + def code_buffer(self): + return self._output_code + + def visit(self, node): + if anno.hasanno(node, anno.Basic.SKIP_PROCESSING): + return + + parent_origin = self.ctx.current_origin + eof_before = len(self._output_code) + if anno.hasanno(node, anno.Basic.ORIGIN): + self.ctx.current_origin = anno.getanno(node, anno.Basic.ORIGIN) + + try: + ret = super(CodeGenerator, self).visit(node) + + # By default, all replacements receive the origin info of the replaced + # node. + eof_after = len(self._output_code) + if eof_before - eof_after: + inherited_origin = anno.getanno( + node, anno.Basic.ORIGIN, default=parent_origin) + if inherited_origin is not None: + self.source_map[(eof_before, eof_after)] = inherited_origin + return ret + finally: + self.ctx.current_origin = parent_origin diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/transpiler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/transpiler.py new file mode 100644 index 0000000000000000000000000000000000000000..013ccc562aab7288839c5b33faeba1e1a1eaabd8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/pyct/transpiler.py @@ -0,0 +1,495 @@ +# 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. +# ============================================================================== +"""Generic source code transformation infrastructure.""" + +import inspect +import threading +import types + +import gast + +from tensorflow.python.autograph.pyct import cache +from tensorflow.python.autograph.pyct import inspect_utils +from tensorflow.python.autograph.pyct import loader +from tensorflow.python.autograph.pyct import naming +from tensorflow.python.autograph.pyct import origin_info +from tensorflow.python.autograph.pyct import parser +from tensorflow.python.autograph.pyct import templates +from tensorflow.python.autograph.pyct import transformer +from tensorflow.python.autograph.utils import ag_logging as logging + + +def _wrap_into_factory(nodes, entity_name, inner_factory_name, + outer_factory_name, closure_vars, factory_args, + future_features): + """Wraps an AST into the body of a factory with consistent lexical context. + + The AST is expected to define some symbol with a name given by `entity_name`. + + This mechanism ensures that the resulting transformed entity has lexical + scoping identical to that of the source entity, while allowing extra + parametrization. + + Two nested factories achieve the following: + + 1. The inner factory dynamically creates the entity represented by `nodes`. + 2. The inner factory is parametrized by a custom set of arguments. + 3. The inner factory has a closure identical to that of the transformed + entity. + 4. The inner factory has local variables named like `args`, which `nodes` may + use as additional parameters. + 5. The inner factory returns the variables given by `entity_name`. + 6. The outer factory is niladic. + 7. The outer factory has no closure. + 8. The outer factory creates the necessary lexical scope for the inner + factory, so that the loaded code has the given configuration for + closure/globals. + 9. The outer factory returns the inner factory. + + Roughly speaking, the following code is generated: + + from __future__ import future_feature_1 + from __future__ import future_feature_2 + ... + + def outer_factory(): + closure_var_1 = None + closure_var_2 = None + ... + + def inner_factory(arg_1, arg_2, ...): + <> + return entity + + return inner_factory + + The lexical scoping is created using dummy symbol declarations which create + local variables in the body of the outer factory, so that the Python parser + correctly marks them as free non-global variables upon load (that is, it + creates cell slots for each symbol. These symbols are initialized with None, + but their values are not expected to be used; instead, the caller is expected + to replace them with the cells of the source entity. For more details, see: + https://docs.python.org/3/reference/executionmodel.html#binding-of-names + + Args: + nodes: Tuple[ast.AST], the source code to wrap. + entity_name: Union[Text, ast.AST], the name of the principal entity that + `nodes` define. + inner_factory_name: Text, the name of the inner factory. + outer_factory_name: Text, the name of the outer factory. + closure_vars: Iterable[Text], names of the closure variables for the inner + factory. + factory_args: Iterable[Text], names of additional arguments for the + inner factory. Useful to configure variables that the converted code can + use. Typically, these are modules. + future_features: Iterable[Text], names of future statements to associate the + code with. + + Returns: + ast.AST + """ + dummy_closure_defs = [] + for var_name in closure_vars: + template = """ + var_name = None + """ + dummy_closure_defs.extend(templates.replace(template, var_name=var_name)) + + if future_features: + future_imports = gast.ImportFrom( + module='__future__', + names=[gast.alias(name=name, asname=None) for name in future_features], + level=0) + else: + future_imports = [] + + factory_args = [ + gast.Name(name, ctx=gast.Param(), annotation=None, type_comment=None) + for name in factory_args + ] + + template = """ + future_imports + def outer_factory_name(): + dummy_closure_defs + def inner_factory_name(factory_args): + entity_defs + return entity_name + return inner_factory_name + """ + return templates.replace( + template, + dummy_closure_defs=dummy_closure_defs, + entity_defs=nodes, + entity_name=entity_name, + factory_args=factory_args, + future_imports=future_imports, + inner_factory_name=inner_factory_name, + outer_factory_name=outer_factory_name) + + +class _PythonFnFactory(object): + """Helper object that wraps a Python function factory.""" + + def __init__(self, name, freevars, extra_locals): + """Creates a new factory for a Python function. + + Args: + name: The function name. + freevars: The list of non-global free variables for the function. + extra_locals: Dict[Text, Any], names and values for custom variables that + are accessible to the generated code as local variables. + """ + self._name = name + self._freevars = freevars + self._extra_locals = extra_locals + + self._unbound_factory = None + self.module = None + self.source_map = None + + def create(self, + nodes, + namer, + inner_factory_name='inner_factory', + outer_factory_name='outer_factory', + future_features=()): + """Initializes a function.""" + if self._unbound_factory is not None: + raise ValueError('double initialization; create a new object instead') + + inner_factory_name = namer.new_symbol(inner_factory_name, ()) + outer_factory_name = namer.new_symbol(outer_factory_name, ()) + nodes = _wrap_into_factory(nodes, self._name, inner_factory_name, + outer_factory_name, self._freevars, + self._extra_locals.keys(), future_features) + + module, _, source_map = loader.load_ast( + nodes, include_source_map=True) + outer_factory = getattr(module, outer_factory_name) + self._unbound_factory = outer_factory() + self.module = module + self.source_map = source_map + + def instantiate(self, + globals_, + closure, + defaults=None, + kwdefaults=None): + """Creates a new function instance.""" + if self._unbound_factory is None: + raise ValueError('call create first') + + factory_code = self._unbound_factory.__code__ + factory_freevars = factory_code.co_freevars + closure_map = dict(zip(self._freevars, closure)) + factory_closure = tuple( + closure_map[name] for name in factory_code.co_freevars) + if len(factory_closure) != len(closure): + raise ValueError( + 'closure mismatch, requested {}, but source function had {}'.format( + self._freevars, factory_freevars)) + + bound_factory = types.FunctionType( + code=factory_code, + globals=globals_, + name=self._name, + argdefs=(), + closure=factory_closure) + + # The lint override is a false positive. + new_fn = bound_factory(**self._extra_locals) # pylint:disable=not-callable + + if defaults: + new_fn.__defaults__ = defaults + if kwdefaults: + new_fn.__kwdefaults__ = kwdefaults + + return new_fn + + +class GenericTranspiler(object): + """A generic transpiler for Python functions. + + Its interface is the `transform` API, which can process Python function + objects. Internally, it handles parsing. + + Users typically subclass this, customizing the `transform_ast` method. The + output of transformed_ast is returned directly by `transform`. Existing + methods like `transform_function` may also be overloaded. + + Example: + + class MyTransformer(GenericTranspiler): + + def transform_ast(self, node, ctx): + result = <> + return result + + transformer = MyTransfomer() + + result = transformer.transform(f, ...) + # result is the output + """ + + def get_transformed_name(self, node): + """Returns a name for the output function. Subclasses may override this.""" + if isinstance(node, gast.Lambda): + return 'lam' + elif isinstance(node, gast.FunctionDef): + return node.name + raise ValueError('Unknown node type {}'.format(node)) + + def transform_ast(self, node, ctx): + """Performs an actual transformation of a function's AST. + + Subclasses must implement this method, and do not usually call it. + + Args: + node: One or more ast.AST nodes representing the AST to be transformed. + ctx: transformer.Context. + """ + raise NotImplementedError('subclasses must override this') + + def transform(self, obj, user_context): + """Transforms a Python object. + + Users typically call this method. + + Args: + obj: A Python object, function, type, etc. + user_context: An opaque object (may be None) that is forwarded to + transform_ast, through the ctx.user attribute. + Returns: + The result of calling transform_function. + + Raises: + NotImplementedError: if the type of obj is not handled. + """ + if inspect.isfunction(obj) or inspect.ismethod(obj): + return self.transform_function(obj, user_context) + + raise NotImplementedError('Non-function: {}'.format(type(obj))) + + def _erase_arg_defaults(self, node): + """Erase arg default expressions, which would otherwise be unbound.""" + args = node.args + for i in range(len(args.defaults)): + args.defaults[i] = parser.parse_expression('None') + for i, d in enumerate(args.kw_defaults): + if d is not None: + args.kw_defaults[i] = parser.parse_expression('None') + return node + + def transform_module(self, mod, user_context): + """Transforms a module. + + Subclasses may override this method. The return value is opaque. + + The method receives the original AST. The result is passed as-is to the + output of `transform`. + + Args: + mod: A Python module. + user_context: An opaque object (may be None) that is forwarded to + transform_ast, through the ctx.user attribute. + Returns: + List[Tuple[Any, Any]]. By default it returns the output of transform_ast, + evaluated on each supported member, other than modules, together with a + `transformer.Context` containing information about the transformation + process. + """ + result = [] + for member in mod.__dict__.values(): + if inspect.ismodule(member): + continue # Not transforming modules recursively. + try: + result.append(self.transform(member, user_context)) + except NotImplementedError: + pass # Skip unsupported elements. + return result + + def transform_function(self, fn, user_context): + """Transforms a function. + + Subclasses may override this method. The return value is opaque. + + The method receives the original AST. The result is passed as-is to the + output of `transform`. + + Args: + fn: A function or lambda. + user_context: An opaque object (may be None) that is forwarded to + transform_ast, through the ctx.user attribute. + Returns: + Tuple[Any, Any]. By default it returns the output of transform_ast, + together with a `transformer.Context` containing information about the + transformation process. + """ + future_features = inspect_utils.getfutureimports(fn) + node, source = parser.parse_entity(fn, future_features=future_features) + logging.log(3, 'Source code of %s:\n\n%s\n', fn, source) + + origin_info.resolve_entity(node, source, fn) + + namespace = inspect_utils.getnamespace(fn) + namer = naming.Namer(namespace) + new_name = namer.new_symbol(self.get_transformed_name(node), ()) + entity_info = transformer.EntityInfo( + name=new_name, + source_code=source, + source_file='', + future_features=future_features, + namespace=namespace) + context = transformer.Context(entity_info, namer, user_context) + + node = self._erase_arg_defaults(node) + result = self.transform_ast(node, context) + + return result, context + + +class PyToPy(GenericTranspiler): + """A generic Python-to-Python transpiler. + + Its `transform` method offers a function-in, function-out interface. + Internally, it takes care of parsing, caching and loading of the translated + code. + + Users typically subclass this, overriding `transform_ast`. + + Usually, instances of this class are singletons, since each instance manages + its own cache. The caching can be controlled by overriding `get_caching_key`. + + Example: + + class MyTransformer(PyToPy): + + def transform_ast(self, node, ctx): + node = <> + return node + + transformer = MyTransfomer() + + new_f, module, source_map = transformer.transform_function(f, ...) + # new_f is a function with signature identical to f + + The transformed function has access to the same namespace as the original + function. To allow access to internal APIs, users may inject additional + symbols by overriding `get_extra_locals`. + """ + + def __init__(self): + self._cache_lock = threading.RLock() + self._cache = cache.CodeObjectCache() + + def get_extra_locals(self): + """Returns extra static local variables to be made to transformed code. + + Subclasses must override this. + + Returns: + extra_locals: A Dict[Text, Any] containing additional variables to make + available to the transformed code. + """ + raise NotImplementedError('subclasses must override this') + + def get_caching_key(self, user_context): + """Returns a unique key to use for caching. + + Subclasses must override this. + + Calls made to `transform_function` with functions that have the same code + object and caching key will return a cached instance on subsequent + invocations. + + Args: + user_context: The context object which was passed to `transform`. + + Returns: + extra_locals: A hashable. + """ + raise NotImplementedError('subclasses must override this') + + def _cached_factory(self, fn, cache_subkey): + cached_factory = self._cache[fn][cache_subkey] + logging.log(3, 'Cache hit for %s subkey %s: %s', fn, cache_subkey, + cached_factory) + return cached_factory + + def transform_function(self, fn, user_context): + """Transforms a function. See GenericTranspiler.trasnform_function. + + This overload wraps the parent's `transform_function`, adding caching and + facilities to instantiate the output as a Python object. It also + adds facilities to make new symbols available to the generated Python code, + visible as local variables - see `get_extra_locals`. + + Args: + fn: A function or lambda. + user_context: An opaque object (may be None) that is forwarded to + transform_ast, through the ctx.user attribute. + Returns: + A tuple: + * A function or lambda with the same signature and closure as `fn` + * The temporary module into which the transformed function was loaded + * The source map as a + Dict[origin_info.LineLocation, origin_info.OriginInfo] + """ + cache_subkey = self.get_caching_key(user_context) + + if self._cache.has(fn, cache_subkey): + # Fast path: use a lock-free check. + factory = self._cached_factory(fn, cache_subkey) + + else: + with self._cache_lock: + # Check again under lock. + if self._cache.has(fn, cache_subkey): + factory = self._cached_factory(fn, cache_subkey) + + else: + logging.log(1, '%s is not cached for subkey %s', fn, cache_subkey) + # TODO(mdan): Confusing overloading pattern. Fix. + nodes, ctx = super(PyToPy, self).transform_function(fn, user_context) + + if isinstance(nodes, gast.Lambda): + nodes = gast.Assign( + targets=[ + gast.Name( + ctx.info.name, + ctx=gast.Store(), + annotation=None, + type_comment=None) + ], + value=nodes) + else: + nodes.name = ctx.info.name + + if logging.has_verbosity(2): + logging.log(2, 'Transformed %s:\n\n%s\n', fn, parser.unparse(nodes)) + + factory = _PythonFnFactory( + ctx.info.name, fn.__code__.co_freevars, self.get_extra_locals()) + factory.create( + nodes, ctx.namer, future_features=ctx.info.future_features) + self._cache[fn][cache_subkey] = factory + + transformed_fn = factory.instantiate( + globals_=fn.__globals__, + closure=fn.__closure__ or (), + defaults=fn.__defaults__, + kwdefaults=getattr(fn, '__kwdefaults__', None)) + return transformed_fn, factory.module, factory.source_map diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e35229464f75b8c33887697435ef60ed05066f1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/__init__.py @@ -0,0 +1,19 @@ +# 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. +# ============================================================================== +"""Utility module that contains APIs usable in the generated code.""" + +from tensorflow.python.autograph.utils.context_managers import control_dependency_on_returns +from tensorflow.python.autograph.utils.misc import alias_tensors +from tensorflow.python.autograph.utils.tensor_list import dynamic_list_append diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/ag_logging.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/ag_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..dd26223d1e9d79a62aed61ff047e5da0b3328e57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/ag_logging.py @@ -0,0 +1,145 @@ +# 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. +# ============================================================================== +"""Logging and debugging utilities.""" + +import os +import sys +import traceback + +# TODO(mdan): Use a custom logger class. +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util.tf_export import tf_export + +VERBOSITY_VAR_NAME = 'AUTOGRAPH_VERBOSITY' +DEFAULT_VERBOSITY = 0 + +verbosity_level = None # vlog-like. Takes precedence over the env variable. +echo_log_to_stdout = False + +# In interactive Python, logging echo is enabled by default. +if hasattr(sys, 'ps1') or hasattr(sys, 'ps2'): + echo_log_to_stdout = True + + +@tf_export('autograph.set_verbosity') +def set_verbosity(level, alsologtostdout=False): + """Sets the AutoGraph verbosity level. + + _Debug logging in AutoGraph_ + + More verbose logging is useful to enable when filing bug reports or doing + more in-depth debugging. + + There are two means to control the logging verbosity: + + * The `set_verbosity` function + + * The `AUTOGRAPH_VERBOSITY` environment variable + + `set_verbosity` takes precedence over the environment variable. + + For example: + + ```python + import os + import tensorflow as tf + + os.environ['AUTOGRAPH_VERBOSITY'] = '5' + # Verbosity is now 5 + + tf.autograph.set_verbosity(0) + # Verbosity is now 0 + + os.environ['AUTOGRAPH_VERBOSITY'] = '1' + # No effect, because set_verbosity was already called. + ``` + + Logs entries are output to [absl](https://abseil.io)'s + [default output](https://abseil.io/docs/python/guides/logging), + with `INFO` level. + Logs can be mirrored to stdout by using the `alsologtostdout` argument. + Mirroring is enabled by default when Python runs in interactive mode. + + Args: + level: int, the verbosity level; larger values specify increased verbosity; + 0 means no logging. When reporting bugs, it is recommended to set this + value to a larger number, like 10. + alsologtostdout: bool, whether to also output log messages to `sys.stdout`. + """ + global verbosity_level + global echo_log_to_stdout + verbosity_level = level + echo_log_to_stdout = alsologtostdout + + +@tf_export('autograph.trace') +def trace(*args): + """Traces argument information at compilation time. + + `trace` is useful when debugging, and it always executes during the tracing + phase, that is, when the TF graph is constructed. + + _Example usage_ + + ```python + import tensorflow as tf + + for i in tf.range(10): + tf.autograph.trace(i) + # Output: + ``` + + Args: + *args: Arguments to print to `sys.stdout`. + """ + print(*args) + + +def get_verbosity(): + global verbosity_level + if verbosity_level is not None: + return verbosity_level + return int(os.getenv(VERBOSITY_VAR_NAME, DEFAULT_VERBOSITY)) + + +def has_verbosity(level): + return get_verbosity() >= level + + +def _output_to_stdout(msg, *args, **kwargs): + print(msg % args) + if kwargs.get('exc_info', False): + traceback.print_exc() + + +def error(level, msg, *args, **kwargs): + if has_verbosity(level): + logging.error(msg, *args, **kwargs) + if echo_log_to_stdout: + _output_to_stdout('ERROR: ' + msg, *args, **kwargs) + + +def log(level, msg, *args, **kwargs): + if has_verbosity(level): + logging.info(msg, *args, **kwargs) + if echo_log_to_stdout: + _output_to_stdout(msg, *args, **kwargs) + + +def warning(msg, *args, **kwargs): + logging.warning(msg, *args, **kwargs) + if echo_log_to_stdout: + _output_to_stdout('WARNING: ' + msg, *args, **kwargs) + sys.stdout.flush() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/context_managers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/context_managers.py new file mode 100644 index 0000000000000000000000000000000000000000..ada33aed15842a19ab822f240b53dbbbd89ef6db --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/context_managers.py @@ -0,0 +1,45 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Various context managers.""" + +import contextlib + +from tensorflow.python.framework import ops +from tensorflow.python.ops import tensor_array_ops + + +def control_dependency_on_returns(return_value): + """Create a TF control dependency on the return values of a function. + + If the function had no return value, a no-op context is returned. + + Args: + return_value: The return value to set as control dependency. + + Returns: + A context manager. + """ + def control_dependency_handle(t): + if isinstance(t, tensor_array_ops.TensorArray): + return t.flow + return t + + if return_value is None: + return contextlib.contextmanager(lambda: (yield))() + # TODO(mdan): Filter to tensor objects. + if not isinstance(return_value, (list, tuple)): + return_value = (return_value,) + return_value = tuple(control_dependency_handle(t) for t in return_value) + return ops.control_dependencies(return_value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/misc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..d14b4758aba03f4300a6109a8da21681ce75292b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/misc.py @@ -0,0 +1,59 @@ +# 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. +# ============================================================================== +"""Miscellaneous utilities that don't fit anywhere else.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops + + +def alias_tensors(*args): + """Wraps any Tensor arguments with an identity op. + + Any other argument, including Variables, is returned unchanged. + + Args: + *args: Any arguments. Must contain at least one element. + + Returns: + Same as *args, with Tensor instances replaced as described. + + Raises: + ValueError: If args doesn't meet the requirements. + """ + + def alias_if_tensor(a): + return array_ops.identity(a) if isinstance(a, tensor.Tensor) else a + + # TODO(mdan): Recurse into containers? + # TODO(mdan): Anything we can do about variables? Fake a scope reuse? + if len(args) > 1: + return (alias_if_tensor(a) for a in args) + elif len(args) == 1: + return alias_if_tensor(args[0]) + + raise ValueError('at least one argument required') + + +def get_range_len(start, limit, delta): + dist = ops.convert_to_tensor(limit - start) + unadjusted_len = dist // delta + adjustment = math_ops.cast( + gen_math_ops.not_equal(dist % delta, + array_ops.zeros_like(unadjusted_len)), dist.dtype) + final_len = unadjusted_len + adjustment + return gen_math_ops.maximum(final_len, array_ops.zeros_like(final_len)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/tensor_list.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/tensor_list.py new file mode 100644 index 0000000000000000000000000000000000000000..c8bdf3ae982982d33c6dd3c901dbeb2a67cb1ba2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/tensor_list.py @@ -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. +# ============================================================================== +"""A typed list in Python.""" + +from tensorflow.python.framework import tensor +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import tensor_array_ops + + +def dynamic_list_append(target, element): + """Converts a list append call inline.""" + if isinstance(target, tensor_array_ops.TensorArray): + return target.write(target.size(), element) + # TODO(mdan): What's the right way to check this? + # TODO(mdan): We may not need this branch. + # It may be possible to use TensorList alone if the loop body will not + # require wrapping it, although we'd have to think about an autoboxing + # mechanism for lists received as parameter. + if isinstance(target, tensor.Tensor): + return list_ops.tensor_list_push_back(target, element) + + # Python targets (including TensorList): fallback to their original append. + target.append(element) + return target + + +class TensorList(object): + """Tensor list wrapper API-compatible with Python built-in list.""" + + def __init__(self, shape, dtype): + self.dtype = dtype + self.shape = shape + self.clear() + + def append(self, value): + self.list_ = list_ops.tensor_list_push_back(self.list_, value) + + def pop(self): + self.list_, value = list_ops.tensor_list_pop_back(self.list_, self.dtype) + return value + + def clear(self): + self.list_ = list_ops.empty_tensor_list(self.shape, self.dtype) + + def count(self): + return list_ops.tensor_list_length(self.list_) + + def __getitem__(self, key): + return list_ops.tensor_list_get_item(self.list_, key, self.dtype) + + def __setitem__(self, key, value): + self.list_ = list_ops.tensor_list_set_item(self.list_, key, value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/tensors.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..0868977844783cf605ce7a7e2dff0988257d5f6b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/tensors.py @@ -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. +# ============================================================================== +"""This module defines tensor utilities not found in TensorFlow. + +The reason these utilities are not defined in TensorFlow is because they may +not be not fully robust, although they work in the vast majority of cases. So +we define them here in order for their behavior to be consistently verified. +""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import tensor_array_ops + + +def is_dense_tensor(t): + # TODO(mdan): Resolve this inconsistency. + return (tensor_util.is_tf_type(t) and + not isinstance(t, sparse_tensor.SparseTensor)) + + +def is_tensor_array(t): + return isinstance(t, tensor_array_ops.TensorArray) + + +def is_tensor_list(t): + # TODO(mdan): This is just a heuristic. + # With TF lacking support for templated types, this is unfortunately the + # closest we can get right now. A dedicated op ought to be possible to + # construct. + return (tensor_util.is_tf_type(t) and t.dtype == dtypes.variant and + not t.shape.ndims) + + +def is_range_tensor(t): + """Returns True if a tensor is the result of a tf.range op. Best effort.""" + return tensor_util.is_tf_type(t) and hasattr(t, 'op') and t.op.type == 'Range' diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/testing.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..2c624ee653c52fb34b0c06766ac015644a5651d4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/testing.py @@ -0,0 +1,168 @@ +# 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. +# ============================================================================== +"""Testing utilities.""" + +import re +import sys +import types +import unittest + +from tensorflow.python.eager import def_function +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +class AutoGraphTestCase(test.TestCase): + """Tests specialized for AutoGraph, which run as tf.functions. + + These tests use a staged programming-like approach: most of the test code runs + as-is inside a tf.function, but the assertions are lifted outside the + function, and run with the corresponding function values instead. + + For example, the test: + + def test_foo(self): + baz = bar(); + self.assertEqual(baz, value) + + is equivalent to writing: + + def test_foo(self): + @tf.function + def test_fn(): + baz = bar(); + return baz, value + + baz_actual, value_actual = test_fn() + self.assertEqual(baz_actual, value_actual) + + Only assertions that require evaluation outside the function are lifted + outside the function scope. The rest execute inline, at function creation + time. + """ + + def __new__(cls, *args): + obj = super().__new__(cls) + + for name in cls.__dict__: + if not name.startswith(unittest.TestLoader.testMethodPrefix): + continue + m = getattr(obj, name) + if callable(m): + wrapper = obj._run_as_tf_function(m) + setattr(obj, name, types.MethodType(wrapper, obj)) + + return obj + + def _op_callback( + self, op_type, inputs, attrs, outputs, op_name=None, graph=None): + self.trace_log.append(op_type) + + def _run_as_tf_function(self, fn): + + def wrapper(self): + @def_function.function(autograph=False) # Testing autograph itself. + def fn_wrapper(): + self.assertions = [] + self.raises_cm = None + self.graph_assertions = [] + self.trace_log = [] + fn() + targets = [args for _, args in self.assertions] + return targets + + try: + tensors = fn_wrapper() + + for assertion in self.graph_assertions: + assertion(fn_wrapper.get_concrete_function().graph) + + actuals = self.evaluate(tensors) + + except: # pylint:disable=bare-except + if self.raises_cm is not None: + # Note: Yes, the Raises and function contexts cross. + self.raises_cm.__exit__(*sys.exc_info()) + return + else: + raise + + for (assertion, _), values in zip(self.assertions, actuals): + assertion(*values) + + return wrapper + + def variable(self, name, value, dtype): + with ops.init_scope(): + if name not in self.variables: + self.variables[name] = variables.Variable(value, dtype=dtype) + self.evaluate(self.variables[name].initializer) + return self.variables[name] + + def setUp(self): + super().setUp() + self.variables = {} + self.trace_log = [] + self.raises_cm = None + op_callbacks.add_op_callback(self._op_callback) + + def tearDown(self): + op_callbacks.remove_op_callback(self._op_callback) + self.trace_log = None + self.variables = None + super().tearDown() + + def assertGraphContains(self, op_regex, n): + def assertion(graph): + matches = [] + for node in graph.as_graph_def().node: + if re.match(op_regex, node.name): + matches.append(node) + for fn in graph.as_graph_def().library.function: + for node_def in fn.node_def: + if re.match(op_regex, node_def.name): + matches.append(node_def) + self.assertLen(matches, n) + + self.graph_assertions.append(assertion) + + def assertOpCreated(self, op_type): + self.assertIn(op_type, self.trace_log) + + def assertOpsNotCreated(self, op_types): + self.assertEmpty(set(op_types) & set(self.trace_log)) + + def assertNoOpsCreated(self): + self.assertEmpty(self.trace_log) + + def assertEqual(self, *args): + self.assertions.append((super().assertEqual, list(args))) + + def assertLess(self, *args): + self.assertions.append((super().assertLess, list(args))) + + def assertGreaterEqual(self, *args): + self.assertions.append((super().assertGreaterEqual, list(args))) + + def assertDictEqual(self, *args): + self.assertions.append((super().assertDictEqual, list(args))) + + def assertRaisesRuntime(self, *args): + if self.raises_cm is not None: + raise ValueError('cannot use more than one assertRaisesRuntime in a test') + self.raises_cm = self.assertRaisesRegex(*args) + self.raises_cm.__enter__() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/type_registry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/type_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..dad222928c284c92fbef8a1a4b0cf5e09fc059af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/autograph/utils/type_registry.py @@ -0,0 +1,62 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Registry mechanism implementing the registry pattern for general use.""" + + +class TypeRegistry(object): + """Provides a type registry for the python registry pattern. + + Contains mappings between types and type specific objects, to implement the + registry pattern. + + Some example uses of this would be to register different functions depending + on the type of object. + """ + + def __init__(self): + self._registry = {} + + def register(self, obj, value): + """Registers a Python object within the registry. + + Args: + obj: The object to add to the registry. + value: The stored value for the 'obj' type. + + Raises: + KeyError: If the same obj is used twice. + """ + if obj in self._registry: + raise KeyError(f"{type(obj)} has already been registered.") + self._registry[obj] = value + + def lookup(self, obj): + """Looks up 'obj'. + + Args: + obj: The object to lookup within the registry. + + Returns: + Value for 'obj' in the registry if found. + Raises: + LookupError: if 'obj' has not been registered. + """ + for registered in self._registry: + if isinstance( + obj, registered + ): + return self._registry[registered] + + raise LookupError(f"{type(obj)} has not been registered.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/async_checkpoint_helper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/async_checkpoint_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..aa801c4bf9a973b73a07dbae4e2a8a0bc47bafbb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/async_checkpoint_helper.py @@ -0,0 +1,628 @@ +# 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. +# ============================================================================== +"""Utilities for saving/loading Trackable objects asynchronously.""" + +import atexit +import copy +import queue +import threading +import time +import weakref + +from absl import logging + +from tensorflow.python.checkpoint import checkpoint_context +from tensorflow.python.checkpoint import trackable_view +from tensorflow.python.distribute import device_util +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import executor +from tensorflow.python.framework import ops +from tensorflow.python.ops import variables +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.trackable import base +from tensorflow.python.util import object_identity + +# Captures the timestamp of the first Checkpoint instantiation or end of a write +# operation. Can be accessed by multiple Checkpoint instances. +_END_TIME_OF_LAST_ASYNC_WRITE = None +_END_TIME_OF_LAST_ASYNC_WRITE_LOCK = threading.Lock() + +# API label for cell names used in async checkpoint metrics. +_ASYNC_CHECKPOINT = "async_checkpoint" + +# Name of TPUEmbedding attribute. This is a temporary workaround +# to identify TPUEmbedding while avoiding import cycles. +_TPU_EMBEDDING_ATTR = "_create_copy_for_async_checkpoint" + + +def _get_duration_microseconds(start_time_seconds, end_time_seconds): + """Calculate the duration between start and end time. + + Args: + start_time_seconds: The start time in seconds. + end_time_seconds: The end time in seconds. + + Returns: + The duration between the start and the end time. Return 0 if + end_time_seconds < start_time_seconds. + """ + if end_time_seconds < start_time_seconds: + # Avoid returning negative value in case of clock skew. + return 0 + return round((end_time_seconds - start_time_seconds) * 1000000) + + +def _get_all_trackables(root, exclude_set): + """Return the list of checkpointable trackables dependent on `root`. + + Args: + root: The root trackable from where we get all its dependent trackables. + exclude_set: An ObjectIdentitySet of Trackables to exclude before returning. + Each element in `exclude_set` is a specific instance of a `Trackable` + and appears precisely once in `TrackableView(root).descendants()`. + + Returns: + saveable_trackables: All trackables that are saveable in `all_trackables` + (see definition of "saveable" in `_trackable_needs_to_be_saved()`). A + subset of `all_trackables`. + all_trackables: All trackables returned by `TrackableView`'s `descendants()` + after excluding `exclude_set`. A superset of `saveable_trackables`. + """ + all_trackables = trackable_view.TrackableView(root=root).descendants() + + # Kick out the trackable we want to exclude. + # The goal of writing such loop is to only scan the list once and stop + # scanning as early as possible (unlike filtering with list comprehension). + trackable_index = 0 + while trackable_index < len(all_trackables) and exclude_set: + # While we have not excluded all items, or gone through all trackables. + if all_trackables[trackable_index] in exclude_set: + # If want to exclude this trackable, we pop it and do not update ptr + exclude_set.discard(all_trackables[trackable_index]) + all_trackables.pop(trackable_index) + else: + # Otherwise update ptr + trackable_index += 1 + + # Kick out trackables that do not need to be saved (e.g. ListWrapper, etc.) + # We define any trackable that does not implement `_serialize_to_tensor` or + # `_gather_saveables` as "no need to be saved". If the trackable has one or + # both of the methods defined, it should have `_copy_trackable_to_cpu` + # defined; if not, we will raise warning in `_copy_to_cpu()`. In case of + # special case, we also check whether a trackable (who has neither of the + # other two methods defined) defines `_copy_trackable_to_cpu` only; we still + # define such cases as "needs to be saved". + def _trackable_needs_to_be_saved(obj): + """Returns whether a trackable needs to be saved. + + Returns a bool to indicate whether obj's class has `_serialize_to_tensors`, + `gather_saveables_for_checkpoint`, or `_copy_trackable_to_cpu` defined. + + Args: + obj: A Trackable object. + """ + if hasattr(obj, "__dict__"): + # Data structure proxy wrappers don't have __dict__. + if ("_serialize_to_tensors" in obj.__dict__ + or "_gather_saveables_for_checkpoint" in obj.__dict__ + or "_copy_trackable_to_cpu" in obj.__dict__): + return True + + # Use MRO so that if a parent class has one of the three methods, we still + # consider `t` as needed to be saved. + for t in type(obj).mro(): + if t is base.Trackable: + # Base class always has them implemented, but would raise error. + continue + elif ("_serialize_to_tensors" in t.__dict__ + or "_gather_saveables_for_checkpoint" in t.__dict__ + or "_copy_trackable_to_cpu" in t.__dict__): + return True + + return False + + saveable_trackables = [x for x in all_trackables if + _trackable_needs_to_be_saved(x)] + + return saveable_trackables, all_trackables + + +class AsyncCheckpointHelper: + """Helper class for async checkpoint.""" + + def __init__(self, checkpointer_impl, root=None, **kwargs): + """Initialize AsyncCheckpoint. + + Args: + checkpointer_impl: The Checkpoint class to power the AsyncCheckpoint. + root: The root object to checkpoint. `root` may be a trackable object or + `WeakRef` of a trackable object. + **kwargs: The keyword arguments representing the checkpointed variables. + + Raises: + AttributeError: when checkpointer_impl is None. + """ + # TODO(chienchunh): Make sure the processing for the root object is + # consistent when integrating with the public API, e.g., adding all kwarg + # items as the child of the root object. + if root: + trackable_root = root() if isinstance(root, weakref.ref) else root + kwargs["root"] = trackable_root + trackable_root._maybe_initialize_trackable() + + # The underlying Checkpoint instance and its items. + if checkpointer_impl is None: + raise AttributeError( + "checkpointer_impl cannot be None for AsyncCheckpointHelper." + ) + self._checkpointer_impl = checkpointer_impl + self._checkpoint_items = kwargs + self._checkpoint = None + self.checkpointer() + self._checkpoint_options = None + + # Indicate whether async checkpoint has finished traversing the variable + # list and created the object map between the original and copied variables. + self._initialized = False + + # The list of all nodes from the original checkpoint items. + # TODO(chienchunh): Consider changing this to local variable. + self._original_nodes = None + # The mapping between the original and the copied resource variables. + # The copied variables are used for the underlying checkpointing. + self._object_map = None + # A list of TPUEmbedding objects included in the checkpoint items. + self._tpu_embedding_objects = None + # A list of highest level `Trackable`s we will copy; does not contain + # TPUEmbedding objects + self._saveable_trackables = None + + self._default_device = device_util.current() or "CPU:0" + self._default_device = device_util.canonicalize(self._default_device) + + self._save_file_prefix = None + self._use_checkpoint_save = False + self._async_save_thread = None + # Concurrent queue that coordinates the events for writing/reading the + # cpu-copied variables. A 'True' in the queue triggers the async thread to + # perform saving; a 'False' breaks the while loop so that the async thread + # exits; no other values will be added to the queue. + # Maxsize is set to 1 only to ensure the exit procedure. We could have used + # queue.join() in _join_async_save_thread(), but queue.join() does not have + # a timeout argument. Hence we use queue.put(timeout=300), in case the last + # checkpoint takes forever. To achieve that, maxsize needs to be 1. + self._queue = queue.Queue(maxsize=1) + + # Register to join the async save thread upon exit. + atexit.register(self._join_async_save_thread) + + self._async_error = None + + global _END_TIME_OF_LAST_ASYNC_WRITE + with _END_TIME_OF_LAST_ASYNC_WRITE_LOCK: + if _END_TIME_OF_LAST_ASYNC_WRITE is None: + _END_TIME_OF_LAST_ASYNC_WRITE = time.time() + + @def_function.function + def _copy_to_cpu(self): + """Copy the checkpointed variables from the accelerator to the host CPU. + + TODO(chienchunh): Get the concrete function before firstly called to avoid + hangining the accelerators idle during function tracing. + """ + for t in self._saveable_trackables: + try: + t._copy_trackable_to_cpu(object_map=self._object_map) # pylint: disable=protected-access + except NotImplementedError as e: + logging.warning("Trackable %s skipped due to: %s", t, e) + + for tpu_embedding in self._tpu_embedding_objects: + tpu_embedding._retrieve_variables() # pylint: disable=protected-access + + def checkpointer(self): + """Gets or creates the underlying Checkpoint instance.""" + if self._checkpoint is None: + self._checkpoint = self._checkpointer_impl(**self._checkpoint_items) + return self._checkpoint + + def _ensure_initialized(self): + """Initialize the async checkpoint internal state.""" + # This map will be used to store the CPU copy of all checkpointable objects + self._object_map = object_identity.ObjectIdentityDictionary() + self._tpu_embedding_objects = [] + + # Populate self._all_tracakbles, but exclude the checkpoint instance itself + # and its save_counter, as they will be returned by `descendants()`. + exclude_set = object_identity.ObjectIdentitySet() + exclude_set.add(self.checkpointer()) + exclude_set.add(self.checkpointer().save_counter) + self._saveable_trackables, all_trackables = _get_all_trackables( + root=self.checkpointer(), exclude_set=exclude_set) + + # Handle special cases: TPU Embedding, and slot variables. + # 1. TPUEmbedding: Different from other trackables, TPUEmbedding needs to + # call `_retrieve_variables` to checkpoint, while populating a dummy copy to + # the object map. + # 2. Slot variables: they need to be handled differently as they cannot be + # retrieved from `TrackableView.descendants()`. + + # Note: dir() is used rather than hasattr() here to avoid triggering + # custom __getattr__ code, see b/152031870 for context. + for t in all_trackables: + # Special case 1: TPU Embedding, populate object_map here + # Special case 1: Handle TPU Embedding by addnig a dummy instance to the + # object map. Also add TPUEmbedding to separate list for special handling + # with values copy. + if hasattr(type(t), _TPU_EMBEDDING_ATTR): + self._handle_tpu_embedding(t) + # Special case 2: handle slot variables. The object_map is populated later + # when the variable values are being copied to host CPU for the first + # time. + if "get_slot_names" in dir(t): + slot_names = t.get_slot_names() + for slot_name in slot_names: + for original_variable in all_trackables: + if not isinstance(original_variable, variables.Variable): + continue + try: + # Usage of hasattr may result in KeyError + original_slot_variable = t.get_slot(original_variable, slot_name) + except (AttributeError, KeyError): + continue + if isinstance(original_slot_variable, base.Trackable): + self._saveable_trackables.append(original_slot_variable) + + # Initiate the underlying Checkpoint instance's save_counter. + save_counter = self.checkpointer().save_counter.numpy() + logging.info("Initializing async checkpoint's save_counter: %d", + save_counter) + + # Pass the object map of the copied variables to the underlying Checkpoint. + self.checkpointer()._saver._object_map = self._object_map # pylint: disable=protected-access + + # We perform a `_copy_to_cpu()` to populate `self._object_map`, + # initializing copies. We do not call `self._copy_to_cpu()` directly + # because it is a tf function, which leads to access out of scope error. + + # TODO(charlieruan) Figure out a better work around to solve the access + # out of scope error. + for t in self._saveable_trackables: + try: + t._copy_trackable_to_cpu(object_map=self._object_map) # pylint: disable=protected-access + except NotImplementedError as e: + logging.warning("Trackable %s skipped due to: %s", t, e) + + for tpu_embedding in self._tpu_embedding_objects: + tpu_embedding._retrieve_variables() # pylint: disable=protected-access + + # Initiate the async thread for checkpoint saving. + self._async_save_thread = threading.Thread( + target=self._async_save, daemon=True) + self._async_save_thread.start() + + self._initialized = True + + def _check_async_thread_error(self): + """Expose the most recent error from the async saving thread to the caller. + """ + if self._async_error: + e = self._async_error + self._async_error = None + logging.error("Propagating the most recent error from the async thread " + "before joining: %s", str(e)) + raise e + + def _join_async_save_thread(self): + """Join the async save thread. + + The steps for terminating the async save thread: + 1). Put will succeed when the last async save event is done. Putting a false + triggers the async save thread's while loop to end. We use put instead + of sync because sync does not have a timeout argument. + 2). Join the async save thread. (The thread may finish before joining.) + """ + try: + self._queue.put(False, timeout=300) # Step-1. + logging.info("Joining the async save thread.") + if self._async_save_thread is not None: + self._async_save_thread.join() # Step-2. + except queue.Full: + logging.error("Timeout waiting for the async save thread; terminating the" + " thread instead. The last checkpoint may be incomeplete.") + finally: + self._check_async_thread_error() + + def _async_save(self): + """The thread function for the async checkpoint save.""" + with context.executor_scope( + executor.new_executor( + enable_async=False, enable_streaming_enqueue=False)): + # The main thread inserts: a True to the queue when the user calls save, + # triggering async save; and a False when we exit the Checkpoint instance. + while self._queue.get(): + logging.info("Starting async checkpoint save on the device: %s", + self._default_device) + + async_save_start_time = time.time() + + # Specify the ops placement on the worker if running with + # coordinator-worker mode. This is required as launching a new thread + # would clear the placement policy and make localhost the default + # placement, while the main thread's default placement would be the + # master worker's CPU:0. + try: + with ops.device(self._default_device): + with checkpoint_context.async_metrics_context(): + if self._use_checkpoint_save: + self.checkpointer().save( + self._save_file_prefix, self._checkpoint_options + ) + else: + self.checkpointer()._write( # pylint: disable=protected-access + self._save_file_prefix, + options=self._checkpoint_options, + ) + except Exception as e: # # pylint: disable=broad-except + self._async_error = e + finally: + self._queue.task_done() + + async_save_end_time = time.time() + metrics.AddAsyncCheckpointWriteDuration( + api_label=_ASYNC_CHECKPOINT, + microseconds=_get_duration_microseconds(async_save_start_time, + async_save_end_time)) + + # Measure the elapsed time since the last checkpoint. + # Due to the nature of async checkpoint, here it actually captures the + # duration between the start_time of the previous checkpoint and the + # start time of this checkpoint. As a result, the duration of the final + # async checkpoint is excluded, which is fine since it does not take + # much time. + global _END_TIME_OF_LAST_ASYNC_WRITE + with _END_TIME_OF_LAST_ASYNC_WRITE_LOCK: + metrics.AddTrainingTimeSaved( + api_label=_ASYNC_CHECKPOINT, + microseconds=_get_duration_microseconds( + _END_TIME_OF_LAST_ASYNC_WRITE, async_save_start_time)) + _END_TIME_OF_LAST_ASYNC_WRITE = async_save_start_time + logging.info("Async save thread reached the end of the execution.") + + def _handle_tpu_embedding(self, tpu_embedding): + """Handle TPUEmbedding. + + This is the only place where we populate object map in the class of + `AsyncCheckpointHelper`. For all other checkpointable trackables, we + populate object map using the trackable's own `_copy_trackable_to_cpu()`. + + Args: + tpu_embedding: TPUEmbedding object to be handled. + + Raises: + AttributeError: if the input trackable is not TPUEmbedding type. + """ + if not hasattr(type(tpu_embedding), _TPU_EMBEDDING_ATTR) or not callable( + tpu_embedding._create_copy_for_async_checkpoint # pylint: disable=protected-access + ): + raise AttributeError( + "Expecting TPUEmbedding type; got %s" % type(tpu_embedding) + ) + + # Create a dummy TPUEmbedding object and add it to the object_map. This is + # to prevent the TPUEmbedding's save_callback from being triggered because + # the embedding values have already being retrieved by AsyncCheckpoint. + # pylint: disable=protected-access + new_embedding = tpu_embedding._create_copy_for_async_checkpoint( + feature_config=tpu_embedding._feature_config, + optimizer=tpu_embedding._table_config[0] + if tpu_embedding._table_config + else None, + pipeline_execution_with_tensor_core=tpu_embedding._pipeline_execution_with_tensor_core, + ) + self._object_map[tpu_embedding] = new_embedding + # pylint: enable=protected-access + + if tpu_embedding not in self._tpu_embedding_objects: + self._tpu_embedding_objects.append(tpu_embedding) + + @property + def save_counter(self): + """An integer variable numbering the checkpoint events. + + This is maintained by the underlying tf.train.Checkpoing object employed by + AsyncCheckpoint class. The number starts at 0 and gets incremented for each + checkpoint event. + + Returns: + The save counter variable. + """ + return self.checkpointer().save_counter + + def write(self, save_path, options=None): + """Save the checkpointed variables. + + Args: + save_path: The file prefix of the checkpoint file. + options: Optional CheckpointOption instance. + + Returns: + The full path of the checkpoint file. + """ + return self._write(save_path, options) + + def _write(self, save_path, options=None): + """Save the checkpointed variables. + + This method has exactly the same logic as save(), except it does not + increment the underlying save_counter, which is done by the caller, e.g., + CheckpointManager. + + Args: + save_path: The file prefix of the checkpoint file. + options: Optional CheckpointOption instance. + + Returns: + The full path of the checkpoint file. + """ + write_start_time = time.time() + + if not self._initialized: + self._ensure_initialized() + else: + # First wait for async thread to finish the previous save, then copy the + # variable values to the host CPU. + self._queue.join() + self._copy_to_cpu() + + # Surface the error from the async thread, if any. + # This step should come after the sem acquision step in the above, so that + # it makes sure it waits until the previous async save finishes storing the + # error. + self._check_async_thread_error() + + # Trigger the async thread to checkpoint the cpu-copied variables. + # Need to wait until the weight copying finishes before checkpoint save. + context.async_wait() + self._save_file_prefix = save_path + self._use_checkpoint_save = False + + # Ensure that we do not request async checkpointing to the underlying + # checkpointer as this could lead to an infinite loop. + self._checkpoint_options = copy.copy(options) if options else None + if self._checkpoint_options: + self._checkpoint_options.experimental_enable_async_checkpoint = False + + self._queue.put(True) # Trigger save in async thread + + write_end_time = time.time() + metrics.AddCheckpointWriteDuration( + api_label=_ASYNC_CHECKPOINT, + microseconds=_get_duration_microseconds(write_start_time, + write_end_time)) + + return save_path + + def save(self, save_path, options=None): + """Save the checkpointed variables. + + Args: + save_path: The file prefix of the checkpoint file. + options: Optional CheckpointOption instance. + + Returns: + The full path of the checkpoint file. + """ + save_start_time = time.time() + + # If this is the first time that AsyncCheckpoint.save() is called, + # initialize the internal states like `self._saveable_trackables`. We also + # populate `self._object_map` (i.e. initializing the cpu-copied variables + # and copy over the value for the first time) by essentially performing a + # `self._copy_to_cpu()`, hence the if-else logic here. + # + # This is not performed in the initializer because some variables, e.g., + # slot variables of the optimizer, were not created until actually running + # the train function, so we could only get the complete list of the + # variables after some train steps were run. + if not self._initialized: + self._ensure_initialized() + else: + # First wait for async thread to finish the previous save, then copy the + # variable values to the host CPU. + self._queue.join() + self._copy_to_cpu() + + # Surface the error from the async thread, if any. + # This step should come after the sem acquision step in the above, so that + # it makes sure it waits until the previous async save finishes storing the + # error. + self._check_async_thread_error() + + # Retrieve the save counter from the underlying checkpoint object to + # re-construct the full path of the checkpoint file. + # This step has to happen before triggering the underlying checkpoint; + # otherwise, the save_counter value may or may not have been updated. + save_counter = self.checkpointer().save_counter.numpy() + 1 + full_path = "{}-{}".format(save_path, save_counter) + + # Trigger the async thread to checkpoint the cpu-copied variables. + # Need to wait until the weight copying finishes before checkpoint save. + context.async_wait() + self._save_file_prefix = save_path + self._use_checkpoint_save = True + + # Ensure that we do not request async checkpointing to the underlying + # checkpointer as this could lead to an infinite loop. + self._checkpoint_options = copy.copy(options) if options else None + if self._checkpoint_options: + self._checkpoint_options.experimental_enable_async_checkpoint = False + + self._queue.put(True) # Trigger save in async thread + + save_end_time = time.time() + metrics.AddCheckpointWriteDuration( + api_label=_ASYNC_CHECKPOINT, + microseconds=_get_duration_microseconds(save_start_time, save_end_time)) + + return full_path + + def read(self, save_path, options=None): + """Restore the checkpointed variables. + + This method has exactly the same logic as restore(). This method is + implemented only to fulfill the duty of subclassing tf.train.Checkpoint. + + Args: + save_path: The full name of the checkpoint file to be restored. + options: CheckpointOption instance. + + Returns: + A load status object, which can be used to make assertions about the + status of a checkpoint restoration. See tf.train.Checkpoint.restore() + for more details. + """ + return self.restore(save_path, options) + + def restore(self, save_path, options=None): + """Restore the checkpointed variables. + + Args: + save_path: The full name of the checkpoint file to be restored. + options: CheckpointOption instance. + + Returns: + A load status object, which can be used to make assertions about the + status of a checkpoint restoration. See tf.train.Checkpoint.restore() + for more details. + """ + # Ensure that we do not request async checkpointing to the underlying + # checkpointer as this could lead to an infinite loop. + self._checkpoint_options = ( + copy.copy(options) if options else self._checkpoint_options) + if self._checkpoint_options: + self._checkpoint_options.experimental_enable_async_checkpoint = False + + # Wait for any ongoing checkpoint event to finish. + self._queue.join() + # Restore values of the cpu-copied variables directly back to accelerators + status = self.checkpointer().restore(save_path, self._checkpoint_options) + + return status + + def sync(self): + """Sync on any ongoing save or restore events.""" + self._queue.join() + logging.info("Sync on ongoing save/restore.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb07ed769919fdfa6f05d738ab81dc4c15390f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint.py @@ -0,0 +1,2728 @@ +"""Utilities for saving/loading Trackable objects.""" +# 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. +# ============================================================================== + +import abc +import collections +import copy +import functools +import glob +import inspect +import os +import threading +import time +import weakref + +from tensorflow.core.protobuf import trackable_object_graph_pb2 +from tensorflow.python.checkpoint import async_checkpoint_helper +from tensorflow.python.checkpoint import checkpoint_context +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.checkpoint import checkpoint_options +from tensorflow.python.checkpoint import functional_saver +from tensorflow.python.checkpoint import graph_view as graph_view_lib +from tensorflow.python.checkpoint import restore as restore_lib +from tensorflow.python.checkpoint import save_util +from tensorflow.python.checkpoint import save_util_v1 +from tensorflow.python.checkpoint import util +from tensorflow.python.client import session as session_lib +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_io_ops as io_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import path_helpers +from tensorflow.python.saved_model.pywrap_saved_model import metrics +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import base +from tensorflow.python.trackable import data_structures +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.training import saver as v1_saver_lib +from tensorflow.python.training.saving import saveable_object as saveable_object_lib +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +# The callable that provide Keras default session that is needed for saving. +_SESSION_PROVIDER = None + +# Captures the timestamp of the first Checkpoint instantiation or end of a write +# operation. Can be accessed by multiple Checkpoint instances. +_END_TIME_OF_LAST_WRITE = None +_END_TIME_OF_LAST_WRITE_LOCK = threading.Lock() + +# API labels for cell names used in checkpoint metrics. +_CHECKPOINT_V1 = "checkpoint_v1" +_CHECKPOINT_V2 = "checkpoint_v2" + +# Async thread used for asynchronous checkpoint. +_ASYNC_CHECKPOINT_THREAD = None + + +def _get_duration_microseconds(start_time_seconds, end_time_seconds): + if end_time_seconds < start_time_seconds: + # Avoid returning negative value in case of clock skew. + return 0 + return round((end_time_seconds - start_time_seconds) * 1000000) + + +@tf_export("__internal__.tracking.register_session_provider", v1=[]) +def register_session_provider(session_provider): + global _SESSION_PROVIDER + # TODO(scottzhu): Change it back to only allow one time setting for session + # provider once we finished the keras repo split. + # if _SESSION_PROVIDER is None: + _SESSION_PROVIDER = session_provider + + +def get_session(): + # Prefer TF's default session since get_session from Keras has side-effects. + session = ops.get_default_session() + if session is None: + global _SESSION_PROVIDER + if _SESSION_PROVIDER is not None: + session = _SESSION_PROVIDER() # pylint: disable=not-callable + return session + + +def _get_checkpoint_size(prefix): + """Calculates filesize of checkpoint based on prefix.""" + size = 0 + # Gather all files beginning with prefix (.index plus sharded data files). + files = glob.glob("{}*".format(prefix)) + for file in files: + # Use TensorFlow's C++ FileSystem API. + size += metrics.CalculateFileSize(file) + return size + + +def _execute_callbacks(callbacks, save_path): + """Executes a list of callback functions, providing `save_path` if needed.""" + for callback in callbacks: + num_params = len(inspect.signature(callback).parameters) + if num_params == 0: + callback() + elif num_params == 1: + callback(save_path) + else: + raise AssertionError( + "Callback functions for checkpoint are required to have 0 or 1" + f"parameters, but this has {num_params} parameters: {callback}" + ) + + +class ObjectGraphProtoPrettyPrinter: + """Lazily traverses an object graph proto to pretty print names. + + If no calls to `node_names` are made this object has no performance + overhead. On the other hand, it will only traverse the object graph once, so + repeated naming is cheap after the first. + """ + + __slots__ = ["_object_graph_proto", "_node_name_cache"] + + def __init__(self, object_graph_proto): + self._object_graph_proto = object_graph_proto + self._node_name_cache = None + + @property + def node_names(self): + """Lazily creates a mapping from node id to ("path", "to", "root").""" + if self._node_name_cache is not None: + return self._node_name_cache + path_to_root = {} + path_to_root[0] = ("(root)",) + to_visit = collections.deque([0]) + while to_visit: + node_id = to_visit.popleft() + obj = self._object_graph_proto.nodes[node_id] + for child in obj.children: + if child.node_id not in path_to_root: + path_to_root[child.node_id] = ( + path_to_root[node_id] + (child.local_name,)) + to_visit.append(child.node_id) + + node_names = {} + for node_id, path_to_root in path_to_root.items(): + node_names[node_id] = ".".join(path_to_root) + + for node_id, node in enumerate(self._object_graph_proto.nodes): + for slot_reference in node.slot_variables: + node_names[slot_reference.slot_variable_node_id] = ( + f"{node_names[node_id]}'s state '{slot_reference.slot_name}' for " + f"{node_names[slot_reference.original_variable_node_id]}") + self._node_name_cache = node_names + return node_names + + +class _CheckpointRestoreCoordinatorDeleter: + """Deleter to avoid overriding _CheckpointRestoreCoordinator.__del__().""" + + __slots__ = [ + "expect_partial", "object_graph_proto", "matched_proto_ids", + "unused_attributes" + ] + + def __init__(self, expect_partial, object_graph_proto, matched_proto_ids, + unused_attributes): + self.expect_partial = expect_partial + self.object_graph_proto = object_graph_proto + self.matched_proto_ids = matched_proto_ids + self.unused_attributes = unused_attributes + + def set_expect_partial(self, expect_partial): + self.expect_partial = expect_partial + + def __del__(self): + if self.expect_partial: + return + if logging is None: + # The logging module may have been unloaded when __del__ is called. + log_fn = print + else: + log_fn = logging.warning + unused_nodes_in_checkpoint = [] + unrestored_attributes_in_object = [] + pretty_printer = ObjectGraphProtoPrettyPrinter(self.object_graph_proto) + for node_id, node in enumerate(self.object_graph_proto.nodes): + if not node.attributes: + continue + if node_id not in self.matched_proto_ids: + unused_nodes_in_checkpoint.append(pretty_printer.node_names[node_id]) + for node_id, attribute_name in self.unused_attributes.items(): + unrestored_attributes_in_object.append(( + pretty_printer.node_names[node_id], attribute_name)) + if unused_nodes_in_checkpoint or unrestored_attributes_in_object: + # pylint:disable=line-too-long + log_fn("Detecting that an object or model or tf.train.Checkpoint is being" + " deleted with unrestored values. See the following logs for the " + "specific values in question. To silence these warnings, use " + "`status.expect_partial()`. See " + "https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#restore" + "for details about the status object returned by the restore " + "function.") + # pylint:enable=line-too-long + for node_path in unused_nodes_in_checkpoint: + log_fn("Value in checkpoint could not be found in the restored object: " + f"{node_path}") + for node_path, attr in unrestored_attributes_in_object: + log_fn("An attribute in the restored object could not be found in the " + f"checkpoint. Object: {node_path}, attribute: {attr}") + + +class _CheckpointRestoreCoordinator: + """Holds the status of an object-based checkpoint load.""" + + def __init__(self, object_graph_proto, save_path, save_path_tensor, reader, + restore_op_cache, graph_view, options, saveables_cache): + """Specify the checkpoint being loaded. + + Args: + object_graph_proto: The TrackableObjectGraph protocol buffer associated + with this checkpoint. + save_path: A string, the path to the checkpoint, as returned by + `tf.train.latest_checkpoint`. + save_path_tensor: A string `Tensor` which contains or will be fed the save + path. + reader: A `CheckpointReader` for `save_path`. If None, + `_CheckpointRestoreCoordinator` will initialize one itself. + restore_op_cache: A dictionary shared between + `_CheckpointRestoreCoordinator`s for the same Python objects, used to + look up restore ops by name to avoid re-creating them across multiple + `restore()` calls. + graph_view: A graph_view_lib.ObjectGraphView object for the restored + objects. + options: A CheckpointOptions object. + saveables_cache: An optional cache storing previously created + SaveableObjects created for each Trackable. Maps Trackables to a + dictionary of attribute names to Trackable. + """ + self.options = options + self.object_graph_proto = object_graph_proto + self.restore_uid = ops.uid() + # Maps from proto ids to lists of attributes which were in the checkpoint + # but not loaded into any object, for error checking. + self.unused_attributes = {} + # Dictionary mapping from an id in the protocol buffer flat array to + # Trackable Python objects. This mapping may be deferred if a + # checkpoint is restored before all dependencies have been tracked. Uses + # weak references so that partial restorations don't create reference cycles + # (as objects with deferred dependencies will generally have references to + # this object). + self.object_by_proto_id = weakref.WeakValueDictionary() + self.matched_proto_ids = set() + # A set of all Python objects we've seen as dependencies, even if we didn't + # use them (for example because of inconsistent references when + # loading). Used to make status assertions fail when loading checkpoints + # that don't quite match. + self.all_python_objects = object_identity.ObjectIdentityWeakSet() + self.save_path_tensor = save_path_tensor + self.save_path_string = save_path + self.dtype_map = reader.get_variable_to_dtype_map() + self.shape_map = reader.get_variable_to_shape_map() + # A NewCheckpointReader for the most recent checkpoint, for streaming Python + # state restoration. + # When graph building, contains a list of ops to run to restore objects from + # this checkpoint. + self.restore_ops = [] + self.restore_ops_by_name = restore_op_cache + self.graph_view = graph_view + self.new_restore_ops_callback = None + # A mapping from optimizer proto ids to lists of slot variables to be + # restored when the optimizer is tracked. Only includes slot variables whose + # regular variables have already been created, and only for optimizer + # objects which have not yet been created/tracked. + self.deferred_slot_restorations = {} + # A mapping from variable proto ids to lists of slot variables to be + # restored when the variable is created/tracked. These get shifted over to + # deferred_slot_restorations if the optimizer hasn't been created when that + # happens. + self.slot_restorations = {} + # Controls whether errors are printed in __del__ if some objects did not + # match. + self.expect_partial_attr = False + for node_index, node in enumerate(self.object_graph_proto.nodes): + for slot_reference in node.slot_variables: + # `node` refers to an `Optimizer`, since only these have slot variables. + self.slot_restorations.setdefault( + slot_reference.original_variable_node_id, []).append( + base._SlotVariableRestoration( # pylint: disable=protected-access + optimizer_id=node_index, + slot_variable_id=slot_reference.slot_variable_node_id, + slot_name=slot_reference.slot_name)) + + self._deleter = _CheckpointRestoreCoordinatorDeleter( + self.expect_partial_attr, + self.object_graph_proto, + self.matched_proto_ids, + self.unused_attributes) + + self.saveables_cache = saveables_cache + + @property + def expect_partial(self): + return self.expect_partial_attr + + @expect_partial.setter + def expect_partial(self, expect_partial): + self.expect_partial_attr = expect_partial + self._deleter.set_expect_partial(expect_partial) + + def new_restore_ops(self, new_ops): + self.restore_ops.extend(new_ops) + if self.new_restore_ops_callback: + self.new_restore_ops_callback(new_ops) # pylint: disable=not-callable + + def restore_saveables( + self, + tensor_saveables, + python_positions, + registered_savers=None, + reader=None, + ): + """Run or build restore operations for SaveableObjects. + + Args: + tensor_saveables: `SaveableObject`s which correspond to Tensors. + python_positions: List of CheckpointPositions bound to `PythonState` + objects which must be restored eagerly. + registered_savers: a dict mapping saver names-> object name -> Trackable. + reader: A `CheckpointReader`. If None, a new instance will be created. + + Returns: + When graph building, a list of restore operations, either cached or newly + created, to restore `tensor_saveables`. + """ + if reader is None: + reader = py_checkpoint_reader.NewCheckpointReader(self.save_path_string) + + restore_ops = [] + # Eagerly run restorations for Python state. + for position in python_positions: + key = position.object_proto.attributes[0].checkpoint_key + position.trackable.deserialize(reader.get_tensor(key)) + + # If we have new SaveableObjects, extract and cache restore ops. + if tensor_saveables or registered_savers: + flat_saveables = saveable_object_util.validate_and_slice_inputs( + tensor_saveables) + new_restore_ops = functional_saver.MultiDeviceSaver.from_saveables( + flat_saveables, + registered_savers).restore(self.save_path_tensor, self.options) + if not context.executing_eagerly(): + for name, restore_op in sorted(new_restore_ops.items()): + restore_ops.append(restore_op) + assert name not in self.restore_ops_by_name + self.restore_ops_by_name[name] = restore_op + return restore_ops + + +class _NameBasedRestoreCoordinator: + """Keeps the status of a name-based checkpoint restore.""" + + def __init__(self, save_path, dtype_map=None): + self.save_path = save_path + self.dtype_map = dtype_map + # A map from trackable objects to unused attribute names. We don't have + # proto IDs when doing a name-based restore, so the map keys differ from + # those in _CheckpointRestoreCoordinator. + self.unused_attributes = object_identity.ObjectIdentityWeakKeyDictionary() + self.restore_uid = ops.uid() + + def globally_named_object_attributes(self, trackable): + """Create globally named SaveableObjects from attributes. + + If an object's attribute has no global name specified (default construction + for the SaveableObject factory), records the failure in + `self.unused_attributes` (which can then be used to make status assertions + fail; see `NameBasedSaverStatus`). + + Args: + trackable: An object to save. + + Yields: + SaveableObjects for `trackable`'s attributes. + """ + for ( + attribute_name, + saveable_factory, + ) in saveable_object_util.saveable_objects_from_trackable( + trackable, tf1_saver=True, + ).items(): + if callable(saveable_factory): + try: + # This saveable object factory does not have a default name= argument, + # which means there's no way to save/restore it using a name-based + # checkpoint. Ignore the error now and make sure assert_consumed() + # fails. + saveable = saveable_factory() + except TypeError: + self.unused_attributes.setdefault(trackable, + []).append(attribute_name) + continue + else: + saveable = saveable_factory + names_to_saveables = saveable_object_util.op_list_to_dict( + [saveable], convert_variable_to_tensor=False) + for name, op in names_to_saveables.items(): + for saveable_object in saveable_object_util.saveable_objects_for_op( + op=op, name=name): + yield saveable_object + + def eager_restore(self, trackable): + """Runs restore ops for `trackable`'s attributes.""" + # When graph building, we don't add any restore ops to the graph until + # run_restore_ops/initialize_or_restore on the status object for name-based + # checkpoints. + assert context.executing_eagerly() + for saveable in self.globally_named_object_attributes(trackable): + restored_tensors = [] + tensor_missing = False + for spec in saveable.specs: + if spec.name in self.dtype_map: + with ops.device("cpu:0"): + restored, = io_ops.restore_v2( + prefix=self.save_path, + tensor_names=[spec.name], + shape_and_slices=[""], + dtypes=[self.dtype_map[spec.name]], + name="%s_checkpoint_read" % (spec.name,)) + restored_tensors.append(array_ops.identity(restored)) + else: + tensor_missing = True + + if tensor_missing: + # Record that this variable didn't match so assertions will fail. + self.unused_attributes.setdefault(trackable, []).append(saveable.name) + else: + # Ignores values missing from the checkpoint, as with object-based + # restore. Status assertions can be used to check exact matches, + # although it's unlikely to ever happen for name-based checkpoints. + saveable.restore( + restored_tensors=restored_tensors, restored_shapes=None) + + +# TODO(allenl): If this ends up in a public API, consider adding LINT.If Change +# or consolidating the implementation with get_variable. +def _default_getter(name, + shape, + dtype, + initializer=None, + partition_info=None, + **kwargs): + """A pared-down version of get_variable which does not reuse variables.""" + dtype = dtypes.as_dtype(dtype) + shape_object = tensor_shape.as_shape(shape) + with ops.init_scope(): + if initializer is None: + initializer, initializing_from_value = ( + variable_scope._get_default_variable_store()._get_default_initializer( # pylint: disable=protected-access + name=name, + shape=shape_object, + dtype=dtype)) + else: + initializing_from_value = not callable(initializer) + # Same logic as get_variable + variable_dtype = dtype.base_dtype + if initializing_from_value: + if shape is not None: + raise ValueError("If initializer is a constant, do not specify shape.") + initial_value = initializer + else: + # Instantiate initializer if provided initializer is a type object. + if isinstance(initializer, type(init_ops.Initializer)): + initializer = initializer(dtype=dtype) + shape_list = None if shape is None else shape_object.as_list() + if "partition_info" in tf_inspect.getargspec(initializer).args: + initial_value = functools.partial(initializer, + shape_list, + dtype=dtype, + partition_info=partition_info) + else: + initial_value = functools.partial(initializer, + shape_list, + dtype=dtype) + + return variable_v1.VariableV1( + initial_value=initial_value, + name=name, + dtype=variable_dtype, + use_resource=True, + **kwargs) + + +def add_variable(trackable, + name, + shape=None, + dtype=dtypes.float32, + initializer=None, + trainable=True): + """Add a variable to a Trackable with no scope influence.""" + return trackable._add_variable_with_custom_getter( # pylint: disable=protected-access + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + getter=_default_getter, + trainable=trainable) + + +def object_metadata(save_path): + """Retrieves information about the objects in a checkpoint. + + Example usage: + + ```python + object_graph = tf.contrib.checkpoint.object_metadata( + tf.train.latest_checkpoint(checkpoint_directory)) + ckpt_variable_names = set() + for node in object_graph.nodes: + for attribute in node.attributes: + ckpt_variable_names.add(attribute.full_name) + ``` + + Args: + save_path: The path to the checkpoint, as returned by `save` or + `tf.train.latest_checkpoint`. + + Returns: + A parsed `tf.contrib.checkpoint.TrackableObjectGraph` protocol buffer. + Raises: + ValueError: If an object graph was not found in the checkpoint. + """ + reader = py_checkpoint_reader.NewCheckpointReader(save_path) + try: + object_graph_string = reader.get_tensor(base.OBJECT_GRAPH_PROTO_KEY) + except errors_impl.NotFoundError: + raise ValueError( + f"The specified checkpoint \"{save_path}\" does not appear to be " + "object-based (saved with TF2) since it is missing the key " + f"\"{base.OBJECT_GRAPH_PROTO_KEY}\". Likely it was created with the " + "TF1 name-based saver and does not contain an object dependency graph.") + object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph()) + object_graph_proto.ParseFromString(object_graph_string) + return object_graph_proto + + +def list_objects(root_trackable): + """Traverse the object graph and list all accessible objects. + + Looks for `Trackable` objects which are dependencies of + `root_trackable`. Includes slot variables only if the variable they are + slotting for and the optimizer are dependencies of `root_trackable` + (i.e. if they would be saved with a checkpoint). + + Args: + root_trackable: A `Trackable` object whose dependencies should be flattened. + + Returns: + A flat list of objects. + """ + return util.list_objects(graph_view_lib.ObjectGraphView(root_trackable)) + + +def gather_initializers(root_trackable): + """Traverse the object graph and find initialization ops. + + Looks for `Trackable` objects which are dependencies of + `root_trackable` and which have an `initializer` property. Includes + initializers for slot variables only if the variable they are slotting for and + the optimizer are dependencies of `root_trackable` (i.e. if they would be + saved with a checkpoint). + + Args: + root_trackable: A `Trackable` object to gather initializers for. + + Returns: + A list of initialization ops. + """ + trackable_objects = list_objects(root_trackable) + return [ + c.initializer + for c in trackable_objects + if hasattr(c, "initializer") and c.initializer is not None + ] + + +@tf_contextlib.contextmanager +def capture_dependencies(template): + """Capture variables created within this scope as `Template` dependencies. + + Requires that `template.variable_scope` is active. + + This scope is intended as a compatibility measure, allowing a trackable + object to add dependencies on variables created in a block of code which is + not aware of object-based saving (and instead uses variable names + heavily). This is how `Template` objects add dependencies on variables and + sub-`Template`s. Where possible, use `tf.compat.v1.make_template` directly. + + Args: + template: The `Template` object to register dependencies with. + + Yields: + None (when used as a context manager). + """ + name_prefix = template.variable_scope.name + + def _trackable_custom_creator(next_creator, + name, + initial_value, + trackable_parent=None, + **kwargs): + """A variable creation hook which adds Trackable dependencies. + + Set for example during a `Template`'s first wrapped function + execution. Ensures that (a) `template` depends on any trackable + objects using their own `capture_dependencies` scope inside this scope which + create variables, and (b) that any variables not in a more deeply nested + scope are added as dependencies directly. + + The `trackable_parent` argument is passed between custom creators but + ignored when the variable object itself is created. This argument indicates + (if not `None`) that a more deeply nested scope has already added the + variable as a dependency, and that parent scopes should add a dependency on + that object rather than on the variable directly. + + Args: + next_creator: See `variable_scope.variable_creator_scope`; the next + creator in the chain. + name: The (full, scope-influenced) name of the variable. The `name_prefix` + itself is stripped for the purposes of object-based dependency tracking, + but scopes opened within this scope are respected. + initial_value: See `variable_scope.variable_creator_scope`. Taken + explicitly so the argument can be re-named and used with + `Trackable._add_variable_with_custom_getter`. + trackable_parent: If not None, a more deeply nested trackable object and + its name prefix which were passed to `capture_dependencies` to add a + dependency on (rather than depending on the variable directly). + **kwargs: Passed through to the next creator. + + Returns: + The output of `next_creator`: the fetched/created variable object. + """ + + def _call_next_creator_renaming_initializer(initializer, **inner_kwargs): + inner_kwargs.pop("name") # Ignored; this is the scope-stripped name which + # we don't want to propagate. + return next_creator(initial_value=initializer, name=name, **inner_kwargs) + + if name is not None and name.startswith(name_prefix): + scope_stripped_name = name[len(name_prefix) + 1:] + if not trackable_parent: + return template._add_variable_with_custom_getter( # pylint: disable=protected-access + initializer=initial_value, + name=scope_stripped_name, + getter=_call_next_creator_renaming_initializer, + # Disable error checking for Trackable. Exceptions are instead + # raised if necessary when the object-based saver tries to + # save/restore the object. + overwrite=True, + trackable_parent=(template, name_prefix), + **kwargs) + else: + parent_object, parent_name_prefix = trackable_parent + template._track_trackable( # pylint: disable=protected-access + parent_object, + name=parent_name_prefix[len(name_prefix) + 1:], + overwrite=True) + return next_creator( + name=name, + initial_value=initial_value, + trackable_parent=(template, name_prefix), + **kwargs) + + with variable_scope.variable_creator_scope(_trackable_custom_creator): + yield + + +class _LoadStatus: + """Abstract base for load status callbacks.""" + + @abc.abstractmethod + def assert_consumed(self): + """Raises an exception unless a non-trivial restoration has completed.""" + pass + + @abc.abstractmethod + def assert_existing_objects_matched(self): + """Raises an exception unless existing Python objects have been matched.""" + pass + + @abc.abstractmethod + def assert_nontrivial_match(self): + """Raises an exception if only the root object matched.""" + pass + + @abc.abstractmethod + def run_restore_ops(self, session=None): + """Runs restore ops from the checkpoint. Requires a valid checkpoint.""" + pass + + @abc.abstractmethod + def initialize_or_restore(self, session=None): + """Runs restore ops from the checkpoint, or initializes variables.""" + pass + + def expect_partial(self): + """Silence warnings about incomplete checkpoint restores.""" + return self + + +@tf_export("__internal__.tracking.streaming_restore", v1=[]) +def streaming_restore(status, session=None): + """When graph building, runs restore ops as soon as they come in. + + Args: + status: A _LoadStatus objects from an object-based saver's restore(). + Streaming restore from name-based checkpoints is not currently supported. + session: A session to run new restore ops in. + """ + if context.executing_eagerly(): + # Streaming restore is the default/only behavior when executing eagerly. + return + if session is None: + session = get_session() + if isinstance(status, NameBasedSaverStatus): + raise NotImplementedError( + "Streaming restore not supported from name-based checkpoints when " + "graph building. File a feature request if this limitation bothers " + "you. As a workaround, consider either using tf.train.Checkpoint to " + "load name-based checkpoints or enabling eager execution.") + status.run_restore_ops(session=session) + # pylint: disable=protected-access + status._checkpoint.new_restore_ops_callback = ( + lambda ops: session.run(ops, feed_dict=status._feed_dict)) + # pylint: enable=protected-access + + +def _objects_with_attributes(full_list): + """Filters out objects with no direct variable dependencies for assertions.""" + return [ + o for o in full_list + if saveable_object_util.saveable_objects_from_trackable(o) + ] + + +class CheckpointLoadStatus(_LoadStatus): + """Checks the status of checkpoint loading and manages restore ops. + + Returned from `Saver.restore`. Since `restore` may defer the loading of values + in the checkpoint which don't yet have corresponding Python objects, + `CheckpointLoadStatus` provides a callback to verify that checkpoint loading + is complete (`assert_consumed`). + + When graph building, `restore` does not run restore ops itself since their + creation may be deferred. The `run_restore_ops` method must be called once all + Python objects with values to restore have been created and added to the + dependency graph (this does not necessarily have to be the whole checkpoint; + calling `run_restore_ops` while `assert_consumed` fails is supported and will + partially restore the checkpoint). + + See `Saver.restore` for usage examples. + """ + + def __init__(self, checkpoint, feed_dict, graph_view): + self._checkpoint = checkpoint + self._feed_dict = feed_dict + self._object_graph_view = graph_view + # Keep a reference to the root, since object_graph_view might only have a + # weakref. + self._root = graph_view.root + + def assert_consumed(self): + """Asserts that all objects in the checkpoint have been created/matched. + + Returns: + `self` for chaining. + Raises: + AssertionError: If there are any Python objects in the dependency graph + which have not been restored from this checkpoint or a later `restore`, + or if there are any checkpointed values which have not been matched to + Python objects. + """ + pretty_printer = ObjectGraphProtoPrettyPrinter( + self._checkpoint.object_graph_proto) + self.assert_existing_objects_matched() + for node_id, node in enumerate(self._checkpoint.object_graph_proto.nodes): + if not node.attributes: + # Only raise exceptions for the nodes with attributes themselves. Either + # they're ultimately not important, or they have a child with an + # attribute. + continue + trackable = self._checkpoint.object_by_proto_id.get(node_id, None) + if trackable is None: + raise AssertionError( + "Unresolved object in checkpoint " + f"{pretty_printer.node_names[node_id]}: {node}") + if self._checkpoint.slot_restorations: + # Sanity check; this collection should be clear if everything has been + # restored. + raise AssertionError( + f"Unresolved slot restorations: {self._checkpoint.slot_restorations}") + if self._checkpoint.unused_attributes: + unused_attribute_messages = [] + for node_id, attribute in self._checkpoint.unused_attributes.items(): + obj = self._checkpoint.object_by_proto_id[node_id] + unused_attribute_messages.append( + f"{pretty_printer.node_names[node_id]} ({obj}): {attribute}") + joined_attribute_messages = "\n".join(unused_attribute_messages) + raise AssertionError( + "Unused attributes in these objects (the attributes exist in the " + f"checkpoint but were not restored):\n{joined_attribute_messages}") + return self + + def assert_existing_objects_matched(self): + """Asserts that trackable Python objects have been matched. + + Note that this is a weaker assertion than `assert_consumed`. It will only + fail for existing Python objects which are (transitive) dependencies of the + root object and which do not have an entry in the checkpoint. + + It will not fail, for example, if a `tf.keras.Layer` object has not yet been + built and so has not created any `tf.Variable` objects. + + Returns: + `self` for chaining. + + Raises: + AssertionError: If a Python object exists in the transitive dependencies + of the root object but does not have a value in the checkpoint. + """ + for node_id, node in enumerate(self._checkpoint.object_graph_proto.nodes): + trackable = self._checkpoint.object_by_proto_id.get(node_id, None) + if (trackable is not None and + trackable._update_uid < self._checkpoint.restore_uid): # pylint: disable=protected-access + raise AssertionError( + f"Object {node} not assigned a value from checkpoint.") + for trackable_object in util.list_objects(self._object_graph_view): + # Remove data structures that do not contain any variables from + # restoration checks. + if (isinstance(trackable_object, + data_structures.TrackableDataStructure) and + not trackable_object._trackable_children( # pylint: disable=protected-access + save_type=base.SaveType.CHECKPOINT)): + continue + self._checkpoint.all_python_objects.add(trackable_object) + unused_python_objects = ( + object_identity.ObjectIdentitySet( + _objects_with_attributes( + self._checkpoint.all_python_objects)) - + object_identity.ObjectIdentitySet( + self._checkpoint.object_by_proto_id.values())) + if unused_python_objects: + num_unused_python_objects = len(list(unused_python_objects)) + # Display max number of 10 variables in error message. + num_variables_to_show = min(10, num_unused_python_objects) + raise AssertionError( + f"Found {num_unused_python_objects} Python objects that were " + "not bound to checkpointed values, likely due to changes in the " + f"Python program. Showing {num_variables_to_show} of " + f"{num_unused_python_objects} unmatched objects: " + f"{list(unused_python_objects)[:num_variables_to_show]}") + return self + + def assert_nontrivial_match(self): + """Raises an exception if only the root object matched.""" + for trackable_object in util.list_objects(self._object_graph_view): + self._checkpoint.all_python_objects.add(trackable_object) + if len(self._checkpoint.object_by_proto_id) <= 1: + unused_python_objects = ( + object_identity.ObjectIdentitySet( + _objects_with_attributes(self._checkpoint.all_python_objects)) - + object_identity.ObjectIdentitySet( + self._checkpoint.object_by_proto_id.values())) + if unused_python_objects: + raise AssertionError( + "Nothing except the root object matched a checkpointed value. " + "Typically this means that the checkpoint does not match the " + "Python program. The following objects have no matching " + f"checkpointed value: {list(unused_python_objects)}") + else: + raise AssertionError( + "Nothing to load. No dependencies have been added to " + f"{self._object_graph_view.root} yet.") + return self + + def run_restore_ops(self, session=None): + """Run operations to restore objects in the dependency graph.""" + if context.executing_eagerly(): + return # Run eagerly + if session is None: + session = get_session() + session.run(self._checkpoint.restore_ops, feed_dict=self._feed_dict) + + def initialize_or_restore(self, session=None): + """Run operations to initialize or restore objects in the dependency graph. + + Any objects in the dependency graph which have initializers but are not in + the checkpoint will have those initializers run, unless those variables are + being restored by a later call to `tf.train.Checkpoint.restore()`. + + This method has a sibling in `InitializationOnlyStatus` which instead + initializes variables. That type is returned if no checkpoint is specified + in `Saver.restore`. + + Args: + session: The session to run init/restore ops in. If `None`, uses the + default session. + """ + if context.executing_eagerly(): + return # Initialization and restoration ops are run eagerly + if session is None: + session = get_session() + all_objects = util.list_objects(self._object_graph_view) + already_initialized_objects = object_identity.ObjectIdentitySet( + self._checkpoint.object_by_proto_id.values()) + initializers_for_non_restored_variables = [ + c.initializer for c in all_objects + if hasattr(c, "initializer") + and c not in already_initialized_objects + and (getattr(c, "_update_uid", self._checkpoint.restore_uid - 1) + < self._checkpoint.restore_uid) + ] + self.run_restore_ops(session=session) + session.run(initializers_for_non_restored_variables) + + def expect_partial(self): + """Silence warnings about incomplete checkpoint restores.""" + self._checkpoint.expect_partial = True + return self + + +class InitializationOnlyStatus(_LoadStatus): + """Returned from `Saver.restore` when no checkpoint has been specified. + + Objects of this type have the same `assert_consumed` method as + `CheckpointLoadStatus`, but it always fails. However, + `initialize_or_restore` works on objects of both types, and will + initialize variables in `InitializationOnlyStatus` objects or restore them + otherwise. + """ + + def __init__(self, object_graph_view, restore_uid): + self._restore_uid = restore_uid + self._object_graph_view = object_graph_view + # Keep a reference to the root, since graph_view might only have a weakref. + self._root = object_graph_view.root + + def assert_consumed(self): + """Assertion for consistency with `CheckpointLoadStatus`. Always fails.""" + raise AssertionError( + "No checkpoint specified (save_path=None); nothing is being restored.") + + def assert_existing_objects_matched(self): + """Assertion for consistency with `CheckpointLoadStatus`. Always fails.""" + raise AssertionError( + "No checkpoint specified (save_path=None); nothing is being restored.") + + def assert_nontrivial_match(self): + """Assertion for consistency with `CheckpointLoadStatus`. Always fails.""" + raise AssertionError( + "No checkpoint specified (save_path=None); nothing is being restored.") + + def run_restore_ops(self, session=None): + """For consistency with `CheckpointLoadStatus`. + + Use `initialize_or_restore` for initializing if no checkpoint was passed + to `Saver.restore` and restoring otherwise. + + Args: + session: Not used. + """ + raise AssertionError( + "No checkpoint specified, so no restore ops are available " + "(save_path=None to Saver.restore).") + + def initialize_or_restore(self, session=None): + """Runs initialization ops for variables. + + Objects which would be saved by `Saver.save` will be initialized, unless + those variables are being restored by a later call to + `tf.train.Checkpoint.restore()`. + + This method does nothing when executing eagerly (initializers get run + eagerly). + + Args: + session: The session to run initialization ops in. If `None`, uses the + default session. + """ + if context.executing_eagerly(): + return # run eagerly + if session is None: + session = get_session() + trackable_objects = util.list_objects(self._object_graph_view) + initializers = [ + c.initializer for c in trackable_objects + if hasattr(c, "initializer") and c.initializer is not None + and (getattr(c, "_update_uid", self._restore_uid - 1) + < self._restore_uid) + ] + session.run(initializers) + + +_DEPRECATED_RESTORE_INSTRUCTIONS = ( + "Restoring a name-based tf.train.Saver checkpoint using the object-based " + "restore API. This mode uses global names to match variables, and so is " + "somewhat fragile. It also adds new restore ops to the graph each time it " + "is called when graph building. Prefer re-encoding training checkpoints in " + "the object-based format: run save() on the object-based saver (the same " + "one this message is coming from) and use that checkpoint in the future.") + + +class NameBasedSaverStatus(_LoadStatus): + """Status for loading a name-based training checkpoint.""" + + # Ideally this deprecation decorator would be on the class, but that + # interferes with isinstance checks. + @deprecation.deprecated( + date=None, instructions=_DEPRECATED_RESTORE_INSTRUCTIONS) + def __init__(self, checkpoint, object_graph_view): + self._checkpoint = checkpoint + self._object_graph_view = object_graph_view + self._optionally_restored = [] + # Keep a reference to the root, since graph_view might only have a weakref. + self._root = object_graph_view.root + + def add_to_optionally_restored(self, var): + """Add a variable to the list of optionally restored variables. + + There are situations where certain variables should be ignored in assertions + such as assert_existing_objects_matched(). One example is that of a + checkpoint saved with train.Saver(), and restored with train.Checkpoint(): + it is possible for the train.Saver() checkpoint to be missing the internal + `save_counter` variable, which we want to ignore on restore. + + Args: + var: The variable to treat as optionally restored. + """ + self._optionally_restored.append(var) + + def assert_consumed(self): + """Raises an exception if any variables are unmatched.""" + unused_attributes = list(self._checkpoint.unused_attributes.items()) + unused_attributes = [ + a for a in unused_attributes + if all(a[0] is not x for x in self._optionally_restored) + ] + if unused_attributes: + unused_attribute_string = "".join( + f"\n {obj}: {attributes}" for obj, attributes in unused_attributes) + raise AssertionError( + "Some objects had attributes which were not restored: " + f"{unused_attribute_string}") + for trackable in util.list_objects(self._object_graph_view): + # pylint: disable=protected-access + trackable._maybe_initialize_trackable() + if trackable._update_uid < self._checkpoint.restore_uid: + raise AssertionError(f"Object not restored: {trackable}") + # pylint: enable=protected-access + return self + + def assert_existing_objects_matched(self): + """Raises an exception if currently created objects are unmatched.""" + # For name-based checkpoints there's no object information in the + # checkpoint, so there's no distinction between + # assert_existing_objects_matched and assert_consumed (and both are less + # useful since we don't touch Python objects or Python state). + return self.assert_consumed() + + def assert_nontrivial_match(self): + """Raises an exception if currently created objects are unmatched.""" + # For name-based checkpoints there's no object information in the + # checkpoint, so there's no distinction between + # assert_nontrivial_match and assert_consumed (and both are less + # useful since we don't touch Python objects or Python state). + return self.assert_consumed() + + def _gather_saveable_objects(self): + """Walk the object graph, using global names for SaveableObjects.""" + objects = util.list_objects(self._object_graph_view) + saveable_objects = [] + for trackable in objects: + # pylint: disable=protected-access + trackable._maybe_initialize_trackable() + if trackable._update_uid < self._checkpoint.restore_uid: + trackable._update_uid = self._checkpoint.restore_uid + else: + continue + # pylint: enable=protected-access + saveable_objects.extend( + self._checkpoint.globally_named_object_attributes(trackable)) + return saveable_objects + + def run_restore_ops(self, session=None): + """Load the name-based checkpoint using a new `tf.compat.v1.train.Saver`.""" + if context.executing_eagerly(): + return # Nothing to do, variables are restored on creation. + if session is None: + session = get_session() + with ops.device("/cpu:0"): + saveables = self._gather_saveable_objects() + v1_saver_lib.Saver(saveables).restore( + sess=session, save_path=self._checkpoint.save_path) + + def initialize_or_restore(self, session=None): + """Alias for `run_restore_ops`.""" + self.run_restore_ops(session=session) + + +class _SessionWithFeedDictAdditions(session_lib.SessionInterface): + """Pretends to be a session, inserts extra feeds on run().""" + + def __init__(self, session, feed_additions): + self._wrapped_session = session + self._feed_additions = feed_additions + + def run(self, fetches, feed_dict=None, **kwargs): + if feed_dict is None: + feed_dict = {} + else: + feed_dict = feed_dict.copy() + feed_dict.update(self._feed_additions) + return self._wrapped_session.run( + fetches=fetches, feed_dict=feed_dict, **kwargs) + + +class TrackableSaver: + """Saves and restores a `Trackable` object and its dependencies. + + See `Trackable` for details of dependency management. `Saver` wraps + `tf.compat.v1.train.Saver` for saving, including extra information about the + graph of + dependencies between Python objects. When restoring, it uses this information + about the save-time dependency graph to more robustly match objects with their + checkpointed values. When executing eagerly, it supports restoring variables + on object creation (see `Saver.restore`). + + Values in a checkpoint are mapped to `Trackable` Python objects + (`Variable`s, `Optimizer`s, `Layer`s) based on the names provided when the + checkpoint was written. To avoid breaking existing checkpoints when modifying + a class, dependency names (the names of attributes to which `Trackable` + objects are assigned) may not change. These names are local to objects, in + contrast to the `Variable.name`-based save/restore from + `tf.compat.v1.train.Saver`, and + so allow additional program transformations. + """ + + def __init__(self, graph_view): + """Configure saving. + + Args: + graph_view: An `ObjectGraphView` object containing a description of the + object graph to save. + """ + self._graph_view = graph_view + + # The following attributes are used when graph building. + + # self._cache: A more generic cache used to cache the serialized tensors and + # TrackableObjectGraph proto attributes. + # self._saveables_cache: A dictionary mapping `Trackable` objects -> + # attribute names -> SaveableObjects, used to avoid re-creating + # SaveableObjects when graph building. + if context.executing_eagerly(): + self._cache = None + self._saveables_cache = None + else: + self._cache = object_identity.ObjectIdentityWeakKeyDictionary() + self._saveables_cache = object_identity.ObjectIdentityWeakKeyDictionary() + + # The file prefix placeholder is created lazily when graph building (and not + # at all when executing eagerly) to avoid creating ops in the constructor + # (when they may never be necessary). + self._file_prefix_placeholder = None + + # Op caching for save + self._object_graph_feed_tensor = None + self._last_save_object_graph = None + self._file_prefix_feed_tensor = None + self._cached_save_operation = None + + # Op caching for restore, shared between _CheckpointRestoreCoordinators + self._restore_op_cache = {} + + # Object map used for checkpoint. This attribute is to be overridden by a + # Checkpoint subclass, e.g., AsyncCheckpoint, to replace the trackable + # objects for checkpoint saving. + self._object_map = None + + def _gather_serialized_tensors(self, object_graph_tensor=None): + """Gathers tensors to save to ckpt and includes the object graph proto.""" + serialized_tensors, feed_additions, registered_savers, graph_proto = ( + save_util.serialize_graph_view(self._graph_view, + self._object_map, + cache=self._cache)) + + if self._saveables_cache is not None: + # Store saveables cache for restoration purposes. + self._saveables_cache = ( + saveable_object_util.serialized_tensors_to_saveable_cache( + serialized_tensors)) + + if object_graph_tensor is None: + with ops.device("/cpu:0"): + object_graph_tensor = constant_op.constant( + graph_proto.SerializeToString(), dtype=dtypes.string) + else: + feed_additions.update( + {object_graph_tensor: graph_proto.SerializeToString()}) + assert base.OBJECT_GRAPH_PROTO_KEY not in serialized_tensors.get(None, {}) + serialized_tensors.setdefault(None, {})[base.OBJECT_GRAPH_PROTO_KEY] = ( + object_graph_tensor) + return serialized_tensors, feed_additions, registered_savers, graph_proto + + def _save_cached_when_graph_building(self, file_prefix, object_graph_tensor, + options): + """Create or retrieve save ops. + + Args: + file_prefix: The prefix for saved checkpoint files. + object_graph_tensor: A `Tensor` to which the current object graph will be + fed. + options: `CheckpointOptions` object. + + Returns: + A two-element tuple with a filename tensor and a feed_dict of tensors to + feed when running it (if graph building). The feed dict contains the + current object graph and any Python state to be saved in the + checkpoint. When executing eagerly only the first argument is meaningful. + """ + serialized_tensors, feed_additions, registered_savers, graph_proto = ( + self._gather_serialized_tensors(object_graph_tensor)) + + if (self._last_save_object_graph != graph_proto + # When executing eagerly, we need to re-create SaveableObjects each + # time save() is called so they pick up new Tensors passed to their + # constructors. That means the Saver needs to be copied with a new + # var_list. + or context.executing_eagerly() or ops.inside_function()): + saver = functional_saver.MultiDeviceSaver(serialized_tensors, + registered_savers) + save_op = saver.save(file_prefix, options=options) + with ops.device("/cpu:0"): + with ops.control_dependencies([save_op]): + self._cached_save_operation = array_ops.identity(file_prefix) + self._last_save_object_graph = graph_proto + return self._cached_save_operation, feed_additions + + def save(self, + file_prefix, + checkpoint_number=None, + session=None, + options=None): + """Save a training checkpoint. + + The saved checkpoint includes variables created by this object and any + Trackable objects it depends on at the time `Saver.save()` is called. + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). Names are generated based on this + prefix and `checkpoint_number`, if provided. + checkpoint_number: An integer variable or Tensor, used to number + checkpoints. Typically this value is saved along with other variables in + training checkpoints, which will happen automatically if it was created + by `root_trackable` or one of its dependencies (via + `Trackable._add_variable`). + session: The session to evaluate variables in. Ignored when executing + eagerly. If not provided when graph building, the default session is + used. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint. + + Raises: + RuntimeError: if called in V1 Graph mode without a default session. + """ + options = options or checkpoint_options.CheckpointOptions() + feed_dict = {} + use_session = (not context.executing_eagerly() and + not ops.inside_function()) + if checkpoint_number: + file_prefix = "%s-%d" % (file_prefix, checkpoint_number) + if use_session: + if self._object_graph_feed_tensor is None: + with ops.device("/cpu:0"): + self._object_graph_feed_tensor = constant_op.constant( + "", dtype=dtypes.string) + self._file_prefix_feed_tensor = constant_op.constant( + "", dtype=dtypes.string) + object_graph_tensor = self._object_graph_feed_tensor + file_prefix_tensor = self._file_prefix_feed_tensor + feed_dict[file_prefix_tensor] = file_prefix + else: + with ops.device("/cpu:0"): + file_prefix_tensor = ops.convert_to_tensor( + file_prefix, dtype=dtypes.string) + object_graph_tensor = None + + if not tensor_util.is_tensor(file_prefix): + file_io.recursive_create_dir(os.path.dirname(file_prefix)) + + save_path, new_feed_additions = self._save_cached_when_graph_building( + file_prefix_tensor, object_graph_tensor, options) + + if new_feed_additions: + feed_dict.update(new_feed_additions) + if not use_session: + session = None + elif session is None: + session = get_session() + + if session: + return session.run(save_path, feed_dict=feed_dict) + elif use_session: + raise RuntimeError(f"Unable to save checkpoint to \"{file_prefix}\" " + "in graph mode without a default session. Please use " + "`with tf.Session():` to create a session.") + else: + return save_path + + def restore(self, save_path, options=None): + """Restore a training checkpoint. + + Restores `root_trackable` and any objects that it tracks + (transitive). Either assigns values immediately if variables to restore have + been created already, or defers restoration until the variables are + created. Dependencies added to the `root_trackable` passed to the + constructor after this call will be matched if they have a corresponding + object in the checkpoint. + + When building a graph, restorations are added to the graph but not run. + + ```python + saver = Saver(root) + saver.restore(path) + ``` + + To ensure that loading is complete and no more deferred restorations will + take place, you can use the `assert_consumed()` method of the status object + returned by the `restore` call. + + The assert will raise an exception unless every object was matched and all + checkpointed values have a matching variable object. + + ```python + saver = Saver(root) + saver.restore(path).assert_consumed() + ``` + + When graph building, `assert_consumed()` indicates that all of the restore + ops which will be created for this checkpoint have been created. They can be + run via the `run_restore_ops()` function of the status object: + + ```python + saver.restore(path).assert_consumed().run_restore_ops() + ``` + + If the checkpoint has not been consumed completely, then the list of restore + ops will grow as more objects are added to the dependency graph. + + Name-based `tf.compat.v1.train.Saver` checkpoints can be loaded using this + method. There is no deferred loading, and names are used to match + variables. No restore ops are created/run until `run_restore_ops()` or + `initialize_or_restore()` are called on the returned status object, even + when executing eagerly. Re-encode name-based checkpoints using this + object-based `Saver.save` as soon as possible. + + Args: + save_path: The path to the checkpoint, as returned by `save` or + `tf.train.latest_checkpoint`. If None (as when there is no latest + checkpoint for `tf.train.latest_checkpoint` to return), returns an + object which may run initializers for objects in the dependency graph. + If the checkpoint was written by the name-based + `tf.compat.v1.train.Saver`, names are used to match variables. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + A load status object, which can be used to make assertions about the + status of checkpoint restoration and run initialization/restore ops + (of type `CheckpointLoadStatus`, or `InitializationOnlyStatus` if + `save_path` is `None`). + + If `save_path` points to a name-based checkpoint, a `NameBasedSaverStatus` + object is returned which runs restore ops from a name-based saver. + + Raises: + RuntimeError: When a checkpoint file saved by async checkpoint is not + available upon restore(). + """ + options = options or checkpoint_options.CheckpointOptions() + if save_path is None: + return InitializationOnlyStatus(self._graph_view, ops.uid()) + + # Wait until the ongoing checkpoint to finish. + # TODO(chienchunh): Allow to load the file while other checkpoint events + # are still ongiing. Need to add timeout mechanism along + # with conditional variables to notify when the checkpoint + # file is ready. + global _ASYNC_CHECKPOINT_THREAD + if _ASYNC_CHECKPOINT_THREAD is not None: + _ASYNC_CHECKPOINT_THREAD.join() + reader = py_checkpoint_reader.NewCheckpointReader(save_path) + graph_building = not context.executing_eagerly() + if graph_building: + dtype_map = None + else: + dtype_map = reader.get_variable_to_dtype_map() + try: + object_graph_string = reader.get_tensor(base.OBJECT_GRAPH_PROTO_KEY) + except errors_impl.NotFoundError: + # The object graph proto does not exist in this checkpoint. Try the + # name-based compatibility mode. + restore_coordinator = _NameBasedRestoreCoordinator( + save_path=save_path, + dtype_map=dtype_map) + if not graph_building: + for existing_trackable in util.list_objects(self._graph_view): + # pylint: disable=protected-access + existing_trackable._maybe_initialize_trackable() + existing_trackable._name_based_restores.add(restore_coordinator) + existing_trackable._name_based_attribute_restore(restore_coordinator) + # pylint: enable=protected-access + return NameBasedSaverStatus( + restore_coordinator, + object_graph_view=self._graph_view) + + if graph_building: + if self._file_prefix_placeholder is None: + with ops.device("/cpu:0"): + self._file_prefix_placeholder = constant_op.constant("model") + file_prefix_tensor = self._file_prefix_placeholder + file_prefix_feed_dict = {self._file_prefix_placeholder: save_path} + else: + with ops.device("/cpu:0"): + file_prefix_tensor = constant_op.constant(save_path) + file_prefix_feed_dict = None + object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph()) + object_graph_proto.ParseFromString(object_graph_string) + checkpoint = _CheckpointRestoreCoordinator( + object_graph_proto=object_graph_proto, + save_path=save_path, + save_path_tensor=file_prefix_tensor, + reader=reader, + restore_op_cache=self._restore_op_cache, + graph_view=self._graph_view, + options=options, + saveables_cache=self._saveables_cache) + restore_lib.CheckpointPosition( + checkpoint=checkpoint, proto_id=0).restore(self._graph_view.root, + reader) + + # Attached dependencies are not attached to the root, so should be restored + # separately. + if self._graph_view.attached_dependencies: + for ref in self._graph_view.attached_dependencies: + if ref.name == "root": + # Root dependency is automatically added to attached dependencies -- + # this can be ignored since it maps back to the root object. + continue + proto_id = None + # Find proto ID of attached dependency (if it is in the proto). + for proto_ref in object_graph_proto.nodes[0].children: + if proto_ref.local_name == ref.name: + proto_id = proto_ref.node_id + break + + if proto_id in checkpoint.object_by_proto_id: + # Object has already been restored. This can happen when there's an + # indirect connection from the attached object to the root. + continue + + if proto_id is None: + # Could not find attached dependency in proto. + continue + + restore_lib.CheckpointPosition( + checkpoint=checkpoint, + proto_id=proto_id).restore(ref.ref, reader) + + load_status = CheckpointLoadStatus( + checkpoint, + graph_view=self._graph_view, + feed_dict=file_prefix_feed_dict) + return load_status + + +def frozen_saver(root_trackable): + """Creates a static `tf.compat.v1.train.Saver` from a trackable object. + + The returned `Saver` saves object-based checkpoints, but these checkpoints + will no longer reflect structural changes to the object graph, only changes to + the values of `Variable`s added as dependencies of the root object before + `freeze` was called. + + `restore` works on the returned `Saver`, but requires that the object graph of + the checkpoint being loaded exactly matches the object graph when `freeze` was + called. This is in contrast the object-based restore performed by + `tf.train.Checkpoint` which attempts a fuzzy matching between a checkpoint's + object graph and the current Python object graph. + + Args: + root_trackable: A trackable object to save. + + Returns: + A saver which saves object-based checkpoints for the object graph frozen at + the time `frozen_saver` was called. + """ + named_saveable_objects, registered_savers = ( + save_util_v1.frozen_saveables_and_savers( + graph_view_lib.ObjectGraphView(root_trackable))) + return functional_saver.MultiDeviceSaver.from_saveables( + named_saveable_objects, registered_savers) + + +def _assert_trackable(obj, name): + if not isinstance( + obj, (base.Trackable, def_function.Function)): + raise ValueError( + f"`Checkpoint` was expecting {name} to be a trackable object (an " + f"object derived from `Trackable`), got {obj}. If you believe this " + "object should be trackable (i.e. it is part of the " + "TensorFlow Python API and manages state), please open an issue.") + + +def _update_checkpoint_state_internal(file_path): + """Update internal checkpoint state.""" + checkpoint_management.update_checkpoint_state_internal( + save_dir=os.path.dirname(file_path), + model_checkpoint_path=file_path, + all_model_checkpoint_paths=[file_path], + save_relative_paths=True) + + +def _convert_file_name_tensor_to_string(tensor): + """Convert file name tensor to string.""" + output = tensor + if tensor_util.is_tf_type(output): + # Convert to numpy if not `tf.function` building. + if context.executing_eagerly(): + output = compat.as_str(output.numpy()) + else: + # Graph + Session, so we already session.ran it. + output = compat.as_str(output) + return output + + +def _copy_single_tensor(tensor): + """Copies a single Tensor / SaveSpec onto the CPU device.""" + device = tensor.device + if isinstance(tensor, saveable_object_lib.SaveSpec): + # Pin the device according to the tensor's device location to + # avoid unnecessary data copies when reading the variables. This is + # aligned with the behavior in MultiDeviceSaver.save(). + with ops.device(device): + tensor = tensor.tensor + + if tensor is not None: + with ops.device(saveable_object_util.set_cpu0(device)): + tensor = array_ops.identity(tensor) # pylint: disable=protected-access + return tensor + + +# Mentions graph building / Sessions. The v2 version is below. +@tf_export(v1=["train.Checkpoint"]) +class CheckpointV1(autotrackable.AutoTrackable): + """Groups trackable objects, saving and restoring them. + + `Checkpoint`'s constructor accepts keyword arguments whose values are types + that contain trackable state, such as `tf.compat.v1.train.Optimizer` + implementations, `tf.Variable`, `tf.keras.Layer` implementations, or + `tf.keras.Model` implementations. It saves these values with a checkpoint, and + maintains a `save_counter` for numbering checkpoints. + + Example usage when graph building: + + ```python + import tensorflow as tf + import os + + checkpoint_directory = "/tmp/training_checkpoints" + checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") + + checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) + status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory)) + train_op = optimizer.minimize( ... ) + status.assert_consumed() # Optional sanity checks. + with tf.compat.v1.Session() as session: + # Use the Session to restore variables, or initialize them if + # tf.train.latest_checkpoint returned None. + status.initialize_or_restore(session) + for _ in range(num_training_steps): + session.run(train_op) + checkpoint.save(file_prefix=checkpoint_prefix) + ``` + + Example usage with eager execution enabled: + + ```python + import tensorflow as tf + import os + + tf.compat.v1.enable_eager_execution() + + checkpoint_directory = "/tmp/training_checkpoints" + checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") + + checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) + status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory)) + for _ in range(num_training_steps): + optimizer.minimize( ... ) # Variables will be restored on creation. + status.assert_consumed() # Optional sanity checks. + checkpoint.save(file_prefix=checkpoint_prefix) + ``` + + `Checkpoint.save` and `Checkpoint.restore` write and read object-based + checkpoints, in contrast to `tf.compat.v1.train.Saver` which writes and reads + `variable.name` based checkpoints. Object-based checkpointing saves a graph of + dependencies between Python objects (`Layer`s, `Optimizer`s, `Variable`s, + etc.) with named edges, and this graph is used to match variables when + restoring a checkpoint. It can be more robust to changes in the Python + program, and helps to support restore-on-create for variables when executing + eagerly. Prefer `tf.train.Checkpoint` over `tf.compat.v1.train.Saver` for new + code. + + `Checkpoint` objects have dependencies on the objects passed as keyword + arguments to their constructors, and each dependency is given a name that is + identical to the name of the keyword argument for which it was created. + TensorFlow classes like `Layer`s and `Optimizer`s will automatically add + dependencies on their variables (e.g. "kernel" and "bias" for + `tf.keras.layers.Dense`). Inheriting from `tf.keras.Model` makes managing + dependencies easy in user-defined classes, since `Model` hooks into attribute + assignment. For example: + + ```python + class Regress(tf.keras.Model): + + def __init__(self): + super().__init__() + self.input_transform = tf.keras.layers.Dense(10) + # ... + + def call(self, inputs): + x = self.input_transform(inputs) + # ... + ``` + + This `Model` has a dependency named "input_transform" on its `Dense` layer, + which in turn depends on its variables. As a result, saving an instance of + `Regress` using `tf.train.Checkpoint` will also save all the variables created + by the `Dense` layer. + + When variables are assigned to multiple workers, each worker writes its own + section of the checkpoint. These sections are then merged/re-indexed to behave + as a single checkpoint. This avoids copying all variables to one worker, but + does require that all workers see a common filesystem. + + While `tf.keras.Model.save_weights` and `tf.train.Checkpoint.save` save in the + same format, note that the root of the resulting checkpoint is the object the + save method is attached to. This means saving a `tf.keras.Model` using + `save_weights` and loading into a `tf.train.Checkpoint` with a `Model` + attached (or vice versa) will not match the `Model`'s variables. See the + [guide to training + checkpoints](https://www.tensorflow.org/guide/checkpoint) for + details. Prefer `tf.train.Checkpoint` over `tf.keras.Model.save_weights` for + training checkpoints. + + Attributes: + save_counter: Incremented when `save()` is called. Used to number + checkpoints. + """ + + def __init__(self, **kwargs): + """Group objects into a training checkpoint. + + Args: + **kwargs: Keyword arguments are set as attributes of this object, and are + saved with the checkpoint. Values must be trackable objects. + + Raises: + ValueError: If objects in `kwargs` are not trackable. + """ + super().__init__() + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + if _END_TIME_OF_LAST_WRITE is None: + _END_TIME_OF_LAST_WRITE = time.time() + + for k, v in sorted(kwargs.items(), key=lambda item: item[0]): + setattr(self, k, v) + if not isinstance( + getattr(self, k), (base.Trackable, def_function.Function)): + raise ValueError( + "`Checkpoint` was expecting a trackable object (an object " + f"derived from `Trackable`), got {v}. If you believe this " + "object should be trackable (i.e. it is part of the " + "TensorFlow Python API and manages state), please open an issue.") + self._save_counter = None # Created lazily for restore-on-create. + self._save_assign_op = None + self._saver = TrackableSaver(graph_view_lib.ObjectGraphView(self)) + + def _maybe_create_save_counter(self): + """Create a save counter if it does not yet exist.""" + if self._save_counter is None: + # Initialized to 0 and incremented before saving. + with ops.device("/cpu:0"): + # add_variable creates a dependency named "save_counter"; NoDependency + # prevents creating a second dependency named "_save_counter". + self._save_counter = data_structures.NoDependency( + add_variable( + self, + name="save_counter", + initializer=0, + dtype=dtypes.int64, + trainable=False)) + + def write(self, file_prefix, session=None, options=None): + """Writes a training checkpoint. + + The checkpoint includes variables created by this object and any + trackable objects it depends on at the time `Checkpoint.write()` is + called. + + `write` does not number checkpoints, increment `save_counter`, or update the + metadata used by `tf.train.latest_checkpoint`. It is primarily intended for + use by higher level checkpoint management utilities. `save` provides a very + basic implementation of these features. + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). + session: The session to evaluate variables in. Ignored when executing + eagerly. If not provided when graph building, the default session is + used. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint (i.e. `file_prefix`). + """ + return self._write(file_prefix, session, options=options) + + def _write(self, file_prefix, session=None, options=None): + """Writes a training checkpoint. + + The checkpoint includes variables created by this object and any + trackable objects it depends on at the time `Checkpoint.write()` is + called. + + `write` does not number checkpoints, increment `save_counter`, or update the + metadata used by `tf.train.latest_checkpoint`. It is primarily intended for + use by higher level checkpoint management utilities. `save` provides a very + basic implementation of these features. + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). + session: The session to evaluate variables in. Ignored when executing + eagerly. If not provided when graph building, the default session is + used. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint (i.e. `file_prefix`). + """ + start_time = time.time() + output = self._saver.save(file_prefix=file_prefix, session=session, + options=options) + end_time = time.time() + + metrics.AddCheckpointWriteDuration( + api_label=_CHECKPOINT_V1, + microseconds=_get_duration_microseconds(start_time, end_time)) + + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + metrics.AddTrainingTimeSaved( + api_label=_CHECKPOINT_V1, + microseconds=_get_duration_microseconds(_END_TIME_OF_LAST_WRITE, + end_time)) + + if checkpoint_context.in_preemption_save_context(): + _preemption_checkpoint_saved_time_usecs.get_cell().increase_by( + _get_duration_microseconds(_END_TIME_OF_LAST_WRITE, end_time) + ) + + _END_TIME_OF_LAST_WRITE = end_time + + if tensor_util.is_tf_type(output): + # Convert to numpy if not `tf.function` building. + if context.executing_eagerly(): + output = compat.as_str(output.numpy()) + else: + # Graph + Session, so we already session.ran it. + output = compat.as_str(output) + + # Execute callbacks + if (options is not None and + options.experimental_write_callbacks is not None): + _execute_callbacks(options.experimental_write_callbacks, output) + + metrics.RecordCheckpointSize( + api_label=_CHECKPOINT_V1, filesize=_get_checkpoint_size(output)) + return output + + @property + def save_counter(self): + """An integer variable which starts at zero and is incremented on save. + + Used to number checkpoints. + + Returns: + The save counter variable. + """ + self._maybe_create_save_counter() + return self._save_counter + + def save(self, file_prefix, session=None, options=None): + """Saves a training checkpoint and provides basic checkpoint management. + + The saved checkpoint includes variables created by this object and any + trackable objects it depends on at the time `Checkpoint.save()` is + called. + + `save` is a basic convenience wrapper around the `write` method, + sequentially numbering checkpoints using `save_counter` and updating the + metadata used by `tf.train.latest_checkpoint`. More advanced checkpoint + management, for example garbage collection and custom numbering, may be + provided by other utilities which also wrap `write` + (`tf.train.CheckpointManager` for example). + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). Names are generated based on this + prefix and `Checkpoint.save_counter`. + session: The session to evaluate variables in. Ignored when executing + eagerly. If not provided when graph building, the default session is + used. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint. + """ + graph_building = not context.executing_eagerly() + if graph_building: + if ops.inside_function(): + raise NotImplementedError( + "Calling tf.train.Checkpoint.save() from a function is not " + "supported, as save() modifies saving metadata in ways not " + "supported by TensorFlow Operations. Consider using " + "tf.train.Checkpoint.write(), a lower-level API which does not " + "update metadata. tf.train.latest_checkpoint and related APIs will " + "not see this checkpoint.") + if session is None: + session = get_session() + if self._save_counter is None: + # When graph building, if this is a new save counter variable then it + # needs to be initialized before assign_add. This is only an issue if + # restore() has not been called first. + session.run(self.save_counter.initializer) + if not graph_building or self._save_assign_op is None: + with ops.colocate_with(self.save_counter): + assign_op = self.save_counter.assign_add(1, read_value=True) + if graph_building: + self._save_assign_op = data_structures.NoDependency(assign_op) + if graph_building: + checkpoint_number = session.run(self._save_assign_op) + else: + checkpoint_number = assign_op.numpy() + file_path = self.write( + "%s-%d" % (file_prefix, checkpoint_number), + session=session, + options=options + ) + checkpoint_management.update_checkpoint_state_internal( + save_dir=os.path.dirname(file_prefix), + model_checkpoint_path=file_path, + all_model_checkpoint_paths=[file_path], + save_relative_paths=True) + return file_path + + def restore(self, save_path): + """Restore a training checkpoint. + + Restores this `Checkpoint` and any objects it depends on. + + When executing eagerly, either assigns values immediately if variables to + restore have been created already, or defers restoration until the variables + are created. Dependencies added after this call will be matched if they have + a corresponding object in the checkpoint (the restore request will queue in + any trackable object waiting for the expected dependency to be added). + + When graph building, restoration ops are added to the graph but not run + immediately. + + ```python + checkpoint = tf.train.Checkpoint( ... ) + checkpoint.restore(path) + ``` + + To ensure that loading is complete and no more deferred restorations will + take place, you can use the `assert_consumed()` method of the status object + returned by `restore`. + The assert will raise an exception if any Python objects in the dependency + graph were not found in the checkpoint, or if any checkpointed values do not + have a matching Python object: + + ```python + checkpoint = tf.train.Checkpoint( ... ) + checkpoint.restore(path).assert_consumed() + ``` + + When graph building, `assert_consumed()` indicates that all of the restore + ops that will be created for this checkpoint have been created. They can be + run via the `run_restore_ops()` method of the status object: + + ```python + checkpoint.restore(path).assert_consumed().run_restore_ops() + ``` + + If the checkpoint has not been consumed completely, then the list of restore + ops will grow as more objects are added to the dependency graph. + + To check that all variables in the Python object have restored values from + checkpoint, use `assert_existing_objects_matched()`. This assertion is + useful when called after the variables in your graph have been created. + + Name-based `tf.compat.v1.train.Saver` checkpoints can be loaded using this + method. Names are used to match variables. No restore ops are created/run + until `run_restore_ops()` or `initialize_or_restore()` are called on the + returned status object when graph building, but there is restore-on-creation + when executing eagerly. Re-encode name-based checkpoints using + `tf.train.Checkpoint.save` as soon as possible. + + Args: + save_path: The path to the checkpoint, as returned by `save` or + `tf.train.latest_checkpoint`. If None (as when there is no latest + checkpoint for `tf.train.latest_checkpoint` to return), returns an + object which may run initializers for objects in the dependency graph. + If the checkpoint was written by the name-based + `tf.compat.v1.train.Saver`, names are used to match variables. + + Returns: + A load status object, which can be used to make assertions about the + status of a checkpoint restoration and run initialization/restore ops. + + The returned status object has the following methods: + + * `assert_consumed()`: + Raises an exception if any variables are unmatched: either + checkpointed values which don't have a matching Python object or + Python objects in the dependency graph with no values in the + checkpoint. This method returns the status object, and so may be + chained with `initialize_or_restore` or `run_restore_ops`. + + * `assert_existing_objects_matched()`: + Raises an exception if any existing Python objects in the dependency + graph are unmatched. Unlike `assert_consumed`, this assertion will + pass if values in the checkpoint have no corresponding Python + objects. For example a `tf.keras.Layer` object which has not yet been + built, and so has not created any variables, will pass this assertion + but will fail `assert_consumed`. Useful when loading part of a larger + checkpoint into a new Python program, e.g. a training checkpoint with + a `tf.compat.v1.train.Optimizer` was saved but only the state required + for inference is being loaded. This method returns the status object, + and so may be chained with `initialize_or_restore` or + `run_restore_ops`. + + * `assert_nontrivial_match()`: Asserts that something aside from the root + object was matched. This is a very weak assertion, but is useful for + sanity checking in library code where objects may exist in the + checkpoint which haven't been created in Python and some Python + objects may not have a checkpointed value. + + * `expect_partial()`: Silence warnings about incomplete checkpoint + restores. Warnings are otherwise printed for unused parts of the + checkpoint file or object when the `Checkpoint` object is deleted + (often at program shutdown). + + * `initialize_or_restore(session=None)`: + When graph building, runs variable initializers if `save_path` is + `None`, but otherwise runs restore operations. If no `session` is + explicitly specified, the default session is used. No effect when + executing eagerly (variables are initialized or restored eagerly). + + * `run_restore_ops(session=None)`: + When graph building, runs restore operations. If no `session` is + explicitly specified, the default session is used. No effect when + executing eagerly (restore operations are run eagerly). May only be + called when `save_path` is not `None`. + """ + start_time = time.time() + status = self._saver.restore(save_path=save_path) + # Create the save counter now so it gets initialized with other variables + # when graph building. Creating it earlier would lead to errors when using, + # say, train.Saver() to save the model before initializing it. + self._maybe_create_save_counter() + if isinstance(status, NameBasedSaverStatus): + status.add_to_optionally_restored(self.save_counter) + + metrics.AddCheckpointReadDuration( + api_label=_CHECKPOINT_V1, + microseconds=_get_duration_microseconds(start_time, time.time())) + return status + + +@tf_export("train.Checkpoint", v1=[]) +class Checkpoint(autotrackable.AutoTrackable): + """Manages saving/restoring trackable values to disk. + + TensorFlow objects may contain trackable state, such as `tf.Variable`s, + `tf.keras.optimizers.Optimizer` implementations, `tf.data.Dataset` iterators, + `tf.keras.Layer` implementations, or `tf.keras.Model` implementations. + These are called **trackable objects**. + + A `Checkpoint` object can be constructed to save either a single or group of + trackable objects to a checkpoint file. It maintains a `save_counter` for + numbering checkpoints. + + Example: + + ```python + model = tf.keras.Model(...) + checkpoint = tf.train.Checkpoint(model) + + # Save a checkpoint to /tmp/training_checkpoints-{save_counter}. Every time + # checkpoint.save is called, the save counter is increased. + save_path = checkpoint.save('/tmp/training_checkpoints') + + # Restore the checkpointed values to the `model` object. + checkpoint.restore(save_path) + ``` + + Example 2: + + ```python + import tensorflow as tf + import os + + checkpoint_directory = "/tmp/training_checkpoints" + checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt") + + # Create a Checkpoint that will manage two objects with trackable state, + # one we name "optimizer" and the other we name "model". + checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) + status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory)) + for _ in range(num_training_steps): + optimizer.minimize( ... ) # Variables will be restored on creation. + status.assert_consumed() # Optional sanity checks. + checkpoint.save(file_prefix=checkpoint_prefix) + ``` + + `Checkpoint.save()` and `Checkpoint.restore()` write and read object-based + checkpoints, in contrast to TensorFlow 1.x's `tf.compat.v1.train.Saver` which + writes and + reads `variable.name` based checkpoints. Object-based checkpointing saves a + graph of dependencies between Python objects (`Layer`s, `Optimizer`s, + `Variable`s, etc.) with named edges, and this graph is used to match variables + when restoring a checkpoint. It can be more robust to changes in the Python + program, and helps to support restore-on-create for variables. + + `Checkpoint` objects have dependencies on the objects passed as keyword + arguments to their constructors, and each dependency is given a name that is + identical to the name of the keyword argument for which it was created. + TensorFlow classes like `Layer`s and `Optimizer`s will automatically add + dependencies on their own variables (e.g. "kernel" and "bias" for + `tf.keras.layers.Dense`). Inheriting from `tf.keras.Model` makes managing + dependencies easy in user-defined classes, since `Model` hooks into attribute + assignment. For example: + + ```python + class Regress(tf.keras.Model): + + def __init__(self): + super().__init__() + self.input_transform = tf.keras.layers.Dense(10) + # ... + + def call(self, inputs): + x = self.input_transform(inputs) + # ... + ``` + + This `Model` has a dependency named "input_transform" on its `Dense` layer, + which in turn depends on its variables. As a result, saving an instance of + `Regress` using `tf.train.Checkpoint` will also save all the variables created + by the `Dense` layer. + + When variables are assigned to multiple workers, each worker writes its own + section of the checkpoint. These sections are then merged/re-indexed to behave + as a single checkpoint. This avoids copying all variables to one worker, but + does require that all workers see a common filesystem. + + This function differs slightly from the Keras Model `save_weights` function. + `tf.keras.Model.save_weights` creates a checkpoint file with the name + specified in `filepath`, while `tf.train.Checkpoint` numbers the checkpoints, + using `filepath` as the prefix for the checkpoint file names. Aside from this, + `model.save_weights()` and `tf.train.Checkpoint(model).save()` are equivalent. + + See the [guide to training + checkpoints](https://www.tensorflow.org/guide/checkpoint) for + details. + + Attributes: + save_counter: Incremented when `save()` is called. Used to number + checkpoints. + """ + + def __init__(self, root=None, **kwargs): + """Creates a training checkpoint for a single or group of objects. + + Args: + root: The root object to checkpoint. `root` may be a trackable object or + `WeakRef` of a trackable object. + **kwargs: Keyword arguments are set as attributes of this object, and are + saved with the checkpoint. All `kwargs` must be trackable objects, or a + nested structure of trackable objects (`list`, `dict`, or `tuple`). + + Raises: + ValueError: If `root` or the objects in `kwargs` are not trackable. A + `ValueError` is also raised if the `root` object tracks different + objects from the ones listed in attributes in kwargs (e.g. + `root.child = A` and `tf.train.Checkpoint(root, child=B)` are + incompatible). + + """ + super().__init__() + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + if _END_TIME_OF_LAST_WRITE is None: + _END_TIME_OF_LAST_WRITE = time.time() + + # Store a reference to root and kwargs if we need to instantiate an + # AsyncCheckpointer later. + self._root = root + self._kwargs = kwargs + self._delete_tracking("_kwargs") + + # Don't instantiate the AsyncCheckpointer unless required. + self._async_checkpointer_impl = None + + # Store checkpoint options during the save/write calls so that subsequent + # read/restore calls are done properly. This is only populated when + # async read/write is enabled. + self._checkpoint_options = None + + attached_dependencies = None + self._save_counter = None # Created lazily for restore-on-create. + self._save_assign_op = None + + if root: + trackable_root = root() if isinstance(root, weakref.ref) else root + _assert_trackable(trackable_root, "root") + attached_dependencies = [] + + # All keyword arguments (including root itself) are set as children + # of root. + kwargs["root"] = root + trackable_root._maybe_initialize_trackable() + + self._save_counter = data_structures.NoDependency( + trackable_root._lookup_dependency("save_counter")) + + for k, v in sorted(kwargs.items(), key=lambda item: item[0]): + setattr(self, k, v) + + # Call getattr instead of directly using v because setattr converts + # v to a Trackable data structure when v is a list/dict/tuple. + converted_v = getattr(self, k) + if isinstance(converted_v, weakref.ref): + converted_v = converted_v() + _assert_trackable(converted_v, k) + + if root: + # Make sure that root doesn't already have dependencies with these names + child = trackable_root._lookup_dependency(k) + if child is None: + attached_dependencies.append( + base.WeakTrackableReference(k, converted_v)) + elif child != converted_v: + raise ValueError( + f"Cannot create a Checkpoint with keyword argument {k} if " + f"root.{k} already exists.") + + self._saver = TrackableSaver( + graph_view_lib.ObjectGraphView( + root if root else self, + attached_dependencies=attached_dependencies)) + self._attached_dependencies = data_structures.NoDependency( + attached_dependencies) + + def _maybe_create_save_counter(self): + """Create a save counter if it does not yet exist.""" + if self._save_counter is None: + # Initialized to 0 and incremented before saving. + with ops.device("/cpu:0"): + # add_variable creates a dependency named "save_counter"; NoDependency + # prevents creating a second dependency named "_save_counter". + self._save_counter = data_structures.NoDependency( + add_variable( + self, + name="save_counter", + initializer=0, + dtype=dtypes.int64, + trainable=False)) + if self._attached_dependencies is not None: + self._attached_dependencies.append( + # Store a stronge reference to the `save_counter`, so that if the + # `Checkpoint` object is deleted, the `save_counter` does not get + # deleted immediately. (The LoadStatus object needs to indirectly + # reference the counter through the ObjectGraphView). + base.TrackableReference("save_counter", self._save_counter)) + # When loading a checkpoint, the save counter is created after + # the checkpoint has been loaded, so it must be handled in a deferred + # manner. + if isinstance(self.root, weakref.ref): + root = self.root() + else: + root = self.root + restore = root._deferred_dependencies.pop("save_counter", ()) # pylint: disable=protected-access + if restore: + restore[0].restore(self._save_counter) + + def write(self, file_prefix, options=None): + """Writes a training checkpoint. + + The checkpoint includes variables created by this object and any + trackable objects it depends on at the time `Checkpoint.write()` is + called. + + `write` does not number checkpoints, increment `save_counter`, or update the + metadata used by `tf.train.latest_checkpoint`. It is primarily intended for + use by higher level checkpoint management utilities. `save` provides a very + basic implementation of these features. + + Checkpoints written with `write` must be read with `read`. + + Example usage: + + ``` + step = tf.Variable(0, name="step") + checkpoint = tf.Checkpoint(step=step) + checkpoint.write("/tmp/ckpt") + + # Later, read the checkpoint with read() + checkpoint.read("/tmp/ckpt") + + # You can also pass options to write() and read(). For example this + # runs the IO ops on the localhost: + options = tf.CheckpointOptions(experimental_io_device="/job:localhost") + checkpoint.write("/tmp/ckpt", options=options) + + # Later, read the checkpoint with read() + checkpoint.read("/tmp/ckpt", options=options) + ``` + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint (i.e. `file_prefix`). + """ + if isinstance(file_prefix, os.PathLike): + file_prefix = os.fspath(file_prefix) + return self._write(file_prefix, options) + + def _async_checkpointer(self): + """Returns an instantiated AsyncCheckpointHelper.""" + if self._async_checkpointer_impl is None: + self._async_checkpointer_impl = ( + async_checkpoint_helper.AsyncCheckpointHelper( + Checkpoint, + **self._kwargs)) + + return self._async_checkpointer_impl + + def _write(self, file_prefix, options=None): + """Internal method that implements Checkpoint.write(). + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint (i.e. `file_prefix`). + """ + # Triggers TF2 async checkpoint handling if: + # 1. async checkpoint is enabled in CheckpointOptions + # 2. running in eager mode + if options and options.experimental_enable_async_checkpoint: + self._checkpoint_options = options + if checkpoint_context.in_preemption_save_context(): + # Make sure all in-progress writes have completed before saving the + # final preemption checkpoint. + if self._async_checkpointer_impl is not None: + self._async_checkpointer_impl.sync() + # Additional work done will not be saved in a future checkpoint, so + # we use regular sync checkpoint to avoid overhead of dispatching + # checkpoint write to a new thread. + logging.warning( + "Switching to regular sync checkpoint for preemption checkpoint." + ) + elif context.executing_eagerly(): + return self._async_checkpointer()._write( # pylint: disable=protected-access + file_prefix, options) + else: + logging.warning( + "Saving async checkpoint in graph mode is currently not supported;" + " switching to regular sync checkpoint instead.") + + start_time = time.time() + options = options or checkpoint_options.CheckpointOptions() + output = self._saver.save(file_prefix=file_prefix, options=options) + output = _convert_file_name_tensor_to_string(output) + + # Execute callbacks (the only place they are executed; i.e. all entry points + # for callbacks will ultimately be directed to here for execution) + if options.experimental_write_callbacks: + _execute_callbacks(options.experimental_write_callbacks, output) + + # Ensure save operations have completed when running in eager runtime. + if context.executing_eagerly(): + context.async_wait() + + end_time = time.time() + + if not checkpoint_context.in_async_metrics_context(): + # This records the time checkpoint._write() blocks on the main thread. + metrics.AddCheckpointWriteDuration( + api_label=_CHECKPOINT_V2, + microseconds=_get_duration_microseconds(start_time, end_time), + ) + + global _END_TIME_OF_LAST_WRITE + with _END_TIME_OF_LAST_WRITE_LOCK: + if not checkpoint_context.in_async_metrics_context(): + metrics.AddTrainingTimeSaved( + api_label=_CHECKPOINT_V2, + microseconds=_get_duration_microseconds( + _END_TIME_OF_LAST_WRITE, end_time) + ) + if checkpoint_context.in_preemption_save_context(): + _preemption_checkpoint_saved_time_usecs.get_cell().increase_by( + _get_duration_microseconds(_END_TIME_OF_LAST_WRITE, end_time) + ) + _END_TIME_OF_LAST_WRITE = end_time + + metrics.RecordCheckpointSize( + api_label=_CHECKPOINT_V2, filesize=_get_checkpoint_size(output) + ) + return output + + @property + def save_counter(self): + """An integer variable which starts at zero and is incremented on save. + + Used to number checkpoints. + + Returns: + The save counter variable. + """ + self._maybe_create_save_counter() + return self._save_counter + + def sync(self): + """Wait for any outstanding save or restore operations.""" + # Subclasses of Checkpoint may not have `_async_checkpointer_impl` so use + # `getattr` for safer check. + if getattr(self, "_async_checkpointer_impl", None) is not None: + self._async_checkpointer_impl.sync() + + def save(self, file_prefix, options=None): + # pylint:disable=line-too-long + """Saves a training checkpoint and provides basic checkpoint management. + + The saved checkpoint includes variables created by this object and any + trackable objects it depends on at the time `Checkpoint.save()` is + called. + + `save` is a basic convenience wrapper around the `write` method, + sequentially numbering checkpoints using `save_counter` and updating the + metadata used by `tf.train.latest_checkpoint`. More advanced checkpoint + management, for example garbage collection and custom numbering, may be + provided by other utilities which also wrap `write` and `read`. + (`tf.train.CheckpointManager` for example). + + ``` + step = tf.Variable(0, name="step") + checkpoint = tf.train.Checkpoint(step=step) + checkpoint.save("/tmp/ckpt") + + # Later, read the checkpoint with restore() + checkpoint.restore("/tmp/ckpt-1") + + # You can also pass options to save() and restore(). For example this + # runs the IO ops on the localhost: + options = tf.train.CheckpointOptions(experimental_io_device="/job:localhost") + checkpoint.save("/tmp/ckpt", options=options) + + # Later, read the checkpoint with restore() + checkpoint.restore("/tmp/ckpt-1", options=options) + ``` + + Args: + file_prefix: A prefix to use for the checkpoint filenames + (/path/to/directory/and_a_prefix). Names are generated based on this + prefix and `Checkpoint.save_counter`. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + The full path to the checkpoint. + """ + # Triggers TF2 async checkpoint handling if: + # 1. async checkpoint is enabled in CheckpointOptions + # 2. running in eager mode + if options and options.experimental_enable_async_checkpoint: + self._checkpoint_options = options + if checkpoint_context.in_preemption_save_context(): + # Make sure all in-progress writes have completed before saving the + # final preemption checkpoint. + if self._async_checkpointer_impl is not None: + self._async_checkpointer_impl.sync() + # Additional work done will not be saved in a future checkpoint, so + # we use regular sync checkpoint to avoid overhead of dispatching + # checkpoint write to a new thread. + logging.warning( + "Switching to regular sync checkpoint for preemption checkpoint." + ) + elif context.executing_eagerly(): + return self._async_checkpointer().save(file_prefix, options) + else: + logging.warning( + "Saving async checkpoint in graph mode is currently not supported;" + " switching to regular sync checkpoint instead.") + + if isinstance(file_prefix, os.PathLike): + file_prefix = os.fspath(file_prefix) + # pylint:enable=line-too-long + # We create a copy so that user's `options` instance would not be mutated + # by internal mechanisms. + options = copy.copy(options) or checkpoint_options.CheckpointOptions() + graph_building = not context.executing_eagerly() + if graph_building: + if ops.inside_function(): + raise NotImplementedError( + "Calling tf.train.Checkpoint.save() from a function is not " + "supported, as save() modifies saving metadata in ways not " + "supported by TensorFlow Operations. Consider using " + "tf.train.Checkpoint.write(), a lower-level API which does not " + "update metadata. tf.train.latest_checkpoint and related APIs will " + "not see this checkpoint.") + session = get_session() + if self._save_counter is None: + # When graph building, if this is a new save counter variable then it + # needs to be initialized before assign_add. This is only an issue if + # restore() has not been called first. + session.run(self.save_counter.initializer) + + if not graph_building or self._save_assign_op is None: + with ops.colocate_with(self.save_counter): + assign_op = self.save_counter.assign_add(1, read_value=True) + if graph_building: + self._save_assign_op = data_structures.NoDependency(assign_op) + + if graph_building: + checkpoint_number = session.run(self._save_assign_op) + else: + checkpoint_number = assign_op.numpy() + + if options.experimental_write_callbacks is None: + options.experimental_write_callbacks = [_update_checkpoint_state_internal] + else: + options.experimental_write_callbacks.append( + _update_checkpoint_state_internal + ) + + return self._write( + "%s-%d" % (file_prefix, checkpoint_number), + options=options) + + def read(self, save_path, options=None): + """Reads a training checkpoint written with `write`. + + Reads this `Checkpoint` and any objects it depends on. + + This method is just like `restore()` but does not expect the `save_counter` + variable in the checkpoint. It only restores the objects that the checkpoint + already depends on. + + The method is primarily intended for use by higher level checkpoint + management utilities that use `write()` instead of `save()` and have their + own mechanisms to number and track checkpoints. + + Example usage: + + ```python + # Create a checkpoint with write() + ckpt = tf.train.Checkpoint(v=tf.Variable(1.)) + path = ckpt.write('/tmp/my_checkpoint') + + # Later, load the checkpoint with read() + # With restore() assert_consumed() would have failed. + checkpoint.read(path).assert_consumed() + + # You can also pass options to read(). For example this + # runs the IO ops on the localhost: + options = tf.train.CheckpointOptions( + experimental_io_device="/job:localhost") + checkpoint.read(path, options=options) + ``` + + Args: + save_path: The path to the checkpoint as returned by `write`. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + A load status object, which can be used to make assertions about the + status of a checkpoint restoration. See `restore` for details. + """ + if options and options.experimental_enable_async_checkpoint: + self._checkpoint_options = options + # Triggers TF2 async checkpoint handling if: + # 1. async checkpoint is enabled in CheckpointOptions + # 2. there's a preceeding async save/write + # 3. running in eager mode + if (self._checkpoint_options and + self._checkpoint_options.experimental_enable_async_checkpoint): + if context.executing_eagerly(): + return self._async_checkpointer().read(save_path, options) + else: + logging.warning( + "Saving async checkpoint in graph mode is currently not supported;" + " switching to regular sync checkpoint instead.") + + start_time = time.time() + if isinstance(save_path, os.PathLike): + save_path = os.fspath(save_path) + options = options or checkpoint_options.CheckpointOptions() + result = self._saver.restore(save_path=save_path, options=options) + metrics.AddCheckpointReadDuration( + api_label=_CHECKPOINT_V2, + microseconds=_get_duration_microseconds(start_time, time.time())) + return result + + def restore(self, save_path, options=None): + """Restores a training checkpoint. + + Restores this `Checkpoint` and any objects it depends on. + + This method is intended to be used to load checkpoints created by `save()`. + For checkpoints created by `write()` use the `read()` method which does not + expect the `save_counter` variable added by `save()`. + + `restore()` either assigns values immediately if variables to restore have + been created already, or defers restoration until the variables are + created. Dependencies added after this call will be matched if they have a + corresponding object in the checkpoint (the restore request will queue in + any trackable object waiting for the expected dependency to be added). + + ```python + checkpoint = tf.train.Checkpoint( ... ) + checkpoint.restore(path) + + # You can additionally pass options to restore(): + options = tf.CheckpointOptions(experimental_io_device="/job:localhost") + checkpoint.restore(path, options=options) + ``` + + To ensure that loading is complete and no more deferred restorations will + take place, use the `assert_consumed()` method of the status object returned + by `restore()`: + + ```python + checkpoint.restore(path, options=options).assert_consumed() + ``` + + The assert will raise an error if any Python objects in the dependency graph + were not found in the checkpoint, or if any checkpointed values do not have + a matching Python object. + + Name-based `tf.compat.v1.train.Saver` checkpoints from TensorFlow 1.x can be + loaded using this method. Names are used to match variables. Re-encode + name-based checkpoints using `tf.train.Checkpoint.save` as soon as possible. + + **Loading from SavedModel checkpoints** + + To load values from a SavedModel, just pass the SavedModel directory + to checkpoint.restore: + + ```python + model = tf.keras.Model(...) + tf.saved_model.save(model, path) # or model.save(path, save_format='tf') + + checkpoint = tf.train.Checkpoint(model) + checkpoint.restore(path).expect_partial() + ``` + + This example calls `expect_partial()` on the loaded status, since + SavedModels saved from Keras often generates extra keys in the checkpoint. + Otherwise, the program prints a lot of warnings about unused keys at exit + time. + + Args: + save_path: The path to the checkpoint, as returned by `save` or + `tf.train.latest_checkpoint`. If the checkpoint was written by the + name-based `tf.compat.v1.train.Saver`, names are used to match + variables. This path may also be a SavedModel directory. + options: Optional `tf.train.CheckpointOptions` object. + + Returns: + A load status object, which can be used to make assertions about the + status of a checkpoint restoration. + + The returned status object has the following methods: + + * `assert_consumed()`: + Raises an exception if any variables are unmatched: either + checkpointed values which don't have a matching Python object or + Python objects in the dependency graph with no values in the + checkpoint. This method returns the status object, and so may be + chained with other assertions. + + * `assert_existing_objects_matched()`: + Raises an exception if any existing Python objects in the dependency + graph are unmatched. Unlike `assert_consumed`, this assertion will + pass if values in the checkpoint have no corresponding Python + objects. For example a `tf.keras.Layer` object which has not yet been + built, and so has not created any variables, will pass this assertion + but fail `assert_consumed`. Useful when loading part of a larger + checkpoint into a new Python program, e.g. a training checkpoint with + a `tf.compat.v1.train.Optimizer` was saved but only the state required + for + inference is being loaded. This method returns the status object, and + so may be chained with other assertions. + + * `assert_nontrivial_match()`: Asserts that something aside from the root + object was matched. This is a very weak assertion, but is useful for + sanity checking in library code where objects may exist in the + checkpoint which haven't been created in Python and some Python + objects may not have a checkpointed value. + + * `expect_partial()`: Silence warnings about incomplete checkpoint + restores. Warnings are otherwise printed for unused parts of the + checkpoint file or object when the `Checkpoint` object is deleted + (often at program shutdown). + + Raises: + NotFoundError: if the a checkpoint or SavedModel cannot be found at + `save_path`. + """ + if options and options.experimental_enable_async_checkpoint: + self._checkpoint_options = options + # Triggers TF2 async checkpoint handling if: + # 1. async checkpoint is enabled in CheckpointOptions + # 2. there's a preceeding async save/write + # 3. running in eager mode + if (self._checkpoint_options and + self._checkpoint_options.experimental_enable_async_checkpoint): + if context.executing_eagerly(): + return self._async_checkpointer().restore(save_path, options) + else: + logging.warning( + "Saving async checkpoint in graph mode is currently not supported;" + " switching to regular sync checkpoint instead.") + + orig_save_path = save_path + if isinstance(save_path, os.PathLike): + save_path = os.fspath(save_path) + + if save_path is not None and gfile.IsDirectory(save_path) and ( + (gfile.Exists(path_helpers.get_saved_model_pb_path(save_path)) or + gfile.Exists(path_helpers.get_saved_model_pbtxt_path(save_path)))): + save_path = path_helpers.get_variables_path(save_path) + + try: + status = self.read(save_path, options=options) + if context.executing_eagerly(): + context.async_wait() # Ensure restore operations have completed. + except errors_impl.NotFoundError as e: + raise errors_impl.NotFoundError( + None, None, + f"Error when restoring from checkpoint or SavedModel at " + f"{orig_save_path}: {e.message}" + f"\nPlease double-check that the path is correct. You may be missing " + "the checkpoint suffix (e.g. the '-1' in 'path/to/ckpt-1').") + # Create the save counter now so it gets initialized with other variables + # when graph building. Creating it earlier would lead to errors when using, + # say, train.Saver() to save the model before initializing it. + self._maybe_create_save_counter() + if isinstance(status, NameBasedSaverStatus): + status.add_to_optionally_restored(self.save_counter) + return status + + +_preemption_checkpoint_saved_time_usecs = monitoring.Counter( + "/tensorflow/api/distribution_strategy/preemption_checkpoint_saved_time_usecs", + "Training time saved by PreemptionCheckpointHandler (us).") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_context.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd27d7889a379b8adafcd97d56721a3b69bab61 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_context.py @@ -0,0 +1,85 @@ +# 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. +# ============================================================================== +"""Context for saving checkpoint.""" + +import contextlib +import threading + + +class PreemptionSaveContext(threading.local): + """A context for saving checkpoint upon preemption.""" + + def __init__(self): + super().__init__() + self._in_preemption_save_context = False + + def enter_preemption_save_context(self): + self._in_preemption_save_context = True + + def exit_preemption_save_context(self): + self._in_preemption_save_context = False + + def in_preemption_save_context(self): + return self._in_preemption_save_context + + +_preemption_save_context = PreemptionSaveContext() + + +@contextlib.contextmanager +def preemption_save_context(): + _preemption_save_context.enter_preemption_save_context() + try: + yield + finally: + _preemption_save_context.exit_preemption_save_context() + + +def in_preemption_save_context(): + return _preemption_save_context.in_preemption_save_context() + + +class AsyncMetricsContext(threading.local): + """A context for controlling metrics recording when async checkpoint is used. + """ + + def __init__(self): + super().__init__() + self._in_async_metrics_context = False + + def enter_async_metrics_context(self): + self._in_async_metrics_context = True + + def exit_async_metrics_context(self): + self._in_async_metrics_context = False + + def in_async_metrics_context(self): + return self._in_async_metrics_context + + +_async_metrics_context = AsyncMetricsContext() + + +@contextlib.contextmanager +def async_metrics_context(): + _async_metrics_context.enter_async_metrics_context() + try: + yield + finally: + _async_metrics_context.exit_async_metrics_context() + + +def in_async_metrics_context(): + return _async_metrics_context.in_async_metrics_context() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_management.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_management.py new file mode 100644 index 0000000000000000000000000000000000000000..a60df0b228ca364485f925960b196d0356cfbde5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_management.py @@ -0,0 +1,894 @@ +# 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. +# ============================================================================== + +# pylint: disable=invalid-name +"""Checkpoint Manager and other utilities for managing checkpoints.""" +import collections +import copy +import os.path +import re +import time + +from google.protobuf import text_format + +from tensorflow.core.protobuf import saver_pb2 +from tensorflow.python.checkpoint import checkpoint_options +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import training_util +from tensorflow.python.training.checkpoint_state_pb2 import CheckpointState +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +def _evaluate(tensor): + """Returns the numpy value of a tensor.""" + if context.executing_eagerly(): + return tensor.numpy() + return ops.get_default_session().run(tensor) + + +def _GetCheckpointFilename(save_dir, latest_filename): + """Returns a filename for storing the CheckpointState. + + Args: + save_dir: The directory for saving and restoring checkpoints. + latest_filename: Name of the file in 'save_dir' that is used + to store the CheckpointState. + + Returns: + The path of the file that contains the CheckpointState proto. + """ + if latest_filename is None: + latest_filename = "checkpoint" + return os.path.join(save_dir, latest_filename) + + +@tf_export(v1=["train.generate_checkpoint_state_proto"]) +def generate_checkpoint_state_proto(save_dir, + model_checkpoint_path, + all_model_checkpoint_paths=None, + all_model_checkpoint_timestamps=None, + last_preserved_timestamp=None): + """Generates a checkpoint state proto. + + Args: + save_dir: Directory where the model was saved. + model_checkpoint_path: The checkpoint file. + all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted + checkpoints, sorted from oldest to newest. If this is a non-empty list, + the last element must be equal to model_checkpoint_path. These paths + are also saved in the CheckpointState proto. + all_model_checkpoint_timestamps: A list of floats, indicating the number of + seconds since the Epoch when each checkpoint was generated. + last_preserved_timestamp: A float, indicating the number of seconds since + the Epoch when the last preserved checkpoint was written, e.g. due to a + `keep_checkpoint_every_n_hours` parameter (see + `tf.train.CheckpointManager` for an implementation). + Returns: + CheckpointState proto with model_checkpoint_path and + all_model_checkpoint_paths updated to either absolute paths or + relative paths to the current save_dir. + + Raises: + ValueError: If `all_model_checkpoint_timestamps` was provided but its length + does not match `all_model_checkpoint_paths`. + """ + if all_model_checkpoint_paths is None: + all_model_checkpoint_paths = [] + + if (not all_model_checkpoint_paths or + all_model_checkpoint_paths[-1] != model_checkpoint_path): + logging.info("%s is not in all_model_checkpoint_paths. Manually adding it.", + model_checkpoint_path) + all_model_checkpoint_paths.append(model_checkpoint_path) + + if (all_model_checkpoint_timestamps + and (len(all_model_checkpoint_timestamps) + != len(all_model_checkpoint_paths))): + raise ValueError( + ("Checkpoint timestamps, if provided, must match checkpoint paths (got " + "paths %s and timestamps %s)") + % (all_model_checkpoint_paths, all_model_checkpoint_timestamps)) + + # Relative paths need to be rewritten to be relative to the "save_dir" + # if model_checkpoint_path already contains "save_dir". + if not os.path.isabs(save_dir): + if not os.path.isabs(model_checkpoint_path): + model_checkpoint_path = os.path.relpath(model_checkpoint_path, save_dir) + for i, p in enumerate(all_model_checkpoint_paths): + if not os.path.isabs(p): + all_model_checkpoint_paths[i] = os.path.relpath(p, save_dir) + + coord_checkpoint_proto = CheckpointState( + model_checkpoint_path=model_checkpoint_path, + all_model_checkpoint_paths=all_model_checkpoint_paths, + all_model_checkpoint_timestamps=all_model_checkpoint_timestamps, + last_preserved_timestamp=last_preserved_timestamp) + + return coord_checkpoint_proto + + +@deprecation.deprecated( + date=None, + instructions=("Use `tf.train.CheckpointManager` to manage checkpoints " + "rather than manually editing the Checkpoint proto.")) +@tf_export(v1=["train.update_checkpoint_state"]) +def update_checkpoint_state(save_dir, + model_checkpoint_path, + all_model_checkpoint_paths=None, + latest_filename=None, + all_model_checkpoint_timestamps=None, + last_preserved_timestamp=None): + """Updates the content of the 'checkpoint' file. + + This updates the checkpoint file containing a CheckpointState + proto. + + Args: + save_dir: Directory where the model was saved. + model_checkpoint_path: The checkpoint file. + all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted + checkpoints, sorted from oldest to newest. If this is a non-empty list, + the last element must be equal to model_checkpoint_path. These paths + are also saved in the CheckpointState proto. + latest_filename: Optional name of the checkpoint file. Default to + 'checkpoint'. + all_model_checkpoint_timestamps: Optional list of timestamps (floats, + seconds since the Epoch) indicating when the checkpoints in + `all_model_checkpoint_paths` were created. + last_preserved_timestamp: A float, indicating the number of seconds since + the Epoch when the last preserved checkpoint was written, e.g. due to a + `keep_checkpoint_every_n_hours` parameter (see + `tf.train.CheckpointManager` for an implementation). + Raises: + RuntimeError: If any of the model checkpoint paths conflict with the file + containing CheckpointSate. + """ + update_checkpoint_state_internal( + save_dir=save_dir, + model_checkpoint_path=model_checkpoint_path, + all_model_checkpoint_paths=all_model_checkpoint_paths, + latest_filename=latest_filename, + save_relative_paths=False, + all_model_checkpoint_timestamps=all_model_checkpoint_timestamps, + last_preserved_timestamp=last_preserved_timestamp) + + +@tf_export("__internal__.train.update_checkpoint_state", v1=[]) +def update_checkpoint_state_internal(save_dir, + model_checkpoint_path, + all_model_checkpoint_paths=None, + latest_filename=None, + save_relative_paths=False, + all_model_checkpoint_timestamps=None, + last_preserved_timestamp=None): + """Updates the content of the 'checkpoint' file. + + This updates the checkpoint file containing a CheckpointState + proto. + + Args: + save_dir: Directory where the model was saved. + model_checkpoint_path: The checkpoint file. + all_model_checkpoint_paths: List of strings. Paths to all not-yet-deleted + checkpoints, sorted from oldest to newest. If this is a non-empty list, + the last element must be equal to model_checkpoint_path. These paths + are also saved in the CheckpointState proto. + latest_filename: Optional name of the checkpoint file. Default to + 'checkpoint'. + save_relative_paths: If `True`, will write relative paths to the checkpoint + state file. + all_model_checkpoint_timestamps: Optional list of timestamps (floats, + seconds since the Epoch) indicating when the checkpoints in + `all_model_checkpoint_paths` were created. + last_preserved_timestamp: A float, indicating the number of seconds since + the Epoch when the last preserved checkpoint was written, e.g. due to a + `keep_checkpoint_every_n_hours` parameter (see + `tf.train.CheckpointManager` for an implementation). + + Raises: + RuntimeError: If any of the model checkpoint paths conflict with the file + containing CheckpointSate. + """ + # Writes the "checkpoint" file for the coordinator for later restoration. + coord_checkpoint_filename = _GetCheckpointFilename(save_dir, latest_filename) + if save_relative_paths: + if os.path.isabs(model_checkpoint_path): + rel_model_checkpoint_path = os.path.relpath( + model_checkpoint_path, save_dir) + else: + rel_model_checkpoint_path = model_checkpoint_path + rel_all_model_checkpoint_paths = [] + for p in all_model_checkpoint_paths: + if os.path.isabs(p): + rel_all_model_checkpoint_paths.append(os.path.relpath(p, save_dir)) + else: + rel_all_model_checkpoint_paths.append(p) + ckpt = generate_checkpoint_state_proto( + save_dir, + rel_model_checkpoint_path, + all_model_checkpoint_paths=rel_all_model_checkpoint_paths, + all_model_checkpoint_timestamps=all_model_checkpoint_timestamps, + last_preserved_timestamp=last_preserved_timestamp) + else: + ckpt = generate_checkpoint_state_proto( + save_dir, + model_checkpoint_path, + all_model_checkpoint_paths=all_model_checkpoint_paths, + all_model_checkpoint_timestamps=all_model_checkpoint_timestamps, + last_preserved_timestamp=last_preserved_timestamp) + + if coord_checkpoint_filename == ckpt.model_checkpoint_path: + raise RuntimeError("Save path '%s' conflicts with path used for " + "checkpoint state. Please use a different save path." % + model_checkpoint_path) + + # Preventing potential read/write race condition by *atomically* writing to a + # file. + file_io.atomic_write_string_to_file(coord_checkpoint_filename, + text_format.MessageToString(ckpt)) + + +@tf_export("train.get_checkpoint_state") +def get_checkpoint_state(checkpoint_dir, latest_filename=None): + """Returns CheckpointState proto from the "checkpoint" file. + + If the "checkpoint" file contains a valid CheckpointState + proto, returns it. + + Args: + checkpoint_dir: The directory of checkpoints. + latest_filename: Optional name of the checkpoint file. Default to + 'checkpoint'. + + Returns: + A CheckpointState if the state was available, None + otherwise. + + Raises: + ValueError: if the checkpoint read doesn't have model_checkpoint_path set. + """ + if isinstance(checkpoint_dir, os.PathLike): + checkpoint_dir = os.fspath(checkpoint_dir) + ckpt = None + coord_checkpoint_filename = _GetCheckpointFilename(checkpoint_dir, + latest_filename) + f = None + try: + # Check that the file exists before opening it to avoid + # many lines of errors from colossus in the logs. + if file_io.file_exists(coord_checkpoint_filename): + file_content = file_io.read_file_to_string( + coord_checkpoint_filename) + ckpt = CheckpointState() + text_format.Merge(file_content, ckpt) + if not ckpt.model_checkpoint_path: + raise ValueError("Invalid checkpoint state loaded from " + + checkpoint_dir) + # For relative model_checkpoint_path and all_model_checkpoint_paths, + # prepend checkpoint_dir. + if not os.path.isabs(ckpt.model_checkpoint_path): + ckpt.model_checkpoint_path = os.path.join(checkpoint_dir, + ckpt.model_checkpoint_path) + for i, p in enumerate(ckpt.all_model_checkpoint_paths): + if not os.path.isabs(p): + ckpt.all_model_checkpoint_paths[i] = os.path.join(checkpoint_dir, p) + except errors.OpError as e: + # It's ok if the file cannot be read + logging.warning("%s: %s", type(e).__name__, e) + logging.warning("%s: Checkpoint ignored", coord_checkpoint_filename) + return None + except text_format.ParseError as e: + logging.warning("%s: %s", type(e).__name__, e) + logging.warning("%s: Checkpoint ignored", coord_checkpoint_filename) + return None + finally: + if f: + f.close() + return ckpt + + +def _prefix_to_checkpoint_path(prefix, format_version): + """Returns the pathname of a checkpoint file, given the checkpoint prefix. + + For V1 checkpoint, simply returns the prefix itself (the data file). For V2, + returns the pathname to the index file. + + Args: + prefix: a string, the prefix of a checkpoint. + format_version: the checkpoint format version that corresponds to the + prefix. + Returns: + The pathname of a checkpoint file, taking into account the checkpoint + format version. + """ + if format_version == saver_pb2.SaverDef.V2: + return prefix + ".index" # The index file identifies a checkpoint. + return prefix # Just the data file. + + +@tf_export("train.latest_checkpoint") +def latest_checkpoint(checkpoint_dir, latest_filename=None): + """Finds the filename of latest saved checkpoint file. + + Gets the checkpoint state given the provided checkpoint_dir and looks for a + corresponding TensorFlow 2 (preferred) or TensorFlow 1.x checkpoint path. + The latest_filename argument is only applicable if you are saving checkpoint + using `v1.train.Saver.save` + + + See the [Training Checkpoints + Guide](https://www.tensorflow.org/guide/checkpoint) for more details and + examples.` + + Args: + checkpoint_dir: Directory where the variables were saved. + latest_filename: Optional name for the protocol buffer file that + contains the list of most recent checkpoint filenames. + See the corresponding argument to `v1.train.Saver.save`. + + Returns: + The full path to the latest checkpoint or `None` if no checkpoint was found. + """ + # Pick the latest checkpoint based on checkpoint state. + ckpt = get_checkpoint_state(checkpoint_dir, latest_filename) + if ckpt and ckpt.model_checkpoint_path: + # Look for either a V2 path or a V1 path, with priority for V2. + v2_path = _prefix_to_checkpoint_path(ckpt.model_checkpoint_path, + saver_pb2.SaverDef.V2) + v1_path = _prefix_to_checkpoint_path(ckpt.model_checkpoint_path, + saver_pb2.SaverDef.V1) + if file_io.get_matching_files(v2_path) or file_io.get_matching_files( + v1_path): + return ckpt.model_checkpoint_path + else: + logging.error("Couldn't match files for checkpoint %s", + ckpt.model_checkpoint_path) + return None + + +def checkpoint_exists_internal(checkpoint_prefix): + """Checks whether a V1 or V2 checkpoint exists with the specified prefix. + + This is an internal function to check if a checkpoint exists, + since it takes into account the naming difference between V1 and V2 formats. + + Args: + checkpoint_prefix: the prefix of a V1 or V2 checkpoint, with V2 taking + priority. Typically the result of `Saver.save()` or that of + `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or + V1/V2. + Returns: + A bool, true if a checkpoint referred to by `checkpoint_prefix` exists. + """ + pathname = _prefix_to_checkpoint_path(checkpoint_prefix, + saver_pb2.SaverDef.V2) + if file_io.get_matching_files(pathname): + return True + elif file_io.get_matching_files(checkpoint_prefix): + return True + else: + return False + + +@deprecation.deprecated( + date=None, + instructions="Use standard file APIs to check for files with this prefix.") +@tf_export(v1=["train.checkpoint_exists"]) +def checkpoint_exists(checkpoint_prefix): + """Checks whether a V1 or V2 checkpoint exists with the specified prefix. + + This is the recommended way to check if a checkpoint exists, since it takes + into account the naming difference between V1 and V2 formats. + + Args: + checkpoint_prefix: the prefix of a V1 or V2 checkpoint, with V2 taking + priority. Typically the result of `Saver.save()` or that of + `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or + V1/V2. + + Returns: + A bool, true if a checkpoint referred to by `checkpoint_prefix` exists. + """ + return checkpoint_exists_internal(checkpoint_prefix) + + +@deprecation.deprecated( + date=None, + instructions="Use standard file utilities to get mtimes.") +@tf_export(v1=["train.get_checkpoint_mtimes"]) +def get_checkpoint_mtimes(checkpoint_prefixes): + """Returns the mtimes (modification timestamps) of the checkpoints. + + Globs for the checkpoints pointed to by `checkpoint_prefixes`. If the files + exist, collect their mtime. Both V2 and V1 checkpoints are considered, in + that priority. + + This is the recommended way to get the mtimes, since it takes into account + the naming difference between V1 and V2 formats. + + Note: If not all checkpoints exist, the length of the returned mtimes list + will be smaller than the length of `checkpoint_prefixes` list, so mapping + checkpoints to corresponding mtimes will not be possible. + + Args: + checkpoint_prefixes: a list of checkpoint paths, typically the results of + `Saver.save()` or those of `tf.train.latest_checkpoint()`, regardless of + sharded/non-sharded or V1/V2. + Returns: + A list of mtimes (in microseconds) of the found checkpoints. + """ + mtimes = [] + + def match_maybe_append(pathname): + fnames = file_io.get_matching_files(pathname) + if fnames: + mtimes.append(file_io.stat(fnames[0]).mtime_nsec / 1e9) + return True + return False + + for checkpoint_prefix in checkpoint_prefixes: + # Tries V2's metadata file first. + pathname = _prefix_to_checkpoint_path(checkpoint_prefix, + saver_pb2.SaverDef.V2) + if match_maybe_append(pathname): + continue + # Otherwise, tries V1, where the prefix is the complete pathname. + match_maybe_append(checkpoint_prefix) + + return mtimes + + +@deprecation.deprecated( + date=None, + instructions="Use standard file APIs to delete files with this prefix.") +@tf_export(v1=["train.remove_checkpoint"]) +def remove_checkpoint(checkpoint_prefix, + checkpoint_format_version=saver_pb2.SaverDef.V2, + meta_graph_suffix="meta"): + """Removes a checkpoint given by `checkpoint_prefix`. + + Args: + checkpoint_prefix: The prefix of a V1 or V2 checkpoint. Typically the result + of `Saver.save()` or that of `tf.train.latest_checkpoint()`, regardless of + sharded/non-sharded or V1/V2. + checkpoint_format_version: `SaverDef.CheckpointFormatVersion`, defaults to + `SaverDef.V2`. + meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. + """ + _delete_file_if_exists( + meta_graph_filename(checkpoint_prefix, meta_graph_suffix)) + if checkpoint_format_version == saver_pb2.SaverDef.V2: + # V2 has a metadata file and some data files. + _delete_file_if_exists(checkpoint_prefix + ".index") + _delete_file_if_exists(checkpoint_prefix + ".data-?????-of-?????") + else: + # V1, Legacy. Exact match on the data file. + _delete_file_if_exists(checkpoint_prefix) + + +def _delete_file_if_exists(filespec): + """Deletes files matching `filespec`.""" + for pathname in file_io.get_matching_files(filespec): + try: + file_io.delete_file(pathname) + except errors.NotFoundError: + logging.warning( + "Hit NotFoundError when deleting '%s', possibly because another " + "process/thread is also deleting/moving the same file", pathname) + + +def meta_graph_filename(checkpoint_filename, meta_graph_suffix="meta"): + """Returns the meta graph filename. + + Args: + checkpoint_filename: Name of the checkpoint file. + meta_graph_suffix: Suffix for `MetaGraphDef` file. Defaults to 'meta'. + + Returns: + MetaGraph file name. + """ + # If the checkpoint_filename is sharded, the checkpoint_filename could + # be of format model.ckpt-step#-?????-of-shard#. For example, + # model.ckpt-123456-?????-of-00005, or model.ckpt-123456-00001-of-00002. + basename = re.sub(r"-[\d\?]+-of-\d+$", "", checkpoint_filename) + suffixed_filename = ".".join([basename, meta_graph_suffix]) + return suffixed_filename + + +# TODO(allenl): Allow tf.keras.Model instances in the constructor directly? +@tf_export("train.CheckpointManager") +class CheckpointManager(object): + """Manages multiple checkpoints by keeping some and deleting unneeded ones. + + Example usage: + + ```python + import tensorflow as tf + checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model) + manager = tf.train.CheckpointManager( + checkpoint, directory="/tmp/model", max_to_keep=5) + status = checkpoint.restore(manager.latest_checkpoint) + while True: + # train + manager.save() + ``` + + `CheckpointManager` preserves its own state across instantiations (see the + `__init__` documentation for details). Only one should be active in a + particular directory at a time. + """ + + def __init__(self, + checkpoint, + directory, + max_to_keep, + keep_checkpoint_every_n_hours=None, + checkpoint_name="ckpt", + step_counter=None, + checkpoint_interval=None, + init_fn=None): + """Configure a `CheckpointManager` for use in `directory`. + + If a `CheckpointManager` was previously used in `directory`, its + state will be restored. This includes the list of managed checkpoints and + the timestamp bookkeeping necessary to support + `keep_checkpoint_every_n_hours`. The behavior of the new `CheckpointManager` + will be the same as the previous `CheckpointManager`, including cleaning up + existing checkpoints if appropriate. + + Checkpoints are only considered for deletion just after a new checkpoint has + been added. At that point, `max_to_keep` checkpoints will remain in an + "active set". Once a checkpoint is preserved by + `keep_checkpoint_every_n_hours` it will not be deleted by this + `CheckpointManager` or any future `CheckpointManager` instantiated in + `directory` (regardless of the new setting of + `keep_checkpoint_every_n_hours`). The `max_to_keep` checkpoints in the + active set may be deleted by this `CheckpointManager` or a future + `CheckpointManager` instantiated in `directory` (subject to its + `max_to_keep` and `keep_checkpoint_every_n_hours` settings). + + `CheckpointManager` can be also used for initializing the model if + there is no checkpoints for restoring in `directory`. An example usage is: + + >>> import tempfile + + >>> tmp_dir = tempfile.mkdtemp() + >>> checkpoint = tf.train.Checkpoint() + >>> init_path = checkpoint.save(os.path.join(tmp_dir, 'init')) + + >>> def init_fn(): + ... # Partially restore the checkpoint from `init_path`. + ... checkpoint.restore(init_path) + + >>> manager = tf.train.CheckpointManager( + ... checkpoint, + ... directory=os.path.join(tmp_dir, 'ckpt'), + ... max_to_keep=None, + ... init_fn=init_fn) + >>> # `restore_or_initialize` will call `init_fn` if there is no existing + >>> # checkpoint in `directory`. + >>> manager.restore_or_initialize() + + Args: + checkpoint: The `tf.train.Checkpoint` instance to save and manage + checkpoints for. + directory: The path to a directory in which to write checkpoints. A + special file named "checkpoint" is also written to this directory (in a + human-readable text format) which contains the state of the + `CheckpointManager`. + max_to_keep: An integer, the number of checkpoints to keep. Unless + preserved by `keep_checkpoint_every_n_hours`, checkpoints will be + deleted from the active set, oldest first, until only `max_to_keep` + checkpoints remain. If `None`, no checkpoints are deleted and everything + stays in the active set. Note that `max_to_keep=None` will keep all + checkpoint paths in memory and in the checkpoint state protocol buffer + on disk. + keep_checkpoint_every_n_hours: Upon removal from the active set, a + checkpoint will be preserved if it has been at least + `keep_checkpoint_every_n_hours` since the last preserved checkpoint. The + default setting of `None` does not preserve any checkpoints in this way. + checkpoint_name: Custom name for the checkpoint file. + step_counter: A `tf.Variable` instance for checking the current step + counter value, in case users want to save checkpoints every N steps. + checkpoint_interval: An integer, indicates the minimum step interval + between two checkpoints. + init_fn: Callable. A function to do customized intialization if no + checkpoints are in the directory. + + Raises: + ValueError: If `max_to_keep` is not a positive integer. + """ + self._checkpoint = checkpoint + self._save_counter_assign = None + if max_to_keep is not None and max_to_keep <= 0: + raise ValueError( + ("Expected a positive integer or `None` for `max_to_keep`, " + "got %d.") + % (max_to_keep,)) + self._max_to_keep = max_to_keep + self._keep_checkpoint_every_n_hours = keep_checkpoint_every_n_hours + if isinstance(directory, os.PathLike): + directory = os.fspath(directory) + self._directory = directory + self._checkpoint_prefix = os.path.join(directory, checkpoint_name) + self._init_fn = init_fn + + if checkpoint_interval is not None: + if step_counter is None: + raise ValueError("`step_counter` should be passed if " + "`checkpoint_interval` is not None.") + self._last_checkpoint_step = None + self._step_counter = step_counter + self._checkpoint_interval = checkpoint_interval + + recovered_state = get_checkpoint_state(directory) + current_clock = time.time() + self._maybe_delete = collections.OrderedDict() + if recovered_state is None: + self._latest_checkpoint = None + # Set the clock back slightly to avoid race conditions when quickly + # re-creating a CheckpointManager. + self._last_preserved_timestamp = current_clock - 1. + else: + self._latest_checkpoint = recovered_state.model_checkpoint_path + self._last_preserved_timestamp = recovered_state.last_preserved_timestamp + if current_clock < self._last_preserved_timestamp: + # Time seems to have reversed itself. In addition to this warning, we'll + # min() saved checkpoint timestamps with the current time to ensure that + # old checkpoints don't get deleted accidentally. + logging.warning( + ("time.time() returned a value %f seconds behind the last " + "preserved checkpoint timestamp.") + % (self._last_preserved_timestamp - current_clock,)) + self._last_preserved_timestamp = current_clock + all_timestamps = recovered_state.all_model_checkpoint_timestamps + all_paths = recovered_state.all_model_checkpoint_paths + del recovered_state # Uses modified values from now on + if not all_timestamps: + all_timestamps = [self._last_preserved_timestamp] * len(all_paths) + + for filename, timestamp in zip(all_paths, all_timestamps): + timestamp = min(timestamp, current_clock) + if timestamp > self._last_preserved_timestamp: + self._maybe_delete[filename] = timestamp + + @property + def directory(self): + return self._directory + + @property + def checkpoint_interval(self): + return self._checkpoint_interval + + @property + def latest_checkpoint(self): + """The prefix of the most recent checkpoint in `directory`. + + Equivalent to `tf.train.latest_checkpoint(directory)` where `directory` is + the constructor argument to `CheckpointManager`. + + Suitable for passing to `tf.train.Checkpoint.restore` to resume training. + + Returns: + The checkpoint prefix. If there are no checkpoints, returns `None`. + """ + return self._latest_checkpoint + + @property + def checkpoints(self): + """A list of managed checkpoints. + + Note that checkpoints saved due to `keep_checkpoint_every_n_hours` will not + show up in this list (to avoid ever-growing filename lists). + + Returns: + A list of filenames, sorted from oldest to newest. + """ + return list(self._maybe_delete.keys()) + + def _sweep(self): + """Deletes or preserves managed checkpoints.""" + if not self._max_to_keep: + # Does not update self._last_preserved_timestamp, since everything is kept + # in the active set. + return + while len(self._maybe_delete) > self._max_to_keep: + filename, timestamp = self._maybe_delete.popitem(last=False) + # Even if we're keeping this checkpoint due to + # keep_checkpoint_every_n_hours, we won't reference it to avoid + # infinitely-growing CheckpointState protos. + if (self._keep_checkpoint_every_n_hours + and (timestamp - self._keep_checkpoint_every_n_hours * 3600. + >= self._last_preserved_timestamp)): + self._last_preserved_timestamp = timestamp + continue + _delete_file_if_exists(filename + ".index") + _delete_file_if_exists(filename + ".data-?????-of-?????") + + def _record_state(self): + """Saves the `CheckpointManager`'s state in `directory`.""" + filenames, timestamps = zip(*self._maybe_delete.items()) + update_checkpoint_state_internal( + self._directory, + model_checkpoint_path=self.latest_checkpoint, + all_model_checkpoint_paths=filenames, + all_model_checkpoint_timestamps=timestamps, + last_preserved_timestamp=self._last_preserved_timestamp, + save_relative_paths=True) + + @property + def _prefix(self): + """A common prefix for all checkpoints saved with this manager. + + For example, if `directory` (a constructor argument) were `"/tmp/tf-model"`, + `prefix` would be `"/tmp/tf-model/ckpt"` and checkpoints would generally be + numbered `"/tmp/tf-model/ckpt-1"`, `"/tmp/tf-model/ckpt-2"`, and so on. Each + checkpoint has several associated files + (e.g. `"/tmp/tf-model/ckpt-2.index"`). + + Returns: + A string prefix. + """ + return self._checkpoint_prefix + + @property + def checkpoint(self): + """Returns the `tf.train.Checkpoint` object.""" + return self._checkpoint + + def save(self, checkpoint_number=None, check_interval=True, options=None): + """Creates a new checkpoint and manages it. + + Args: + checkpoint_number: An optional integer, or an integer-dtype `Variable` or + `Tensor`, used to number the checkpoint. If `None` (default), + checkpoints are numbered using `checkpoint.save_counter`. Even if + `checkpoint_number` is provided, `save_counter` is still incremented. A + user-provided `checkpoint_number` is not incremented even if it is a + `Variable`. + check_interval: An optional boolean. The argument is only effective when + `checkpoint_interval` is passed into the manager. If `True`, the manager + will only save the checkpoint if the interval between checkpoints is + larger than `checkpoint_interval`. Otherwise it will always save the + checkpoint unless a checkpoint has already been saved for the current + step. + options: Optional `tf.train.CheckpointOptions` object. This argument only + works with TF2 checkpoint objects. For example, options = + tf.saved_model.SaveOptions(experimental_io_device='/job:localhost') + + Returns: + The path to the new checkpoint. It is also recorded in the `checkpoints` + and `latest_checkpoint` properties. `None` if no checkpoint is saved. + """ + if self._checkpoint_interval is not None: + current_step = _evaluate(self._step_counter) + if self._last_checkpoint_step is not None: + if current_step == self._last_checkpoint_step: + return None + if check_interval and current_step < ( + self._last_checkpoint_step + self._checkpoint_interval): + return None + self._last_checkpoint_step = current_step + + # Save counter logic duplicated from tf.train.Checkpoint, soon to diverge + # slightly with a custom numbering option. + if context.executing_eagerly(): + save_counter = self._checkpoint.save_counter + save_counter.assign_add(1) + session = None + else: + session = ops.get_default_session() + + def _initializing_creator(next_creator, **kwargs): + """Initialize the save counter if it has been newly created.""" + v = next_creator(**kwargs) + session.run(v.initializer) + return v + + with variable_scope.variable_creator_scope(_initializing_creator): + save_counter = self._checkpoint.save_counter + if self._save_counter_assign is None: + self._save_counter_assign = save_counter.assign_add(1, read_value=False) + session.run(self._save_counter_assign) + if checkpoint_number is None: + checkpoint_number = save_counter + if not isinstance(checkpoint_number, compat.integral_types): + checkpoint_number = training_util.global_step( + sess=session, global_step_tensor=checkpoint_number) + prefix = "%s-%d" % (self._prefix, checkpoint_number) + + def _record_and_sweep_state(save_path): + timestamp = time.time() + # If this is an overwritten checkpoint we were previously tracking, delete + # and reinsert it to make sure it goes to the end of the queue. + if save_path in self._maybe_delete: + del self._maybe_delete[save_path] + self._maybe_delete[save_path] = timestamp + self._latest_checkpoint = save_path + # Before deleting anything we update the Checkpoint proto with the new + # checkpoint. We'll go back and correct it after cleaning up old files, + # but a preemption while deleting will be more likely to see the new + # checkpoint this way. + self._record_state() + self._sweep() + # Write out the Checkpoint proto a second time, now without the deleted + # checkpoints. + self._record_state() + + # Register `_record_and_sweep_state` as a callback in `CheckpointOptions` + if options is None: + options = checkpoint_options.CheckpointOptions( + experimental_write_callbacks=[_record_and_sweep_state] + ) + else: + # We create a copy so that user's `options` instance would not be mutated + # by internal mechanisms. + options = copy.copy(options) + if options.experimental_write_callbacks is None: + options.experimental_write_callbacks = [_record_and_sweep_state] + else: + options.experimental_write_callbacks.append(_record_and_sweep_state) + + save_path = self._checkpoint._write(prefix, options=options) # pylint: disable=protected-access + return save_path + + def restore_or_initialize(self): + """Restore items in `checkpoint` from the latest checkpoint file. + + This method will first try to restore from the most recent checkpoint in + `directory`. If no checkpoints exist in `directory`, and `init_fn` is + specified, this method will call `init_fn` to do customized + initialization. This can be used to support initialization from pretrained + models. + + Note that unlike `tf.train.Checkpoint.restore()`, this method doesn't return + a load status object that users can run assertions on + (e.g. assert_consumed()). Thus to run assertions, users should directly use + `tf.train.Checkpoint.restore()` method. + + Returns: + The restored checkpoint path if the lastest checkpoint is found and + restored. Otherwise None. + """ + # TODO(chienchunh): When AsyncCheckpoint is used, we may need to force to + # sync until any ongoing async save is done. Otherwise, if this is the first + # checkpoint and _latest_checkpoint has not been updated due to async write, + # this would resort to init_fn instead of restoring from the checkpoin file. + # This should be fixed once AsyncCheckpoint is integrated with the public + # API so that we can rely on CheckpointOptions to tell whether we should + # sync for AsyncCheckpoint. + if self._latest_checkpoint is not None: + self._checkpoint.restore(self._latest_checkpoint) + if self._checkpoint_interval is not None: + self._last_checkpoint_step = _evaluate(self._step_counter) + return self._latest_checkpoint + + if self._init_fn is not None: + self._init_fn() + logging.info( + "Customized initialization is done through the passed `init_fn`.") + return None + + def sync(self): + """Wait for any outstanding save or restore operations.""" + if self._checkpoint: + self._checkpoint.sync() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_options.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_options.py new file mode 100644 index 0000000000000000000000000000000000000000..662fdcc455c4a3bbfdc1a7fb2e2d1421b9a9807e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_options.py @@ -0,0 +1,111 @@ +# 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. +# ============================================================================== +"""Options for saving Checkpoints.""" + +import copy +import inspect + +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("train.CheckpointOptions") +class CheckpointOptions(object): + """Options for constructing a Checkpoint. + + Used as the `options` argument to either `tf.train.Checkpoint.save()` or + `tf.train.Checkpoint.restore()` methods to adjust how variables are + saved/restored. + + Example: Run IO ops on "localhost" while saving a checkpoint: + + ``` + step = tf.Variable(0, name="step") + checkpoint = tf.train.Checkpoint(step=step) + options = tf.train.CheckpointOptions(experimental_io_device="/job:localhost") + checkpoint.save("/tmp/ckpt", options=options) + ``` + """ + + # Define object attributes in __slots__ for improved memory and performance. + __slots__ = ( + "experimental_io_device", + "experimental_enable_async_checkpoint", + "experimental_write_callbacks", + "enable_async", + ) + + @deprecated_args( + None, "Use enable_async instead", "experimental_enable_async_checkpoint" + ) + def __init__( + self, + experimental_io_device=None, + experimental_enable_async_checkpoint=False, + experimental_write_callbacks=None, + enable_async=False, + ): + """Creates an object that stores options for a Checkpoint. + + Args: + experimental_io_device: string. Applies in a distributed setting. + Tensorflow device to use to access the filesystem. If `None` (default) + then for each variable the filesystem is accessed from the CPU:0 device + of the host where that variable is assigned. If specified, the + filesystem is instead accessed from that device for all variables. + + This is for example useful if you want to save to a local directory, + such as "/tmp" when running in a distributed setting. In that case pass + a device for the host where the "/tmp" directory is accessible. + + experimental_enable_async_checkpoint: bool Type. Deprecated, please use + the enable_async option. + + experimental_write_callbacks: List[Callable]. A list of callback functions + that will be executed after each saving event finishes (i.e. after + `save()` or `write()`). For async checkpoint, the callbacks will be + executed only after the async thread finishes saving. + + The return values of the callback(s) will be ignored. The callback(s) + can optionally take the `save_path` (the result of `save()` or + `write()`) as an argument. The callbacks will be executed in the same + order of this list after the checkpoint has been written. + + enable_async: bool Type. Indicates whether async checkpointing is enabled. + Default is False, i.e., no async checkpoint. + + Async checkpoint moves the checkpoint file writing off the main thread, + so that the model can continue to train while the checkpoing file + writing runs in the background. Async checkpoint reduces TPU device idle + cycles and speeds up model training process, while memory consumption + may increase. + """ + self.experimental_io_device = experimental_io_device + self.enable_async = experimental_enable_async_checkpoint or enable_async + self.experimental_enable_async_checkpoint = self.enable_async + # Ensure that each callback only has either 0 or 1 parameter + if experimental_write_callbacks is not None: + for callback in experimental_write_callbacks: + assert len(inspect.signature(callback).parameters) <= 1 + self.experimental_write_callbacks = experimental_write_callbacks + + def __copy__(self): + # Only `experimental_write_callbacks` needs special treatment to Ensure that + # the list is deep-copied, but the callbacks are not deep-copied. + result = copy.copy(super()) # First invoke the non-overridden copy method. + result.experimental_write_callbacks = copy.copy( + self.experimental_write_callbacks + ) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_view.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_view.py new file mode 100644 index 0000000000000000000000000000000000000000..e3772e819d7c8769b6c5555e6fb4b650723ebf4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/checkpoint_view.py @@ -0,0 +1,301 @@ +"""Manages a Checkpoint View.""" +# 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. +# ============================================================================== +import collections + +from tensorflow.core.protobuf import trackable_object_graph_pb2 +from tensorflow.python.checkpoint import trackable_view +from tensorflow.python.framework import errors_impl +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base +from tensorflow.python.training import py_checkpoint_reader +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("train.CheckpointView", v1=[]) +class CheckpointView(object): + """Gathers and serializes a checkpoint view. + + This is for loading specific portions of a module from a + checkpoint, and be able to compare two modules by matching components. + + Example usage: + + >>> class SimpleModule(tf.Module): + ... def __init__(self, name=None): + ... super().__init__(name=name) + ... self.a_var = tf.Variable(5.0) + ... self.b_var = tf.Variable(4.0) + ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] + + >>> root = SimpleModule(name="root") + >>> root.leaf = SimpleModule(name="leaf") + >>> ckpt = tf.train.Checkpoint(root) + >>> save_path = ckpt.save('/tmp/tf_ckpts') + >>> checkpoint_view = tf.train.CheckpointView(save_path) + + Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the dictionary + of all children directly linked to the checkpoint root. + + >>> for name, node_id in checkpoint_view.children(0).items(): + ... print(f"- name: '{name}', node_id: {node_id}") + - name: 'a_var', node_id: 1 + - name: 'b_var', node_id: 2 + - name: 'vars', node_id: 3 + - name: 'leaf', node_id: 4 + - name: 'root', node_id: 0 + - name: 'save_counter', node_id: 5 + + """ + + def __init__(self, save_path): + """Configure the checkpoint view. + + Args: + save_path: The path to the checkpoint. + + Raises: + ValueError: If the save_path does not lead to a TF2 checkpoint. + """ + + reader = py_checkpoint_reader.NewCheckpointReader(save_path) + try: + object_graph_string = reader.get_tensor(base.OBJECT_GRAPH_PROTO_KEY) + except errors_impl.NotFoundError as not_found_error: + raise ValueError( + f"The specified checkpoint \"{save_path}\" does not appear to be " + "object-based (saved with TF2) since it is missing the key " + f"\"{base.OBJECT_GRAPH_PROTO_KEY}\". Likely it was created with the " + "TF1 name-based saver and does not contain an object dependency graph." + ) from not_found_error + object_graph_proto = (trackable_object_graph_pb2.TrackableObjectGraph()) + object_graph_proto.ParseFromString(object_graph_string) + self._object_graph_proto = object_graph_proto + + def children(self, node_id): + """Returns all child trackables attached to obj. + + Args: + node_id: Id of the node to return its children. + + Returns: + Dictionary of all children attached to the object with name to node_id. + """ + return { + child.local_name: child.node_id + for child in self._object_graph_proto.nodes[node_id].children + } + + def descendants(self): + """Returns a list of trackables by node_id attached to obj.""" + + return list(self._descendants_with_paths().keys()) + + def _descendants_with_paths(self): + """Returns a dict of descendants by node_id and paths to node. + + The names returned by this private method are subject to change. + """ + + all_nodes_with_paths = {} + to_visit = collections.deque([0]) + # node_id:0 will always be "root". + all_nodes_with_paths[0] = "root" + path = all_nodes_with_paths.get(0) + while to_visit: + node_id = to_visit.popleft() + obj = self._object_graph_proto.nodes[node_id] + for child in obj.children: + if child.node_id == 0 or child.node_id in all_nodes_with_paths.keys(): + continue + path = all_nodes_with_paths.get(node_id) + if child.node_id not in all_nodes_with_paths.keys(): + to_visit.append(child.node_id) + all_nodes_with_paths[child.node_id] = path + "." + child.local_name + return all_nodes_with_paths + + def match(self, obj): + """Returns all matching trackables between CheckpointView and Trackable. + + Matching trackables represents trackables with the same name and position in + graph. + + Args: + obj: `Trackable` root. + + Returns: + Dictionary containing all overlapping trackables that maps `node_id` to + `Trackable`. + + Example usage: + + >>> class SimpleModule(tf.Module): + ... def __init__(self, name=None): + ... super().__init__(name=name) + ... self.a_var = tf.Variable(5.0) + ... self.b_var = tf.Variable(4.0) + ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] + + >>> root = SimpleModule(name="root") + >>> leaf = root.leaf = SimpleModule(name="leaf") + >>> leaf.leaf3 = tf.Variable(6.0, name="leaf3") + >>> leaf.leaf4 = tf.Variable(7.0, name="leaf4") + >>> ckpt = tf.train.Checkpoint(root) + >>> save_path = ckpt.save('/tmp/tf_ckpts') + >>> checkpoint_view = tf.train.CheckpointView(save_path) + + >>> root2 = SimpleModule(name="root") + >>> leaf2 = root2.leaf2 = SimpleModule(name="leaf2") + >>> leaf2.leaf3 = tf.Variable(6.0) + >>> leaf2.leaf4 = tf.Variable(7.0) + + Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the + dictionary of all children directly linked to the checkpoint root. + + >>> checkpoint_view_match = checkpoint_view.match(root2).items() + >>> for item in checkpoint_view_match: + ... print(item) + (0, ...) + (1, ) + (2, ) + (3, ListWrapper([, ])) + (6, ) + (7, ) + + """ + if not isinstance(obj, base.Trackable): + raise ValueError(f"Expected a Trackable, got {obj} of type {type(obj)}.") + + overlapping_nodes = {} + # Root node is always matched. + overlapping_nodes[0] = obj + + # Queue of tuples of node_id and trackable. + to_visit = collections.deque([(0, obj)]) + visited = set() + view = trackable_view.TrackableView(obj) + while to_visit: + current_node_id, current_trackable = to_visit.popleft() + trackable_children = view.children(current_trackable) + for child_name, child_node_id in self.children(current_node_id).items(): + if child_node_id in visited or child_node_id == 0: + continue + if child_name in trackable_children: + current_assignment = overlapping_nodes.get(child_node_id) + if current_assignment is None: + overlapping_nodes[child_node_id] = trackable_children[child_name] + to_visit.append((child_node_id, trackable_children[child_name])) + else: + # The object was already mapped for this checkpoint load, which + # means we don't need to do anything besides check that the mapping + # is consistent (if the dependency DAG is not a tree then there are + # multiple paths to the same object). + if current_assignment is not trackable_children[child_name]: + logging.warning( + "Inconsistent references when matching the checkpoint into " + "this object graph. The referenced objects are: " + f"({current_assignment} and " + f"{trackable_children[child_name]}).") + visited.add(current_node_id) + return overlapping_nodes + + def diff(self, obj): + """Returns diff between CheckpointView and Trackable. + + This method is intended to be used to compare the object stored in a + checkpoint vs a live model in Python. For example, if checkpoint + restoration fails the `assert_consumed()` or + `assert_existing_objects_matched()` checks, you can use this to list out + the objects/checkpoint nodes which were not restored. + + Example Usage: + + >>> class SimpleModule(tf.Module): + ... def __init__(self, name=None): + ... super().__init__(name=name) + ... self.a_var = tf.Variable(5.0) + ... self.b_var = tf.Variable(4.0) + ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] + + >>> root = SimpleModule(name="root") + >>> leaf = root.leaf = SimpleModule(name="leaf") + >>> leaf.leaf3 = tf.Variable(6.0, name="leaf3") + >>> leaf.leaf4 = tf.Variable(7.0, name="leaf4") + >>> ckpt = tf.train.Checkpoint(root) + >>> save_path = ckpt.save('/tmp/tf_ckpts') + >>> checkpoint_view = tf.train.CheckpointView(save_path) + + >>> root2 = SimpleModule(name="root") + >>> leaf2 = root2.leaf2 = SimpleModule(name="leaf2") + >>> leaf2.leaf3 = tf.Variable(6.0) + >>> leaf2.leaf4 = tf.Variable(7.0) + + Pass `node_id=0` to `tf.train.CheckpointView.children()` to get the + dictionary of all children directly linked to the checkpoint root. + + >>> checkpoint_view_diff = checkpoint_view.diff(root2) + >>> checkpoint_view_match = checkpoint_view_diff[0].items() + >>> for item in checkpoint_view_match: + ... print(item) + (0, ...) + (1, ) + (2, ) + (3, ListWrapper([, ])) + (6, ) + (7, ) + + >>> only_in_checkpoint_view = checkpoint_view_diff[1] + >>> print(only_in_checkpoint_view) + [4, 5, 8, 9, 10, 11, 12, 13, 14] + + >>> only_in_trackable = checkpoint_view_diff[2] + >>> print(only_in_trackable) + [..., , + , + ListWrapper([, + ]), + , + , + , + ] + + Args: + obj: `Trackable` root. + + Returns: + Tuple of ( + - Overlaps: Dictionary containing all overlapping trackables that maps + `node_id` to `Trackable`, same as CheckpointView.match(). + - Only in CheckpointView: List of `node_id` that only exist in + CheckpointView. + - Only in Trackable: List of `Trackable` that only exist in Trackable. + ) + + """ + + overlapping_nodes = self.match(obj) + only_in_checkpoint_view = [] + only_in_trackable = [] + for node_id in self.descendants(): + if node_id not in overlapping_nodes.keys(): + only_in_checkpoint_view.append(node_id) + for trackable in trackable_view.TrackableView(obj).descendants(): + if trackable not in object_identity.ObjectIdentitySet( + overlapping_nodes.values()): + only_in_trackable.append(trackable) + return overlapping_nodes, only_in_checkpoint_view, only_in_trackable diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/functional_saver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/functional_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdefdf934f5c1f98b54ff71b29e28d0d04f4c8c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/functional_saver.py @@ -0,0 +1,501 @@ +# 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. +# ============================================================================== +"""Saves and restore variables inside traced @tf.functions.""" + +from tensorflow.core.protobuf import saver_pb2 +from tensorflow.python.checkpoint import checkpoint_options +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_io_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.saved_model import registration +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training.saving import saveable_object +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity + + +class _SingleDeviceSaver(object): + """Saves and restores checkpoints from the current device.""" + + __slots__ = ["_tensor_slice_dict"] + + def __init__(self, tensor_slice_dict): + """Specify a list of `SaveableObject`s to save and restore. + + Args: + tensor_slice_dict: A dict mapping checkpoint key -> slice_spec -> tensor. + """ + self._tensor_slice_dict = tensor_slice_dict + + def save(self, file_prefix, options=None): + """Save the saveable objects to a checkpoint with `file_prefix`. + + Args: + file_prefix: A string or scalar string Tensor containing the prefix to + save under. + options: Optional `CheckpointOptions` object. + Returns: + An `Operation`, or None when executing eagerly. + """ + options = options or checkpoint_options.CheckpointOptions() + tensor_names = [] + tensors = [] + slice_specs = [] + for checkpoint_key, tensor_slices in self._tensor_slice_dict.items(): + for slice_spec, tensor in tensor_slices.items(): + if isinstance(tensor, saveable_object.SaveSpec): + tensor_value = tensor.tensor + # A tensor value of `None` indicates that this SaveableObject gets + # recorded in the object graph, but that no value is saved in the + # checkpoint. + if tensor_value is not None: + tensor_names.append(tensor.name) + tensors.append(tensor_value) + slice_specs.append(tensor.slice_spec) + else: + tensor_names.append(checkpoint_key) + tensors.append(tensor) + slice_specs.append(slice_spec) + save_device = options.experimental_io_device or ( + len(tensors) and saveable_object_util.set_cpu0(tensors[0].device)) + save_device = save_device or "cpu:0" + with ops.device(save_device): + return io_ops.save_v2(file_prefix, tensor_names, slice_specs, tensors) + + def restore(self, file_prefix, options=None): + """Restore the saveable objects from a checkpoint with `file_prefix`. + + Args: + file_prefix: A string or scalar string Tensor containing the prefix for + files to read from. + options: Optional `CheckpointOptions` object. + + Returns: + A restored tensor dict (maps checkpoint_key -> slice_spec -> tensor). + """ + options = options or checkpoint_options.CheckpointOptions() + tensor_names = [] + tensor_dtypes = [] + slice_specs = [] + + for checkpoint_key, tensor_slices in self._tensor_slice_dict.items(): + for slice_spec, tensor in tensor_slices.items(): + tensor_dtypes.append(tensor.dtype) + if isinstance(tensor, saveable_object.SaveSpec): + slice_specs.append(tensor.slice_spec) + tensor_names.append(tensor.name) + else: + slice_specs.append(slice_spec) + tensor_names.append(checkpoint_key) + + restore_device = options.experimental_io_device or "cpu:0" + with ops.device(restore_device): + restored_tensors = io_ops.restore_v2( + file_prefix, tensor_names, slice_specs, tensor_dtypes) + + restored_tensor_dict = {} + for checkpoint_key, tensor_slices in self._tensor_slice_dict.items(): + for slice_spec in tensor_slices: + restored_tensor = restored_tensors.pop(0) + restored_tensor_dict.setdefault(checkpoint_key, {})[slice_spec] = ( + restored_tensor) + return restored_tensor_dict + + +def sharded_filename(filename_tensor, shard, num_shards): + """Append sharding information to a filename. + + Args: + filename_tensor: A string tensor. + shard: Integer. The shard for the filename. + num_shards: An int Tensor for the number of shards. + + Returns: + A string tensor. + """ + return gen_io_ops.sharded_filename(filename_tensor, shard, num_shards) + + +def registered_saver_filename(filename_tensor, saver_name): + return string_ops.string_join( + [filename_tensor, constant_op.constant(f"-{saver_name}")]) + + +def _get_mapped_registered_save_fn(fn, trackables, call_with_mapped_captures): + """Converts the function to a python or tf.function with a single file arg.""" + + def save_fn(file_prefix): + return fn(trackables=trackables, file_prefix=file_prefix) + if call_with_mapped_captures is None: + return save_fn + else: + tf_fn = def_function.function(save_fn, autograph=False) + concrete = tf_fn.get_concrete_function( + file_prefix=tensor_spec.TensorSpec(shape=(), dtype=dtypes.string)) + + def save_fn_with_replaced_captures(file_prefix): + return call_with_mapped_captures(concrete, [file_prefix]) + + return save_fn_with_replaced_captures + + +def _get_mapped_registered_restore_fn(fn, trackables, + call_with_mapped_captures): + """Converts the function to a python or tf.function with a single file arg.""" + + def restore_fn(merged_prefix): + return fn(trackables=trackables, merged_prefix=merged_prefix) + if call_with_mapped_captures is None: + return restore_fn + else: + tf_fn = def_function.function(restore_fn, autograph=False) + concrete = tf_fn.get_concrete_function( + merged_prefix=tensor_spec.TensorSpec(shape=(), dtype=dtypes.string)) + + def restore_fn_with_replaced_captures(merged_prefix): + return call_with_mapped_captures(concrete, [merged_prefix]) + + return restore_fn_with_replaced_captures + + +_restore_noop = lambda *args, **kwargs: None + + +class MultiDeviceSaver(object): + """Saves checkpoints directly from multiple devices. + + Note that this is a low-level utility which stores Tensors in the keys + specified by `SaveableObject`s. Higher-level utilities for object-based + checkpointing are built on top of it. + """ + + def __init__(self, + serialized_tensors, + registered_savers=None, + call_with_mapped_captures=None): + """Specify a list of `SaveableObject`s to save and restore. + + Args: + serialized_tensors: A dictionary mapping `Trackable` to a tensor dict, + which maps checkpoint_key -> (slice_spec ->) -> Tensor/SaveSpec. The + `Trackable` key is used to get the `restore_from_tensors` function, + and may be `None` if the tensor is not meant to be restored. + registered_savers: A dictionary mapping `registration.RegisteredSaver` + namedtuples to a dictionary of named Trackables. The keys of the + Trackable dictionary are string names that uniquely identify the + Trackable in the checkpoint. + call_with_mapped_captures: TODO + """ + # Keep these two data structures so that we can map restored tensors to + # the Trackable restore functions. + self._keys_to_restore_fn = {} + self._restore_fn_to_keys = {} + + # Extract serialized tensors and separate by device. + tensors_by_device = {} # device -> checkpoint key -> (slice_spec ->) tensor + + for obj, tensor_dict in serialized_tensors.items(): + restore_fn = _restore_noop if obj is None else obj._restore_from_tensors + + # Divide tensor_dict by device. + for checkpoint_key, maybe_tensor in tensor_dict.items(): + if not isinstance(maybe_tensor, dict): + # Make sure that maybe_tensor is structured as {slice_spec -> tensor}. + maybe_tensor = {"": maybe_tensor} + + for slice_spec, tensor in maybe_tensor.items(): + if (checkpoint_key, slice_spec) in self._keys_to_restore_fn: + raise ValueError( + "Recieved multiple tensors with the same checkpoint key and " + "slice spec. This is invalid because one will overwrite the " + "other in the checkpoint. This indicates a bug in the " + "Checkpoint key-generation.") + self._keys_to_restore_fn[(checkpoint_key, slice_spec)] = restore_fn + self._restore_fn_to_keys.setdefault(restore_fn, []).append( + (checkpoint_key, slice_spec)) + + host_device = saveable_object_util.set_cpu0(tensor.device) + (tensors_by_device + .setdefault(host_device, {}) + .setdefault(checkpoint_key, {})[slice_spec]) = tensor + self._single_device_savers = { + device: _SingleDeviceSaver(tensor_slice_dict) + for device, tensor_slice_dict in tensors_by_device.items()} + + self._registered_savers = {} + if registered_savers: + for registered_name, trackables in registered_savers.items(): + save_fn = _get_mapped_registered_save_fn( + registration.get_save_function(registered_name), + trackables, call_with_mapped_captures) + restore_fn = _get_mapped_registered_restore_fn( + registration.get_restore_function(registered_name), + trackables, call_with_mapped_captures) + self._registered_savers[registered_name] = (save_fn, restore_fn) + + @classmethod + def from_saveables(cls, saveables, registered_savers=None, + call_with_mapped_captures=None): + serialized_tensors = object_identity.ObjectIdentityDictionary() + for saveable in saveables: + trackable = saveable_object_util.SaveableCompatibilityConverter( + saveable, saveables=[saveable]) + serialized_tensors[trackable] = trackable._serialize_to_tensors() # pylint: disable=protected-access + return cls(serialized_tensors, registered_savers, call_with_mapped_captures) + + def to_proto(self): + """Serializes to a SaverDef referencing the current graph.""" + filename_tensor = array_ops.placeholder( + shape=[], dtype=dtypes.string, name="saver_filename") + save_tensor = self._traced_save(filename_tensor) + restore_op = self._traced_restore(filename_tensor).op + return saver_pb2.SaverDef( + filename_tensor_name=filename_tensor.name, + save_tensor_name=save_tensor.name, + restore_op_name=restore_op.name, + version=saver_pb2.SaverDef.V2) + + @def_function.function( + input_signature=(tensor_spec.TensorSpec(shape=(), dtype=dtypes.string),), + autograph=False) + def _traced_save(self, file_prefix): + save_op = self.save(file_prefix) + with ops.device("cpu:0"): + with ops.control_dependencies([save_op]): + return array_ops.identity(file_prefix) + + @def_function.function( + input_signature=(tensor_spec.TensorSpec(shape=(), dtype=dtypes.string),), + autograph=False) + def _traced_restore(self, file_prefix): + restore_ops = self.restore(file_prefix) + with ops.device("cpu:0"): + with ops.control_dependencies(restore_ops.values()): + return array_ops.identity(file_prefix) + + def save(self, file_prefix, options=None): + """Save the saveable objects to a checkpoint with `file_prefix`. + + Args: + file_prefix: A string or scalar string Tensor containing the prefix to + save under. + options: Optional `CheckpointOptions` object. + Returns: + An `Operation`, or None when executing eagerly. + """ + options = options or checkpoint_options.CheckpointOptions() + + # IMPLEMENTATION DETAILS: most clients should skip. + # + # Suffix for any well-formed "checkpoint_prefix", when sharded. + # Transformations: + # * Users pass in "save_path" in save() and restore(). Say "myckpt". + # * checkpoint_prefix gets fed . + # + # Example: + # During runtime, a temporary directory is first created, which contains + # files + # + # /myckpt_temp/ + # part-?????-of-?????{.index, .data-00000-of-00001} + # + # Before .save() finishes, they will be (hopefully, atomically) renamed to + # + # / + # myckpt{.index, .data-?????-of-?????} + # + # Filesystems with eventual consistency (such as S3), don't need a + # temporary location. Using a temporary directory in those cases might + # cause situations where files are not available during copy. + # + # Users only need to interact with the user-specified prefix, which is + # "/myckpt" in this case. Save() and Restore() work with the + # prefix directly, instead of any physical pathname. (On failure and + # subsequent restore, an outdated and orphaned temporary directory can be + # safely removed.) + with ops.device("CPU"): + sharded_suffix = array_ops.where( + string_ops.regex_full_match(file_prefix, "^s3://.*"), + constant_op.constant(".part"), + constant_op.constant("_temp/part")) + tmp_checkpoint_prefix = string_ops.string_join( + [file_prefix, sharded_suffix]) + registered_paths = { + saver_name: registered_saver_filename(file_prefix, saver_name) + for saver_name in self._registered_savers + } + + def save_fn(): + saved_prefixes = [] + # Save with the registered savers. These run before default savers due to + # the API contract. + for saver_name, (save_fn, _) in self._registered_savers.items(): + maybe_saved_prefixes = save_fn(registered_paths[saver_name]) + if maybe_saved_prefixes is not None: + flattened_saved_prefixes = nest.flatten(maybe_saved_prefixes) + if not all( + tensor_util.is_tf_type(x) and x.dtype == dtypes.string + for x in flattened_saved_prefixes): + raise ValueError( + "Registered saver must return a (maybe empty) list of " + f"string type tensors. Got {maybe_saved_prefixes}.") + saved_prefixes.extend(flattened_saved_prefixes) + + # (Default saver) Save with single device savers. + num_shards = len(self._single_device_savers) + sharded_saves = [] + num_shards_tensor = constant_op.constant(num_shards, name="num_shards") + last_device = None + for shard, (device, saver) in enumerate( + sorted(self._single_device_savers.items())): + last_device = device + with ops.device(saveable_object_util.set_cpu0(device)): + shard_prefix = sharded_filename(tmp_checkpoint_prefix, shard, + num_shards_tensor) + saved_prefixes.append(shard_prefix) + with ops.device(device): + # _SingleDeviceSaver will use the CPU device when necessary, but + # initial read operations should be placed on the SaveableObject's + # device. + sharded_saves.append(saver.save(shard_prefix, options)) + + with ops.control_dependencies(sharded_saves): + # Merge on the io_device if specified, otherwise co-locates the merge op + # with the last device used. + merge_device = ( + options.experimental_io_device or + saveable_object_util.set_cpu0(last_device)) + with ops.device(merge_device): + # V2 format write path consists of a metadata merge step. Once + # merged, attempts to delete the temporary directory, + # "_temp". + return gen_io_ops.merge_v2_checkpoints( + saved_prefixes, file_prefix, delete_old_dirs=True) + + # Since this will causes a function re-trace on each save, limit this to the + # cases where it is needed: eager and when there are multiple tasks/single + # device savers. Note that the retrace is needed to ensure we pickup the + # latest values of options like experimental_io_device. + if context.executing_eagerly() and len(self._single_device_savers) > 1: + # Explicitly place the identity op on the first device. + @def_function.function(jit_compile=False) + def tf_function_save(): + save_fn() + tf_function_save() + else: + return save_fn() + + def restore(self, file_prefix, options=None): + """Restore the saveable objects from a checkpoint with `file_prefix`. + + Args: + file_prefix: A string or scalar string Tensor containing the prefix for + files to read from. + options: Optional `CheckpointOptions` object. + + Returns: + When not run eagerly or when saving on a single device, returns a + dictionary mapping from SaveableObject names to restore operations; + otherwise, returns an empty dict. + """ + options = options or checkpoint_options.CheckpointOptions() + + def restore_fn(): + restore_fn_inputs = {} + restore_fn_input_count = { + fn: len(keys) for fn, keys in self._restore_fn_to_keys.items()} + + restore_ops = {} + # Sort by device name to avoid propagating non-deterministic dictionary + # ordering in some Python versions. + for device, saver in sorted(self._single_device_savers.items()): + with ops.device(device): + # Load values from checkpoint + restored_tensor_dict = saver.restore(file_prefix, options) + + # Map restored tensors to the corresponding restore_fn, and see if all + # inputs have all been loaded. Call `restore_fn` if that is the case. + for checkpoint_key, slice_and_tensor in restored_tensor_dict.items(): + for slice_spec, tensor in slice_and_tensor.items(): + restore_fn = self._keys_to_restore_fn[(checkpoint_key, + slice_spec)] + + # Processing the returned restored_tensor_dict to prepare for the + # Trackable `restore` function. The `restore` function expects a + # map of `string name (checkpoint_key) -> Tensor`. Unless there is + # a slice_spec, in which case the map will be of + # `string name (checkpoint_key)-> slice_spec -> Tensor`. + if slice_spec: + (restore_fn_inputs.setdefault(restore_fn, {}).setdefault( + checkpoint_key, {})[slice_spec]) = tensor + else: + restore_fn_inputs.setdefault(restore_fn, + {})[checkpoint_key] = tensor + restore_fn_input_count[restore_fn] -= 1 + + if restore_fn_input_count[restore_fn] == 0: + restored_tensors = {} + # Extracts the substring after the "/.ATTRIBUTES/" in the + # ckpt_key from restore_fn_inputs[restore_fn] to + # restored_tensors. For example, if restore_fn_input[restore_fn] + # is dict { "/.ATTIBUTES/a": Tensor}, restored_tensors will be + # changed to dict {"a": Tensor} + for ckpt_key, tensor in restore_fn_inputs[restore_fn].items(): + restored_tensors[trackable_utils.extract_local_name( + ckpt_key)] = tensor + ret = restore_fn(restored_tensors) + if isinstance(ret, dict): + restore_ops.update(ret) + # Run registered restore methods after the default restore ops. + for _, (_, restore_fn) in self._registered_savers.items(): + restore_fn(file_prefix) + return restore_ops + + has_custom_device_saver = any([ + context.is_custom_device(d) for d in self._single_device_savers.keys() + ]) + # Since this will cause a function re-trace on each restore, limit this to + # cases where it is needed: eager and when there are multiple tasks/single + # device savers or any single device saver is a custom device. Note that the + # retrace is needed to ensure we pickup the latest values of options like + # experimental_io_device. + # + # We run in a function when there is a custom device saver because custom + # devices, such as DTensor, usually do a sharded save and restore. + # Doing a sharded save and restore requires knowledge about what shards + # of variables we are restoring to. In practice, this means that custom + # devices need the AssignVariableOps along with the Restore op within the + # same graph to infer shapes and shard specs for Restore op. + if context.executing_eagerly() and (len(self._single_device_savers) > 1 or + has_custom_device_saver): + @def_function.function(jit_compile=False, autograph=False) + def tf_function_restore(): + restore_fn() + return {} + + restore_ops = tf_function_restore() + else: + restore_ops = restore_fn() + + return restore_ops diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/graph_view.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/graph_view.py new file mode 100644 index 0000000000000000000000000000000000000000..3e92d03a09875b9704c6f52b9c1133b8487f1dc9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/graph_view.py @@ -0,0 +1,167 @@ +"""Manages a graph of Trackable objects.""" +# 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. +# ============================================================================== +import copy +import weakref + +from tensorflow.python.checkpoint import save_util_v1 +from tensorflow.python.checkpoint import trackable_view +from tensorflow.python.trackable import base +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.tracking.ObjectGraphView", v1=[]) +class ObjectGraphView(trackable_view.TrackableView): + """Gathers and serializes an object graph.""" + + def __init__(self, root, attached_dependencies=None): + """Configure the graph view. + + Args: + root: A `Trackable` object whose variables (including the variables of + dependencies, recursively) should be saved. May be a weak reference. + attached_dependencies: List of dependencies to attach to the root object. + Used when saving a Checkpoint with a defined root object. To avoid + reference cycles, this should use the WeakTrackableReference class. + """ + trackable_view.TrackableView.__init__(self, root) + # ObjectGraphView should never contain a strong reference to root, since it + # may result in a cycle: + # root -> deferred dependencies -> CheckpointPosition + # -> CheckpointRestoreCoordinator -> ObjectGraphView -> root + self._root_ref = (root if isinstance(root, weakref.ref) + else weakref.ref(root)) + self._attached_dependencies = attached_dependencies + + def __deepcopy__(self, memo): + # By default, weak references are not copied, which leads to surprising + # deepcopy behavior. To fix, we first we copy the object itself, then we + # make a weak reference to the copy. + strong_root = self._root_ref() + if strong_root is not None: + strong_copy = copy.deepcopy(strong_root, memo) + memo[id(self._root_ref)] = weakref.ref(strong_copy) + # super() does not have a __deepcopy__, so we need to re-implement it + copied = super().__new__(type(self)) + memo[id(self)] = copied + for key, value in vars(self).items(): + setattr(copied, key, copy.deepcopy(value, memo)) + return copied + + def list_children(self, obj, save_type=base.SaveType.CHECKPOINT, **kwargs): + """Returns list of all child trackables attached to obj. + + Args: + obj: A `Trackable` object. + save_type: A string, can be 'savedmodel' or 'checkpoint'. + **kwargs: kwargs to use when retrieving the object's children. + + Returns: + List of all children attached to the object. + """ + children = [] + for name, ref in super(ObjectGraphView, + self).children(obj, save_type, **kwargs).items(): + children.append(base.TrackableReference(name, ref)) + + # GraphView objects may define children of the root object that are not + # actually attached, e.g. a Checkpoint object's save_counter. + if obj is self.root and self._attached_dependencies: + children.extend(self._attached_dependencies) + return children + + def children(self, obj, save_type=base.SaveType.CHECKPOINT, **kwargs): + """Returns all child trackables attached to obj. + + Args: + obj: A `Trackable` object. + save_type: A string, can be 'savedmodel' or 'checkpoint'. + **kwargs: kwargs to use when retrieving the object's children. + + Returns: + Dictionary of all children attached to the object with name to trackable. + """ + children = {} + for name, ref in self.list_children(obj, **kwargs): + children[name] = ref + return children + + @property + def attached_dependencies(self): + """Returns list of dependencies that should be saved in the checkpoint. + + These dependencies are not tracked by root, but are in the checkpoint. + This is defined when the user creates a Checkpoint with both root and kwargs + set. + + Returns: + A list of TrackableReferences. + """ + return self._attached_dependencies + + @property + def root(self): + if isinstance(self._root_ref, weakref.ref): + derefed = self._root_ref() + assert derefed is not None + return derefed + else: + return self._root_ref + + def breadth_first_traversal(self): + return self._breadth_first_traversal() + + def _breadth_first_traversal(self): + """Find shortest paths to all dependencies of self.root.""" + return super(ObjectGraphView, self)._descendants_with_paths() + + def serialize_object_graph(self, saveables_cache=None): + """Determine checkpoint keys for variables and build a serialized graph. + + Non-slot variables are keyed based on a shortest path from the root saveable + to the object which owns the variable (i.e. the one which called + `Trackable._add_variable` to create it). + + Slot variables are keyed based on a shortest path to the variable being + slotted for, a shortest path to their optimizer, and the slot name. + + Args: + saveables_cache: An optional cache storing previously created + SaveableObjects created for each Trackable. Maps Trackables to a + dictionary of attribute names to Trackable. + + Returns: + A tuple of (named_variables, object_graph_proto, feed_additions): + named_variables: A dictionary mapping names to variable objects. + object_graph_proto: A TrackableObjectGraph protocol buffer + containing the serialized object graph and variable references. + feed_additions: A dictionary mapping from Tensors to values which should + be fed when saving. + + Raises: + ValueError: If there are invalid characters in an optimizer's slot names. + """ + named_saveable_objects, object_graph_proto, feed_additions, _ = ( + save_util_v1.serialize_object_graph_with_registered_savers( + self, saveables_cache)) + return named_saveable_objects, object_graph_proto, feed_additions + + def frozen_saveable_objects(self, + object_map=None, + to_graph=None, + call_with_mapped_captures=None): + """Creates SaveableObjects with the current object graph frozen.""" + return save_util_v1.frozen_saveables_and_savers( + self, object_map, to_graph, call_with_mapped_captures)[0] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/restore.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/restore.py new file mode 100644 index 0000000000000000000000000000000000000000..953648fa65ca5c78e3906af991502bb0a563b5ef --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/restore.py @@ -0,0 +1,725 @@ +# 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. +# ============================================================================== +"""Logic for restoring checkpointed values for Trackables.""" + +import collections + +from tensorflow.python.checkpoint import checkpoint_view +from tensorflow.python.checkpoint import functional_saver +from tensorflow.python.checkpoint import save_util_v1 +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_io_ops as io_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import registration +from tensorflow.python.trackable import base +from tensorflow.python.trackable import constants +from tensorflow.python.trackable import python_state +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import object_identity + + +class CheckpointPosition(object): + """Indicates a position within a `_CheckpointRestoreCoordinator`.""" + + __slots__ = ["_checkpoint", "_proto_id", "skip_restore"] + + def __init__(self, checkpoint, proto_id): + """Specify an object within a checkpoint. + + Args: + checkpoint: A _CheckpointRestoreCoordinator object. + proto_id: The index of this object in TrackableObjectGraph.nodes. + """ + self._checkpoint = checkpoint + self._proto_id = proto_id + # This may be set to True if the registered saver cannot be used with this + # object. + self.skip_restore = False + + def restore(self, trackable, reader=None): + """Restore this value into `trackable`.""" + with ops.init_scope(): + if self.bind_object(trackable): + # This object's correspondence with a checkpointed object is new, so + # process deferred restorations for it and its dependencies. + restore_ops = self._restore_descendants(reader) + if restore_ops: + self._checkpoint.new_restore_ops(restore_ops) + + def bind_object(self, trackable): + """Set a checkpoint<->object correspondence. + + Args: + trackable: The object to record a correspondence for. + + Returns: + True if this is a new assignment, False if this object has already been + mapped to a checkpointed `Object` proto. + Raises: + AssertionError: If another object is already bound to the `Object` proto. + """ + checkpoint = self.checkpoint + checkpoint.all_python_objects.add(trackable) + current_assignment = checkpoint.object_by_proto_id.get(self._proto_id, None) + checkpoint.matched_proto_ids.add(self._proto_id) + if current_assignment is None: + checkpoint.object_by_proto_id[self._proto_id] = trackable + return True # New assignment + else: + # The object was already mapped for this checkpoint load, which means + # we don't need to do anything besides check that the mapping is + # consistent (if the dependency DAG is not a tree then there are + # multiple paths to the same object). + if current_assignment is not trackable: + logging.warning( + "Inconsistent references when loading the checkpoint into this " + "object graph. For example, in the saved checkpoint object, " + "`model.layer.weight` and `model.layer_copy.weight` reference the " + "same variable, while in the current object these are two different" + " variables. The referenced variables are:" + f"({current_assignment} and {trackable}).") + return False # Not a new assignment + + def is_simple_variable(self): + """Determine whether this value is restorable with a Tensor initializer.""" + attributes = self.object_proto.attributes + return (len(attributes) == 1 and + attributes[0].name == constants.VARIABLE_VALUE_KEY and + not self.object_proto.children) + + def value_tensors(self, shape_and_slices=None): + """Create value `Tensor`s for this object's attributes. + + Does not require that the Python object has been created. Used for + restore-on-create when executing eagerly. + + Args: + shape_and_slices: A dict mapping from object attribute names to a shape + and slice string that will be passed to a RestoreV2 op. If the dict is + None or if an object attribute is not in the dict, the full tensor will + be restored. + + Returns: + A dictionary mapping from object attribute names to `Tensor`s. + """ + value_tensors = {} + for serialized_tensor in self.object_proto.attributes: + checkpoint_key = serialized_tensor.checkpoint_key + dtype = self._checkpoint.dtype_map[checkpoint_key] + base_type = dtype.base_dtype + io_device = self._checkpoint.options.experimental_io_device or "cpu:0" + with ops.init_scope(): + with ops.device(io_device): + # Run the restore itself on the io_device(CPU or specified). + if (shape_and_slices is not None and + serialized_tensor.name in shape_and_slices): + shape_and_slice = shape_and_slices[serialized_tensor.name] + else: + shape_and_slice = "" + value, = io_ops.restore_v2( + prefix=self._checkpoint.save_path_tensor, + tensor_names=[checkpoint_key], + shape_and_slices=[shape_and_slice], + dtypes=[base_type], + name="%s_checkpoint_read" % (serialized_tensor.name,)) + # Copy the value to the current device if necessary. + value_tensors[serialized_tensor.name] = array_ops.identity(value) + return value_tensors + + def gather_ops_or_named_saveables(self): + """Looks up or creates SaveableObjects which don't have cached ops. + + Returns: + A tuple of ( + existing_restore_ops: list, + named_saveables: dict, + python_positions: list, + registered_savers: dict) + """ + + recorded_registered_saver = self.get_registered_saver_name() + if not (self.object_proto.attributes or recorded_registered_saver): + return [], {}, [], {} + + existing_restore_ops = [] + named_saveables = {} + python_positions = [] + registered_savers = collections.defaultdict(dict) + + saveable_factories = saveable_object_util.saveable_objects_from_trackable( + self.trackable) + saver_name = registration.get_registered_saver_name(self.trackable) + + if recorded_registered_saver: + if not self.skip_restore: + name = self.object_proto.registered_saver.object_name + registered_savers[recorded_registered_saver][name] = self.trackable + # Else: Skip restoration of this Trackable. This skip only happens if the + # registered saver has enabled `option_restore`. Otherwise, an error would + # have been raised at `self.get_registered_saver_name()`. + elif saver_name: + # In this case, the checkpoint has a recorded serialized tensor but no + # registered saver, while the Trackable loading the checkpoint has + # migrated to the registered checkpoint functionality (TPUEmbedding is an + # example of this). + + # Set the Trackable's object name to the first checkpoint key that is + # stored in checkpoint. If there is a use case that requires the other + # keys, then we can take another look at this. + registered_savers[saver_name] = { + self.object_proto.attributes[0].checkpoint_key: self.trackable + } + elif isinstance(self.trackable, python_state.PythonState): + python_positions.append(self) + elif saveable_factories.keys() == { + trackable_utils.SERIALIZE_TO_TENSORS_NAME + }: + existing_restore_ops, named_saveables = ( + self._create_serialize_to_tensor_saveable(saveable_factories)) + elif saveable_factories: + existing_restore_ops, named_saveables = ( + self._create_saveables_by_attribute_name(saveable_factories)) + else: + # If no registered savers were found, then it means that one or more + # serialized tensors were never used. + for serialized_tensor in self.object_proto.attributes: + self._checkpoint.unused_attributes.setdefault( + self._proto_id, []).append(serialized_tensor.name) + return (existing_restore_ops, named_saveables, python_positions, + registered_savers) + + def _create_serialize_to_tensor_saveable(self, saveable_factories): + """Creates a saveable using the _serialize_to_tensor method.""" + # Extract the saveable name from the checkpoint key. This will be used as + # the cache key or the name to pass to the saveable factory. + suffix = saveable_compat.get_saveable_name(self.trackable) or "" + saveable_name = _extract_saveable_name( + self.object_proto.attributes[0].checkpoint_key) + suffix + + # Try to find the cached saveable (only in graph mode). + if not context.executing_eagerly(): + existing_op = self._checkpoint.restore_ops_by_name.get( + saveable_name, None) + if existing_op is not None: + return [existing_op], {} + + saveables_cache = self._checkpoint.saveables_cache.setdefault( + self.trackable, {}) + if saveable_name in saveables_cache: + return [], {saveable_name: saveables_cache[saveable_name]} + + saveable = saveable_factories[trackable_utils.SERIALIZE_TO_TENSORS_NAME]( + name=saveable_name) + if not context.executing_eagerly(): + saveables_cache[saveable_name] = saveable + return [], {saveable_name: saveable} + + def _create_saveables_by_attribute_name(self, saveable_factories): + """Creates or caches SaveableObjects by matching the attribute names. + + The attribute name keys in the `saveable_factories` is used to find the + corresponding attribute in the object proto. Attributes contain checkpoint + keys which are passed to the factory function to generate the + SaveableObject. + + Args: + saveable_factories: a dict mapping attribute name to a callable factory + function that produces a SaveableObject. + + Returns: + A tuple of ( + existing_restore_ops: list, + named_saveables: dict) + """ + # Name saveables based on the name this object had when it was checkpointed. + named_saveables = {} + existing_restore_ops = [] + + # Forward compatibility code: when loading a future checkpoint, there may + # be multiple SerializedTensors mapped to a single saveable. + created_compat_names = set() + + for serialized_tensor in self.object_proto.attributes: + if context.executing_eagerly(): + existing_op = None + else: + existing_op = self._checkpoint.restore_ops_by_name.get( + serialized_tensor.checkpoint_key, None) + if existing_op is not None: + existing_restore_ops.append(existing_op) + continue + + if any(serialized_tensor.name.startswith(name) + for name in created_compat_names): + continue # Saveable has already been created for this tensor. + + # Only if we don't have cached ops for this SaveableObject, we'll see if + # the SaveableObject itself has been cached. If not, we'll make it, and + # either way we'll extract new ops from it (or if it has Python state to + # restore, we'll run that). + saveables_cache = self._checkpoint.saveables_cache + if saveables_cache is None: + # No SaveableObject caching when executing eagerly. + saveable = None + else: + # If we've already created and cached a SaveableObject for this + # attribute, we can re-use it to avoid re-creating some ops when graph + # building. + saveable_list = saveables_cache.get(self.trackable, + {}).get(serialized_tensor.name, + (None,)) + if len(saveable_list) == 1: + # Almost every attribute will have exactly one SaveableObject. + saveable, = saveable_list + else: + # Don't use cached SaveableObjects for partitioned variables, which is + # the only case where we'd have a list of SaveableObjects. Op caching + # will catch them. + saveable = None + if saveable is not None: + # The name of this attribute has changed, so we need to re-generate + # the SaveableObject. + if serialized_tensor.checkpoint_key not in saveable.name: + saveable = None + del saveables_cache[self.trackable] + if saveable is None: + # If there was no cached SaveableObject, create one. + # Use the name to check if the Python object has the same attribute. + saveable = _get_saveable_from_factory(saveable_factories, + serialized_tensor, + created_compat_names) + if saveable is None: + # Purposefully does not throw an exception if attributes have been + # added or deleted. Stores unused attributes so an exception can be + # raised if the user decides to check that everything in the + # checkpoint was loaded. + self._checkpoint.unused_attributes.setdefault( + self._proto_id, []).append(serialized_tensor.name) + continue + if saveables_cache is not None: + saveables_cache.setdefault(self.trackable, + {})[serialized_tensor.name] = [saveable] + named_saveables[serialized_tensor.checkpoint_key] = saveable + + return existing_restore_ops, named_saveables + + def restore_ops(self, reader=None): + """Create or fetch restore ops for this object's attributes. + + Requires that the `Trackable` Python object has been bound to an object + ID in the checkpoint. + + Args: + reader: A `CheckpointReader`. If None, a new instance will be created. + + Returns: + A list of operations when graph building, or an empty list when executing + eagerly. + """ + if self._has_registered_saver(): + raise ValueError("Unable to run individual checkpoint restore for objects" + " with registered savers.") + (restore_ops, tensor_saveables, python_positions, + _) = self.gather_ops_or_named_saveables() + restore_ops.extend( + self._checkpoint.restore_saveables( + tensor_saveables, python_positions, reader=reader)) + return restore_ops + + @property + def checkpoint(self): + return self._checkpoint + + @property + def trackable(self): + return self._checkpoint.object_by_proto_id[self._proto_id] + + @property + def object_proto(self): + return self._checkpoint.object_graph_proto.nodes[self._proto_id] + + @property + def proto_id(self): + return self._proto_id + + @property + def restore_uid(self): + return self._checkpoint.restore_uid + + def __repr__(self): + return repr(self.object_proto) + + def value_shape(self): + """The shape of the VARIABLE_VALUE tensor. + + Returns: + If found a TensorShape object, otherwise None. + """ + for serialized_tensor in self.object_proto.attributes: + if serialized_tensor.name == constants.VARIABLE_VALUE_KEY: + return self._checkpoint.shape_map[serialized_tensor.checkpoint_key] + return None + + def _has_registered_saver(self): + return bool(self.object_proto.registered_saver.name) + + def get_registered_saver_name(self): + """Returns the registered saver name defined in the Checkpoint.""" + if self._has_registered_saver(): + saver_name = self.object_proto.registered_saver.name + try: + registration.validate_restore_function(self.trackable, saver_name) + except ValueError as e: + if registration.get_strict_predicate_restore(saver_name): + raise e + self.skip_restore = True + return saver_name + return None + + def create_slot_variable_position(self, optimizer_object, variable, + slot_variable_id, slot_name): + """Generates CheckpointPosition for a slot variable. + + Args: + optimizer_object: Optimizer that owns the slot variable. + variable: Variable associated with the slot variable. + slot_variable_id: ID of the slot variable. + slot_name: Name of the slot variable. + + Returns: + If there is a slot variable in the `optimizer_object` that has not been + bound to the checkpoint, this function returns a tuple of ( + new `CheckpointPosition` for the slot variable, + the slot variable itself). + """ + slot_variable_position = CheckpointPosition( + checkpoint=self.checkpoint, proto_id=slot_variable_id) + # pylint: disable=protected-access + slot_variable = optimizer_object._create_or_restore_slot_variable( + slot_variable_position=slot_variable_position, + variable=variable, + slot_name=slot_name) + # pylint: enable=protected-access + if (slot_variable is not None and + slot_variable_position.bind_object(slot_variable)): + return slot_variable_position, slot_variable + else: + return None, None + + def create_child_position(self, node_id): + return CheckpointPosition(checkpoint=self.checkpoint, proto_id=node_id) + + def _restore_descendants(self, reader=None): + """Restore the bound Trackable and dependencies (may be deferred).""" + # Attempt a breadth-first traversal, since presumably the user has more + # control over shorter paths. If we don't have all of the dependencies at + # this point, the end result is not breadth-first (since other deferred + # traversals will happen later). + + # You may be wondering why elements in the `visit_queue` are tuples that + # contains both CheckpointPositions and their Trackable. The reason is that + # Optimizers will not keep a strong reference to slot vars for + # ShardedVariables. The slot variable must be kept in memory until the + # restore saveables have been created. + visit_queue = collections.deque([(self, self.trackable)]) + restore_ops = [] + tensor_saveables = {} + python_positions = [] + registered_savers = collections.defaultdict(dict) + while visit_queue: + current_position, _ = visit_queue.popleft() + + # Restore using the ops defined in a Saveable or registered function. + (new_restore_ops, new_tensor_saveables, new_python_positions, + new_registered_savers) = current_position._single_restore() # pylint: disable=protected-access + restore_ops.extend(new_restore_ops) + tensor_saveables.update(new_tensor_saveables) + python_positions.extend(new_python_positions) + for saver_name, trackable_map in new_registered_savers.items(): + registered_savers[saver_name].update(trackable_map) + + # Pass the restoration to the dependencies. + _queue_children_for_restoration(current_position, visit_queue) + _queue_slot_variables(current_position, visit_queue) + + restore_ops.extend( + current_position.checkpoint.restore_saveables( + tensor_saveables, + python_positions, + registered_savers, + reader=reader)) + return restore_ops + + def _single_restore(self): + """Restores the trackable.""" + trackable = self.trackable + trackable._maybe_initialize_trackable() # pylint: disable=protected-access + checkpoint = self.checkpoint + # If the UID of this restore is lower than our current update UID, we don't + # need to actually restore the object. + if checkpoint.restore_uid > trackable._update_uid: # pylint: disable=protected-access + restore_ops, tensor_saveables, python_positions, registered_savers = ( + self.gather_ops_or_named_saveables()) + trackable._update_uid = checkpoint.restore_uid # pylint: disable=protected-access + else: + restore_ops = () + tensor_saveables = {} + python_positions = () + registered_savers = {} + return restore_ops, tensor_saveables, python_positions, registered_savers + + +def restore_nodes(save_path, nodes_to_restore): + """Restores nodes from a dict. + + Requires that the `Trackable` Python object has been bound to an object + ID in the checkpoint. + + Args: + save_path: a string represents path to the checkpoint. + nodes_to_restore: a dict maps `node_id` to `trackable` to be restored. + """ + if save_path is None: + raise ValueError("save_path cannot be empty.") + if not isinstance(nodes_to_restore, dict): + raise ValueError( + "Expecting a dictionary of node_id to Trackable for nodes_to_restore.") + + ckpt_view = checkpoint_view.CheckpointView(save_path) + ckpt_view_descendants = ckpt_view.descendants() + for node_id, trackable in nodes_to_restore.items(): + # node_id does not have a corresponding Checkpoint value. + if (node_id not in ckpt_view_descendants or + ckpt_view._object_graph_proto.nodes[ # pylint: disable=protected-access + node_id] is None): + raise ValueError( + f"The expected node_id: {node_id} to Trackable {trackable} to " + "restore does not exist in the checkpoint.") + # Trackable mapped to node_id to restore is empty. + if trackable is None or not isinstance(trackable, base.Trackable): + raise ValueError( + f"Expecting a valid Trackable to node_id: {node_id} but got " + f"trackable: {trackable}." + ) + + serialized_tensors = object_identity.ObjectIdentityDictionary() + for node_id, current_trackable in nodes_to_restore.items(): + ckpt_contains_serialized_tensors = ckpt_view._object_graph_proto.nodes[ # pylint: disable=protected-access + node_id].attributes + node = ckpt_view._object_graph_proto.nodes[node_id] # pylint: disable=protected-access + trackable_has_serialize_to_tensor = saveable_object_util.trackable_has_serialize_to_tensor( + current_trackable) + if not trackable_has_serialize_to_tensor: + if not node.attributes: + if saveable_object_util.saveable_objects_from_trackable( + current_trackable): + raise ValueError( + f"Trackable {current_trackable} expects checkpointed values but " + "checkpoint does not contain serialized tensors for node_id: " + f"{node_id}.") + else: + continue + object_names = object_identity.ObjectIdentityDictionary() + object_names[current_trackable] = trackable_utils.extract_object_name( + node.attributes[0].checkpoint_key) + checkpoint_factory_map, _ = save_util_v1.get_checkpoint_factories_and_keys( + object_names, None) + saveable_objects = save_util_v1.generate_saveable_objects( + checkpoint_factory_map)[0] + if len(node.attributes) != len(saveable_objects): + raise ValueError("Size for saveable_objects for Trackable: " + f"{len(saveable_objects)} did not match the size for " + "serialized_tensors for checkpoint: " + f"{len(node.attributes)}.") + current_trackable = saveable_object_util.SaveableCompatibilityConverter( + current_trackable, saveable_objects) + + serialized_tensors[ + current_trackable] = current_trackable._serialize_to_tensors() # pylint: disable=protected-access + trackable_expects_ckpted_value = bool(serialized_tensors[current_trackable]) + + if trackable_expects_ckpted_value and not ckpt_contains_serialized_tensors: + raise ValueError( + f"Trackable {current_trackable} expects checkpointed values but " + "checkpoint does not contain serialized tensors for node_id: " + f"{node_id}.") + + if not trackable_expects_ckpted_value and ckpt_contains_serialized_tensors: + raise ValueError( + f"Trackable {current_trackable} does not expect checkpointed " + "values but checkpoint contains serialized tensors: " + f"{ckpt_contains_serialized_tensors} for node_id: {node_id}.") + + if len(node.attributes) != len(serialized_tensors[current_trackable]): + raise ValueError("Size for serialized_tensors for Trackable: " + f"{len(serialized_tensors[current_trackable])} did not " + "match size for serialized_tensors for checkpoint: " + f"{len(node.attributes)}.") + + if not trackable_has_serialize_to_tensor: + functional_saver.MultiDeviceSaver(serialized_tensors).restore(save_path) + else: + # Converts attribute.name to attribute.checkpoint_key since that's what + # restore method is expecting. i.e., converts "a" to "/.ATTRIBUTES/a". + serialized_tensors_renamed = object_identity.ObjectIdentityDictionary() + serialized_tensors_renamed[current_trackable] = {} + for attribute in node.attributes: + name = attribute.name + checkpoint_key = attribute.checkpoint_key + serialized_tensors_renamed[current_trackable][ + checkpoint_key] = serialized_tensors[current_trackable][name] + functional_saver.MultiDeviceSaver(serialized_tensors_renamed).restore( + save_path) + + +def _queue_children_for_restoration(checkpoint_position, visit_queue): + """Queues the restoration of trackable's children or defers them.""" + # pylint: disable=protected-access + trackable = checkpoint_position.trackable + trackable_children = trackable._trackable_children() + for child in checkpoint_position.object_proto.children: + # trackable._lookup_dependency can be expensive so first check if this node + # already has an object correspondence. If so we skip this node. + correspondence = checkpoint_position.checkpoint.object_by_proto_id.get( + child.node_id, None + ) + if correspondence is not None: + continue + child_position = checkpoint_position.create_child_position(child.node_id) + local_object = trackable._lookup_dependency(child.local_name, + trackable_children) + child_proto = child_position.object_proto + if local_object is None: + # We don't yet have a dependency registered with this name. Save it + # in case we do. + if child_proto.HasField("has_checkpoint_values"): + has_value = child_proto.has_checkpoint_values.value + else: + # If the field is not set, do a simple check to see if the dependency + # has children and/or checkpointed values. + has_value = bool( + child_proto.children or child_proto.attributes or + child_proto.slot_variables or + child_proto.HasField("registered_saver")) + if has_value: + trackable._deferred_dependencies.setdefault(child.local_name, + []).append(child_position) + else: + if child_position.bind_object(trackable=local_object): + # This object's correspondence is new, so dependencies need to be + # visited. Delay doing it so that we get a breadth-first dependency + # resolution order (shallowest paths first). The caller is responsible + # for emptying visit_queue. + visit_queue.append((child_position, local_object)) + + +_DeferredSlotVariableRestoration = collections.namedtuple( + "_DeferredSlotVariableRestoration", [ + "original_variable", + "slot_variable_id", + "slot_name", + ]) + + +def _queue_slot_variables(checkpoint_position, visit_queue): + """Queues slot variables for restoration.""" + trackable = checkpoint_position.trackable + checkpoint = checkpoint_position.checkpoint + for deferred_slot_restoration in (checkpoint.deferred_slot_restorations.pop( + checkpoint_position.proto_id, ())): + slot_variable_position, slot_variable = ( + checkpoint_position.create_slot_variable_position( + trackable, deferred_slot_restoration.original_variable, + deferred_slot_restoration.slot_variable_id, + deferred_slot_restoration.slot_name)) + if slot_variable_position is not None: + visit_queue.append((slot_variable_position, slot_variable)) + for slot_restoration in checkpoint.slot_restorations.pop( + checkpoint_position.proto_id, ()): + optimizer_object = checkpoint.object_by_proto_id.get( + slot_restoration.optimizer_id, None) + if optimizer_object is None: + # The optimizer has not yet been created or tracked. Record in the + # checkpoint that the slot variables need to be restored when it is. + checkpoint.deferred_slot_restorations.setdefault( + slot_restoration.optimizer_id, []).append( + _DeferredSlotVariableRestoration( + original_variable=trackable, + slot_variable_id=slot_restoration.slot_variable_id, + slot_name=slot_restoration.slot_name)) + + # `optimizer_object` can be a `Checkpoint` when user only needs the + # attributes the optimizer holds, such as `iterations`. In those cases, + # it would not have the optimizer's `_create_or_restore_slot_variable` + # method. + elif hasattr(optimizer_object, "_create_or_restore_slot_variable"): + slot_variable_position, slot_variable = ( + checkpoint_position.create_slot_variable_position( + optimizer_object, trackable, slot_restoration.slot_variable_id, + slot_restoration.slot_name)) + if slot_variable_position is not None: + visit_queue.append((slot_variable_position, slot_variable)) + + +def _extract_saveable_name(checkpoint_key): + # Substring the checkpoint key to the end of the "{...}.ATTRIBUTES/" + search_key = trackable_utils.OBJECT_ATTRIBUTES_NAME + "/" + return checkpoint_key[:checkpoint_key.index(search_key) + len(search_key)] + + +def _get_saveable_from_factory(saveable_factories, serialized_tensor, + created_compat_names): + """Returns the saveable generated from the factory method.""" + matched_factory = None + + # The `expected_factory_name` is used to find the right saveable factory, + # while the `factory_input_name` is the value that is passed to the factory + # method to instantiate the SaveableObject. + expected_factory_name = serialized_tensor.name + factory_input_name = serialized_tensor.checkpoint_key + + # Case 1: the name already exactly matches a key in saveable_factories. + if expected_factory_name in saveable_factories: + matched_factory = saveable_factories[expected_factory_name] + + # Case 2: (Forward compat) The serialized name is composed of + # "factory_name" + "SUFFIX". Get the matching factory name. + if matched_factory is None: + + for factory_name, factory in saveable_factories.items(): + if expected_factory_name.startswith(factory_name): + if matched_factory is not None: + # This condition is met in the extreme edge case where the object + # returns two saveable factories with similar names. This is very + # unlikely because there zero objects inside TensorFlow that use + # more than one saveable factory. + raise ValueError("Forward compatibility load error: Unable to load " + "checkpoint saved in future version of TensorFlow. " + "Please update your version of TensorFlow to the " + "version in which the checkpoint was saved.") + + matched_factory = factory + factory_input_name = _extract_saveable_name( + serialized_tensor.checkpoint_key) + factory_name + created_compat_names.add(factory_name) + + if callable(matched_factory): + return matched_factory(name=factory_input_name) + return matched_factory diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/save_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/save_util.py new file mode 100644 index 0000000000000000000000000000000000000000..5c455c5910e34d2a9971ef15f42449afaab5554d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/save_util.py @@ -0,0 +1,344 @@ +# 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. +# ============================================================================== +"""Extracts tensors for checkpointing while updating a TrackableObjectGraph. + +The tensors are extracted from `Trackable._serialize_to_tensors`. +""" +import collections + +from typing import Any, Callable, List, Optional, Tuple, Mapping, Union, Dict + +from tensorflow.core.protobuf import trackable_object_graph_pb2 +from tensorflow.python.checkpoint import graph_view as graph_view_lib +from tensorflow.python.checkpoint import save_util_v1 +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.checkpoint import util +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.saved_model import registration +from tensorflow.python.trackable import base +from tensorflow.python.trackable import python_state +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training.saving import saveable_object as saveable_object_lib +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.types import core +from tensorflow.python.util import object_identity + +# Attributes for each Trackable in the checkpointed object graph. +_TrackableData = collections.namedtuple("_TrackableData", [ + # A trackable in the root Trackable object graph. + "trackable", + # The index at which the Trackable appears in TrackableObjectGraph.nodes. + "node_id", + # The BFS-generated path from the root object / used to generate readable + # checkpoint keys. + "object_name", + # A list of ObjectReference for each child connected to this Trackable. + "children_proto", + # A list of SlotVariableReference to save to the object (only valid for + # Optimizer objects). + "slot_variable_proto", + # The object to save to checkpoint. Usually this is the same as `trackable`, + # but can differ when the the caller wants to specify a different object to + # save. For example, when saving checkpoints asynchronously, variables are + # copied to the CPU. `object_to_save` is set as the copied variable. + "object_to_save", + ]) + + +def _split_trackables( + trackable_data: List[_TrackableData] +) -> Tuple[List[_TrackableData], List[_TrackableData], + Dict[str, List[_TrackableData]]]: + """Splits Trackables into 3 categories (tensor/pystate/registered).""" + tensor_trackables = [] + pystate_trackables = [] + registered_trackables = collections.defaultdict(list) + + for td in trackable_data: + saver_name = registration.get_registered_saver_name(td.object_to_save) + if isinstance(td.object_to_save, python_state.PythonState): + pystate_trackables.append(td) + elif saver_name: + registered_trackables[saver_name].append(td) + else: + tensor_trackables.append(td) + + return tensor_trackables, pystate_trackables, registered_trackables + + +def _gather_trackable_data( + graph_view: graph_view_lib.ObjectGraphView, + object_map: Mapping[base.Trackable, base.Trackable] +) -> Tuple[List[_TrackableData], Dict[base.Trackable, int]]: + """Returns a list of generated TrackableData based on the ObjectGraphView.""" + trackable_objects, node_paths = graph_view.breadth_first_traversal() + object_names = object_identity.ObjectIdentityDictionary() + for obj, path in node_paths.items(): + object_names[obj] = trackable_utils.object_path_to_string(path) + node_ids = object_identity.ObjectIdentityDictionary() + for node_id, node in enumerate(trackable_objects): + node_ids[node] = node_id + slot_variables = util.serialize_slot_variables( + trackable_objects=trackable_objects, + node_ids=node_ids, + object_names=object_names) + trackable_data = [] + for trackable in trackable_objects: + children_proto = [] + for child in graph_view.list_children(trackable): + children_proto.append( + trackable_object_graph_pb2.TrackableObjectGraph.TrackableObject + .ObjectReference(node_id=node_ids[child.ref], + local_name=child.name)) + + trackable_data.append(_TrackableData( + trackable, + node_id=node_ids[trackable], + object_name=object_names[trackable], + children_proto=children_proto, + slot_variable_proto=slot_variables.get(trackable, []), + object_to_save=util.get_mapped_trackable(trackable, object_map))) + return trackable_data, node_ids + + +def _fill_object_graph_proto( + trackable_data: List[_TrackableData] +) -> trackable_object_graph_pb2.TrackableObjectGraph: + """Name non-slot `Trackable`s and add them to `object_graph_proto`.""" + object_graph_proto = trackable_object_graph_pb2.TrackableObjectGraph() + for checkpoint_id, td in enumerate(trackable_data): + assert td.node_id == checkpoint_id + object_graph_proto.nodes.add( + slot_variables=td.slot_variable_proto, + children=td.children_proto) + return object_graph_proto + + +def _get_and_write_tensors_to_serialize( + tensor_trackables: List[_TrackableData], + node_ids: Dict[base.Trackable, int], + call_with_mapped_captures: Union[Callable[..., Any], None], + cache: Union[Dict[base.Trackable, any], None], + object_graph_proto: trackable_object_graph_pb2.TrackableObjectGraph +) -> Dict[base.Trackable, Any]: + """Creates dictionary of tensors to checkpoint, and updates the proto.""" + # Maps trackable to the a dictionary of tensors, which maps + # checkpoint key (-> slice_spec) -> tensor. + serialized_tensors = object_identity.ObjectIdentityDictionary() + + for td in tensor_trackables: + if cache is not None and td.object_to_save in cache: + trackable, tensor_dict, object_proto = cache[td.object_to_save] + serialized_tensors[trackable] = tensor_dict + object_graph_proto.nodes[td.node_id].attributes.MergeFrom(object_proto) + continue + + legacy_name = saveable_compat.get_saveable_name(td.object_to_save) or "" + + if (not saveable_object_util.trackable_has_serialize_to_tensor( + td.object_to_save) or + legacy_name): + # Use the legacy code path for objects that are using SaveableObjects + # or the compat saveable name decorator. + trackable, tensor_dict = _get_tensors_from_legacy_saveable( + td, node_ids, call_with_mapped_captures, object_graph_proto) + else: + tensor_dict = _get_tensors_from_trackable( + td, call_with_mapped_captures, object_graph_proto) + trackable = td.object_to_save + serialized_tensors[trackable] = tensor_dict + + if cache is not None and td.object_to_save not in cache: + cache[td.object_to_save] = ( + trackable, tensor_dict, + object_graph_proto.nodes[td.node_id].attributes) + + return serialized_tensors + + +def _get_tensors_from_legacy_saveable( + trackable_data: _TrackableData, + node_ids: Dict[base.Trackable, int], + call_with_mapped_captures: Callable[..., Any], + object_graph_proto: trackable_object_graph_pb2.TrackableObjectGraph +) -> Tuple[base.Trackable, Dict[str, Any]]: + """Gets tensors to serialize from a Trackable with legacy SaveableObjects.""" + # Call `save_util_v1` methods to create legacy SaveableObjects and update the + # proto. + object_names = object_identity.ObjectIdentityDictionary() + object_names[trackable_data.trackable] = trackable_data.object_name + object_map = object_identity.ObjectIdentityDictionary() + object_map[trackable_data.trackable] = trackable_data.object_to_save + + checkpoint_factory_map, _ = save_util_v1.get_checkpoint_factories_and_keys( + object_names, object_map) + named_saveable_objects, _ = ( + save_util_v1.generate_saveable_objects( + checkpoint_factory_map, + object_graph_proto, + node_ids, + object_map, + call_with_mapped_captures, + saveables_cache=None)) + trackable = ( + saveable_object_util.SaveableCompatibilityConverter( + trackable_data.object_to_save, named_saveable_objects)) + return trackable, trackable._serialize_to_tensors() # pylint: disable=protected-access + + +def _get_tensors_from_trackable( + trackable_data: _TrackableData, + call_with_mapped_captures: Union[Callable[..., Any], None], + object_graph_proto: trackable_object_graph_pb2.TrackableObjectGraph +) -> Dict[str, Any]: + """Gets tensors to serialize from a Trackable.""" + trackable = trackable_data.object_to_save + save_fn = trackable._serialize_to_tensors # pylint: disable=protected-access + + if (call_with_mapped_captures and + isinstance(save_fn, core.ConcreteFunction)): + ret_tensor_dict = call_with_mapped_captures(save_fn, []) + else: + ret_tensor_dict = save_fn() + + # Create checkpoint keys for each entry in the returned tensor dict, and + # write each entry to the object proto. + tensor_dict = {} + for tensor_name, maybe_tensor in ret_tensor_dict.items(): + local_name = trackable_utils.escape_local_name(tensor_name) + checkpoint_key = trackable_utils.checkpoint_key(trackable_data.object_name, + local_name) + tensor_dict[checkpoint_key] = maybe_tensor + + # TODO(b/261786493): Delete this when DCheckpoint is removed. + if isinstance(maybe_tensor, saveable_object_lib.SaveSpec): + maybe_tensor.name = checkpoint_key + maybe_tensor.slice_spec = "" + + if object_graph_proto is not None: + object_graph_proto.nodes[trackable_data.node_id].attributes.add( + name=local_name, + checkpoint_key=checkpoint_key, + full_name=util.get_full_name(trackable)) + + return tensor_dict + + +def _get_and_write_pystate_feed_additions( + pystate_trackables: List[_TrackableData], + cache: Union[Dict[base.Trackable, Any], None], + object_graph_proto=None +) -> Tuple[Dict[base.Trackable, Any], Dict[base.Trackable, Any]]: + """Gets feed additions needed for checkpointing Python State.""" + serialized_tensors = object_identity.ObjectIdentityDictionary() + # Maps tensor placeholders to python values. + feed_additions = {} + + for td in pystate_trackables: + trackable = td.object_to_save + checkpoint_key = trackable_utils.checkpoint_key(td.object_name, + python_state.PYTHON_STATE) + if trackable in cache: + save_string = cache[td.object_to_save][python_state.PYTHON_STATE] + else: + with ops.device("/cpu:0"): + save_string = constant_op.constant("", dtype=dtypes.string) + cache[trackable] = {python_state.PYTHON_STATE: save_string} + + with ops.init_scope(): + value = trackable.serialize() + feed_additions[save_string] = value + serialized_tensors[trackable] = {checkpoint_key: save_string} + + object_graph_proto.nodes[td.node_id].attributes.add( + name=python_state.PYTHON_STATE, + checkpoint_key=checkpoint_key, + full_name=util.get_full_name(trackable)) + + return serialized_tensors, feed_additions + + +def _get_and_write_registered_savers( + registered_trackables: Dict[str, List[_TrackableData]], + object_graph_proto: trackable_object_graph_pb2.TrackableObjectGraph +) -> Dict[str, Dict[str, base.Trackable]]: + """Generates dictionary of registered savers and updates the proto.""" + registered_savers = collections.defaultdict(dict) + for saver_name, trackables in registered_trackables.items(): + for td in trackables: + registered_savers[saver_name][td.object_name] = td.object_to_save + + object_proto = object_graph_proto.nodes[td.node_id] + object_proto.registered_saver.name = saver_name + object_proto.registered_saver.object_name = td.object_name + + return registered_savers + + +def serialize_graph_view( + graph_view: graph_view_lib.ObjectGraphView, + object_map: Optional[Mapping[base.Trackable, base.Trackable]] = None, + call_with_mapped_captures: Optional[Callable[..., Any]] = None, + cache: Optional[Dict[base.Trackable, Any]] = None) -> ...: + """Gathers serialization objects, and creates a TrackableObjectGraph proto.""" + # There are 3 types of checkpoint serialization types supported: + # 1. Trackables that override `Trackable._serialize_to_tensor()`. + # 2. PythonState: A special type of Trackable that serializes a Python string. + # 3. Registered Trackable Savers: For objects that need to define advanced + # checkpointing operations not supported by (1) or (2). + trackable_data, node_ids = _gather_trackable_data(graph_view, object_map) + tensor_trackables, pystate_trackables, registered_trackables = ( + _split_trackables(trackable_data)) + + object_graph_proto = _fill_object_graph_proto(trackable_data) + + serialized_tensors = _get_and_write_tensors_to_serialize( + tensor_trackables, + node_ids, + call_with_mapped_captures, + cache, + object_graph_proto) + registered_savers = _get_and_write_registered_savers( + registered_trackables, object_graph_proto) + + # PythonState trackables must be treated differently depending on if the + # checkpoint is being saved in TF1 graph mode (`cache` exists) or + # eager mode (`cache` is None). + if cache is None: + # When the tensor cache is None, get the serialized tensors directly. + feed_additions = None + serialized_tensors.update(_get_and_write_tensors_to_serialize( + pystate_trackables, + node_ids, + call_with_mapped_captures, + cache, + object_graph_proto)) + else: + # Python state is not automatically updated within a TF session so these + # values must be passed to sess.run(feed_additions=...). + new_serialized_tensors, feed_additions = ( + _get_and_write_pystate_feed_additions(pystate_trackables, + cache, + object_graph_proto)) + serialized_tensors.update(new_serialized_tensors) + + # Gather all trackables that have checkpoint values or descendants with + # checkpoint values, and add that info to the proto. + util.add_checkpoint_values_check(object_graph_proto) + return (serialized_tensors, feed_additions, registered_savers, + object_graph_proto) + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/save_util_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/save_util_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..b6652e6758d4c20224a1d453bb8a9ca6710486af --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/save_util_v1.py @@ -0,0 +1,319 @@ +# 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. +# ============================================================================== +"""Extracts tensors for checkpointing while updating a TrackableObjectGraph. + +This is labelled "v1" because the methods here use SaveableObject, which will +soon be deprecated. +""" + +import collections + +from tensorflow.core.protobuf import trackable_object_graph_pb2 +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.checkpoint import util +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.saved_model import registration +from tensorflow.python.trackable import base +from tensorflow.python.trackable import python_state +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.training.saving import saveable_object as saveable_object_lib +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import object_identity + +# Factory and related info used to build a SaveableObject that saves a Trackable +# to checkpoint. +_CheckpointFactoryData = collections.namedtuple( + "_CheckpointFactoryData", ["factory", "name", "checkpoint_key"]) + + +def get_checkpoint_factories_and_keys(object_names, object_map=None): + """Gets a map of saveable factories and corresponding checkpoint keys. + + Args: + object_names: a dictionary that maps `Trackable` objects to auto-generated + string names. + object_map: a dictionary mapping `Trackable` to copied `Trackable` objects. + The copied objects are generated from `Trackable. + _export_to_saved_model_graph()` which copies the object into another + graph. Generally only resource objects (e.g. Variables, Tables) will be + in this map. + + Returns: + A tuple of ( + Dictionary mapping trackable -> list of _CheckpointFactoryData, + Dictionary mapping registered saver name -> {object name -> trackable}) + """ + checkpoint_factory_map = object_identity.ObjectIdentityDictionary() + unmapped_registered_savers = collections.defaultdict(dict) + for trackable, object_name in object_names.items(): + # object_to_save is only used to retrieve the saving functionality. For keys + # and other data, use the original `trackable`. + object_to_save = util.get_mapped_trackable(trackable, object_map) + + saver_name = registration.get_registered_saver_name(object_to_save) + if saver_name: + # Add the original trackable instead of `object_to_save` to the returned + # dict because the original is needed for writing the object proto. + unmapped_registered_savers[saver_name][object_name] = trackable + else: + checkpoint_factory_map[trackable] = [] + for name, saveable_factory in ( + saveable_object_util.saveable_objects_from_trackable( + object_to_save).items()): # pylint: disable=protected-access + # Retrieve the legacy saveable name (for compatibility purposes during + # SaveableObject deprecation) + + key_suffix = saveable_compat.get_saveable_name(object_to_save) or name + checkpoint_key = trackable_utils.checkpoint_key(object_name, key_suffix) + + if not saveable_compat.force_checkpoint_conversion_enabled(): + # Make sure the set the name as the legacy saveable name if there + # is one (only when checkpoint conversion is diabled) + name = key_suffix + + checkpoint_factory_map[trackable].append( + _CheckpointFactoryData( + factory=saveable_factory, + name=name, + checkpoint_key=checkpoint_key)) + return checkpoint_factory_map, unmapped_registered_savers + + +def _add_attributes_to_object_graph(trackable_objects, object_graph_proto, + node_ids, object_names, object_map, + call_with_mapped_captures, saveables_cache): + """Create saveables/savers and corresponding protos in the object graph.""" + # The loop below creates TrackableObject protos in the TrackableObjectGraph, + # which are filled in the `_add_attributes_to_object_graph_for_*` methods. + for checkpoint_id, (trackable, unused_object_proto) in enumerate( + zip(trackable_objects, object_graph_proto.nodes)): + assert node_ids[trackable] == checkpoint_id + + checkpoint_factory_map, unmapped_registered_savers = ( + get_checkpoint_factories_and_keys(object_names, object_map)) + + # Add attributes, which describe what values are saved in checkpoint for + # this trackable. + registered_savers = _add_attributes_to_object_graph_for_registered_savers( + unmapped_registered_savers, object_graph_proto, node_ids, object_map) + named_saveable_objects, feed_additions = ( + generate_saveable_objects(checkpoint_factory_map, object_graph_proto, + node_ids, object_map, call_with_mapped_captures, + saveables_cache)) + return named_saveable_objects, feed_additions, registered_savers + + +def _add_attributes_to_object_graph_for_registered_savers( + unmapped_registered_savers, object_graph_proto, node_ids, object_map): + """Fills the object graph proto with data about the registered savers.""" + registered_savers = collections.defaultdict(dict) + for saver_name, trackables in unmapped_registered_savers.items(): + for object_name, trackable in trackables.items(): + object_proto = object_graph_proto.nodes[node_ids[trackable]] + object_proto.registered_saver.name = saver_name + object_proto.registered_saver.object_name = object_name + + object_to_save = util.get_mapped_trackable(trackable, object_map) + registered_savers[saver_name][object_name] = object_to_save + return registered_savers + + +def generate_saveable_objects(checkpoint_factory_map, + object_graph_proto=None, + node_ids=None, + object_map=None, + call_with_mapped_captures=None, + saveables_cache=None): + """Create SaveableObjects and corresponding SerializedTensor protos.""" + named_saveable_objects = [] + if saveables_cache is None: + # No SaveableObject caching. Either we're executing eagerly, or building a + # static save which is specialized to the current Python state. + feed_additions = None + else: + # If we are caching SaveableObjects, we need to build up a feed_dict with + # functions computing volatile Python state to be saved with the + # checkpoint. + feed_additions = {} + for trackable, factory_data_list in checkpoint_factory_map.items(): + fill_object_proto = object_graph_proto is not None and node_ids is not None + if fill_object_proto: + object_proto = object_graph_proto.nodes[node_ids[trackable]] + object_to_save = util.get_mapped_trackable(trackable, object_map) + if saveables_cache is not None: + cached_attributes = saveables_cache.setdefault(object_to_save, {}) + else: + cached_attributes = None + + for factory_data in factory_data_list: + name = factory_data.name + key = factory_data.checkpoint_key + saveable_factory = factory_data.factory + + # See if we can skip saving this checkpoint key. + saveables = cached_attributes.get(name) if cached_attributes else None + if saveables is not None: + for saveable in saveables: + if key not in saveable.name: + # The checkpoint key for this SaveableObject is different. We + # need to re-create it. + saveables = None + del cached_attributes[name] + break + + if saveables is None: + if callable(saveable_factory): + maybe_saveable = saveable_object_util.create_saveable_object( + name, key, saveable_factory, call_with_mapped_captures) + else: + maybe_saveable = saveable_factory + if isinstance(maybe_saveable, saveable_object_lib.SaveableObject): + saveables = (maybe_saveable,) + else: + saveables = tuple( + saveable_object_util.saveable_objects_for_op( + op=maybe_saveable, name=key)) + for saveable in saveables: + if key not in saveable.name: + raise AssertionError( + f"The object {trackable} produced a SaveableObject with name " + f"'{saveable.name}' for attribute '{name}'. Expected a name" + f" containing '{key}'.") + if cached_attributes is not None: + cached_attributes[name] = saveables + + if isinstance(object_to_save, python_state.PythonState): + assert len(saveables) == 1 + saveable = saveables[0] + + if feed_additions is None: + assert saveables_cache is None + # If we're not caching saveables, then we're either executing + # eagerly or building a static save/restore (e.g. for a + # SavedModel). In either case, we should embed the current Python + # state in the graph rather than relying on a feed dict. + saveables = (saveable.freeze(),) + else: + feed_additions.update(saveable.feed_dict_additions()) + named_saveable_objects.extend(saveables) + + # Update the object proto. + # For updated Trackables that override serialize_to_tensors, add an + # attribute for each tensor that is serialized. + # For Trackables that have SaveableObjects or a legacy saveable name, + # add a single attribute to the proto. + if not fill_object_proto: + continue + if (isinstance(saveables[0], saveable_object_util.TrackableSaveable) and + (saveable_compat.force_checkpoint_conversion_enabled() or + saveable_compat.get_saveable_name(object_to_save) is None)): + for local_name, local_key in ( + saveables[0].get_proto_names_and_checkpoint_keys()): + object_proto.attributes.add( + name=local_name, + checkpoint_key=local_key, + full_name=util.get_full_name(object_to_save)) + else: + object_proto.attributes.add( + name=name, + checkpoint_key=key, + full_name=util.get_full_name(object_to_save)) + + return named_saveable_objects, feed_additions + + +def _fill_object_graph_proto(graph_view, + trackable_objects, + node_ids, + slot_variables): + """Name non-slot `Trackable`s and add them to `object_graph_proto`.""" + object_graph_proto = trackable_object_graph_pb2.TrackableObjectGraph() + for checkpoint_id, trackable in enumerate(trackable_objects): + assert node_ids[trackable] == checkpoint_id + object_proto = object_graph_proto.nodes.add( + slot_variables=slot_variables.get(trackable, ()) + ) + for child in graph_view.list_children(trackable): + object_proto.children.add( + node_id=node_ids[child.ref], + local_name=child.name) + return object_graph_proto + + +def serialize_gathered_objects(graph_view, + object_map=None, + call_with_mapped_captures=None, + saveables_cache=None): + """Create SaveableObjects and protos for gathered objects.""" + trackable_objects, node_paths = graph_view.breadth_first_traversal() + object_names = object_identity.ObjectIdentityDictionary() + for obj, path in node_paths.items(): + object_names[obj] = trackable_utils.object_path_to_string(path) + node_ids = object_identity.ObjectIdentityDictionary() + for node_id, node in enumerate(trackable_objects): + node_ids[node] = node_id + slot_variables = util.serialize_slot_variables( + trackable_objects=trackable_objects, + node_ids=node_ids, + object_names=object_names) + object_graph_proto = _fill_object_graph_proto( + graph_view=graph_view, + trackable_objects=trackable_objects, + node_ids=node_ids, + slot_variables=slot_variables) + named_saveable_objects, feed_additions, registered_savers = ( + _add_attributes_to_object_graph( + trackable_objects=trackable_objects, + object_graph_proto=object_graph_proto, + node_ids=node_ids, + object_names=object_names, + object_map=object_map, + call_with_mapped_captures=call_with_mapped_captures, + saveables_cache=saveables_cache)) + # Gather all trackables that have checkpoint values or descendants with + # checkpoint values, and add that info to the proto. + util.add_checkpoint_values_check(object_graph_proto) + return (named_saveable_objects, object_graph_proto, feed_additions, + registered_savers) + + +def serialize_object_graph_with_registered_savers(graph_view, saveables_cache): + """Determine checkpoint keys for variables and build a serialized graph.""" + return serialize_gathered_objects(graph_view, saveables_cache=saveables_cache) + + +def frozen_saveables_and_savers(graph_view, + object_map=None, + to_graph=None, + call_with_mapped_captures=None, + saveables_cache=None): + """Generates SaveableObjects and registered savers in the frozen graph.""" + if to_graph: + target_context = to_graph.as_default + else: + target_context = ops.NullContextmanager + with target_context(): + named_saveable_objects, graph_proto, _, registered_savers = ( + serialize_gathered_objects(graph_view, object_map, + call_with_mapped_captures, saveables_cache)) + with ops.device("/cpu:0"): + object_graph_tensor = constant_op.constant( + graph_proto.SerializeToString(), dtype=dtypes.string) + named_saveable_objects.append( + base.NoRestoreSaveable( + tensor=object_graph_tensor, name=base.OBJECT_GRAPH_PROTO_KEY)) + return named_saveable_objects, registered_savers diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/saveable_compat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/saveable_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..13c96bfa6376b29703122039bd58e4466f71c9fa --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/saveable_compat.py @@ -0,0 +1,115 @@ +# 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. +# ============================================================================== +"""Checkpoint compatibility functions with SaveableObject. + +Compatibility methods to ensure that checkpoints are saved with the same +metadata attributes before/after the SaveableObject deprecation. +""" + +_LEGACY_SAVEABLE_NAME = "_LEGACY_SAVEABLE_NAME" + + +def legacy_saveable_name(name): + """Decorator to set the local name to use in the Checkpoint. + + Needed for migrating certain Trackables (see next paragraph) from the legacy + `_gather_saveables_for_checkpoint` to the new `_serialize_to_tensors` + function. + + This decorator should be used if the SaveableObject generates tensors with + different names from the name that is passed to the factory. + + Example migration: + + *Before* + + ``` + class MyTrackable(Trackable): + def _gather_saveables_for_checkpoint(self): + return {"key": _MySaveable} + + class _MySaveable(SaveableObject): + def __init__(self, name): + specs = [ + SaveSpec(tensor1, "", name + "-1") + SaveSpec(tensor2, "", name + "-2") + ] + super().__init__(None, specs, name) + ``` + + *After* + + ``` + @legacy_saveable_name("key") + class MyTrackable(Trackable): + + def _serialize_to_tensors(self): + return {"key-1": tensor1, "key-2": tensor2} + ``` + + Args: + name: String name of the SaveableObject factory (the key returned in the + `_gather_saveables_for_checkpoint` function) + + Returns: + A decorator. + """ + def decorator(cls_or_obj): + setattr(cls_or_obj, _LEGACY_SAVEABLE_NAME, name) + return cls_or_obj + return decorator + + +def get_saveable_name(cls_or_obj): + return getattr(cls_or_obj, _LEGACY_SAVEABLE_NAME, None) + + +_FORCE_CHECKPOINT_CONVERSION = False + + +def force_checkpoint_conversion(value=True): + """Forces checkpoint to use the new implementation. + + The new checkpoint implementation is changing the saved metadata slightly, + and therefore may break forward compatibility in newly saved checkpoints. This + means: + + - Previous versions of TensorFlow may not be able to load new checkpoints. + - Backwards compatibility is unchanged: Old checkpoints can still be loaded. + + TensorFlow guarantees 3 weeks of forward compatibility, so this flag will be + removed in the future weeks, after which checkpoint conversion will happen by + default. + + **What happens when this flag is enabled?** + + The checkpoint will be saved with different metadata, meaning that previous + versions of TensorFlow (<=2.10) will not be able to load this checkpoint. + + Args: + value: Boolean value, whether or not to force checkpoint conversion to the + new implementation. + """ + # TODO(kathywu): Add definite date for flag removal. + global _FORCE_CHECKPOINT_CONVERSION + _FORCE_CHECKPOINT_CONVERSION = value + + +def force_checkpoint_conversion_enabled(): + return _FORCE_CHECKPOINT_CONVERSION + + +class CheckpointConversionError(Exception): + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/tensor_callable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/tensor_callable.py new file mode 100644 index 0000000000000000000000000000000000000000..474e99bafcdab4dc95993c43fc13960783a0566b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/tensor_callable.py @@ -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. +# ============================================================================== +"""`Callable` class used for checkpointing.""" + +from tensorflow.python.training.saving import saveable_object + + +class Callable(saveable_object.SaveSpec): + """A callable that represents a Tensor that should be saved to checkpoint. + + This can be returned from `_serialize_to_tensor` in place of a Tensor. The + callable will be executed on the specified device when the checkpoint is + about to be written. + + Any class can use `Callable` for checkpointing, but for SavedModel export, + only resource-type variables* are supported. + + * `resource_variable_ops.is_resource_variable(obj)` must return True. + """ + + def __init__(self, tensor_callable, dtype, device): + """Initializes a `Callable` object. + + Args: + tensor_callable: A callable that takes no arguments and returns a Tensor. + dtype: Dtype of the tensor returned by the callable. + device: Device of the tensor returned by the callable. + """ + super().__init__(tensor_callable, None, None, dtype, device) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/trackable_view.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/trackable_view.py new file mode 100644 index 0000000000000000000000000000000000000000..145897c10f78fc12bf4f1a79bdb3201d6414ffd4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/trackable_view.py @@ -0,0 +1,117 @@ +"""Manages a Trackable object graph.""" +# 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. +# ============================================================================== +import collections +import weakref + +from tensorflow.python.trackable import base +from tensorflow.python.trackable import converter +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("train.TrackableView", v1=[]) +class TrackableView(object): + """Gathers and serializes a trackable view. + + Example usage: + + >>> class SimpleModule(tf.Module): + ... def __init__(self, name=None): + ... super().__init__(name=name) + ... self.a_var = tf.Variable(5.0) + ... self.b_var = tf.Variable(4.0) + ... self.vars = [tf.Variable(1.0), tf.Variable(2.0)] + + >>> root = SimpleModule(name="root") + >>> root.leaf = SimpleModule(name="leaf") + >>> trackable_view = tf.train.TrackableView(root) + + Pass root to tf.train.TrackableView.children() to get the dictionary of all + children directly linked to root by name. + >>> trackable_view_children = trackable_view.children(root) + >>> for item in trackable_view_children.items(): + ... print(item) + ('a_var', ) + ('b_var', ) + ('vars', ListWrapper([, ])) + ('leaf', ...) + + """ + + def __init__(self, root): + """Configure the trackable view. + + Args: + root: A `Trackable` object whose variables (including the variables of + dependencies, recursively) should be saved. May be a weak reference. + """ + # TrackableView should never contain a strong reference to root, since it + # may result in a cycle: + # root -> deferred dependencies -> CheckpointPosition + # -> CheckpointRestoreCoordinator -> TrackableView -> root + self._root_ref = (root if isinstance(root, weakref.ref) + else weakref.ref(root)) + + @classmethod + def children(cls, obj, save_type=base.SaveType.CHECKPOINT, **kwargs): + """Returns all child trackables attached to obj. + + Args: + obj: A `Trackable` object. + save_type: A string, can be 'savedmodel' or 'checkpoint'. + **kwargs: kwargs to use when retrieving the object's children. + + Returns: + Dictionary of all children attached to the object with name to trackable. + """ + # pylint: disable=protected-access + obj._maybe_initialize_trackable() + children = {} + for name, ref in obj._trackable_children(save_type, **kwargs).items(): + ref = converter.convert_to_trackable(ref, parent=obj) + children[name] = ref + return children + + @property + def root(self): + if isinstance(self._root_ref, weakref.ref): + derefed = self._root_ref() + assert derefed is not None + return derefed + else: + return self._root_ref + + def descendants(self): + """Returns a list of all nodes from self.root using a breadth first traversal.""" + return self._descendants_with_paths()[0] + + def _descendants_with_paths(self): + """Returns a list of all nodes and its paths from self.root using a breadth first traversal.""" + bfs_sorted = [] + to_visit = collections.deque([self.root]) + node_paths = object_identity.ObjectIdentityDictionary() + node_paths[self.root] = () + while to_visit: + current_trackable = to_visit.popleft() + bfs_sorted.append(current_trackable) + for name, dependency in self.children(current_trackable).items(): + if dependency not in node_paths: + node_paths[dependency] = ( + node_paths[current_trackable] + + (base.TrackableReference(name, dependency),)) + to_visit.append(dependency) + return bfs_sorted, node_paths diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/util.py new file mode 100644 index 0000000000000000000000000000000000000000..eb37585f88eb0dff5e42e602d0b5e80844fd9ebb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/checkpoint/util.py @@ -0,0 +1,174 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities for extracting and writing checkpoint info`.""" + +from tensorflow.core.protobuf import trackable_object_graph_pb2 +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.trackable import trackable_utils +from tensorflow.python.util import object_identity + + +def serialize_slot_variables(trackable_objects, node_ids, object_names): + """Gather and name slot variables.""" + non_slot_objects = list(trackable_objects) + slot_variables = object_identity.ObjectIdentityDictionary() + for trackable in non_slot_objects: + # TODO(b/110718070): Fix Keras imports. + # Note: dir() is used rather than hasattr() here to avoid triggering + # custom __getattr__ code, see b/152031870 for context. + if "get_slot_names" in dir(trackable): + slot_names = trackable.get_slot_names() + for slot_name in slot_names: + for original_variable_node_id, original_variable in enumerate( + non_slot_objects): + try: + slot_variable = trackable.get_slot(original_variable, slot_name) + except (AttributeError, KeyError): + slot_variable = None + if slot_variable is None: + continue + slot_variable._maybe_initialize_trackable() # pylint: disable=protected-access + if slot_variable._trackable_children(): # pylint: disable=protected-access + # TODO(allenl): Gather dependencies of slot variables. + raise NotImplementedError( + "Currently only variables with no dependencies can be saved as " + "slot variables. File a feature request if this limitation " + "bothers you.") + if slot_variable in node_ids: + raise NotImplementedError( + "A slot variable was re-used as a dependency of a Trackable " + f"object: {slot_variable}. This is not currently allowed. " + "File a feature request if this limitation bothers you.") + checkpoint_name = trackable_utils.slot_variable_key( + variable_path=object_names[original_variable], + optimizer_path=object_names[trackable], + slot_name=slot_name) + object_names[slot_variable] = checkpoint_name + slot_variable_node_id = len(trackable_objects) + node_ids[slot_variable] = slot_variable_node_id + trackable_objects.append(slot_variable) + slot_variable_proto = ( + trackable_object_graph_pb2.TrackableObjectGraph.TrackableObject + .SlotVariableReference( + slot_name=slot_name, + original_variable_node_id=original_variable_node_id, + slot_variable_node_id=slot_variable_node_id)) + slot_variables.setdefault(trackable, []).append(slot_variable_proto) + return slot_variables + + +def get_mapped_trackable(trackable, object_map): + """Returns the mapped trackable if possible, otherwise returns trackable.""" + if object_map is None: + return trackable + else: + return object_map.get(trackable, trackable) + + +def get_full_name(var): + """Gets the full name of variable for name-based checkpoint compatiblity.""" + # pylint: disable=protected-access + if (not (isinstance(var, variables.Variable) or + # Some objects do not subclass Variable but still act as one. + resource_variable_ops.is_resource_variable(var))): + return "" + + if getattr(var, "_save_slice_info", None) is not None: + # Use getattr because `var._save_slice_info` may be set as `None`. + return var._save_slice_info.full_name + else: + return var._shared_name + # pylint: enable=protected-access + + +def add_checkpoint_values_check(object_graph_proto): + """Determines which objects have checkpoint values and save this to the proto. + + Args: + object_graph_proto: A `TrackableObjectGraph` proto. + """ + # Trackable -> set of all trackables that depend on it (the "parents"). + # If a trackable has checkpoint values, then all of the parents can be + # marked as having checkpoint values. + parents = {} + checkpointed_trackables = object_identity.ObjectIdentitySet() + + # First pass: build dictionary of parent objects and initial set of + # checkpointed trackables. + checkpointed_trackables = set() + for node_id, object_proto in enumerate(object_graph_proto.nodes): + if (object_proto.attributes or object_proto.slot_variables or + object_proto.HasField("registered_saver")): + checkpointed_trackables.add(node_id) + for child_proto in object_proto.children: + child = child_proto.node_id + if child not in parents: + parents[child] = set() + parents[child].add(node_id) + + # Second pass: add all connected parents to set of checkpointed trackables. + to_visit = set() + to_visit.update(checkpointed_trackables) + + while to_visit: + trackable = to_visit.pop() + if trackable not in parents: + # Some trackables may not have parents (e.g. slot variables). + continue + current_parents = parents.pop(trackable) + checkpointed_trackables.update(current_parents) + for parent in current_parents: + if parent in parents: + to_visit.add(parent) + + for node_id, object_proto in enumerate(object_graph_proto.nodes): + object_proto.has_checkpoint_values.value = bool( + node_id in checkpointed_trackables) + + +def objects_ids_and_slot_variables_and_paths(graph_view): + """Traverse the object graph and list all accessible objects. + + Looks for `Trackable` objects which are dependencies of + `root_trackable`. Includes slot variables only if the variable they are + slotting for and the optimizer are dependencies of `root_trackable` + (i.e. if they would be saved with a checkpoint). + + Args: + graph_view: A GraphView object. + + Returns: + A tuple of (trackable objects, paths from root for each object, + object -> node id, slot variables, object_names) + """ + trackable_objects, node_paths = graph_view.breadth_first_traversal() + object_names = object_identity.ObjectIdentityDictionary() + for obj, path in node_paths.items(): + object_names[obj] = trackable_utils.object_path_to_string(path) + node_ids = object_identity.ObjectIdentityDictionary() + for node_id, node in enumerate(trackable_objects): + node_ids[node] = node_id + slot_variables = serialize_slot_variables( + trackable_objects=trackable_objects, + node_ids=node_ids, + object_names=object_names) + return (trackable_objects, node_paths, node_ids, slot_variables, object_names) + + +def list_objects(graph_view): + """Traverse the object graph and list all accessible objects.""" + trackable_objects = objects_ids_and_slot_variables_and_paths(graph_view)[0] + return trackable_objects diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_debug_events_writer.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_debug_events_writer.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b16b36a53d5c428e638382e41d83a5efa2374703 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_debug_events_writer.pyi @@ -0,0 +1,26 @@ +# 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. +# ============================================================================== + +def Close(arg0: str) -> None: ... +def FlushExecutionFiles(arg0: str) -> None: ... +def FlushNonExecutionFiles(arg0: str) -> None: ... +def Init(arg0: str, arg1: str, arg2: int) -> None: ... +def RegisterDeviceAndGetId(arg0: str, arg1: str) -> int: ... +def WriteDebuggedGraph(arg0: str, arg1: object) -> None: ... +def WriteExecution(arg0: str, arg1: object) -> None: ... +def WriteGraphExecutionTrace(arg0: str, arg1: object) -> None: ... +def WriteGraphOpCreation(arg0: str, arg1: object) -> None: ... +def WriteSourceFile(arg0: str, arg1: object) -> None: ... +def WriteStackFrameWithId(arg0: str, arg1: object) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_device_lib.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_device_lib.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3a39ae2a23620c605e09c15fcc9a37ae59a6f15b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_device_lib.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def list_devices(arg0: object) -> list: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_tf_session.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_tf_session.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a453092aeee274472907d2a7309f67a3c4975dbe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/_pywrap_tf_session.pyi @@ -0,0 +1,470 @@ +# 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. +# ============================================================================== + +from typing import Any, ClassVar, Iterator, Optional + +from typing import overload +TF_ABORTED: TF_Code +TF_BFLOAT16: TF_DataType +TF_BOOL: TF_DataType +TF_CANCELLED: TF_Code +TF_COMPLEX: TF_DataType +TF_COMPLEX128: TF_DataType +TF_COMPLEX64: TF_DataType +TF_DATA_LOSS: TF_Code +TF_DEADLINE_EXCEEDED: TF_Code +TF_DOUBLE: TF_DataType +TF_FAILED_PRECONDITION: TF_Code +TF_FLOAT: TF_DataType +TF_HALF: TF_DataType +TF_INT16: TF_DataType +TF_INT32: TF_DataType +TF_INT64: TF_DataType +TF_INT8: TF_DataType +TF_INTERNAL: TF_Code +TF_INVALID_ARGUMENT: TF_Code +TF_OK: TF_Code +TF_OUT_OF_RANGE: TF_Code +TF_PERMISSION_DENIED: TF_Code +TF_QINT16: TF_DataType +TF_QINT32: TF_DataType +TF_QINT8: TF_DataType +TF_QUINT16: TF_DataType +TF_QUINT8: TF_DataType +TF_RESOURCE: TF_DataType +TF_RESOURCE_EXHAUSTED: TF_Code +TF_STRING: TF_DataType +TF_UINT16: TF_DataType +TF_UINT32: TF_DataType +TF_UINT64: TF_DataType +TF_UINT8: TF_DataType +TF_UNAUTHENTICATED: TF_Code +TF_UNIMPLEMENTED: TF_Code +TF_UNKNOWN: TF_Code +TF_VARIANT: TF_DataType + +class ItemsView[int, object]: + def __init__(self, *args, **kwargs) -> None: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + +class ItemsView[str, object]: + def __init__(self, *args, **kwargs) -> None: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + +class KeysView[int]: + def __init__(self, *args, **kwargs) -> None: ... + @overload + def __contains__(self, arg0: int) -> bool: ... + @overload + def __contains__(self, arg0: object) -> bool: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + +class KeysView[str]: + def __init__(self, *args, **kwargs) -> None: ... + @overload + def __contains__(self, arg0: str) -> bool: ... + @overload + def __contains__(self, arg0: object) -> bool: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + +class OpsById: + def __init__(self) -> None: ... + def items(self) -> ItemsView[int,object]: ... + def keys(self) -> KeysView[int]: ... + def values(self) -> ValuesView[object]: ... + def __bool__(self) -> bool: ... + @overload + def __contains__(self, arg0: int) -> bool: ... + @overload + def __contains__(self, arg0: object) -> bool: ... + def __delitem__(self, arg0: int) -> None: ... + def __getitem__(self, arg0: int) -> object: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + def __setitem__(self, arg0: int, arg1: object) -> None: ... + +class OpsByName: + def __init__(self) -> None: ... + def items(self) -> ItemsView[str,object]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[object]: ... + def __bool__(self) -> bool: ... + @overload + def __contains__(self, arg0: str) -> bool: ... + @overload + def __contains__(self, arg0: object) -> bool: ... + def __delitem__(self, arg0: str) -> None: ... + def __getitem__(self, arg0: str) -> object: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + def __setitem__(self, arg0: str, arg1: object) -> None: ... + +class PyGraph: + @classmethod + def __init__(cls, *args, **kwargs) -> None: ... + @classmethod + def Dismantle(cls, *args, **kwargs) -> Any: ... + @classmethod + def _add_op(cls, *args, **kwargs) -> Any: ... + @classmethod + def _get_operation_by_name(cls, *args, **kwargs) -> Any: ... + @classmethod + def _op_def_for_type(cls, *args, **kwargs) -> Any: ... + @classmethod + def get_operations(cls, *args, **kwargs) -> Any: ... + @classmethod + def new_operations(cls, *args, **kwargs) -> Any: ... + @classmethod + def num_operations(cls, *args, **kwargs) -> Any: ... + @property + def _nodes_by_id(self) -> OpsById: ... + @property + def _nodes_by_name(self) -> OpsByName: ... + @property + def _version_def(self) -> bytes: ... + @property + def operations(self) -> list: ... + @property + def version(self) -> int: ... + +class PyOperation: + graph: object + @classmethod + def __init__(cls, *args, **kwargs) -> None: ... + @classmethod + def _add_control_input(cls, *args, **kwargs) -> Any: ... + @classmethod + def _add_control_inputs(cls, *args, **kwargs) -> Any: ... + @classmethod + def _add_outputs(cls, *args, **kwargs) -> Any: ... + @classmethod + def _init_outputs(cls, *args, **kwargs) -> Any: ... + @classmethod + def _remove_all_control_inputs(cls, *args, **kwargs) -> Any: ... + @classmethod + def _set_device_from_string(cls, *args, **kwargs) -> Any: ... + @classmethod + def _tf_input(cls, *args, **kwargs) -> Any: ... + @classmethod + def _tf_output(cls, *args, **kwargs) -> Any: ... + @property + def _c_op(self) -> TF_Operation: ... + @property + def _control_outputs(self) -> list: ... + @property + def _is_stateful(self) -> bool: ... + @property + def _node_def(self) -> bytes: ... + @property + def _op_def(self) -> bytes: ... + @property + def control_inputs(self) -> list: ... + @property + def device(self) -> str: ... + @property + def name(self) -> str: ... + @property + def outputs(self) -> list: ... + @property + def type(self) -> str: ... + +class PyTensor: + _id: object + _name: object + _shape_val: object + @classmethod + def __init__(cls, *args, **kwargs) -> None: ... + @classmethod + def _as_tf_output(cls, *args, **kwargs) -> Any: ... + @classmethod + def _rank(cls, *args, **kwargs) -> Any: ... + @classmethod + def _set_shape(cls, *args, **kwargs) -> Any: ... + @classmethod + def consumers(cls, *args, **kwargs) -> Any: ... + @property + def _dtype(self) -> object: ... + @property + def _op(self) -> object: ... + @property + def _shape(self) -> object: ... + @property + def device(self) -> str: ... + @property + def graph(self) -> object: ... + @property + def ndim(self) -> int: ... + @property + def op(self) -> object: ... + @property + def value_index(self) -> int: ... + +class TF_ApiDefMap: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Buffer: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Code: + __members__: ClassVar[dict] = ... # read-only + TF_ABORTED: ClassVar[TF_Code] = ... + TF_CANCELLED: ClassVar[TF_Code] = ... + TF_DATA_LOSS: ClassVar[TF_Code] = ... + TF_DEADLINE_EXCEEDED: ClassVar[TF_Code] = ... + TF_FAILED_PRECONDITION: ClassVar[TF_Code] = ... + TF_INTERNAL: ClassVar[TF_Code] = ... + TF_INVALID_ARGUMENT: ClassVar[TF_Code] = ... + TF_OK: ClassVar[TF_Code] = ... + TF_OUT_OF_RANGE: ClassVar[TF_Code] = ... + TF_PERMISSION_DENIED: ClassVar[TF_Code] = ... + TF_RESOURCE_EXHAUSTED: ClassVar[TF_Code] = ... + TF_UNAUTHENTICATED: ClassVar[TF_Code] = ... + TF_UNIMPLEMENTED: ClassVar[TF_Code] = ... + TF_UNKNOWN: ClassVar[TF_Code] = ... + __entries: ClassVar[dict] = ... + def __init__(self, value: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> None: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class TF_DataType: + __members__: ClassVar[dict] = ... # read-only + TF_BFLOAT16: ClassVar[TF_DataType] = ... + TF_BOOL: ClassVar[TF_DataType] = ... + TF_COMPLEX: ClassVar[TF_DataType] = ... + TF_COMPLEX128: ClassVar[TF_DataType] = ... + TF_COMPLEX64: ClassVar[TF_DataType] = ... + TF_DOUBLE: ClassVar[TF_DataType] = ... + TF_FLOAT: ClassVar[TF_DataType] = ... + TF_HALF: ClassVar[TF_DataType] = ... + TF_INT16: ClassVar[TF_DataType] = ... + TF_INT32: ClassVar[TF_DataType] = ... + TF_INT64: ClassVar[TF_DataType] = ... + TF_INT8: ClassVar[TF_DataType] = ... + TF_QINT16: ClassVar[TF_DataType] = ... + TF_QINT32: ClassVar[TF_DataType] = ... + TF_QINT8: ClassVar[TF_DataType] = ... + TF_QUINT16: ClassVar[TF_DataType] = ... + TF_QUINT8: ClassVar[TF_DataType] = ... + TF_RESOURCE: ClassVar[TF_DataType] = ... + TF_STRING: ClassVar[TF_DataType] = ... + TF_UINT16: ClassVar[TF_DataType] = ... + TF_UINT32: ClassVar[TF_DataType] = ... + TF_UINT64: ClassVar[TF_DataType] = ... + TF_UINT8: ClassVar[TF_DataType] = ... + TF_VARIANT: ClassVar[TF_DataType] = ... + __entries: ClassVar[dict] = ... + def __init__(self, value: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> None: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class TF_DeprecatedSession: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_ImportGraphDefOptions: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_ImportGraphDefResults: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Input: + index: int + oper: TF_Operation + def __init__(self) -> None: ... + +class TF_Library: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Operation: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_OperationDescription: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Output: + index: int + oper: TF_Operation + def __init__(self) -> None: ... + +class TF_Server: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Session: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_SessionOptions: + def __init__(self, *args, **kwargs) -> None: ... + +class TF_Status: + def __init__(self, *args, **kwargs) -> None: ... + +class ValuesView[object]: + def __init__(self, *args, **kwargs) -> None: ... + def __iter__(self) -> Iterator: ... + def __len__(self) -> int: ... + +def AddWhileInputHack(arg0: PyGraph, arg1: TF_Output, arg2: TF_Operation) -> None: ... +def ClearAttr(arg0: PyGraph, arg1: TF_Operation, arg2: str) -> None: ... +@overload +def EqualAttrValueWrapper(arg0: str, arg1: str) -> str: ... +@overload +def EqualAttrValueWrapper(arg0: str, arg1: str) -> str: ... +def EqualGraphDefWrapper(arg0: str, arg1: str) -> str: ... +def ExtendSession(arg0: TF_Session) -> None: ... +def GetHandleShapeAndType(arg0: PyGraph, arg1: TF_Output) -> bytes: ... +def GetOperationInputs(arg0: TF_Operation) -> list[TF_Output]: ... +def SetAttr(arg0: PyGraph, arg1: TF_Operation, arg2: str, arg3: TF_Buffer) -> None: ... +def SetFullType(arg0: PyGraph, arg1: TF_Operation, arg2: TF_Buffer) -> None: ... +def SetHandleShapeAndType(arg0: PyGraph, arg1: TF_Output, arg2: bytes) -> None: ... +def TF_AddControlInput(arg0: TF_OperationDescription, arg1: TF_Operation) -> None: ... +def TF_AddInput(arg0: TF_OperationDescription, arg1: TF_Output) -> None: ... +def TF_AddInputList(arg0: TF_OperationDescription, arg1: object) -> None: ... +def TF_ApiDefMapGet(arg0: TF_ApiDefMap, arg1: str, arg2: int) -> TF_Buffer: ... +def TF_ApiDefMapPut(arg0: TF_ApiDefMap, arg1: str, arg2: int) -> None: ... +def TF_CloseSession(arg0: TF_Session) -> None: ... +def TF_CreatePlaceholders(arg0: PyGraph, arg1: object, arg2: str) -> list[TF_Output]: ... +def TF_DeleteApiDefMap(arg0: TF_ApiDefMap) -> None: ... +def TF_DeleteBuffer(arg0: TF_Buffer) -> None: ... +@overload +def TF_DeleteDeviceList(arg0: TF_DeviceList) -> None: ... +@overload +def TF_DeleteDeviceList(arg0: TF_DeviceList) -> None: ... +def TF_DeleteFunction(arg0: TF_Function) -> None: ... +def TF_DeleteImportGraphDefOptions(arg0: TF_ImportGraphDefOptions) -> None: ... +def TF_DeleteImportGraphDefResults(arg0: TF_ImportGraphDefResults) -> None: ... +def TF_DeleteLibraryHandle(arg0: TF_Library) -> None: ... +def TF_DeleteSession(arg0: TF_Session) -> None: ... +def TF_DeleteSessionOptions(arg0: TF_SessionOptions) -> None: ... +def TF_DeleteStatus(arg0: TF_Status) -> None: ... +def TF_DeviceListCount(arg0: TF_DeviceList) -> int: ... +def TF_DeviceListIncarnation(arg0: TF_DeviceList, arg1: int) -> int: ... +def TF_DeviceListMemoryBytes(arg0: TF_DeviceList, arg1: int) -> int: ... +def TF_DeviceListName(arg0: TF_DeviceList, arg1: int) -> str: ... +def TF_DeviceListType(arg0: TF_DeviceList, arg1: int) -> str: ... +def TF_FinishOperation(arg0: TF_OperationDescription) -> TF_Operation: ... +def TF_FunctionImportFunctionDef(arg0: bytes) -> TF_Function: ... +def TF_FunctionSetAttrValueProto(arg0: TF_Function, arg1: str, arg2: bytes) -> None: ... +def TF_FunctionToFunctionDef(arg0: TF_Function, arg1: TF_Buffer) -> None: ... +def TF_GetAllOpList() -> TF_Buffer: ... +def TF_GetAllRegisteredKernels() -> TF_Buffer: ... +def TF_GetBuffer(arg0: TF_Buffer) -> object: ... +def TF_GetCode(arg0: TF_Status) -> TSL_Code: ... +def TF_GetOpList(arg0: TF_Library) -> object: ... +def TF_GetRegisteredKernelsForOp(arg0: str) -> TF_Buffer: ... +def TF_GetXlaAutoJitEnabled() -> int: ... +def TF_GetXlaConstantFoldingDisabled() -> int: ... +def TF_GraphCopyFunction(arg0: PyGraph, arg1: TF_Function, arg2: TF_Function) -> None: ... +def TF_GraphImportGraphDefWithResults(arg0: PyGraph, arg1: TF_Buffer, arg2: TF_ImportGraphDefOptions) -> TF_ImportGraphDefResults: ... +def TF_GraphNextOperation(arg0: PyGraph, arg1: int) -> tuple: ... +def TF_GraphRemoveFunction(arg0: PyGraph, arg1: str) -> None: ... +def TF_GraphSetOutputHandleShapesAndTypes_wrapper(arg0: PyGraph, arg1: TF_Output, arg2: list[Optional[list[int]]], arg3: list[int], arg4: object) -> None: ... +def TF_GraphToFunction_wrapper(arg0: PyGraph, arg1: str, arg2: bool, arg3: Optional[list[TF_Operation]], arg4: list[TF_Output], arg5: list[TF_Output], arg6: list[bytes], arg7: list[TF_Operation], arg8: list[bytes], arg9: None, arg10: str) -> TF_Function: ... +def TF_GraphToGraphDef(arg0: PyGraph, arg1: TF_Buffer) -> None: ... +def TF_GraphToGraphDefPybind(*args, **kwargs) -> Any: ... +def TF_ImportGraphDefOptionsAddInputMapping(arg0: TF_ImportGraphDefOptions, arg1: str, arg2: int, arg3: TF_Output) -> None: ... +def TF_ImportGraphDefOptionsAddReturnOperation(arg0: TF_ImportGraphDefOptions, arg1: str) -> None: ... +def TF_ImportGraphDefOptionsAddReturnOutput(arg0: TF_ImportGraphDefOptions, arg1: str, arg2: int) -> None: ... +def TF_ImportGraphDefOptionsRemapControlDependency(arg0: TF_ImportGraphDefOptions, arg1: str, arg2: TF_Operation) -> None: ... +def TF_ImportGraphDefOptionsSetPrefix(arg0: TF_ImportGraphDefOptions, arg1: str) -> None: ... +def TF_ImportGraphDefOptionsSetPropagateDeviceSpec(arg0: TF_ImportGraphDefOptions, arg1: int) -> None: ... +def TF_ImportGraphDefOptionsSetUniquifyNames(arg0: TF_ImportGraphDefOptions, arg1: int) -> None: ... +def TF_ImportGraphDefOptionsSetValidateColocationConstraints(arg0: TF_ImportGraphDefOptions, arg1: int) -> None: ... +def TF_ImportGraphDefResultsMissingUnusedInputMappings_wrapper(arg0: TF_ImportGraphDefResults) -> list[str]: ... +def TF_ImportGraphDefResultsReturnOperations(arg0: TF_ImportGraphDefResults) -> list: ... +def TF_ImportGraphDefResultsReturnOutputs(arg0: TF_ImportGraphDefResults) -> list: ... +def TF_LoadLibrary(arg0: str) -> TF_Library: ... +def TF_LoadPluggableDeviceLibrary(arg0: str) -> TF_Library: ... +def TF_NewApiDefMap(arg0: TF_Buffer) -> TF_ApiDefMap: ... +def TF_NewBuffer() -> TF_Buffer: ... +def TF_NewBufferFromString(arg0: bytes) -> TF_Buffer: ... +def TF_NewImportGraphDefOptions() -> TF_ImportGraphDefOptions: ... +def TF_NewOperation(arg0: PyGraph, arg1: str, arg2: str) -> TF_OperationDescription: ... +def TF_NewServer(arg0: bytes) -> TF_Server: ... +def TF_NewSession(arg0: PyGraph, arg1: TF_SessionOptions) -> TF_Session: ... +def TF_NewSessionRef(arg0: PyGraph, arg1: TF_SessionOptions) -> TF_Session: ... +def TF_NewStatus() -> TF_Status: ... +def TF_OperationDevice(arg0: TF_Operation) -> str: ... +def TF_OperationGetAttrBool(arg0: TF_Operation, arg1: str) -> object: ... +def TF_OperationGetAttrInt(arg0: TF_Operation, arg1: str) -> object: ... +def TF_OperationGetAttrType(arg0: TF_Operation, arg1: str) -> TF_DataType: ... +def TF_OperationGetAttrValueProto(arg0: TF_Operation, arg1: str, arg2: TF_Buffer) -> None: ... +def TF_OperationGetControlOutputs_wrapper(arg0: TF_Operation) -> list[TF_Operation]: ... +def TF_OperationGetStackTrace(arg0: TF_Operation) -> object: ... +def TF_OperationInputType(arg0: TF_Input) -> TF_DataType: ... +def TF_OperationName(arg0: TF_Operation) -> str: ... +def TF_OperationNumInputs(arg0: TF_Operation) -> int: ... +def TF_OperationNumOutputs(arg0: TF_Operation) -> int: ... +def TF_OperationOpType(arg0: TF_Operation) -> str: ... +def TF_OperationOutputType(arg0: TF_Output) -> TF_DataType: ... +def TF_OperationToNodeDef(arg0: TF_Operation, arg1: TF_Buffer) -> None: ... +def TF_PluggableDeviceLibraryHandle(arg0: TF_Library) -> None: ... +def TF_RegisterFilesystemPlugin(arg0: str) -> None: ... +def TF_Reset_wrapper(arg0: TF_SessionOptions, arg1: list[bytes]) -> None: ... +def TF_ServerJoin(arg0: TF_Server) -> None: ... +def TF_ServerStart(arg0: TF_Server) -> None: ... +def TF_ServerStop(arg0: TF_Server) -> None: ... +def TF_ServerTarget(arg0: TF_Server) -> str: ... +def TF_SessionListDevices(arg0: TF_Session) -> TF_DeviceList: ... +def TF_SessionMakeCallable(arg0: TF_Session, arg1: TF_Buffer) -> int: ... +def TF_SessionPRunSetup_wrapper(arg0: TF_Session, arg1: list[TF_Output], arg2: list[TF_Output], arg3: list[TF_Operation]) -> str: ... +def TF_SessionPRun_wrapper(arg0: TF_Session, arg1: str, arg2: object, arg3: list[TF_Output]) -> object: ... +def TF_SessionReleaseCallable(arg0: TF_Session, arg1: int) -> None: ... +def TF_SessionRunCallable(arg0: TF_Session, arg1: int, arg2: object, arg3: TF_Buffer) -> list: ... +def TF_SessionRun_wrapper(arg0: TF_Session, arg1: TF_Buffer, arg2: object, arg3: list[TF_Output], arg4: list[TF_Operation], arg5: TF_Buffer) -> object: ... +def TF_SetAttrValueProto(arg0: TF_OperationDescription, arg1: str, arg2: bytes) -> None: ... +def TF_SetDevice(arg0: TF_OperationDescription, arg1: str) -> None: ... +def TF_SetOpStackTrace(arg0: TF_Operation, arg1) -> None: ... +def TF_SetTfXlaCpuGlobalJit(arg0: int) -> int: ... +def TF_SetXlaAutoJitMode(arg0: str) -> None: ... +def TF_SetXlaConstantFoldingDisabled(arg0: int) -> None: ... +def TF_SetXlaEnableLazyCompilation(arg0: int) -> int: ... +def TF_SetXlaMinClusterSize(arg0: int) -> None: ... +def TF_TryEvaluateConstant_wrapper(arg0: PyGraph, arg1: TF_Output) -> object: ... +def UpdateEdge(arg0: PyGraph, arg1: TF_Output, arg2: TF_Input) -> None: ... +def _TF_NewSessionOptions() -> TF_SessionOptions: ... +def _TF_SetConfig(arg0: TF_SessionOptions, arg1: bytes) -> None: ... +def _TF_SetTarget(arg0: TF_SessionOptions, arg1: str) -> None: ... +def get_compiler_version() -> str: ... +def get_cxx11_abi_flag() -> int: ... +def get_cxx_version() -> int: ... +def get_eigen_max_align_bytes() -> int: ... +def get_git_version() -> str: ... +def get_graph_def_version() -> int: ... +def get_graph_def_version_min_consumer() -> int: ... +def get_graph_def_version_min_producer() -> int: ... +def get_monolithic_build() -> int: ... +def get_tensor_handle_key() -> str: ... +def get_version() -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/client_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/client_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..83bfbd6436d3524b43fae9ba48eca43a8544bc57 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/client_lib.py @@ -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. +# ============================================================================== + +"""Support for launching graphs and executing operations. + +See the [Client](https://www.tensorflow.org/guide/graphs) guide. +""" + +# pylint: disable=unused-import +from tensorflow.python.client.session import InteractiveSession +from tensorflow.python.client.session import Session + +from tensorflow.python.framework import errors +from tensorflow.python.framework.errors import OpError + +from tensorflow.python.framework.ops import get_default_session diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/device_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/device_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..06f610330cae1cf937ee4c07ba342c6a8458dd08 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/device_lib.py @@ -0,0 +1,42 @@ +# 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 Python interface for creating TensorFlow servers.""" + +from tensorflow.core.framework import device_attributes_pb2 +# pylint: disable=invalid-import-order, g-bad-import-order, wildcard-import, unused-import, undefined-variable +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.client import _pywrap_device_lib + + +def list_local_devices(session_config=None): + """List the available devices available in the local process. + + Args: + session_config: a session config proto or None to use the default config. + + Returns: + A list of `DeviceAttribute` protocol buffers. + """ + def _convert(pb_str): + m = device_attributes_pb2.DeviceAttributes() + m.ParseFromString(pb_str) + return m + + serialized_config = None + if session_config is not None: + serialized_config = session_config.SerializeToString() + return [ + _convert(s) for s in _pywrap_device_lib.list_devices(serialized_config) + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/pywrap_tf_session.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/pywrap_tf_session.py new file mode 100644 index 0000000000000000000000000000000000000000..b4586c7d62398248b3322a89c32e0110deea14ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/pywrap_tf_session.py @@ -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. +# ============================================================================== +"""Python module for Session ops, vars, and functions exported by pybind11.""" + +# pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.client._pywrap_tf_session import * +from tensorflow.python.client._pywrap_tf_session import _TF_SetTarget +from tensorflow.python.client._pywrap_tf_session import _TF_SetConfig +from tensorflow.python.client._pywrap_tf_session import _TF_NewSessionOptions + +# Register pybind11 type caster for StackTraceWrapper/AbstractStackTrace +from tensorflow.python.util import tf_stack + +# Convert versions to strings for Python2 and keep api_compatibility_test green. +# We can remove this hack once we remove Python2 presubmits. pybind11 can only +# return unicode for Python2 even with py::str. +# https://pybind11.readthedocs.io/en/stable/advanced/cast/strings.html#returning-c-strings-to-python +# pylint: disable=undefined-variable +__version__ = str(get_version()) +__git_version__ = str(get_git_version()) +__compiler_version__ = str(get_compiler_version()) +__cxx11_abi_flag__ = get_cxx11_abi_flag() +__cxx_version__ = get_cxx_version() +__monolithic_build__ = get_monolithic_build() + +# User getters to hold attributes rather than pybind11's m.attr due to +# b/145559202. +GRAPH_DEF_VERSION = get_graph_def_version() +GRAPH_DEF_VERSION_MIN_CONSUMER = get_graph_def_version_min_consumer() +GRAPH_DEF_VERSION_MIN_PRODUCER = get_graph_def_version_min_producer() +TENSOR_HANDLE_KEY = get_tensor_handle_key() + +# pylint: enable=undefined-variable + + +# Disable pylint invalid name warnings for legacy functions. +# pylint: disable=invalid-name +def TF_NewSessionOptions(target=None, config=None): + # NOTE: target and config are validated in the session constructor. + opts = _TF_NewSessionOptions() + if target is not None: + _TF_SetTarget(opts, target) + if config is not None: + config_str = config.SerializeToString() + _TF_SetConfig(opts, config_str) + return opts + + +# Disable pylind undefined-variable as the variable is exported in the shared +# object via pybind11. +# pylint: disable=undefined-variable +def TF_Reset(target, containers=None, config=None): + opts = TF_NewSessionOptions(target=target, config=config) + try: + TF_Reset_wrapper(opts, containers) + finally: + TF_DeleteSessionOptions(opts) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/session.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/session.py new file mode 100644 index 0000000000000000000000000000000000000000..70e5b8558399671d1353250e6bb0ef8dc98a404d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/session.py @@ -0,0 +1,1826 @@ +# 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 client interface for TensorFlow.""" + +import collections +import functools +import re +import threading +import warnings + +import numpy as np +import wrapt + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.client import pywrap_tf_session as tf_session +from tensorflow.python.eager import context +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import device +from tensorflow.python.framework import error_interpolation +from tensorflow.python.framework import errors +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import stack +from tensorflow.python.framework import tensor +from tensorflow.python.ops import session_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training.experimental import mixed_precision_global_state +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +_python_session_create_counter = monitoring.Counter( + '/tensorflow/api/python/session_create_counter', + 'Counter for number of sessions created in Python.') + + +class SessionInterface(object): + """Base class for implementations of TensorFlow client sessions.""" + + @property + def graph(self): + """The underlying TensorFlow graph, to be used in building Operations.""" + raise NotImplementedError('graph') + + @property + def sess_str(self): + """The TensorFlow process to which this session will connect.""" + raise NotImplementedError('sess_str') + + def run(self, fetches, feed_dict=None, options=None, run_metadata=None): + """Runs operations in the session. See `BaseSession.run()` for details.""" + raise NotImplementedError('run') + + def partial_run_setup(self, fetches, feeds=None): + """Sets up the feeds and fetches for partial runs in the session.""" + raise NotImplementedError('partial_run_setup') + + def partial_run(self, handle, fetches, feed_dict=None): + """Continues the execution with additional feeds and fetches.""" + raise NotImplementedError('partial_run') + + +def _get_indexed_slices_value_from_fetches(fetched_vals): + return indexed_slices.IndexedSlicesValue( + fetched_vals[0], fetched_vals[1], + fetched_vals[2] if len(fetched_vals) == 3 else None) + + +def _get_feeds_for_indexed_slices(feed, feed_val): + return list( + zip([feed.values, feed.indices] if feed.dense_shape is None else + [feed.values, feed.indices, feed.dense_shape], feed_val)) + + +# List of extensions supported to convert run arguments into actual fetches and +# feeds. +# +# Each element in the list is a tuple of (Type, fetch_fn, feed_fn1, feed_fn2), +# where the function signatures are: +# fetch_fn : Type -> (list of Tensors, +# lambda: list of fetched np.ndarray -> TypeVal) +# feed_fn1 : Type, TypeVal -> list of (Tensor, value) +# feed_fn2 : Type -> list of Tensors +# +# `fetch_fn` describes how to expand fetch into its +# component Tensors and how to contract the fetched results back into +# a single return value. +# +# Each feed function describes how to unpack a single fed value and map it to +# feeds of one or more tensors and their corresponding values: `feed_fn1` is +# used to feed a run, `feed_fn2` to set up a partial run. +# +# TODO(touts): We could reimplement these as specialized _FeedMapper +# implementations after we refactor the feed handling code to use them. +# +# Eventually, this registration could be opened up to support custom Tensor +# expansions. +# pylint: disable=g-long-lambda +_REGISTERED_EXPANSIONS = [ + # SparseTensors are fetched as SparseTensorValues. They can be fed + # SparseTensorValues or normal tuples. + (sparse_tensor.SparseTensor, lambda fetch: ([ + fetch.indices, fetch.values, fetch.dense_shape + ], lambda fetched_vals: sparse_tensor.SparseTensorValue(*fetched_vals)), + lambda feed, feed_val: list( + zip([feed.indices, feed.values, feed.dense_shape], feed_val)), + lambda feed: [feed.indices, feed.values, feed.dense_shape]), + # IndexedSlices are fetched as IndexedSlicesValues. They can be fed + # IndexedSlicesValues or normal tuples. + (indexed_slices.IndexedSlices, + lambda fetch: ([fetch.values, fetch.indices] if fetch.dense_shape is None + else [fetch.values, fetch.indices, fetch.dense_shape + ], _get_indexed_slices_value_from_fetches), + _get_feeds_for_indexed_slices, + lambda feed: [feed.values, feed.indices] if feed.dense_shape is None else + [feed.values, feed.indices, feed.dense_shape]), + # The default catches all other types and performs no expansions. + (object, lambda fetch: ([fetch], lambda fetched_vals: fetched_vals[0]), + lambda feed, feed_val: [(feed, feed_val)], lambda feed: [feed]) +] + +# pylint: enable=g-long-lambda + + +def _convert_to_numpy_obj(numpy_dtype, obj): + """Explicitly convert obj based on numpy type except for string type.""" + return numpy_dtype(obj) if numpy_dtype is not object else str(obj) + + +def register_session_run_conversion_functions( + tensor_type, + fetch_function, + feed_function=None, + feed_function_for_partial_run=None): + """Register fetch and feed conversion functions for `tf.Session.run()`. + + This function registers a triple of conversion functions for fetching and/or + feeding values of user-defined types in a call to tf.Session.run(). + + An example + + ```python + class SquaredTensor(object): + def __init__(self, tensor): + self.sq = tf.square(tensor) + #you can define conversion functions as follows: + fetch_function = lambda squared_tensor:([squared_tensor.sq], + lambda val: val[0]) + feed_function = lambda feed, feed_val: [(feed.sq, feed_val)] + feed_function_for_partial_run = lambda feed: [feed.sq] + #then after invoking this register function, you can use as follows: + session.run(squared_tensor1, + feed_dict = {squared_tensor2 : some_numpy_array}) + ``` + + Args: + tensor_type: The type for which you want to register a conversion function. + fetch_function: A callable that takes an object of type `tensor_type` and + returns a tuple, where the first element is a list of `tf.Tensor` objects, + and the second element is a callable that takes a list of ndarrays and + returns an object of some value type that corresponds to `tensor_type`. + fetch_function describes how to expand fetch into its component Tensors + and how to contract the fetched results back into a single return value. + feed_function: A callable that takes feed_key and feed_value as input, and + returns a list of tuples (feed_tensor, feed_val), feed_key must have type + `tensor_type`, and feed_tensor must have type `tf.Tensor`. Each feed + function describes how to unpack a single fed value and map it to feeds of + one or more tensors and their corresponding values. + feed_function_for_partial_run: A callable for specifying tensor values to + feed when setting up a partial run, which takes a `tensor_type` type + object as input, and returns a list of Tensors. + + Raises: + ValueError: If `tensor_type` has already been registered. + """ + for conversion_function in _REGISTERED_EXPANSIONS: + if issubclass(conversion_function[0], tensor_type): + raise ValueError(f'{tensor_type} has already been registered so ignore ' + 'it.') + + _REGISTERED_EXPANSIONS.insert(0, (tensor_type, fetch_function, feed_function, + feed_function_for_partial_run)) + + +def _is_attrs_instance(obj): + """Returns True if the given obj is an instance of attrs-decorated class.""" + return getattr(obj.__class__, '__attrs_attrs__', None) is not None + + +def _get_attrs_values(obj): + """Returns the list of values from an attrs instance.""" + attrs = getattr(obj.__class__, '__attrs_attrs__') + return [getattr(obj, a.name) for a in attrs] + + +class _FetchMapper(object): + """Definition of the interface provided by fetch mappers. + + Fetch mappers are utility classes used by the _FetchHandler to handle + arbitrary structures for the `fetch` argument to `Session.run()`. + + The `fetch` argument can be of various shapes: single tensor or op, list of + fetches, tuple of fetches, namedtuple of fetches, or dict of fetches. The + structures can be arbitrarily nested. + + The low level run() API only wants a list of tensor or op names. The various + `_FetchMapper` subclasses below take care of handling the different shapes: + uniquifying the fetches, and constructing results with the original shape. + """ + + def unique_fetches(self): + """Return the list of unique tensors or ops needed by this fetch mapper. + + Returns: + A list of tensors or ops. + """ + raise NotImplementedError( + 'unique_fetches must be implemented by subclasses') + + def build_results(self, values): + """Build results that match the original shape of the fetch. + + Args: + values: List of values returned by run(). The values correspond exactly to + the list tensors or ops returned by unique_fetches(). + + Returns: + A struct of the same shape as the original fetch object handled by + this fetch mapper. In the returned struct, the original fetches are + replaced by their fetched values. + """ + raise NotImplementedError('build_results must be implemented by subclasses') + + @staticmethod + def for_fetch(fetch): + """Creates fetch mapper that handles the structure of `fetch`. + + The default graph must be the one from which we want to fetch values when + this function is called. + + Args: + fetch: An arbitrary fetch structure: singleton, list, tuple, namedtuple, + or dict. + + Returns: + An instance of a subclass of `_FetchMapper` that handles the shape. + """ + if fetch is None: + raise TypeError(f'Argument `fetch` = {fetch} has invalid type ' + f'"{type(fetch).__name__}". Cannot be None') + elif isinstance(fetch, (list, tuple)): + # NOTE(touts): This is also the code path for namedtuples. + return _ListFetchMapper(fetch) + elif isinstance(fetch, collections_abc.Mapping): + return _DictFetchMapper(fetch) + elif _is_attrs_instance(fetch): + return _AttrsFetchMapper(fetch) + else: + # Look for a handler in the registered expansions. + for tensor_type, fetch_fn, _, _ in _REGISTERED_EXPANSIONS: + if isinstance(fetch, tensor_type): + fetches, contraction_fn = fetch_fn(fetch) + return _ElementFetchMapper(fetches, contraction_fn) + # Did not find anything. + raise TypeError(f'Argument `fetch` = {fetch} has invalid type ' + f'"{type(fetch).__name__}"') + + +class _ElementFetchMapper(_FetchMapper): + """Fetch mapper for singleton tensors and ops.""" + + def __init__(self, fetches, contraction_fn): + """Creates an _ElementFetchMapper. + + This is the fetch mapper used for leaves in the fetch struct. Because of + the expansions mechanism, a leaf can actually fetch more than one tensor. + + Also note that the fetches here can be just strings (tensor or op names) or + any other object that the graph knows how to convert to a tensor, such as a + Variable. So we have to run each fetch through `as_graph_element()` to get + the corresponding tensor or op. + + Args: + fetches: List of objects, as returned by a fetch_fn defined in + _REGISTERED_EXPANSIONS. + contraction_fn: Callable as returned by a fetch_fn. + """ + self._unique_fetches = [] + for fetch in fetches: + try: + self._unique_fetches.append(ops.get_default_graph().as_graph_element( + fetch, allow_tensor=True, allow_operation=True)) + except TypeError as e: + raise TypeError(f'Argument `fetch` = {fetch} has invalid type ' + f'"{type(fetch).__name__}" must be a string or Tensor. ' + f'({str(e)})') + except ValueError as e: + raise ValueError(f'Argument `fetch` = {fetch} cannot be interpreted as ' + f'a Tensor. ({str(e)})') + except KeyError as e: + raise ValueError(f'Argument `fetch` = {fetch} cannot be interpreted as ' + f'a Tensor. ({str(e)})') + self._contraction_fn = contraction_fn + + def unique_fetches(self): + return self._unique_fetches + + def build_results(self, values): + if not values: + # 'Operation' case + return None + else: + return self._contraction_fn(values) + + +def _uniquify_fetches(fetch_mappers): + """Uniquifies fetches from a list of fetch_mappers. + + This is a utility function used by _ListFetchMapper and _DictFetchMapper. It + gathers all the unique fetches from a list of mappers and builds a list + containing all of them but without duplicates (unique_fetches). + + It also returns a 2-D list of integers (values_indices) indicating at which + index in unique_fetches the fetches of the mappers are located. + + This list is as follows: + values_indices[mapper_index][mapper_fetch_index] = unique_fetches_index + + Args: + fetch_mappers: list of fetch mappers. + + Returns: + A list of fetches. + A 2-D list of integers. + """ + unique_fetches = [] + value_indices = [] + seen_fetches = {} + for m in fetch_mappers: + m_value_indices = [] + for f in m.unique_fetches(): + j = seen_fetches.get(id(f)) + if j is None: + j = len(seen_fetches) + seen_fetches[id(f)] = j + unique_fetches.append(f) + m_value_indices.append(j) + value_indices.append(m_value_indices) + return unique_fetches, value_indices + + +class _ListFetchMapper(_FetchMapper): + """Fetch mapper for lists, tuples, and namedtuples.""" + + def __init__(self, fetches): + """Creates a _ListFetchMapper. + + Args: + fetches: List, tuple, or namedtuple of fetches. + """ + if isinstance(fetches, wrapt.ObjectProxy): + self._fetch_type = type(fetches.__wrapped__) + else: + self._fetch_type = type(fetches) + self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches] + self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) + + def unique_fetches(self): + return self._unique_fetches + + def build_results(self, values): + # Create the list of results for each mapper. + results = [] + for m, vi in zip(self._mappers, self._value_indices): + results.append(m.build_results([values[j] for j in vi])) + # Return a value of the original type of the fetches. + if issubclass(self._fetch_type, list): + return results + elif self._fetch_type == tuple: + return tuple(results) + else: + # This is the code path for namedtuple. + return self._fetch_type(*results) + + +class _DictFetchMapper(_FetchMapper): + """Fetch mapper for dicts.""" + + def __init__(self, fetches): + """Creates a _DictFetchMapper. + + Args: + fetches: Dict of fetches. + """ + self._fetch_type = type(fetches) + if isinstance(fetches, collections.defaultdict): + self._type_ctor = functools.partial(collections.defaultdict, + fetches.default_factory) + else: + self._type_ctor = self._fetch_type + + self._keys = fetches.keys() + self._mappers = [ + _FetchMapper.for_fetch(fetch) for fetch in fetches.values() + ] + self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) + + def unique_fetches(self): + return self._unique_fetches + + def build_results(self, values): + + def _generator(): + for k, m, vi in zip(self._keys, self._mappers, self._value_indices): + yield k, m.build_results([values[j] for j in vi]) + + return self._type_ctor(_generator()) + + +class _AttrsFetchMapper(_FetchMapper): + """Fetch mapper for attrs decorated classes.""" + + def __init__(self, fetches): + """Creates a _AttrsFetchMapper. + + Args: + fetches: An instance of an attrs decorated class. + """ + values = _get_attrs_values(fetches) + self._fetch_type = type(fetches) + self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in values] + self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers) + + def unique_fetches(self): + return self._unique_fetches + + def build_results(self, values): + results = [] + for m, vi in zip(self._mappers, self._value_indices): + results.append(m.build_results([values[j] for j in vi])) + return self._fetch_type(*results) + + +class _FetchHandler(object): + """Handler for structured fetches. + + Given a graph, a user-provided structure for fetches, and a feed dict, this + class takes care of generating a list of tensor names to fetch and op names + to run for a low level `run()` call. + + Given the results of the low level run call, this class can also rebuild a + result structure matching the user-provided structure for fetches, but + containing the corresponding results. + """ + + # TODO(touts): Make this class also take care of destructuring the feed + # dict instead of doing it in the callers. + + def __init__(self, graph, fetches, feeds, feed_handles=None): + """Creates a fetch handler. + + Args: + graph: Graph of the fetches. Used to check for fetchability and to + convert all fetches to tensors or ops as needed. + fetches: An arbitrary fetch structure: singleton, list, tuple, namedtuple, + or dict. + feeds: A feed dict where keys are Tensors. + feed_handles: A dict from feed Tensors to TensorHandle objects used as + direct feeds. + """ + with graph.as_default(): + self._fetch_mapper = _FetchMapper.for_fetch(fetches) + self._fetches = [] + self._targets = [] + self._feeds = feeds + self._feed_handles = feed_handles or {} + self._ops = [] + self._fetch_handles = {} + for fetch in self._fetch_mapper.unique_fetches(): + if isinstance(fetch, ops.Operation): + self._assert_fetchable(graph, fetch) + self._targets.append(fetch) + self._ops.append(True) + else: + self._assert_fetchable(graph, fetch.op) + self._fetches.append(fetch) + self._ops.append(False) + # Remember the fetch if it is for a tensor handle. + if (isinstance(fetch, tensor.Tensor) and + (fetch.op.type == 'GetSessionHandle' or + fetch.op.type == 'GetSessionHandleV2')): + self._fetch_handles[fetch.ref()] = fetch.op.inputs[0].dtype + self._final_fetches = [x for x in self._fetches if x.ref() not in feeds] + + def _assert_fetchable(self, graph, op): + if not graph.is_fetchable(op): + raise errors.InaccessibleTensorError( + f'Operation {op.name} has been marked as not fetchable. Typically ' + 'this happens when it is defined in another function or code block. ' + 'Use return values, explicit Python locals or TensorFlow collections ' + 'to access it.') + + def fetches(self): + """Return the unique names of tensors to fetch. + + Returns: + A list of strings. + """ + return self._final_fetches + + def targets(self): + """Return the unique names of ops to run. + + Returns: + A list of strings. + """ + return self._targets + + def build_results(self, session, tensor_values): + """Build results matching the original fetch shape. + + `tensor_values` must be a list of the same length as + the one returned by `fetches()`, and holding the requested + fetch values. + + This method builds a struct with the same shape as the original `fetches` + passed to the constructor, in which the fetches are replaced by their + fetched value. + + Args: + session: The enclosing session. Used for tensor handles. + tensor_values: List of values matching the list returned by fetches(). + + Returns: + A structure of the same shape as the original `fetches` argument but + containing tensors or None (for fetched ops). + """ + full_values = [] + assert len(self._final_fetches) == len(tensor_values) + i = 0 + j = 0 + for is_op in self._ops: + if is_op: + full_values.append(None) + else: + # If the fetch was in the feeds, use the fed value, otherwise + # use the returned value. + if self._fetches[i].ref() in self._feed_handles: + # A fetch had a corresponding direct TensorHandle feed. Call eval() + # to obtain the Tensor value from the TensorHandle. + value = self._feed_handles[self._fetches[i].ref()].eval() + else: + value = self._feeds.get(self._fetches[i].ref()) + if value is None: + value = tensor_values[j] + j += 1 + dtype = self._fetch_handles.get(self._fetches[i].ref()) + if dtype: + full_values.append(session_ops.TensorHandle(value, dtype, session)) + else: + full_values.append(value) + i += 1 + assert j == len(tensor_values) + return self._fetch_mapper.build_results(full_values) + + +def _name_list(tensor_list): + """Utility function for transitioning to the new session API. + + Args: + tensor_list: a list of `Tensor`s. + + Returns: + A list of each `Tensor`s name (as byte arrays). + """ + return [compat.as_bytes(t.name) for t in tensor_list] + + +class _DeviceAttributes(object): + """Struct-like object describing a device's attributes. + + Each device has 3 key properties: + - name: the fully-qualified TensorFlow path to the device. For + example: /job:worker/replica:0/task:3/device:CPU:0 + - device_type: the type of the device (e.g. CPU, GPU, TPU, etc.) + - memory_limit_bytes: the maximum amount of memory available on the device + (in bytes). + """ + + def __init__(self, name, device_type, memory_limit_bytes, incarnation): + self._name = device.canonical_name(name) + self._device_type = device_type + self._memory_limit_bytes = memory_limit_bytes + self._incarnation = incarnation + + @property + def name(self): + return self._name + + @property + def device_type(self): + return self._device_type + + @property + def memory_limit_bytes(self): + return self._memory_limit_bytes + + @property + def incarnation(self): + return self._incarnation + + def __repr__(self): + return '_DeviceAttributes(%s, %s, %d, %d)' % ( + self.name, + self.device_type, + self.memory_limit_bytes, + self.incarnation, + ) + + +class BaseSession(SessionInterface): + """A class for interacting with a TensorFlow computation. + + The BaseSession enables incremental graph building with inline + execution of Operations and evaluation of Tensors. + """ + + def __init__(self, target='', graph=None, config=None): + """Constructs a new TensorFlow session. + + Args: + target: (Optional) The TensorFlow execution engine to connect to. + graph: (Optional) The graph to be used. If this argument is None, the + default graph will be used. + config: (Optional) ConfigProto proto used to configure the session. If no + config is specified, the global default will be used. The global default + can be configured via the tf.config APIs. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + creating the TensorFlow session. + TypeError: If one of the arguments has the wrong type. + """ + _python_session_create_counter.get_cell().increase_by(1) + if graph is None: + self._graph = ops.get_default_graph() + else: + if not isinstance(graph, ops.Graph): + raise TypeError('Argument `graph` must be a tf.Graph, but got ' + f'"{type(graph).__name__}"') + self._graph = graph + + self._closed = False + + if target is not None: + try: + self._target = compat.as_bytes(target) + except TypeError: + if isinstance(target, config_pb2.ConfigProto): + raise TypeError('Argument `target` must be a string, but got ' + f'"{type(target).__name__}". Did you do ' + '"Session(config)" instead of ' + '"Session(config=config)"?') + raise TypeError('Argument `target` must be a string, but got ' + f'"{type(target).__name__}"') + else: + self._target = None + + self._delete_lock = threading.Lock() + self._dead_handles = [] + + if config is None: + config = context.context().config + + if not isinstance(config, config_pb2.ConfigProto): + raise TypeError('Argument `config` must be a tf.ConfigProto, but got ' + f'"{type(config).__name__}"') + + if (mixed_precision_global_state.is_mixed_precision_graph_rewrite_enabled() + and config.graph_options.rewrite_options.auto_mixed_precision != + rewriter_config_pb2.RewriterConfig.OFF): + new_config = config_pb2.ConfigProto() + new_config.CopyFrom(config) + new_config.graph_options.rewrite_options.auto_mixed_precision = ( + rewriter_config_pb2.RewriterConfig.ON) + config = new_config + elif (config.graph_options.rewrite_options.auto_mixed_precision != + rewriter_config_pb2.RewriterConfig.ON): + mixed_precision_global_state.set_non_mixed_precision_session_created(True) + + self._config = config + self._add_shapes = config.graph_options.infer_shapes + + self._session = None + opts = tf_session.TF_NewSessionOptions(target=self._target, config=config) + try: + # pylint: disable=protected-access + with self._graph._c_graph.get() as c_graph: + self._session = tf_session.TF_NewSessionRef(c_graph, opts) + # pylint: enable=protected-access + finally: + tf_session.TF_DeleteSessionOptions(opts) + + def list_devices(self): + """Lists available devices in this session. + + ```python + devices = sess.list_devices() + for d in devices: + print(d.name) + ``` + + Where: + Each element in the list has the following properties + name: A string with the full name of the device. ex: + `/job:worker/replica:0/task:3/device:CPU:0` + device_type: The type of the device (e.g. `CPU`, `GPU`, `TPU`.) + memory_limit: The maximum amount of memory available on the device. + Note: depending on the device, it is possible the usable memory could + be substantially less. + + Raises: + tf.errors.OpError: If it encounters an error (e.g. session is in an + invalid state, or network errors occur). + + Returns: + A list of devices in the session. + """ + raw_device_list = tf_session.TF_SessionListDevices(self._session) + device_list = [] + size = tf_session.TF_DeviceListCount(raw_device_list) + for i in range(size): + name = tf_session.TF_DeviceListName(raw_device_list, i) + device_type = tf_session.TF_DeviceListType(raw_device_list, i) + memory = tf_session.TF_DeviceListMemoryBytes(raw_device_list, i) + incarnation = tf_session.TF_DeviceListIncarnation(raw_device_list, i) + device_list.append( + _DeviceAttributes(name, device_type, memory, incarnation)) + tf_session.TF_DeleteDeviceList(raw_device_list) + return device_list + + def close(self): + """Closes this session. + + Calling this method frees all resources associated with the session. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + closing the TensorFlow session. + """ + if self._session and not self._closed: + self._closed = True + tf_session.TF_CloseSession(self._session) + + def __del__(self): + # cleanly ignore all exceptions + try: + self.close() + except Exception: # pylint: disable=broad-except + pass + if self._session is not None: + try: + tf_session.TF_DeleteSession(self._session) + except (AttributeError, TypeError): + # At shutdown, `c_api_util`, `tf_session`, or + # `tf_session.TF_DeleteSession` may have been garbage collected, causing + # the above method calls to fail. In this case, silently leak since the + # program is about to terminate anyway. + pass + self._session = None + + @property + def graph(self): + """The graph that was launched in this session.""" + return self._graph + + @property + def graph_def(self): + """A serializable version of the underlying TensorFlow graph. + + Returns: + A graph_pb2.GraphDef proto containing nodes for all of the Operations in + the underlying TensorFlow graph. + """ + return self._graph.as_graph_def(add_shapes=self._add_shapes) + + @property + def sess_str(self): + return self._target + + def as_default(self): + """Returns a context manager that makes this object the default session. + + Use with the `with` keyword to specify that calls to + `tf.Operation.run` or `tf.Tensor.eval` should be executed in + this session. + + ```python + c = tf.constant(..) + sess = tf.compat.v1.Session() + + with sess.as_default(): + assert tf.compat.v1.get_default_session() is sess + print(c.eval()) + ``` + + To get the current default session, use `tf.compat.v1.get_default_session`. + + *N.B.* The `as_default` context manager *does not* close the + session when you exit the context, and you must close the session + explicitly. + + ```python + c = tf.constant(...) + sess = tf.compat.v1.Session() + with sess.as_default(): + print(c.eval()) + # ... + with sess.as_default(): + print(c.eval()) + + sess.close() + ``` + + Alternatively, you can use `with tf.compat.v1.Session():` to create a + session that is automatically closed on exiting the context, + including when an uncaught exception is raised. + + *N.B.* The default session is a property of the current thread. If you + create a new thread, and wish to use the default session in that + thread, you must explicitly add a `with sess.as_default():` in that + thread's function. + + *N.B.* Entering a `with sess.as_default():` block does not affect + the current default graph. If you are using multiple graphs, and + `sess.graph` is different from the value of + `tf.compat.v1.get_default_graph`, you must explicitly enter a + `with sess.graph.as_default():` block to make `sess.graph` the default + graph. + + Returns: + A context manager using this session as the default session. + """ + return stack.default_session(self) + + def run(self, fetches, feed_dict=None, options=None, run_metadata=None): + """Runs operations and evaluates tensors in `fetches`. + + This method runs one "step" of TensorFlow computation, by + running the necessary graph fragment to execute every `Operation` + and evaluate every `Tensor` in `fetches`, substituting the values in + `feed_dict` for the corresponding input values. + + The `fetches` argument may be a single graph element, or an arbitrarily + nested list, tuple, namedtuple, dict, or OrderedDict containing graph + elements at its leaves. A graph element can be one of the following types: + + * A `tf.Operation`. + The corresponding fetched value will be `None`. + * A `tf.Tensor`. + The corresponding fetched value will be a numpy ndarray containing the + value of that tensor. + * A `tf.sparse.SparseTensor`. + The corresponding fetched value will be a + `tf.compat.v1.SparseTensorValue` + containing the value of that sparse tensor. + * A `get_tensor_handle` op. The corresponding fetched value will be a + numpy ndarray containing the handle of that tensor. + * A `string` which is the name of a tensor or operation in the graph. + + The value returned by `run()` has the same shape as the `fetches` argument, + where the leaves are replaced by the corresponding values returned by + TensorFlow. + + Example: + + ```python + a = tf.constant([10, 20]) + b = tf.constant([1.0, 2.0]) + # 'fetches' can be a singleton + v = session.run(a) + # v is the numpy array [10, 20] + # 'fetches' can be a list. + v = session.run([a, b]) + # v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the + # 1-D array [1.0, 2.0] + # 'fetches' can be arbitrary lists, tuples, namedtuple, dicts: + MyData = collections.namedtuple('MyData', ['a', 'b']) + v = session.run({'k1': MyData(a, b), 'k2': [b, a]}) + # v is a dict with + # v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and + # 'b' (the numpy array [1.0, 2.0]) + # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array + # [10, 20]. + ``` + + The optional `feed_dict` argument allows the caller to override + the value of tensors in the graph. Each key in `feed_dict` can be + one of the following types: + + * If the key is a `tf.Tensor`, the + value may be a Python scalar, string, list, or numpy ndarray + that can be converted to the same `dtype` as that + tensor. Additionally, if the key is a + `tf.compat.v1.placeholder`, the shape of + the value will be checked for compatibility with the placeholder. + * If the key is a + `tf.sparse.SparseTensor`, + the value should be a + `tf.compat.v1.SparseTensorValue`. + * If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value + should be a nested tuple with the same structure that maps to their + corresponding values as above. + + Each value in `feed_dict` must be convertible to a numpy array of the dtype + of the corresponding key. + + The optional `options` argument expects a [`RunOptions`] proto. The options + allow controlling the behavior of this particular step (e.g. turning tracing + on). + + The optional `run_metadata` argument expects a [`RunMetadata`] proto. When + appropriate, the non-Tensor output of this step will be collected there. For + example, when users turn on tracing in `options`, the profiled info will be + collected into this argument and passed back. + + Args: + fetches: A single graph element, a list of graph elements, or a dictionary + whose values are graph elements or lists of graph elements (described + above). + feed_dict: A dictionary that maps graph elements to values (described + above). + options: A [`RunOptions`] protocol buffer + run_metadata: A [`RunMetadata`] protocol buffer + + Returns: + Either a single value if `fetches` is a single graph element, or + a list of values if `fetches` is a list, or a dictionary with the + same keys as `fetches` if that is a dictionary (described above). + Order in which `fetches` operations are evaluated inside the call + is undefined. + + Raises: + RuntimeError: If this `Session` is in an invalid state (e.g. has been + closed). + TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type. + ValueError: If `fetches` or `feed_dict` keys are invalid or refer to a + `Tensor` that doesn't exist. + """ + options_ptr = tf_session.TF_NewBufferFromString( + compat.as_bytes(options.SerializeToString())) if options else None + run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None + + try: + result = self._run(None, fetches, feed_dict, options_ptr, + run_metadata_ptr) + if run_metadata: + proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) + run_metadata.ParseFromString(compat.as_bytes(proto_data)) + finally: + if run_metadata_ptr: + tf_session.TF_DeleteBuffer(run_metadata_ptr) + if options: + tf_session.TF_DeleteBuffer(options_ptr) + return result + + @deprecation.deprecated( + '2023-06-01', + 'This function is deprecated and we do not expect adding new' + 'functionality to it. Please do not have your code depending' + 'on this function.', + ) + def partial_run(self, handle, fetches, feed_dict=None): + """Continues the execution with more feeds and fetches. + + NOTE: This function is deprecated and we do not expect adding new + functionality to it. Please do not have your code depending on this + function. + + This is EXPERIMENTAL and subject to change. + + To use partial execution, a user first calls `partial_run_setup()` and + then a sequence of `partial_run()`. `partial_run_setup` specifies the + list of feeds and fetches that will be used in the subsequent + `partial_run` calls. + + The optional `feed_dict` argument allows the caller to override + the value of tensors in the graph. See run() for more information. + + Below is a simple example: + + ```python + a = array_ops.placeholder(dtypes.float32, shape=[]) + b = array_ops.placeholder(dtypes.float32, shape=[]) + c = array_ops.placeholder(dtypes.float32, shape=[]) + r1 = math_ops.add(a, b) + r2 = math_ops.multiply(r1, c) + + h = sess.partial_run_setup([r1, r2], [a, b, c]) + res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) + res = sess.partial_run(h, r2, feed_dict={c: res}) + ``` + + Args: + handle: A handle for a sequence of partial runs. + fetches: A single graph element, a list of graph elements, or a dictionary + whose values are graph elements or lists of graph elements (see + documentation for `run`). + feed_dict: A dictionary that maps graph elements to values (described + above). + + Returns: + Either a single value if `fetches` is a single graph element, or + a list of values if `fetches` is a list, or a dictionary with the + same keys as `fetches` if that is a dictionary + (see documentation for `run`). + + Raises: + tf.errors.OpError: Or one of its subclasses on error. + """ + # TODO(touts): Support feeding and fetching the same tensor. + return self._run(handle, fetches, feed_dict, None, None) + + @deprecation.deprecated( + '2023-06-01', + 'This function is deprecated and we do not expect adding new' + 'functionality to it. Please do not have your code depending' + 'on this function.', + ) + def partial_run_setup(self, fetches, feeds=None): + """Sets up a graph with feeds and fetches for partial run. + + NOTE: This function is deprecated and we do not expect adding new + functionality to it. Please do not have your code depending on this + function. + + This is EXPERIMENTAL and subject to change. + + Note that contrary to `run`, `feeds` only specifies the graph elements. + The tensors will be supplied by the subsequent `partial_run` calls. + + Args: + fetches: A single graph element, or a list of graph elements. + feeds: A single graph element, or a list of graph elements. + + Returns: + A handle for partial run. + + Raises: + RuntimeError: If this `Session` is in an invalid state (e.g. has been + closed). + TypeError: If `fetches` or `feed_dict` keys are of an inappropriate type. + tf.errors.OpError: Or one of its subclasses if a TensorFlow error happens. + """ + + def _feed_fn(feed): + for tensor_type, _, _, feed_fn in _REGISTERED_EXPANSIONS: + if isinstance(feed, tensor_type): + return feed_fn(feed) + raise TypeError(f'Feed argument {feed} has invalid type ' + f'"{type(feed).__name__}"') + + # Check session. + if self._closed: + raise RuntimeError('Attempted to use a closed Session.') + if self.graph.version == 0: + raise RuntimeError('The Session graph is empty. Add operations to the ' + 'graph before calling run().') + + if feeds is None: + feeds = [] + # Create request. + feed_list = [] + + # Validate and process feed_list. + is_list_feed = isinstance(feeds, (list, tuple)) + if not is_list_feed: + feeds = [feeds] + for feed in feeds: + for subfeed in _feed_fn(feed): + try: + subfeed_t = self.graph.as_graph_element( + subfeed, allow_tensor=True, allow_operation=False) + # pylint: disable=protected-access + feed_list.append(subfeed_t._as_tf_output()) + # pylint: enable=protected-access + except Exception as e: + e.message = ('Cannot interpret argument `feed` key as Tensor: ' + f'{e.message}') + e.args = (e.message,) + raise e + + # Validate and process fetches. + # TODO(touts): Support feeding and fetching the same tensor. + fetch_handler = _FetchHandler(self._graph, fetches, {}) + + # Set up a graph with feeds and fetches for partial run. + def _setup_fn(session, feed_list, fetch_list, target_list): + self._extend_graph() + return tf_session.TF_SessionPRunSetup_wrapper(session, feed_list, + fetch_list, target_list) + + # pylint: disable=protected-access + final_fetches = [t._as_tf_output() for t in fetch_handler.fetches()] + final_targets = [op._c_op for op in fetch_handler.targets()] + # pylint: enable=protected-access + + return self._do_call(_setup_fn, self._session, feed_list, final_fetches, + final_targets) + + def _run(self, handle, fetches, feed_dict, options, run_metadata): + """Perform either run or partial_run, depending the presence of `handle`.""" + + def _feed_fn(feed, feed_val): + for tensor_type, _, feed_fn, _ in _REGISTERED_EXPANSIONS: + if isinstance(feed, tensor_type): + return feed_fn(feed, feed_val) + raise TypeError(f'{feed} in argument `feed_dict` has invalid type ' + f'"{type(feed).__name__}"') + + # Check session. + if self._closed: + raise RuntimeError('Attempted to use a closed Session.') + if self.graph.version == 0: + raise RuntimeError('The Session graph is empty. Add operations to the ' + 'graph before calling run().') + + # Create request. + feed_dict_tensor = {} + feed_map = {} + + # Validate and process feed_dict. + feed_handles = {} + if feed_dict: + feed_dict = nest.flatten_dict_items(feed_dict) + for feed, feed_val in feed_dict.items(): + for subfeed, subfeed_val in _feed_fn(feed, feed_val): + try: + subfeed_t = self.graph.as_graph_element( + subfeed, allow_tensor=True, allow_operation=False) + except Exception as e: + raise TypeError( + f'Cannot interpret feed_dict key as Tensor: {e.args[0]}') + + if isinstance(subfeed_val, tensor.Tensor): + raise TypeError( + 'The value of a feed cannot be a tf.Tensor object. Acceptable ' + 'feed values include Python scalars, strings, lists, numpy ' + 'ndarrays, or TensorHandles. For reference, the tensor object ' + f'was {str(feed_val)} which was passed to the argument ' + f'`feed_dict` with key {str(feed)}.') + + subfeed_dtype = subfeed_t.dtype.as_numpy_dtype + if isinstance(subfeed_val, int) and _convert_to_numpy_obj( + subfeed_dtype, subfeed_val) != subfeed_val: + raise TypeError( + f'Type of feed value {str(subfeed_val)} with type ' + + f'{str(type(subfeed_val))} is not compatible with Tensor type ' + f'{str(subfeed_dtype)}. Try explicitly setting the type of the ' + 'feed tensor to a larger type (e.g. int64).') + + is_tensor_handle_feed = isinstance(subfeed_val, + session_ops.TensorHandle) + if is_tensor_handle_feed: + np_val = subfeed_val.to_numpy_array() + feed_handles[subfeed_t.ref()] = subfeed_val + else: + np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) + + if (not is_tensor_handle_feed and + not subfeed_t.get_shape().is_compatible_with(np_val.shape)): + raise ValueError( + f'Cannot feed value of shape {str(np_val.shape)} for Tensor ' + f'{subfeed_t.name}, which has shape ' + f'{str(subfeed_t.get_shape())}') + if not self.graph.is_feedable(subfeed_t): + raise ValueError(f'Tensor {subfeed_t.name} may not be fed.') + + feed_dict_tensor[subfeed_t.ref()] = np_val + feed_map[compat.as_bytes(subfeed_t.name)] = (subfeed_t, subfeed_val) + + # Create a fetch handler to take care of the structure of fetches. + fetch_handler = _FetchHandler( + self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles) + + # Run request and get response. + # We need to keep the returned movers alive for the following _do_run(). + # These movers are no longer needed when _do_run() completes, and + # are deleted when `movers` goes out of scope when this _run() ends. + # TODO(yuanbyu, keveman): Revisit whether we should just treat feeding + # of a handle from a different device as an error. + _ = self._update_with_movers(feed_dict_tensor, feed_map) + final_fetches = fetch_handler.fetches() + final_targets = fetch_handler.targets() + # We only want to really perform the run if fetches or targets are provided, + # or if the call is a partial run that specifies feeds. + if final_fetches or final_targets or (handle and feed_dict_tensor): + results = self._do_run(handle, final_targets, final_fetches, + feed_dict_tensor, options, run_metadata) + else: + results = [] + return fetch_handler.build_results(self, results) + + def make_callable(self, fetches, feed_list=None, accept_options=False): + """Returns a Python callable that runs a particular step. + + The returned callable will take `len(feed_list)` arguments whose types + must be compatible feed values for the respective elements of `feed_list`. + For example, if element `i` of `feed_list` is a `tf.Tensor`, the `i`th + argument to the returned callable must be a numpy ndarray (or something + convertible to an ndarray) with matching element type and shape. See + `tf.Session.run` for details of the allowable feed key and value types. + + The returned callable will have the same return type as + `tf.Session.run(fetches, ...)`. For example, if `fetches` is a `tf.Tensor`, + the callable will return a numpy ndarray; if `fetches` is a `tf.Operation`, + it will return `None`. + + Args: + fetches: A value or list of values to fetch. See `tf.Session.run` for + details of the allowable fetch types. + feed_list: (Optional.) A list of `feed_dict` keys. See `tf.Session.run` + for details of the allowable feed key types. + accept_options: (Optional.) If `True`, the returned `Callable` will be + able to accept `tf.compat.v1.RunOptions` and `tf.compat.v1.RunMetadata` + as optional keyword arguments `options` and `run_metadata`, + respectively, with the same syntax and semantics as `tf.Session.run`, + which is useful for certain use cases (profiling and debugging) but will + result in measurable slowdown of the `Callable`'s + performance. Default: `False`. + + Returns: + A function that when called will execute the step defined by + `feed_list` and `fetches` in this session. + + Raises: + TypeError: If `fetches` or `feed_list` cannot be interpreted + as arguments to `tf.Session.run`. + """ + if feed_list is not None: + if not isinstance(feed_list, (list, tuple)): + raise TypeError('Argument `feed_list` must be a list or tuple. ' + f'Received: feed_list={feed_list}') + # Delegate any non-empty feed lists to the existing `run()` logic. + # TODO(mrry): Refactor the feed handling logic from + # `Session._run()` so that we can convert the feeds to a list of + # strings here. + def _generic_run(*feed_args, **kwargs): + feed_dict = { + feed: feed_val for feed, feed_val in zip(feed_list, feed_args) + } + return self.run(fetches, feed_dict=feed_dict, **kwargs) + + return _generic_run + + # Ensure any changes to the graph are reflected in the runtime. + # Note that we don't need to do this on subsequent calls to the + # returned object, because the arguments to `fetches` must already be + # in the graph. + self._extend_graph() + + # Create a fetch handler to take care of the structure of fetches. + fetch_handler = _FetchHandler(self._graph, fetches, {}) + # pylint: disable=protected-access + fetch_list = [t._as_tf_output() for t in fetch_handler.fetches()] + target_list = [op._c_op for op in fetch_handler.targets()] + + # pylint: enable=protected-access + + def _callable_template_with_options_and_metadata(fetch_list, + target_list, + fetch_handler, + options=None, + run_metadata=None): + """Template callable that accepts RunOptions and RunMetadata.""" + options_ptr = tf_session.TF_NewBufferFromString( + compat.as_bytes(options.SerializeToString())) if options else None + run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None + try: + results = self._call_tf_sessionrun(options_ptr, {}, fetch_list, + target_list, run_metadata_ptr) + if fetch_handler: + results = fetch_handler.build_results(self, results) + else: + results = results[0] if results else None + if run_metadata: + proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) + run_metadata.ParseFromString(compat.as_bytes(proto_data)) + finally: + if run_metadata_ptr: + tf_session.TF_DeleteBuffer(run_metadata_ptr) + if options: + tf_session.TF_DeleteBuffer(options_ptr) + return results + + if accept_options: + return functools.partial(_callable_template_with_options_and_metadata, + fetch_list, target_list, fetch_handler) + elif isinstance(fetches, ops.Operation): + # Special case for fetching a single operation, because the + # function will have no return value. + assert not fetch_list + assert len(target_list) == 1 + + def _single_operation_run(): + self._call_tf_sessionrun(None, {}, [], target_list, None) + + return _single_operation_run + elif isinstance(fetches, tensor.Tensor): + # Special case for fetching a single tensor, because the + # function can return the result of `TF_Run()` directly. + assert len(fetch_list) == 1 + assert not target_list + + def _single_tensor_run(): + results = self._call_tf_sessionrun(None, {}, fetch_list, [], None) + return results[0] + + return _single_tensor_run + else: + # In all other cases, we must use `fetch_handler` to build the + # results for us. + def _fetch_handler_run(): + results = self._call_tf_sessionrun(None, {}, fetch_list, target_list, + None) + return fetch_handler.build_results(self, results) + + return _fetch_handler_run + + # Captures the name of a node in an error status. The regex below matches + # both the old and the new formats: + # Old format: [[Node: = ...]] + # New format: [[{{node }} = ...]] + _NODEDEF_NAME_RE = re.compile( + r'\[\[(Node: )?(\{\{node )?([^\} ]*)(\}\})?\s*=*') + + def _do_run(self, handle, target_list, fetch_list, feed_dict, options, + run_metadata): + """Runs a step based on the given fetches and feeds. + + Args: + handle: a handle for partial_run. None if this is just a call to run(). + target_list: A list of operations to be run, but not fetched. + fetch_list: A list of tensors to be fetched. + feed_dict: A dictionary that maps tensors to numpy ndarrays. + options: A (pointer to a) [`RunOptions`] protocol buffer, or None + run_metadata: A (pointer to a) [`RunMetadata`] protocol buffer, or None + + Returns: + A list of numpy ndarrays, corresponding to the elements of + `fetch_list`. If the ith element of `fetch_list` contains the + name of an operation, the first Tensor output of that operation + will be returned for that element. + + Raises: + tf.errors.OpError: Or one of its subclasses on error. + """ + # pylint: disable=protected-access + feeds = dict((t.deref()._as_tf_output(), v) for t, v in feed_dict.items()) + fetches = [t._as_tf_output() for t in fetch_list] + targets = [op._c_op for op in target_list] + + # pylint: enable=protected-access + + def _run_fn(feed_dict, fetch_list, target_list, options, run_metadata): + # Ensure any changes to the graph are reflected in the runtime. + self._extend_graph() + return self._call_tf_sessionrun(options, feed_dict, fetch_list, + target_list, run_metadata) + + def _prun_fn(handle, feed_dict, fetch_list): + if target_list: + raise RuntimeError('partial_run() requires empty `target_list`. ' + f'Received: target_list={target_list} (non-empty)') + return self._call_tf_sessionprun(handle, feed_dict, fetch_list) + + if handle is None: + return self._do_call(_run_fn, feeds, fetches, targets, options, + run_metadata) + else: + return self._do_call(_prun_fn, handle, feeds, fetches) + + def _do_call(self, fn, *args): + try: + return fn(*args) + except errors.OpError as e: + message = compat.as_text(e.message) + m = BaseSession._NODEDEF_NAME_RE.search(message) + node_def = None + op = None + if m is not None: + node_name = m.group(3) + try: + op = self._graph.get_operation_by_name(node_name) + node_def = op.node_def + except KeyError: + pass + message = error_interpolation.interpolate_graph(message, self._graph) + if 'only supports NHWC tensor format' in message: + message += ('\nA possible workaround: Try disabling Grappler optimizer' + '\nby modifying the config for creating the session eg.' + '\nsession_config.graph_options.rewrite_options.' + 'disable_meta_optimizer = True') + raise type(e)(node_def, op, message) # pylint: disable=no-value-for-parameter + + def _extend_graph(self): + with self._graph._session_run_lock(): # pylint: disable=protected-access + tf_session.ExtendSession(self._session) + + # The threshold to run garbage collection to delete dead tensors. + _DEAD_HANDLES_THRESHOLD = 10 + + def _register_dead_handle(self, handle): + # Register a dead handle in the session. Delete the dead tensors when + # the number of dead tensors exceeds certain threshold. + tensors_to_delete = None + with self._delete_lock: + self._dead_handles.append(handle) + if len(self._dead_handles) == BaseSession._DEAD_HANDLES_THRESHOLD: + tensors_to_delete = self._dead_handles + self._dead_handles = [] + # Delete the dead tensors. + if tensors_to_delete: + feeds = {} + fetches = [] + for deleter_key, tensor_handle in enumerate(tensors_to_delete): + holder, deleter = session_ops._get_handle_deleter( + self.graph, deleter_key, tensor_handle) + feeds[holder] = tensor_handle + fetches.append(deleter) + self.run(fetches, feed_dict=feeds) + + def _update_with_movers(self, feed_dict, feed_map): + # If a tensor handle that is fed to a device incompatible placeholder, + # we move the tensor to the right device, generate a new tensor handle, + # and update `feed_dict` to use the new handle. + handle_movers = [] + for feed_name, val in feed_map.items(): + mover = session_ops._get_handle_mover(self.graph, *val) + if mover: + handle_movers.append((feed_name, val[1], mover)) + # Transfer a tensor to the right device if needed. + if not handle_movers: + return [] + else: + feeds = {} + fetches = [] + for _, handle, mover in handle_movers: + feeds[mover[0]] = handle + fetches.append(mover[1]) + handles = self.run(fetches, feed_dict=feeds) + for handle_mover, handle in zip(handle_movers, handles): + np_val = np.array(handle.handle, dtype=np.object_) + feed_name = handle_mover[0] + feed_tensor = feed_map[feed_name][0] + feed_dict[feed_tensor.ref()] = np_val + return handles + + def _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, + run_metadata): + return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict, + fetch_list, target_list, + run_metadata) + + def _call_tf_sessionprun(self, handle, feed_dict, fetch_list): + return tf_session.TF_SessionPRun_wrapper(self._session, handle, feed_dict, + fetch_list) + + # pylint: disable=protected-access + class _Callable(object): + """Experimental wrapper for the C++ `Session::MakeCallable()` API.""" + + def __init__(self, session, callable_options): + self._session = session + self._handle = None + options_ptr = tf_session.TF_NewBufferFromString( + compat.as_bytes(callable_options.SerializeToString())) + try: + self._handle = tf_session.TF_SessionMakeCallable( + session._session, options_ptr) + finally: + tf_session.TF_DeleteBuffer(options_ptr) + + def __call__(self, *args, **kwargs): + run_metadata = kwargs.get('run_metadata', None) + try: + run_metadata_ptr = tf_session.TF_NewBuffer() if run_metadata else None + ret = tf_session.TF_SessionRunCallable(self._session._session, + self._handle, args, + run_metadata_ptr) + if run_metadata: + proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) + run_metadata.ParseFromString(compat.as_bytes(proto_data)) + finally: + if run_metadata_ptr: + tf_session.TF_DeleteBuffer(run_metadata_ptr) + return ret + + def __del__(self): + # NOTE(mrry): It is possible that `self._session.__del__()` could be + # called before this destructor, in which case `self._session._session` + # will be `None`. + if (self._handle is not None and self._session._session is not None and + not self._session._closed): + tf_session.TF_SessionReleaseCallable(self._session._session, + self._handle) + + # pylint: enable=protected-access + + def _make_callable_from_options(self, callable_options): + """Returns a handle to a "callable" with the given options. + + Args: + callable_options: A `CallableOptions` protocol buffer message describing + the computation that will be performed by the callable. + + Returns: + A handle to the new callable. + """ + self._extend_graph() + return BaseSession._Callable(self, callable_options) + + +@tf_export(v1=['Session']) +class Session(BaseSession): + """A class for running TensorFlow operations. + + A `Session` object encapsulates the environment in which `Operation` + objects are executed, and `Tensor` objects are evaluated. For + example: + + ```python + tf.compat.v1.disable_eager_execution() # need to disable eager in TF2.x + # Build a graph. + a = tf.constant(5.0) + b = tf.constant(6.0) + c = a * b + + # Launch the graph in a session. + sess = tf.compat.v1.Session() + + # Evaluate the tensor `c`. + print(sess.run(c)) # prints 30.0 + ``` + + A session may own resources, such as + `tf.Variable`, `tf.queue.QueueBase`, + and `tf.compat.v1.ReaderBase`. It is important to release + these resources when they are no longer required. To do this, either + invoke the `tf.Session.close` method on the session, or use + the session as a context manager. The following two examples are + equivalent: + + ```python + # Using the `close()` method. + sess = tf.compat.v1.Session() + sess.run(...) + sess.close() + + # Using the context manager. + with tf.compat.v1.Session() as sess: + sess.run(...) + ``` + + The + [`ConfigProto`](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto) + protocol buffer exposes various configuration options for a + session. For example, to create a session that uses soft constraints + for device placement, and log the resulting placement decisions, + create a session as follows: + + ```python + # Launch the graph in a session that allows soft device placement and + # logs the placement decisions. + sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto( + allow_soft_placement=True, + log_device_placement=True)) + ``` + + @compatibility(TF2) + `Session` does not work with either eager execution or `tf.function`, and you + should not invoke it directly. To migrate code that uses sessions to TF2, + rewrite the code without it. See the + [migration + guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) + on replacing `Session.run` calls. + @end_compatibility + """ + + def __init__(self, target='', graph=None, config=None): + """Creates a new TensorFlow session. + + If no `graph` argument is specified when constructing the session, + the default graph will be launched in the session. If you are + using more than one graph (created with `tf.Graph()`) in the same + process, you will have to use different sessions for each graph, + but each graph can be used in multiple sessions. In this case, it + is often clearer to pass the graph to be launched explicitly to + the session constructor. + + Args: + target: (Optional.) The execution engine to connect to. Defaults to using + an in-process engine. See + [Distributed TensorFlow](https://tensorflow.org/deploy/distributed) for + more examples. + graph: (Optional.) The `Graph` to be launched (described above). + config: (Optional.) A + [`ConfigProto`](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto) + protocol buffer with configuration options for the session. + """ + super(Session, self).__init__(target, graph, config=config) + # NOTE(mrry): Create these on first `__enter__` to avoid a reference cycle. + self._default_graph_context_manager = None + self._default_session_context_manager = None + + def __enter__(self) -> 'Session': + if self._default_graph_context_manager is None: + self._default_graph_context_manager = self.graph.as_default() + else: + raise RuntimeError('Session context managers are not re-entrant. ' + 'Use `Session.as_default()` if you want to enter ' + 'a session multiple times.') + if self._default_session_context_manager is None: + self._default_session_context_manager = self.as_default() + self._default_graph_context_manager.__enter__() + return self._default_session_context_manager.__enter__() + + def __exit__(self, exec_type, exec_value, exec_tb): + if exec_type is errors.OpError: + logging.error('Session closing due to OpError: %s', (exec_value,)) + try: + self._default_session_context_manager.__exit__(exec_type, exec_value, + exec_tb) + except RuntimeError as error: + if error == exec_value: + # NOTE(skyewm): for some reason, in Python3, + # _default_session_context_manager.__exit__ will re-raise the "not + # re-entrant" exception raised in __enter__ above (note that if we're + # here, we're in the outer session context manager, since __exit__ is + # not called when __enter__ raises an exception). We still want to + # continue cleaning up this context manager before the exception is + # further propagated, so we ignore it here (note that it'll continue + # being propagated after this method completes). + pass + else: + raise + self._default_graph_context_manager.__exit__(exec_type, exec_value, exec_tb) + + self._default_session_context_manager = None + self._default_graph_context_manager = None + + # If we are closing due to an exception, set a time limit on our Close() to + # avoid blocking forever. + # TODO(b/120204635) remove this when deadlock is fixed. + if exec_type: + close_thread = threading.Thread( + name='SessionCloseThread', target=self.close) + close_thread.daemon = True + close_thread.start() + close_thread.join(30.0) + if close_thread.is_alive(): + logging.error( + 'Session failed to close after 30 seconds. Continuing after this ' + 'point may leave your program in an undefined state.') + else: + self.close() + + @staticmethod + def reset(target, containers=None, config=None): + """Resets resource containers on `target`, and close all connected sessions. + + A resource container is distributed across all workers in the + same cluster as `target`. When a resource container on `target` + is reset, resources associated with that container will be cleared. + In particular, all Variables in the container will become undefined: + they lose their values and shapes. + + NOTE: + (i) reset() is currently only implemented for distributed sessions. + (ii) Any sessions on the master named by `target` will be closed. + + If no resource containers are provided, all containers are reset. + + Args: + target: The execution engine to connect to. + containers: A list of resource container name strings, or `None` if all of + all the containers are to be reset. + config: (Optional.) Protocol buffer with configuration options. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + resetting containers. + """ + if target is not None: + target = compat.as_bytes(target) + if containers is not None: + containers = [compat.as_bytes(c) for c in containers] + else: + containers = [] + tf_session.TF_Reset(target, containers, config) + + +@tf_export(v1=['InteractiveSession']) +class InteractiveSession(BaseSession): + """A TensorFlow `Session` for use in interactive contexts, such as a shell. + + The only difference with a regular `Session` is that an `InteractiveSession` + installs itself as the default session on construction. + The methods `tf.Tensor.eval` + and `tf.Operation.run` + will use that session to run ops. + + This is convenient in interactive shells and [IPython + notebooks](http://ipython.org), as it avoids having to pass an explicit + `Session` object to run ops. + + For example: + + ```python + sess = tf.compat.v1.InteractiveSession() + a = tf.constant(5.0) + b = tf.constant(6.0) + c = a * b + # We can just use 'c.eval()' without passing 'sess' + print(c.eval()) + sess.close() + ``` + + Note that a regular session installs itself as the default session when it + is created in a `with` statement. The common usage in non-interactive + programs is to follow that pattern: + + ```python + a = tf.constant(5.0) + b = tf.constant(6.0) + c = a * b + with tf.compat.v1.Session(): + # We can also use 'c.eval()' here. + print(c.eval()) + ``` + """ + + _count_lock = threading.Lock() + _active_session_count = 0 # GUARDED_BY(_count_lock) + + def __init__(self, target='', graph=None, config=None): + """Creates a new interactive TensorFlow session. + + If no `graph` argument is specified when constructing the session, + the default graph will be launched in the session. If you are + using more than one graph (created with `tf.Graph()`) in the same + process, you will have to use different sessions for each graph, + but each graph can be used in multiple sessions. In this case, it + is often clearer to pass the graph to be launched explicitly to + the session constructor. + + Args: + target: (Optional.) The execution engine to connect to. Defaults to using + an in-process engine. + graph: (Optional.) The `Graph` to be launched (described above). + config: (Optional) `ConfigProto` proto used to configure the session. + """ + if not config: + # If config is not provided, choose some reasonable defaults for + # interactive use: + # + # - Grow GPU memory as needed at the cost of fragmentation. + gpu_options = config_pb2.GPUOptions(allow_growth=True) + config = config_pb2.ConfigProto(gpu_options=gpu_options) + # Interactive sessions always place pruned graphs. + config.graph_options.place_pruned_graph = True + + super(InteractiveSession, self).__init__(target, graph, config) + with InteractiveSession._count_lock: + if InteractiveSession._active_session_count > 0: + warnings.warn('An interactive session is already active. This can ' + 'cause out-of-memory errors in some cases. You must ' + 'explicitly call `InteractiveSession.close()` to release ' + 'resources held by the other session(s).') + InteractiveSession._active_session_count += 1 + # NOTE(mrry): We do not use `Session._closed` here because it has unhelpful + # semantics (in particular, it is not set to true if `Session.close()` is + # called on a session that has not been "opened" by running a step) and we + # cannot change those semantics without breaking existing code. + self._explicitly_closed = False + + self._default_session = self.as_default() + self._default_session.enforce_nesting = False + self._default_session.__enter__() + self._explicit_graph = graph + if self._explicit_graph is not None: + self._default_graph = graph.as_default() + self._default_graph.enforce_nesting = False + self._default_graph.__enter__() + + def close(self): + """Closes an `InteractiveSession`.""" + super(InteractiveSession, self).close() + with InteractiveSession._count_lock: + if not self._explicitly_closed: + InteractiveSession._active_session_count -= 1 + self._explicitly_closed = True + else: + return + if self._explicit_graph is not None: + self._default_graph.__exit__(None, None, None) + self._default_graph = None + self._default_session.__exit__(None, None, None) + self._default_session = None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/timeline.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/timeline.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7457d0f792995765d863edb7ed649123e69346 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/client/timeline.py @@ -0,0 +1,733 @@ +# 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. +# ============================================================================== +"""Timeline visualization for TensorFlow using Chrome Trace Format.""" + +import collections +import copy +import json +import re + +# The timeline target is usually imported as part of BUILD target +# "platform_test", which includes also includes the "platform" +# dependency. This is why the logging import here is okay. +from tensorflow.python.platform import build_info +from tensorflow.python.platform import tf_logging as logging + + +class AllocationMaximum(collections.namedtuple( + 'AllocationMaximum', ('timestamp', 'num_bytes', 'tensors'))): + """Stores the maximum allocation for a given allocator within the timelne. + + Parameters: + timestamp: `tensorflow::Env::NowMicros()` when this maximum was reached. + num_bytes: the total memory used at this time. + tensors: the set of tensors allocated at this time. + """ + pass + + +class StepStatsAnalysis(collections.namedtuple( + 'StepStatsAnalysis', ('chrome_trace', 'allocator_maximums'))): + """Stores the step stats analysis output. + + Parameters: + chrome_trace: A dict containing the chrome trace analysis. + allocator_maximums: A dict mapping allocator names to AllocationMaximum. + """ + pass + + +class _ChromeTraceFormatter(object): + """A helper class for generating traces in Chrome Trace Format.""" + + def __init__(self, show_memory=False): + """Constructs a new Chrome Trace formatter.""" + self._show_memory = show_memory + self._events = [] + self._metadata = [] + + def _create_event(self, ph, category, name, pid, tid, timestamp): + """Creates a new Chrome Trace event. + + For details of the file format, see: + https://github.com/catapult-project/catapult/blob/master/tracing/README.md + + Args: + ph: The type of event - usually a single character. + category: The event category as a string. + name: The event name as a string. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + timestamp: The timestamp of this event as a long integer. + + Returns: + A JSON compatible event object. + """ + event = {} + event['ph'] = ph + event['cat'] = category + event['name'] = name + event['pid'] = pid + event['tid'] = tid + event['ts'] = timestamp + return event + + def emit_pid(self, name, pid): + """Adds a process metadata event to the trace. + + Args: + name: The process name as a string. + pid: Identifier of the process as an integer. + """ + event = {} + event['name'] = 'process_name' + event['ph'] = 'M' + event['pid'] = pid + event['args'] = {'name': name} + self._metadata.append(event) + + def emit_tid(self, name, pid, tid): + """Adds a thread metadata event to the trace. + + Args: + name: The thread name as a string. + pid: Identifier of the process as an integer. + tid: Identifier of the thread as an integer. + """ + event = {} + event['name'] = 'thread_name' + event['ph'] = 'M' + event['pid'] = pid + event['tid'] = tid + event['args'] = {'name': name} + self._metadata.append(event) + + def emit_region(self, timestamp, duration, pid, tid, category, name, args): + """Adds a region event to the trace. + + Args: + timestamp: The start timestamp of this region as a long integer. + duration: The duration of this region as a long integer. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + category: The event category as a string. + name: The event name as a string. + args: A JSON-compatible dictionary of event arguments. + """ + event = self._create_event('X', category, name, pid, tid, timestamp) + event['dur'] = duration + event['args'] = args + self._events.append(event) + + def emit_obj_create(self, category, name, timestamp, pid, tid, object_id): + """Adds an object creation event to the trace. + + Args: + category: The event category as a string. + name: The event name as a string. + timestamp: The timestamp of this event as a long integer. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + object_id: Identifier of the object as an integer. + """ + event = self._create_event('N', category, name, pid, tid, timestamp) + event['id'] = object_id + self._events.append(event) + + def emit_obj_delete(self, category, name, timestamp, pid, tid, object_id): + """Adds an object deletion event to the trace. + + Args: + category: The event category as a string. + name: The event name as a string. + timestamp: The timestamp of this event as a long integer. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + object_id: Identifier of the object as an integer. + """ + event = self._create_event('D', category, name, pid, tid, timestamp) + event['id'] = object_id + self._events.append(event) + + def emit_obj_snapshot(self, category, name, timestamp, pid, tid, object_id, + snapshot): + """Adds an object snapshot event to the trace. + + Args: + category: The event category as a string. + name: The event name as a string. + timestamp: The timestamp of this event as a long integer. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + object_id: Identifier of the object as an integer. + snapshot: A JSON-compatible representation of the object. + """ + event = self._create_event('O', category, name, pid, tid, timestamp) + event['id'] = object_id + event['args'] = {'snapshot': snapshot} + self._events.append(event) + + def emit_flow_start(self, name, timestamp, pid, tid, flow_id): + """Adds a flow start event to the trace. + + When matched with a flow end event (with the same 'flow_id') this will + cause the trace viewer to draw an arrow between the start and end events. + + Args: + name: The event name as a string. + timestamp: The timestamp of this event as a long integer. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + flow_id: Identifier of the flow as an integer. + """ + event = self._create_event('s', 'DataFlow', name, pid, tid, timestamp) + event['id'] = flow_id + self._events.append(event) + + def emit_flow_end(self, name, timestamp, pid, tid, flow_id): + """Adds a flow end event to the trace. + + When matched with a flow start event (with the same 'flow_id') this will + cause the trace viewer to draw an arrow between the start and end events. + + Args: + name: The event name as a string. + timestamp: The timestamp of this event as a long integer. + pid: Identifier of the process generating this event as an integer. + tid: Identifier of the thread generating this event as an integer. + flow_id: Identifier of the flow as an integer. + """ + event = self._create_event('t', 'DataFlow', name, pid, tid, timestamp) + event['id'] = flow_id + self._events.append(event) + + def emit_counter(self, category, name, pid, timestamp, counter, value): + """Emits a record for a single counter. + + Args: + category: The event category as a string. + name: The event name as a string. + pid: Identifier of the process generating this event as an integer. + timestamp: The timestamp of this event as a long integer. + counter: Name of the counter as a string. + value: Value of the counter as an integer. + """ + event = self._create_event('C', category, name, pid, 0, timestamp) + event['args'] = {counter: value} + self._events.append(event) + + def emit_counters(self, category, name, pid, timestamp, counters): + """Emits a counter record for the dictionary 'counters'. + + Args: + category: The event category as a string. + name: The event name as a string. + pid: Identifier of the process generating this event as an integer. + timestamp: The timestamp of this event as a long integer. + counters: Dictionary of counter values. + """ + event = self._create_event('C', category, name, pid, 0, timestamp) + event['args'] = counters.copy() + self._events.append(event) + + def format_to_string(self, pretty=False): + """Formats the chrome trace to a string. + + Args: + pretty: (Optional.) If True, produce human-readable JSON output. + + Returns: + A JSON-formatted string in Chrome Trace format. + """ + trace = {} + trace['traceEvents'] = self._metadata + self._events + if pretty: + return json.dumps(trace, indent=4, separators=(',', ': ')) + else: + return json.dumps(trace, separators=(',', ':')) + + +class _TensorTracker(object): + """An internal class to track the lifetime of a Tensor.""" + + def __init__(self, name, object_id, timestamp, pid, allocator, num_bytes): + """Creates an object to track tensor references. + + This class is not thread safe and is intended only for internal use by + the 'Timeline' class in this file. + + Args: + name: The name of the Tensor as a string. + object_id: Chrome Trace object identifier assigned for this Tensor. + timestamp: The creation timestamp of this event as a long integer. + pid: Process identifier of the associated device, as an integer. + allocator: Name of the allocator used to create the Tensor. + num_bytes: Number of bytes allocated (long integer). + + Returns: + A 'TensorTracker' object. + """ + self._name = name + self._pid = pid + self._object_id = object_id + self._create_time = timestamp + self._allocator = allocator + self._num_bytes = num_bytes + self._ref_times = [] + self._unref_times = [] + + @property + def name(self): + """Name of this tensor.""" + return self._name + + @property + def pid(self): + """ID of the process which created this tensor (an integer).""" + return self._pid + + @property + def create_time(self): + """Timestamp when this tensor was created (long integer).""" + return self._create_time + + @property + def object_id(self): + """Returns the object identifier of this tensor (integer).""" + return self._object_id + + @property + def num_bytes(self): + """Size of this tensor in bytes (long integer).""" + return self._num_bytes + + @property + def allocator(self): + """Name of the allocator used to create this tensor (string).""" + return self._allocator + + @property + def last_unref(self): + """Last unreference timestamp of this tensor (long integer).""" + return max(self._unref_times) + + def add_ref(self, timestamp): + """Adds a reference to this tensor with the specified timestamp. + + Args: + timestamp: Timestamp of object reference as an integer. + """ + self._ref_times.append(timestamp) + + def add_unref(self, timestamp): + """Adds an unref to this tensor with the specified timestamp. + + Args: + timestamp: Timestamp of object unreference as an integer. + """ + self._unref_times.append(timestamp) + + +class Timeline(object): + """A class for visualizing execution timelines of TensorFlow steps.""" + + def __init__(self, step_stats, graph=None): + """Constructs a new Timeline. + + A 'Timeline' is used for visualizing the execution of a TensorFlow + computation. It shows the timings and concurrency of execution at + the granularity of TensorFlow Ops. + This class is not thread safe. + + Args: + step_stats: The 'StepStats' proto recording execution times. + graph: (Optional) The 'Graph' that was executed. + """ + + self._origin_step_stats = step_stats + self._step_stats = None + self._graph = graph + self._chrome_trace = _ChromeTraceFormatter() + self._next_pid = 0 + self._device_pids = {} # device name -> pid for compute activity. + self._tensor_pids = {} # device name -> pid for tensors. + self._tensors = {} # tensor_name -> TensorTracker + self._next_flow_id = 0 + self._flow_starts = {} # tensor_name -> (timestamp, pid, tid) + self._alloc_times = {} # tensor_name -> ( time, allocator, size ) + self._allocator_maximums = {} # allocator name => maximum bytes long + + def _alloc_pid(self): + """Allocate a process Id.""" + pid = self._next_pid + self._next_pid += 1 + return pid + + def _alloc_flow_id(self): + """Allocate a flow Id.""" + flow_id = self._next_flow_id + self._next_flow_id += 1 + return flow_id + + def _parse_op_label(self, label): + """Parses the fields in a node timeline label.""" + # Expects labels of the form: name = op(arg, arg, ...). + match = re.match(r'(.*) = (.*)\((.*)\)', label) + if match is None: + return 'unknown', 'unknown', [] + nn, op, inputs = match.groups() + if not inputs: + inputs = [] + else: + inputs = inputs.split(', ') + return nn, op, inputs + + def _parse_kernel_label(self, label, node_name): + """Parses the fields in a node timeline label.""" + # Expects labels of the form: retval (arg) detail @@annotation + start = label.find('@@') + end = label.find('#') + if start >= 0 and end >= 0 and start + 2 < end: + node_name = label[start + 2:end] + # Node names should always have the form 'name:op'. + fields = node_name.split(':') + ['unknown'] + name, op = fields[:2] + return name, op + + def _assign_lanes(self): + """Assigns non-overlapping lanes for the activities on each device.""" + for device_stats in self._step_stats.dev_stats: + # TODO(pbar): Genuine thread IDs in NodeExecStats might be helpful. + lanes = [0] + for ns in device_stats.node_stats: + l = -1 + for (i, lts) in enumerate(lanes): + if ns.all_start_micros > lts: + l = i + lanes[l] = ns.all_start_micros + ns.all_end_rel_micros + break + if l < 0: + l = len(lanes) + lanes.append(ns.all_start_micros + ns.all_end_rel_micros) + ns.thread_id = l + + def _emit_op(self, nodestats, pid, is_gputrace): + """Generates a Chrome Trace event to show Op execution. + + Args: + nodestats: The 'NodeExecStats' proto recording op execution. + pid: The pid assigned for the device where this op ran. + is_gputrace: If True then this op came from the GPUTracer. + """ + node_name = nodestats.node_name + start = nodestats.all_start_micros + duration = nodestats.all_end_rel_micros + tid = nodestats.thread_id + inputs = [] + if is_gputrace: + node_name, op = self._parse_kernel_label(nodestats.timeline_label, + node_name) + elif node_name == 'RecvTensor': + # RPC tracing does not use the standard timeline_label format. + op = 'RecvTensor' + else: + _, op, inputs = self._parse_op_label(nodestats.timeline_label) + args = {'name': node_name, 'op': op} + if build_info.build_info['is_rocm_build']: + args['kernel'] = nodestats.timeline_label.split('@@')[0] + for i, iname in enumerate(inputs): + args['input%d' % i] = iname + self._chrome_trace.emit_region(start, duration, pid, tid, 'Op', op, args) + + def _emit_tensor_snapshot(self, tensor, timestamp, pid, tid, value): + """Generate Chrome Trace snapshot event for a computed Tensor. + + Args: + tensor: A 'TensorTracker' object. + timestamp: The timestamp of this snapshot as a long integer. + pid: The pid assigned for showing the device where this op ran. + tid: The tid of the thread computing the tensor snapshot. + value: A JSON-compliant snapshot of the object. + """ + desc = str(value.tensor_description).replace('"', '') + snapshot = {'tensor_description': desc} + self._chrome_trace.emit_obj_snapshot('Tensor', tensor.name, timestamp, pid, + tid, tensor.object_id, snapshot) + + def _produce_tensor(self, name, timestamp, tensors_pid, allocator, num_bytes): + object_id = len(self._tensors) + tensor = _TensorTracker(name, object_id, timestamp, tensors_pid, allocator, + num_bytes) + self._tensors[name] = tensor + return tensor + + def _is_gputrace_device(self, device_name): + """Returns true if this device is part of the GPUTracer logging.""" + return '/stream:' in device_name or '/memcpy' in device_name + + def _allocate_pids(self): + """Allocate fake process ids for each device in the StepStats.""" + self._allocators_pid = self._alloc_pid() + self._chrome_trace.emit_pid('Allocators', self._allocators_pid) + + # Add processes in the Chrome trace to show compute and data activity. + for dev_stats in self._step_stats.dev_stats: + device_pid = self._alloc_pid() + self._device_pids[dev_stats.device] = device_pid + tensors_pid = self._alloc_pid() + self._tensor_pids[dev_stats.device] = tensors_pid + self._chrome_trace.emit_pid(dev_stats.device + ' Compute', device_pid) + self._chrome_trace.emit_pid(dev_stats.device + ' Tensors', tensors_pid) + + def _analyze_tensors(self, show_memory): + """Analyze tensor references to track dataflow.""" + for dev_stats in self._step_stats.dev_stats: + device_pid = self._device_pids[dev_stats.device] + tensors_pid = self._tensor_pids[dev_stats.device] + for node_stats in dev_stats.node_stats: + tid = node_stats.thread_id + node_name = node_stats.node_name + start_time = node_stats.all_start_micros + end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros + for index, output in enumerate(node_stats.output): + if index: + output_name = '%s:%d' % (node_name, index) + else: + output_name = node_name + + allocation = output.tensor_description.allocation_description + num_bytes = allocation.requested_bytes + allocator_name = allocation.allocator_name + tensor = self._produce_tensor(output_name, start_time, tensors_pid, + allocator_name, num_bytes) + tensor.add_ref(start_time) + tensor.add_unref(end_time) + self._flow_starts[output_name] = (end_time, device_pid, tid) + + if show_memory: + self._chrome_trace.emit_obj_create('Tensor', output_name, + start_time, tensors_pid, tid, + tensor.object_id) + self._emit_tensor_snapshot(tensor, end_time - 1, tensors_pid, tid, + output) + + def _show_compute(self, show_dataflow): + """Visualize the computation activity.""" + for dev_stats in self._step_stats.dev_stats: + device_name = dev_stats.device + device_pid = self._device_pids[device_name] + is_gputrace = self._is_gputrace_device(device_name) + + for node_stats in dev_stats.node_stats: + tid = node_stats.thread_id + start_time = node_stats.all_start_micros + end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros + self._emit_op(node_stats, device_pid, is_gputrace) + + if is_gputrace or node_stats.node_name == 'RecvTensor': + continue + + _, _, inputs = self._parse_op_label(node_stats.timeline_label) + for input_name in inputs: + if input_name not in self._tensors: + # This can happen when partitioning has inserted a Send/Recv. + # We remove the numeric suffix so that the dataflow appears to + # come from the original node. Ideally, the StepStats would + # contain logging for the Send and Recv nodes. + index = input_name.rfind('/_') + if index > 0: + input_name = input_name[:index] + + if input_name in self._tensors: + tensor = self._tensors[input_name] + tensor.add_ref(start_time) + tensor.add_unref(end_time - 1) + + if show_dataflow: + # We use a different flow ID for every graph edge. + create_time, create_pid, create_tid = self._flow_starts[ + input_name] + # Don't add flows when producer and consumer ops are on the same + # pid/tid since the horizontal arrows clutter the visualization. + if create_pid != device_pid or create_tid != tid: + flow_id = self._alloc_flow_id() + self._chrome_trace.emit_flow_start(input_name, create_time, + create_pid, create_tid, + flow_id) + self._chrome_trace.emit_flow_end(input_name, start_time, + device_pid, tid, flow_id) + else: + logging.vlog(1, 'Can\'t find tensor %s - removed by CSE?', + input_name) + + def _show_memory_counters(self): + """Produce a counter series for each memory allocator.""" + # Iterate over all tensor trackers to build a list of allocations and + # frees for each allocator. Then sort the lists and emit a cumulative + # counter series for each allocator. + allocations = {} + for name in self._tensors: + tensor = self._tensors[name] + self._chrome_trace.emit_obj_delete('Tensor', name, tensor.last_unref, + tensor.pid, 0, tensor.object_id) + allocator = tensor.allocator + if allocator not in allocations: + allocations[allocator] = [] + num_bytes = tensor.num_bytes + allocations[allocator].append((tensor.create_time, num_bytes, name)) + allocations[allocator].append((tensor.last_unref, -num_bytes, name)) + + alloc_maxes = {} + + # Generate a counter series showing total allocations for each allocator. + for allocator in allocations: + alloc_list = allocations[allocator] + alloc_list.sort() + total_bytes = 0 + alloc_tensor_set = set() + alloc_maxes[allocator] = AllocationMaximum( + timestamp=0, num_bytes=0, tensors=set()) + for time, num_bytes, name in sorted( + alloc_list, key=lambda allocation: allocation[0]): + total_bytes += num_bytes + if num_bytes < 0: + alloc_tensor_set.discard(name) + else: + alloc_tensor_set.add(name) + + if total_bytes > alloc_maxes[allocator].num_bytes: + alloc_maxes[allocator] = AllocationMaximum( + timestamp=time, + num_bytes=total_bytes, + tensors=copy.deepcopy(alloc_tensor_set)) + + self._chrome_trace.emit_counter('Memory', allocator, + self._allocators_pid, time, allocator, + total_bytes) + self._allocator_maximums = alloc_maxes + + def _preprocess_op_time(self, op_time): + """Update the start and end time of ops in step stats. + + Args: + op_time: How the execution time of op is shown in timeline. Possible values + are "schedule", "gpu" and "all". "schedule" will show op from the time it + is scheduled to the end of the scheduling. Notice by the end of its + scheduling its async kernels may not start yet. It is shown using the + default value from step_stats. "gpu" will show op with the execution time + of its kernels on GPU. "all" will show op from the start of its scheduling + to the end of its last kernel. + """ + if op_time == 'schedule': + self._step_stats = self._origin_step_stats + return + self._step_stats = copy.deepcopy(self._origin_step_stats) + # Separate job task and gpu tracer stream + stream_all_stats = [] + job_stats = [] + for stats in self._step_stats.dev_stats: + if '/stream:all' in stats.device: + stream_all_stats.append(stats) + elif '/job' in stats.device: + job_stats.append(stats) + + # Record the start time of the first kernel and the end time of + # the last gpu kernel for all ops. + op_gpu_start = {} + op_gpu_end = {} + for stats in stream_all_stats: + for kernel in stats.node_stats: + name, _ = self._parse_kernel_label(kernel.timeline_label, + kernel.node_name) + start = kernel.all_start_micros + end = kernel.all_start_micros + kernel.all_end_rel_micros + if name in op_gpu_start: + op_gpu_start[name] = min(op_gpu_start[name], start) + op_gpu_end[name] = max(op_gpu_end[name], end) + else: + op_gpu_start[name] = start + op_gpu_end[name] = end + + # Update the start and end time of each op according to the op_time + for stats in job_stats: + for op in stats.node_stats: + if op.node_name in op_gpu_start: + end = max(op_gpu_end[op.node_name], + op.all_start_micros + op.all_end_rel_micros) + if op_time == 'gpu': + op.all_start_micros = op_gpu_start[op.node_name] + op.all_end_rel_micros = end - op.all_start_micros + + def analyze_step_stats(self, + show_dataflow=True, + show_memory=True, + op_time='schedule'): + """Analyze the step stats and format it into Chrome Trace Format. + + Args: + show_dataflow: (Optional.) If True, add flow events to the trace + connecting producers and consumers of tensors. + show_memory: (Optional.) If True, add object snapshot events to the trace + showing the sizes and lifetimes of tensors. + op_time: (Optional.) How the execution time of op is shown in timeline. + Possible values are "schedule", "gpu" and "all". "schedule" will show op + from the time it is scheduled to the end of the scheduling. Notice by + the end of its scheduling its async kernels may not start yet. It is + shown using the default value from step_stats. "gpu" will show op with + the execution time of its kernels on GPU. "all" will show op from the + start of its scheduling to the end of its last kernel. + + Returns: + A 'StepStatsAnalysis' object. + """ + self._preprocess_op_time(op_time) + self._allocate_pids() + self._assign_lanes() + self._analyze_tensors(show_memory) + self._show_compute(show_dataflow) + if show_memory: + self._show_memory_counters() + return StepStatsAnalysis( + chrome_trace=self._chrome_trace, + allocator_maximums=self._allocator_maximums) + + def generate_chrome_trace_format(self, + show_dataflow=True, + show_memory=False, + op_time='schedule'): + """Produces a trace in Chrome Trace Format. + + Args: + show_dataflow: (Optional.) If True, add flow events to the trace + connecting producers and consumers of tensors. + show_memory: (Optional.) If True, add object snapshot events to the trace + showing the sizes and lifetimes of tensors. + op_time: (Optional.) How the execution time of op is shown in timeline. + Possible values are "schedule", "gpu" and "all". + "schedule" will show op from the time it is scheduled to the end of + the scheduling. + Notice by the end of its scheduling its async kernels may not start + yet. It is shown using the default value from step_stats. + "gpu" will show op with the execution time of its kernels on GPU. + "all" will show op from the start of its scheduling to the end of + its last kernel. + + Returns: + A JSON formatted string in Chrome Trace format. + """ + step_stats_analysis = self.analyze_step_stats( + show_dataflow=show_dataflow, show_memory=show_memory, op_time=op_time) + + return step_stats_analysis.chrome_trace.format_to_string(pretty=True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/compat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..5aaf72598fa4b05e38e5c0ef9fee4579849c8e6f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/compat.py @@ -0,0 +1,168 @@ +# 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. +# ============================================================================== +"""Utilities for API compatibility between TensorFlow release versions. + +See [Version +Compatibility](https://tensorflow.org/guide/version_compat#backward_forward) +""" + +import datetime +import os + +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.tf_export import tf_export + + +# This value changes every day with an automatic CL. It can be modified in code +# via `forward_compatibility_horizon()` or with the environment variable +# TF_FORWARD_COMPATIBILITY_DELTA_DAYS, which is added to the compatibility date. +_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2023, 10, 10) +_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME = "TF_FORWARD_COMPATIBILITY_DELTA_DAYS" +_FORWARD_COMPATIBILITY_DATE_NUMBER = None + + +def _date_to_date_number(year, month, day): + return (year << 9) | (month << 5) | day + + +def _update_forward_compatibility_date_number(date_to_override=None): + """Update the base date to compare in forward_compatible function.""" + + global _FORWARD_COMPATIBILITY_DATE_NUMBER + + if date_to_override: + date = date_to_override + else: + date = _FORWARD_COMPATIBILITY_HORIZON + delta_days = os.getenv(_FORWARD_COMPATIBILITY_DELTA_DAYS_VAR_NAME) + if delta_days: + date += datetime.timedelta(days=int(delta_days)) + + if date < _FORWARD_COMPATIBILITY_HORIZON: + logging.warning("Trying to set the forward compatibility date to the past" + " date %s. This will be ignored by TensorFlow." % (date)) + return + _FORWARD_COMPATIBILITY_DATE_NUMBER = _date_to_date_number( + date.year, date.month, date.day) + + +_update_forward_compatibility_date_number() + + +@tf_export("compat.forward_compatible") +def forward_compatible(year, month, day): + """Return true if the forward compatibility window has expired. + + See [Version + compatibility](https://www.tensorflow.org/guide/versions#backward_and_partial_forward_compatibility). + + Forward-compatibility refers to scenarios where the producer of a TensorFlow + model (a GraphDef or SavedModel) is compiled against a version of the + TensorFlow library newer than what the consumer was compiled against. The + "producer" is typically a Python program that constructs and trains a model + while the "consumer" is typically another program that loads and serves the + model. + + TensorFlow has been supporting a 3 week forward-compatibility window for + programs compiled from source at HEAD. + + For example, consider the case where a new operation `MyNewAwesomeAdd` is + created with the intent of replacing the implementation of an existing Python + wrapper - `tf.add`. The Python wrapper implementation should change from + something like: + + ```python + def add(inputs, name=None): + return gen_math_ops.add(inputs, name) + ``` + + to: + + ```python + from tensorflow.python.compat import compat + + def add(inputs, name=None): + if compat.forward_compatible(year, month, day): + # Can use the awesome new implementation. + return gen_math_ops.my_new_awesome_add(inputs, name) + # To maintain forward compatibility, use the old implementation. + return gen_math_ops.add(inputs, name) + ``` + + Where `year`, `month`, and `day` specify the date beyond which binaries + that consume a model are expected to have been updated to include the + new operations. This date is typically at least 3 weeks beyond the date + the code that adds the new operation is committed. + + Args: + year: A year (e.g., 2018). Must be an `int`. + month: A month (1 <= month <= 12) in year. Must be an `int`. + day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an + `int`. + + Returns: + True if the caller can expect that serialized TensorFlow graphs produced + can be consumed by programs that are compiled with the TensorFlow library + source code after (year, month, day). + """ + return _FORWARD_COMPATIBILITY_DATE_NUMBER > _date_to_date_number( + year, month, day) + + +@tf_export("compat.forward_compatibility_horizon") +@tf_contextlib.contextmanager +def forward_compatibility_horizon(year, month, day): + """Context manager for testing forward compatibility of generated graphs. + + See [Version + compatibility](https://www.tensorflow.org/guide/versions#backward_and_partial_forward_compatibility). + + To ensure forward compatibility of generated graphs (see `forward_compatible`) + with older binaries, new features can be gated with: + + ```python + if compat.forward_compatible(year=2018, month=08, date=01): + generate_graph_with_new_features() + else: + generate_graph_so_older_binaries_can_consume_it() + ``` + + However, when adding new features, one may want to unittest it before + the forward compatibility window expires. This context manager enables + such tests. For example: + + ```python + from tensorflow.python.compat import compat + + def testMyNewFeature(self): + with compat.forward_compatibility_horizon(2018, 08, 02): + # Test that generate_graph_with_new_features() has an effect + ``` + + Args: + year: A year (e.g., 2018). Must be an `int`. + month: A month (1 <= month <= 12) in year. Must be an `int`. + day: A day (1 <= day <= 31, or 30, or 29, or 28) in month. Must be an + `int`. + + Yields: + Nothing. + """ + try: + _update_forward_compatibility_date_number(datetime.date(year, month, day)) + yield + finally: + _update_forward_compatibility_date_number() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..481c3c69e3485528cd1d8db53c23ec810ede6d2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py @@ -0,0 +1,125 @@ +# 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. +# ============================================================================== +"""Switching v2 features on and off.""" + +from tensorflow.python import tf2 +from tensorflow.python.data.experimental.ops import counter +from tensorflow.python.data.experimental.ops import interleave_ops +from tensorflow.python.data.experimental.ops import random_ops +from tensorflow.python.data.experimental.ops import readers as exp_readers +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import readers +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import control_flow_v2_toggles +from tensorflow.python.ops import variable_scope + +from tensorflow.python.util.tf_export import tf_export + +# Metrics to track the status of v2_behavior +_v2_behavior_usage_gauge = monitoring.BoolGauge( + "/tensorflow/version/v2_behavior", + "whether v2_behavior is enabled or disabled", "status") + + +@tf_export(v1=["enable_v2_behavior"]) +def enable_v2_behavior(): + """Enables TensorFlow 2.x behaviors. + + This function can be called at the beginning of the program (before `Tensors`, + `Graphs` or other structures have been created, and before devices have been + initialized. It switches all global behaviors that are different between + TensorFlow 1.x and 2.x to behave as intended for 2.x. + + This function is called in the main TensorFlow `__init__.py` file, user should + not need to call it, except during complex migrations. + + @compatibility(TF2) + This function is not necessary if you are using TF2. V2 behavior is enabled by + default. + @end_compatibility + """ + _v2_behavior_usage_gauge.get_cell("enable").set(True) + # TF2 behavior is enabled if either 1) enable_v2_behavior() is called or + # 2) the TF2_BEHAVIOR=1 environment variable is set. In the latter case, + # the modules below independently check if tf2.enabled(). + tf2.enable() + ops.enable_eager_execution() + tensor_shape.enable_v2_tensorshape() # Also switched by tf2 + variable_scope.enable_resource_variables() + tensor.enable_tensor_equality() + # Enables TensorArrayV2 and control flow V2. + control_flow_v2_toggles.enable_control_flow_v2() + # Make sure internal uses of tf.data symbols map to V2 versions. + dataset_ops.Dataset = dataset_ops.DatasetV2 + readers.FixedLengthRecordDataset = readers.FixedLengthRecordDatasetV2 + readers.TFRecordDataset = readers.TFRecordDatasetV2 + readers.TextLineDataset = readers.TextLineDatasetV2 + counter.Counter = counter.CounterV2 + interleave_ops.choose_from_datasets = interleave_ops.choose_from_datasets_v2 + interleave_ops.sample_from_datasets = interleave_ops.sample_from_datasets_v2 + random_ops.RandomDataset = random_ops.RandomDatasetV2 + exp_readers.CsvDataset = exp_readers.CsvDatasetV2 + exp_readers.SqlDataset = exp_readers.SqlDatasetV2 + exp_readers.make_batched_features_dataset = ( + exp_readers.make_batched_features_dataset_v2) + exp_readers.make_csv_dataset = exp_readers.make_csv_dataset_v2 + + +@tf_export(v1=["disable_v2_behavior"]) +def disable_v2_behavior(): + """Disables TensorFlow 2.x behaviors. + + This function can be called at the beginning of the program (before `Tensors`, + `Graphs` or other structures have been created, and before devices have been + initialized. It switches all global behaviors that are different between + TensorFlow 1.x and 2.x to behave as intended for 1.x. + + User can call this function to disable 2.x behavior during complex migrations. + + @compatibility(TF2) + Using this function indicates that your software is not compatible + with eager execution and `tf.function` in TF2. + + To migrate to TF2, rewrite your code to be compatible with eager execution. + Please refer to the [migration guide] + (https://www.tensorflow.org/guide/migrate) for additional resource on the + topic. + @end_compatibility + """ + _v2_behavior_usage_gauge.get_cell("disable").set(True) + tf2.disable() + ops.disable_eager_execution() + tensor_shape.disable_v2_tensorshape() # Also switched by tf2 + variable_scope.disable_resource_variables() + tensor.disable_tensor_equality() + # Disables TensorArrayV2 and control flow V2. + control_flow_v2_toggles.disable_control_flow_v2() + # Make sure internal uses of tf.data symbols map to V1 versions. + dataset_ops.Dataset = dataset_ops.DatasetV1 + readers.FixedLengthRecordDataset = readers.FixedLengthRecordDatasetV1 + readers.TFRecordDataset = readers.TFRecordDatasetV1 + readers.TextLineDataset = readers.TextLineDatasetV1 + counter.Counter = counter.CounterV1 + interleave_ops.choose_from_datasets = interleave_ops.choose_from_datasets_v1 + interleave_ops.sample_from_datasets = interleave_ops.sample_from_datasets_v1 + random_ops.RandomDataset = random_ops.RandomDatasetV1 + exp_readers.CsvDataset = exp_readers.CsvDatasetV1 + exp_readers.SqlDataset = exp_readers.SqlDatasetV1 + exp_readers.make_batched_features_dataset = ( + exp_readers.make_batched_features_dataset_v1) + exp_readers.make_csv_dataset = exp_readers.make_csv_dataset_v1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/mlir/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/mlir/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/mlir/mlir.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/mlir/mlir.py new file mode 100644 index 0000000000000000000000000000000000000000..320614dd9eb0eeeba29390cfd817df8865d8d195 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/mlir/mlir.py @@ -0,0 +1,206 @@ +# 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. +# ============================================================================= +"""mlir is an experimental library that provides support APIs for MLIR.""" + +from tensorflow.python import pywrap_mlir +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('mlir.experimental.convert_graph_def') +def convert_graph_def( + graph_def, pass_pipeline='tf-standard-pipeline', show_debug_info=False +): + """Import a GraphDef and convert it to a textual MLIR module. + + This API is only intended for inspecting the internals of TensorFlow and the + string returned is at the moment intended for debugging purposes. + + Args: + graph_def: An object of type graph_pb2.GraphDef or a textual proto + representation of a valid GraphDef. + pass_pipeline: A textual description of an MLIR Pass Pipeline to run on the + module, see MLIR documentation for the [textual pass pipeline + syntax](https://mlir.llvm.org/docs/PassManagement/#textual-pass-pipeline-specification). + show_debug_info: Whether to include locations in the emitted textual form. + + Returns: + A textual representation of the MLIR module corresponding to the graphdef. + + Raises: + InvalidArgumentError: if graph_def is invalid or cannot be converted to + MLIR. + """ + return pywrap_mlir.import_graphdef(graph_def, pass_pipeline, show_debug_info) + + +@tf_export('mlir.experimental.convert_function') +def convert_function( + concrete_function, + pass_pipeline='tf-standard-pipeline', + show_debug_info=False, +): + """Import a ConcreteFunction and convert it to a textual MLIR module. + + This API is only intended for inspecting the internals of TensorFlow and the + string returned is at the moment intended for debugging purposes. + + A [tf.function](https://www.tensorflow.org/api_docs/python/tf/function) can be + imported and converted from TensorFlow to TensorFlow MLIR with this API by + extracting its ConcreteFunction (eagerly-executing wrapper around a + [tf.Graph](https://www.tensorflow.org/api_docs/python/tf/Graph)). + + For example: + >>> @tf.function + ... def add(a, b): + ... return a + b + + >>> concrete_function = add.get_concrete_function( + ... tf.TensorSpec(None, tf.dtypes.float32), + ... tf.TensorSpec(None, tf.dtypes.float32)) + >>> tf.mlir.experimental.convert_function(concrete_function) + '...module attributes {...} {...}...' + + Args: + concrete_function: An object of type ConcreteFunction. + pass_pipeline: A textual description of an MLIR Pass Pipeline to run on the + module, see MLIR documentation for the [textual pass pipeline + syntax](https://mlir.llvm.org/docs/PassManagement/#textual-pass-pipeline-specification). + show_debug_info: Whether to include locations in the emitted textual form. + + Returns: + A textual representation of the MLIR module corresponding to the + ConcreteFunction. + + Raises: + InvalidArgumentError: if concrete_function is invalid or cannot be converted + to MLIR. + """ + return pywrap_mlir.import_function( + concrete_function, pass_pipeline, show_debug_info + ) + + +@tf_export('mlir.experimental.convert_saved_model') +def convert_saved_model( + saved_model_path, exported_names, show_debug_info=False +): + """Converts a SavedModel to MLIR module. + + Args: + saved_model_path: Path to SavedModel. + exported_names: Names to export. + show_debug_info: Whether to include locations in the emitted textual form. + + Returns: + A textual representation of the MLIR module corresponding to the + SavedModel. + """ + return pywrap_mlir.experimental_convert_saved_model_to_mlir( + saved_model_path, exported_names, show_debug_info + ) + + +@tf_export('mlir.experimental.convert_saved_model_v1') +def convert_saved_model_v1( + saved_model_path, + exported_names, + tags, + lift_variables, + include_variables_in_initializers, + upgrade_legacy=True, + show_debug_info=False, +): + """Converts a v1 SavedModel to MLIR module. + + Args: + saved_model_path: Path to SavedModel. + exported_names: Names to export. + tags: MetaGraphDef to be loaded is identified by the supplied tags. + lift_variables: Whether to promote tf.VarHandleOp to resource arguments. + include_variables_in_initializers: Keeps the variables in initializers + before lifting variables. + upgrade_legacy: Functionalize the input graph before importing. + show_debug_info: Whether to include locations in the emitted textual form. + + Returns: + A textual representation of the MLIR module corresponding to the + SavedModule. + """ + return pywrap_mlir.experimental_convert_saved_model_v1_to_mlir( + saved_model_path, + exported_names, + tags, + lift_variables, + include_variables_in_initializers, + upgrade_legacy, + show_debug_info, + ) + + +@tf_export('mlir.experimental.run_pass_pipeline') +def run_pass_pipeline(mlir_txt, pass_pipeline, show_debug_info=False): + """Runs a pipeline over input module. + + Args: + mlir_txt: Textual representation of the MLIR module. + pass_pipeline: Pass pipeline to run on module. + show_debug_info: Whether to include locations in the emitted textual form. + + Returns: + A textual representation of the MLIR module corresponding to the + transformed module. + """ + return pywrap_mlir.experimental_run_pass_pipeline( + mlir_txt, pass_pipeline, show_debug_info + ) + + +@tf_export('mlir.experimental.write_bytecode') +def experimental_write_bytecode(filename, mlir_txt): + """Writes an MLIR module out as bytecode. + + Args: + filename: The filename to write to. + mlir_txt: The MLIR module in textual format. + """ + pywrap_mlir.experimental_write_bytecode(filename, mlir_txt) + + +@tf_export('mlir.experimental.tflite_to_tosa_bytecode') +def tflite_to_tosa_bytecode( + flatbuffer, + bytecode, + use_external_constant=False, + ordered_input_arrays=None, + ordered_output_arrays=None, +): + """Converts TFLite flatbuffer to TOSA dialect in MLIR bytecode. + + Args: + flatbuffer: Path to flatbuffer. + bytecode: Path to output bytecode. + use_external_constant: Whether to create `tfl.external_const` instead of + `tfl.const`. + ordered_input_arrays: + ordered_output_arrays: If ordered_output_arrays is not empty, then the + function will only return nodes in ordered_output_arrays in the same order + """ + pywrap_mlir.experimental_tflite_to_tosa_bytecode( + flatbuffer, + bytecode, + use_external_constant, + ordered_input_arrays, + ordered_output_arrays, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6565203b81f634e6f94da8b5fd26a941510c8773 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/__init__.py @@ -0,0 +1,19 @@ +# 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. +# ============================================================================= +"""Exposes the python wrapper for TensorRT graph transforms.""" + +# pylint: disable=unused-import,line-too-long +from tensorflow.python.compiler.tensorrt import trt_convert as trt +# pylint: enable=unused-import,line-too-long diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/test/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..06784c0910641c6e09c78027c060d2bd00eebbb4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/test/tf_trt_integration_test_base.py @@ -0,0 +1,1214 @@ +# 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. +# ============================================================================== +"""Utilities to test TF-TensorRT integration.""" + +import collections +import errno +import gc +import itertools +import os +import re +import shutil +import tempfile +import warnings + +from contextlib import contextmanager + +import numpy as np + +from tensorflow.compiler.tf2tensorrt._pywrap_py_utils import is_tensorrt_enabled +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.compiler.tensorrt import trt_convert +from tensorflow.python.compiler.tensorrt import utils as trt_utils +from tensorflow.python.eager import def_function +from tensorflow.python.framework import config +from tensorflow.python.framework import graph_io +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace +from tensorflow.python.saved_model import builder +from tensorflow.python.saved_model import load +from tensorflow.python.saved_model import loader +from tensorflow.python.saved_model import save +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import signature_def_utils +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.saved_model import utils +from tensorflow.python.tools import saved_model_utils +from tensorflow.python.trackable import autotrackable +from tensorflow.python.util import nest + +logging.get_logger().propagate = False + +TfTrtIntegrationTestParams = collections.namedtuple( + "TfTrtIntegrationTestParams", + [ + # A function that creates the TF graph for testing. + "graph_fn", + # A list of specifications for input tensors. + "input_specs", + # A list of specifications for output tensors. + "output_specs", + # A list of list of input shapes. Each shape must match the + # corresponding element in `input_specs`. + "input_dims", + # A list of list of expected output shapes. Each shape must match the + # corresponding element in `output_specs`. + "expected_output_dims" + ]) + +RunParams = collections.namedtuple( + "RunParams", + [ + # Whether to run the conversion online with RewriterConfig, or offline + # with TrtGraphConverter. + "convert_online", + "precision_mode", + "dynamic_engine", + "use_calibration", + "test_name", + # Is this test for TF 2.0? + "is_v2", + "dynamic_shape", + ]) + +FP32 = "FP32" +FP16 = "FP16" +INT8 = "INT8" +PRECISION_MODES = [FP32, FP16, INT8] + + +def IsQuantizationMode(mode): + return mode == "INT8" + + +def IsQuantizationWithCalibration(params): + return IsQuantizationMode(params.precision_mode) and params.use_calibration + + +def IsQuantizationWithoutCalibration(params): + return IsQuantizationMode( + params.precision_mode) and not params.use_calibration + + +@contextmanager +def disable_tensorfloat32(): + start_value = config.tensor_float_32_execution_enabled() + + config.enable_tensor_float_32_execution(False) + + logging.info("TensorFloat32 Arithmetic Disabled") + + try: + yield + # Finally block always gets executed either exception is generated or not + finally: + config.enable_tensor_float_32_execution(start_value) + + +class GraphState(object): + ORIGINAL = 0 + CALIBRATE = 1 + INFERENCE = 2 + + +class TfTrtIntegrationTestBase(test_util.TensorFlowTestCase): + """Class to test Tensorflow-TensorRT integration.""" + + @property + def trt_incompatible_op(self): + return math_ops.erfc + + @property + def trt_incompatible_binary_op(self): + return math_ops.igamma + + @property + def precision_modes(self): + return ["FP32", "FP16", "INT8"] + + # str is bytes in py2, but unicode in py3. + def _ToUnicode(self, s): + if isinstance(s, str): + return s + return s.decode("utf-8") + + def _ToBytes(self, s): + if isinstance(s, str): + return s.encode("utf-8") + return s + + def _ToString(self, s): + if isinstance(s, str): + return s + return s.decode("utf-8") + + def __init__(self, methodName="runTest"): # pylint: disable=invalid-name + super(TfTrtIntegrationTestBase, self).__init__(methodName) + self._trt_test_params = None + self._disable_non_trt_optimizers = False + self._profile_strategy = "ImplicitBatchModeCompatible" + + def setUp(self): + """Setup method.""" + super().setUp() + warnings.simplefilter("always") + + if not is_tensorrt_enabled(): + self.skipTest("Test requires TensorRT") + + def tearDown(self): + """Making sure to clean artifact.""" + idx = 0 + while gc.garbage: + gc.collect() # Force GC to destroy the TRT engine cache. + idx += 1 + if idx >= 10: # After 10 iterations, break to avoid infinite collect. + break + + def _GetTensorSpec(self, shape, mask, dtype, name): + # Set dimension i to None if mask[i] == False + assert len(shape) == len(mask), ( + f"len(shape): {len(shape)} == len(mask): {len(mask)}") + + new_shape = [s if m else None for s, m in zip(shape, mask)] + return tensor_spec.TensorSpec(new_shape, dtype, name) + + def BuildParams(self, graph_fn, dtype, input_shapes, output_shapes): + """Build test parameters. + + The input_shapes and output_shapes arguments are known (static) shapes that + can be used to generate test data. To define the model, we also specify + corresponding input/output TensorSpecs. These are defined using the shape + arguments. For each input tensor we define: + + input_spec = [None] + input_shape[1:] + + and similarly for output shapes. This means that we leave the first (batch) + dimension unknown, the rest is just copied from the shapes arg. + + Args: + graph_fn: The function to build the graph. + dtype: The element type. + input_shapes: The input shapes. + output_shapes: The output shapes. + + Returns: + The test parameters. + """ + + input_mask = [[False] + [True] * (len(shape) - 1) for shape in input_shapes] + output_mask = [[False] + [True] * (len(shape) - 1) if shape else [] + for shape in output_shapes] + + return self.BuildParamsWithMask(graph_fn, dtype, input_shapes, + output_shapes, input_mask, output_mask, [], + []) + + def BuildParamsWithMask(self, graph_fn, dtype, input_shapes, output_shapes, + input_mask, output_mask, extra_inputs, extra_outputs): + """Build test parameters with static or dynamic input shapes. + + To define dynamic shapes give a boolean mask that describes which + dimensions to treat as known. The values in input_mask are interpreted the + following way: + - True: known dim (use the corresponding value from input_shapes) + - False: unknown dim (replace the corresponding value from input_shapes + with None) + For example, to define the first two dimension with unknown size use + input_shapes=[[1,2,1,8]], input_mask=[[False, False, True, True]]. + + Args: + graph_fn: The function to build the graph. + dtype: The element type. + input_shapes: The input shapes. + output_shapes: The output shapes. + input_mask: The input shape masks. + output_mask: the output shape masks. + extra_inputs: list of additional input shapes + extra_outputs: list of additional outputs shapes + + Returns: + The test parameters. + """ + + def _ValidateShapes(shapes): + # Make sure all the shapes are fully specified. + for shape in shapes: + assert all(shape), f"Shape unspecified: {shape}" + + _ValidateShapes(input_shapes) + _ValidateShapes(output_shapes) + + assert len(input_mask) == len(input_shapes), ( + f"Inconsistent input_mask and input_shapes: len({input_mask}) != " + f"len({input_shapes}).") + assert len(output_mask) == len(output_shapes), ( + f"Inconsistent output_mask and output_shapes: len({output_mask}) != " + f"len({output_shapes}).") + for extra_in_shape, extra_out_shape in zip(extra_inputs, extra_outputs): + assert len(input_shapes) == len(extra_in_shape), ( + f"Inconsistent input_shapes and extra_in_shape: len({input_shapes}) " + f"!= len({extra_in_shape}).") + assert len(output_shapes) == len(extra_out_shape), ( + f"Inconsistent output_shapes and extra_out_shape: " + f"len({output_shapes}) != len({extra_out_shape}).") + + return TfTrtIntegrationTestParams( + graph_fn=graph_fn, + input_specs=[ + self._GetTensorSpec(shape, mask, dtype, "input_%d" % i) + for i, (shape, mask) in enumerate(zip(input_shapes, input_mask)) + ], + output_specs=[ + self._GetTensorSpec(shape, mask, dtype, "output_%d" % i) + for i, (shape, mask) in enumerate(zip(output_shapes, output_mask)) + ], + input_dims=[input_shapes] + extra_inputs, + expected_output_dims=[output_shapes] + extra_outputs) + + def DisableNonTrtOptimizers(self): + self._disable_non_trt_optimizers = True + + def GetParams(self): + """Returns a TfTrtIntegrationTestParams for the test.""" + raise NotImplementedError() + + def GetConversionParams(self, run_params): + """Returns a TrtConversionParams for test.""" + conversion_params = trt_convert.TrtConversionParams( + # We use the minimum of all the batch sizes, so when multiple different + # input shapes are provided it'll always create new engines in the + # cache, and we can therefore test the cache behavior. + max_workspace_size_bytes=( + trt_convert.DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES), + precision_mode=run_params.precision_mode, + minimum_segment_size=2, + maximum_cached_engines=1, + use_calibration=run_params.use_calibration) + return conversion_params + + def GetMaxBatchSize(self, run_params): + """Returns the max_batch_size that the converter should use for tests.""" + if run_params.dynamic_engine: + return None + batch_list = [] + for dims_list in self._GetParamsCached().input_dims: + assert dims_list, f"Expect non-empty `dim_list` but got: {dims_list}" + # Each list of shapes should have same batch size. + input_batches = [dims[0] for dims in dims_list] + assert max(input_batches) == min(input_batches), ( + f"Inconsistent batch_size: max({input_batches}) != " + f"min({input_batches}).") + batch_list.append(input_batches[0]) + return max(batch_list) + + def ShouldRunTest(self, run_params): + """Whether to run the test.""" + # Ensure use_calibration=True in case of INT8 precision + return (run_params.use_calibration or not IsQuantizationMode( + run_params.precision_mode)), "test either calibration or non-INT8" + + def ExpectedEnginesToBuild(self, run_params): + """Returns the expected engines to build, implemented by subclass.""" + raise NotImplementedError() + + def ExpectedConnections(self, run_params): + """Returns the expected edges or an empty dict to skip the check.""" + return {} + + def ExpectedMaxBatchSizes(self, run_params): + """Returns the expected maximum batch sizes of the build engines.""" + return None + + def ExpectedAbsoluteTolerance(self, run_params): + """The absolute tolerance to compare floating point results.""" + if run_params.precision_mode == "INT8": + return 3e-1 + return 1.e-05 if run_params.precision_mode == "FP32" else 2.e-02 + + def ExpectedRelativeTolerance(self, run_params): + """The relative tolerance to compare floating point results.""" + if run_params.precision_mode == "INT8": + return 1e-1 + return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-02 + + def _GetParamsCached(self): + if self._trt_test_params is None: + self._trt_test_params = self.GetParams() + return self._trt_test_params + + def _GetGPUOptions(self): + gpu_options = config_pb2.GPUOptions() + gpu_options.allow_growth = True + return gpu_options + + def _GetConfigProto(self, run_params, graph_state): + """Get config proto based on specific settings.""" + conversion_params = self.GetConversionParams(run_params) + max_batch_size = self.GetMaxBatchSize(run_params) + + if graph_state == GraphState.INFERENCE and run_params.convert_online: + rewriter_cfg = trt_convert.get_tensorrt_rewriter_config( + conversion_params, + is_dynamic_op=run_params.dynamic_engine, + max_batch_size=max_batch_size, + disable_non_trt_optimizers=self._disable_non_trt_optimizers) + else: + rewriter_cfg = rewriter_config_pb2.RewriterConfig() + if self._disable_non_trt_optimizers: + trt_utils.disable_non_trt_optimizers_in_rewriter_config(rewriter_cfg) + + config = config_pb2.ConfigProto( + gpu_options=self._GetGPUOptions(), + graph_options=config_pb2.GraphOptions(rewrite_options=rewriter_cfg)) + return config + + def _GetFeedNames(self): + params = self._GetParamsCached() + # Construct the feeds tensor names by appending :0 to the node names. + return [spec.name + ":0" for spec in params.input_specs] + + def _GetFetchNames(self): + params = self._GetParamsCached() + # Construct the fetches tensor names by appending :0 to the node names. + return [spec.name + ":0" for spec in params.output_specs] + + def _GetFeedDict(self, inputs_data): + return {name: data for name, data in zip(self._GetFeedNames(), inputs_data)} + + def _RunGraphV1(self, saved_model_dir, inputs_data, config, num_runs=2): + """Run given graphdef multiple times using TF 1.x runtime.""" + params = self._GetParamsCached() + fetches = self._GetFetchNames() + g = ops.Graph() + with g.as_default(): + with self.session(graph=g, config=config, use_gpu=True) as sess: + loader.load(sess, [tag_constants.SERVING], saved_model_dir) + vals = [] + # Run for each input(s) shape + for expected_shapes, current_input_data in zip( + params.expected_output_dims, inputs_data): + val = None + for _ in range(num_runs): + new_val = sess.run(fetches, self._GetFeedDict(current_input_data)) + self.assertEqual(len(expected_shapes), len(new_val)) + for expected_shape, actual_val in zip(expected_shapes, new_val): + self.assertEqual(list(expected_shape), list(actual_val.shape)) + if val is not None: + # Some ops may have nondeterministic output. E.g. Conv2D may use + # winograd algorithm. So we set atol/rtol be larger than 1.e-06. + self.assertAllClose(val, new_val, atol=1.e-05, rtol=1.e-05) + val = new_val + vals.append(val) + return vals + + def _RunGraphV2(self, saved_model_dir, inputs_data, graph_state, num_runs=2): + """Run given graphdef multiple times using TF 2.0 runtime.""" + params = self._GetParamsCached() + root = load.load(saved_model_dir) + func = root.signatures[ + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] + results = [] + for expected_shapes, current_input_data in zip(params.expected_output_dims, + inputs_data): + val = None + for _ in range(num_runs): + feed_dict = { + params.input_specs[i].name: current_input_data[i] + for i in range(len(params.input_specs)) + } + new_val = func(**feed_dict) + assert isinstance( + new_val, dict), (f"Invalid type for `new_val`, expected `dict`. " + f"Got: {type(new_val)}.") + # The key of the output map is always like output_i. + new_val = [new_val[key] for key in sorted(new_val)] + # Each element is an eager Tensor, and accessing individual elements is + # very expensive, so we convert them to a numpy array first. + new_val = [v.numpy() for v in new_val] + self.assertEqual(len(expected_shapes), len(new_val)) + for expected_shape, actual_val in zip(expected_shapes, new_val): + self.assertEqual(list(expected_shape), list(actual_val.shape)) + if val is not None: + # Some ops may have nondeterministic output. E.g. Conv2D may use + # winograd algorithm. So we set atol/rtol be larger than 1.e-06. + self.assertAllClose(val, new_val, atol=1.e-05, rtol=1.e-05) + val = new_val + results.append(val) + + return results + + def _RunGraph(self, + run_params, + saved_model_dir, + inputs_data, + graph_state, + num_runs=2): + params = self._GetParamsCached() + for data in inputs_data: + assert len(params.input_specs) == len(data), ( + f"Inconsistent params.input_specs and data: " + f"len({params.input_specs}) != len({data}).") + + if run_params.is_v2: + results = self._RunGraphV2(saved_model_dir, inputs_data, graph_state, + num_runs) + gc.collect() # Force GC to destroy the TRT engine cache. + return results + + # The default config for tf.session is None. Create a config with + # TensorRTOptimizer enabled to support convert_online for inference. + config = None + # TODO(b/170220818): use the default session config to run inferenence + # graphs for the offline conversion case after fixing the bug. + if graph_state == GraphState.INFERENCE: + config = self._GetConfigProto(run_params, GraphState.INFERENCE) + return self._RunGraphV1(saved_model_dir, inputs_data, config, num_runs) + + def _CreateConverter(self, run_params, saved_model_dir, conversion_params): + """Returns a TrtGraphConverter.""" + if run_params.is_v2: + converter_v2 = trt_convert.TrtGraphConverterV2( + input_saved_model_dir=saved_model_dir, + use_dynamic_shape=run_params.dynamic_shape, + dynamic_shape_profile_strategy=self._profile_strategy, + **conversion_params._asdict()) + if self._disable_non_trt_optimizers: + converter_v2._test_only_disable_non_trt_optimizers = True # pylint: disable=protected-access + return converter_v2 + + converter_v1 = trt_convert.TrtGraphConverter( + input_saved_model_dir=saved_model_dir, + max_batch_size=self.GetMaxBatchSize(run_params), + max_workspace_size_bytes=conversion_params.max_workspace_size_bytes, + precision_mode=conversion_params.precision_mode, + minimum_segment_size=conversion_params.minimum_segment_size, + is_dynamic_op=run_params.dynamic_engine, + maximum_cached_engines=conversion_params.maximum_cached_engines, + use_calibration=conversion_params.use_calibration) + if self._disable_non_trt_optimizers: + converter_v1._test_only_disable_non_trt_optimizers = True # pylint: disable=protected-access + return converter_v1 + + def _GetCalibratedInferGraph(self, run_params, saved_model_dir, inputs_data): + """Return trt converted graphdef in INT8 mode.""" + conversion_params = self.GetConversionParams(run_params) + logging.info(conversion_params) + assert conversion_params.precision_mode == "INT8", ( + f"Incorrect precision mode, expected INT8 but got: " + f"{conversion_params.precision_mode}.") + assert run_params.dynamic_engine, "dynamic_engine parameter must be True." + assert conversion_params.maximum_cached_engines == 1, ( + f"maximum_cached_engines: {conversion_params.maximum_cached_engines} " + f"== 1") + assert conversion_params.use_calibration, "use_calibration must be True." + + # We only support calibrating single engine. + # TODO(aaroey): fix this. + assert len(inputs_data) == 1, (f"len(inputs_data): {len(inputs_data)} == 1") + + converter = self._CreateConverter(run_params, saved_model_dir, + conversion_params) + if run_params.is_v2: + + def CalibrationInputFn(): + for data_tensors in inputs_data: + yield data_tensors + + converter.convert(calibration_input_fn=CalibrationInputFn) + else: + int8_gdef = converter.convert() + self._VerifyGraphDef(run_params, saved_model_dir, int8_gdef, + GraphState.CALIBRATE) + + converter.calibrate( + fetch_names=self._GetFetchNames(), + num_runs=5, + feed_dict_fn=lambda: self._GetFeedDict(inputs_data[0])) + + if run_params.dynamic_shape and self._ShouldConverterBuild(run_params): + logging.info("Using build mode") + + def _BuildInputFn(): + for shapes in self._GetParamsCached().input_dims: + yield [ + array_ops.zeros(x, dtype=spec.dtype) + for (x, spec) in zip(shapes, + self._GetParamsCached().input_specs) + ] + + converter.build(input_fn=_BuildInputFn) + + trt_saved_model_dir = self._GetSavedModelDir(run_params, + GraphState.CALIBRATE) + converter.save(trt_saved_model_dir) + return trt_saved_model_dir + + def _ShouldConverterBuild(self, run_params): + return True + + def _GetInferGraph(self, run_params, saved_model_dir): + """Return trt converted graphdef.""" + conversion_params = self.GetConversionParams(run_params) + logging.info(conversion_params) + + converter = self._CreateConverter(run_params, saved_model_dir, + conversion_params) + converter.convert() + + if run_params.is_v2: + try: + line_length = max(160, os.get_terminal_size().columns) + except OSError: + line_length = 160 + converter.summary(line_length=line_length, detailed=True) + + if run_params.dynamic_shape and self._ShouldConverterBuild(run_params): + logging.info("Using build mode") + + def _BuildInputFn(): + for shapes in self._GetParamsCached().input_dims: + yield [ + array_ops.zeros(x, dtype=spec.dtype) + for (x, spec) in zip(shapes, + self._GetParamsCached().input_specs) + ] + + converter.build(input_fn=_BuildInputFn) + + trt_saved_model_dir = self._GetSavedModelDir(run_params, + GraphState.INFERENCE) + converter.save(trt_saved_model_dir) + return trt_saved_model_dir + + def _GetGraphStateLabel(self, graph_state): + if graph_state == GraphState.ORIGINAL: + return "Original" + elif graph_state == GraphState.CALIBRATE: + return "CalibEngine" + elif graph_state == GraphState.INFERENCE: + return "InferEngine" + else: + return "UnknownState" + + def _WriteGraph(self, run_params, gdef, graph_state): + temp_dir = os.getenv("TRT_TEST_TMPDIR") + if not temp_dir: + return + + graph_name = ( + self.__class__.__name__ + "_" + run_params.test_name + "_" + + self._GetGraphStateLabel(graph_state) + ".pbtxt") + logging.info("Writing graph to %s/%s", temp_dir, graph_name) + graph_io.write_graph(gdef, temp_dir, graph_name) + + # Removes the prefix(s) of function name(s). + # The input value can be a string or a sequence of string. + def _Canonicalize(self, value): + if isinstance(value, str): + return self._ToString(value.split("/")[-1]) + elif isinstance(value, collections.abc.Iterable): + return set(self._Canonicalize(nm) for nm in value) + else: + raise TypeError( + "'_Canonicalize' can only be used on strings or sequence of strings!") + + # Removes the graph sequence number prefix from the name(s) only if the + # name(s) has a prefix TRTEngineOp_n_. When expecting_prefix is true, asserts + # such a prefix exists. + # The input value can be a string or a sequence of string. + def _RemoveGraphSequenceNumberImpl(self, value, expecting_prefix): + if isinstance(value, str): + match = re.search(r"TRTEngineOp_\d{3,}_", value) + has_prefix = match and value.startswith(match.group(0)) + assert (not expecting_prefix) or has_prefix, ( + f"Expect (not expecting_prefix) or has_prefix but got: " + f"- expecting_prefix = {expecting_prefix}\n" + f"- has_prefix = {has_prefix}") + if has_prefix: + parts = value.split("_", maxsplit=2) + assert len(parts) == 3, ( + f"Incorrect `parts` of length == 3, but got: len({parts}).") + return parts[0] + "_" + parts[2] + return value + elif isinstance(value, collections.abc.Iterable): + return set( + self._RemoveGraphSequenceNumberImpl(nm, expecting_prefix) + for nm in value) + else: + raise TypeError( + "'_RemoveGraphSequenceNumberImpl' can only be used on strings " + "or sequence of strings!") + + def _RemoveGraphSequenceNumber(self, name): + return self._RemoveGraphSequenceNumberImpl(name, True) + + def _MayRemoveGraphSequenceNumber(self, name): + return self._RemoveGraphSequenceNumberImpl(name, False) + + def _VerifyConnections(self, expected_engines, expected_input_map, + original_gdef, converted_gdef): + """Checks that the converted graph contains the expected connections.""" + old_to_new_node_map = { + self._ToString(node.name): self._ToString(node.name) + for node in original_gdef.node + } + for engine_name, node_names in expected_engines.items(): + for node_name in node_names: + old_to_new_node_map[node_name] = engine_name + + def _InputName(inp): + inp = self._ToString(inp) + prefix = "" + if inp[0] == "^": + prefix = "^" + inp = inp[1:] + parts = inp.split(":") + if len(parts) > 1 and parts[-1].isdigit(): + inp = inp[:-len(parts[-1]) - 1] + return (prefix, inp) + + # Compute the actual mapping from each node to its input nodes. If a cast + # op doesn't exist in the original graph, we replace the use of the cast op + # with the input of the op. This allows the verification to handle the case + # where the TF-TRT bridge splits a cast op into a chain of two cast ops. + new_cast_op_name_to_node_map = { + node.name: node + for node in converted_gdef.node + if (node.name not in old_to_new_node_map and node.op == "Cast") + } + actual_input_map = {} + for node in converted_gdef.node: + name_str = node.name + # Only nodes from the original graph or TRTEngineOp nodes are added as + # keys to the map. + if node.op == "TRTEngineOp": + name_str = self._RemoveGraphSequenceNumber(name_str) + elif name_str not in old_to_new_node_map: + continue + actual_input_map[name_str] = set() + input_set = actual_input_map[name_str] + for inp in node.input: + (prefix, node_name) = _InputName(inp) + node_name = self._MayRemoveGraphSequenceNumber(node_name) + if node_name in new_cast_op_name_to_node_map: + (prefix, node_name) = _InputName( + new_cast_op_name_to_node_map[node_name].input[0]) + input_set.add(prefix + node_name) + + self.assertEqual( + expected_input_map, + actual_input_map, + msg="\nexpected:\n%s\nvs actual:\n%s" % + (sorted(expected_input_map.items()), sorted(actual_input_map.items()))) + + def _VerifyMaxBatchSizeAnnotations( + self, + expected_engines, + original_gdef, + converted_gdef, + default_max_batch_size, + expected_max_batch_sizes=None, + ): + """Verifies the max batch size annotations in the original and converted GraphDef. + + Args: + expected_engines: A sequence of engines names. + original_gdef: GraphDef. The graph def before TensorRT conversion. + converted_gdef: GraphDef. The graph def after TensorRT conversion. + default_max_batch_size: The default maximum batch size to use if no node + inside a segment is annoted with a customized max batch size. This value + is None when the graph is converted to TF-TRT with dynamic engines. + expected_max_batch_sizes: Optional. A sequence of max batch sizes for all + the engines. `None` if does not check enforce max batch sizes. + """ + if isinstance(expected_max_batch_sizes, collections.abc.Collection): + self.assertEqual(len(expected_max_batch_sizes), len(expected_engines)) + else: + self.assertIsNone( + expected_max_batch_sizes, + "'expected_max_batch_sizes' shall only be a sequence " + "of integers or `None`.") + + def _ChainAllNodes(graph_def): + return itertools.chain( + graph_def.node, + itertools.chain( + *[func.node_def for func in graph_def.library.function])) + + old_name_to_node_map = { + self._ToString(node.name): node + for node in _ChainAllNodes(original_gdef) + } + new_name_to_func_map = { + self._ToString(func.signature.name): func + for func in converted_gdef.library.function + } + + def _DetectStaticBatchSize(node_def): + """Returns the static batch size of an operation or None. + + It is incorrect to use the output shapes to find the batch size of an + operation, as the segmenter actually uses the input shapes. However, it is + a simplication and works for most of the cases for the test purposes. + + Args: + node_def: `tf.NodeDef`. The target node for analysis. + + Returns: + If all the outputs of the node have the same static batch size, returns + the int value for the batch size. Otherwise returns None. + """ + shapes = node_def.attr["_output_shapes"].list.shape + batch_size = set( + list(s.dim)[0].size if len(s.dim) >= 2 else None for s in shapes) + if len(batch_size) == 1 and list(batch_size)[0] >= 1: + return list(batch_size)[0] + return None + + name_to_engines_map = {} + actual_max_batch_sizes = [] + for node in _ChainAllNodes(converted_gdef): + if node.op == "TRTEngineOp": + engine = node + engine_name = self._RemoveGraphSequenceNumber( + self._Canonicalize(self._ToString(engine.name))) + self.assertIn(engine_name, expected_engines) + name_to_engines_map[engine_name] = engine + # The input nodes shall not have the conflicting annotation (no + # annotation or the same annotation) with the maximum batch size + # annotation. If the engine has maximum batch size annotation as the + # non-default maximum batch size, then at least one input node shall + # have the same annotation to be the source. + self.assertIn("max_batch_size", node.attr) + engine_max_batch_size = node.attr["max_batch_size"].i + self.assertIsInstance(engine_max_batch_size, int) + actual_max_batch_sizes.append(engine_max_batch_size) + seg_func = node.attr["segment_func"].func + self.assertIsNotNone(seg_func) + self.assertIn(seg_func.name, new_name_to_func_map) + seg_func_def = new_name_to_func_map[seg_func.name] + logging.info("Segment function name: %s. Including %d nodes.", + seg_func.name, len(seg_func_def.node_def)) + node_max_batch_size_all_none = True + # Use the native segment to search for replaced nodes + for alternative_node in seg_func_def.node_def: + node_name = self._Canonicalize(self._ToString(alternative_node.name)) + if node_name not in old_name_to_node_map: + continue + original_node = old_name_to_node_map[node_name] + node_max_batch_size = None + if "_tftrt_op_max_batch_size" in original_node.attr: + node_max_batch_size = original_node.attr[ + "_tftrt_op_max_batch_size"].i + elif (original_node.op != "Const" and + alternative_node.op != "Const" and + "_output_shapes" in original_node.attr): + node_max_batch_size = _DetectStaticBatchSize(original_node) + logging.info( + "'{%s}(%s)'s max batch size annotation is %s. " + "'{%s}'s max batch size is %s.", node_name, original_node.op, + str(node_max_batch_size), engine_name, str(engine_max_batch_size)) + node_max_batch_size_all_none &= node_max_batch_size is None + self.assertTrue(engine_max_batch_size == node_max_batch_size or + node_max_batch_size is None) + logging.info("'{%s}'s max batch size is %d.", engine_name, + engine_max_batch_size) + self.assertTrue(default_max_batch_size is None or + engine_max_batch_size == default_max_batch_size or + not node_max_batch_size_all_none) + + self.assertCountEqual(expected_engines, tuple(name_to_engines_map.keys())) + if expected_max_batch_sizes is not None: + self.assertCountEqual(expected_max_batch_sizes, actual_max_batch_sizes) + + def _GetGraphDef(self, run_params, gdef_or_saved_model_dir): + if isinstance(gdef_or_saved_model_dir, str): + if run_params.is_v2: + root = load.load(gdef_or_saved_model_dir) + func = root.signatures[ + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] + gdef = func.graph.as_graph_def() + # Manually unref the loaded saved model and force GC to destroy the TRT + # engine cache after load(). There is currently a reference cycle in 2.0 + # which prevents auto deletion of the resource. + # TODO(laigd): fix this. + del func + del root + gc.collect() + return gdef + return saved_model_utils.get_meta_graph_def( + gdef_or_saved_model_dir, tag_constants.SERVING).graph_def + assert isinstance(gdef_or_saved_model_dir, graph_pb2.GraphDef), ( + f"Incorrect `gdef_or_saved_model_dir` type, expected " + f"`graph_pb2.GraphDef`, but got: {type(gdef_or_saved_model_dir)}.") + return gdef_or_saved_model_dir + + def _VerifyGraphDefV1(self, run_params, original_gdef, gdef_to_verify, + graph_state): + expected_engines = self.ExpectedEnginesToBuild(run_params) + num_engines = 0 + functions = [f.signature.name for f in gdef_to_verify.library.function] + for node in gdef_to_verify.node: + if node.op == "TRTEngineOp": + logging.info("Found TRTEngineOp: " + node.name) + num_engines += 1 + segment_funcdef_name = node.attr["segment_func"].func.name + function_name = node.name + "_native_segment" + is_dynamic_engine = not node.attr["static_engine"].b + self.assertNotEmpty(segment_funcdef_name, node.name) + self.assertIn(function_name, functions) + if (not IsQuantizationWithCalibration(run_params) and + not is_dynamic_engine): + self.assertTrue(len(node.attr["serialized_segment"].s), node.name) + self.assertIn( + self._RemoveGraphSequenceNumber(node.name), expected_engines) + if IsQuantizationWithoutCalibration(run_params): + # TODO(bixia): Refine this check by inspecting nodes in the engine. + if self._ToBytes("INT8") != node.attr["precision_mode"].s: + self.assertEqual( + self._ToBytes("FP16"), node.attr["precision_mode"].s, node.name) + else: + self.assertEqual( + self._ToBytes(run_params.precision_mode), + node.attr["precision_mode"].s, node.name) + + self.assertEqual(run_params.dynamic_engine, is_dynamic_engine, + node.name) + self.assertEqual(node.attr["use_calibration"].b, + run_params.use_calibration, node.name) + + has_calibration_data = len(node.attr["calibration_data"].s) + if (IsQuantizationWithCalibration(run_params) and + graph_state == GraphState.INFERENCE): + self.assertTrue(has_calibration_data, node.name) + else: + self.assertFalse(has_calibration_data, node.name) + if graph_state == GraphState.ORIGINAL: + self.assertEqual(0, num_engines) + else: + self.assertEqual(num_engines, len(expected_engines)) + expected_connections = self.ExpectedConnections(run_params) + if expected_connections: + self._VerifyConnections(expected_engines, expected_connections, + original_gdef, gdef_to_verify) + self._VerifyMaxBatchSizeAnnotations( + expected_engines=expected_engines, + original_gdef=original_gdef, + converted_gdef=gdef_to_verify, + expected_max_batch_sizes=self.ExpectedMaxBatchSizes(run_params), + default_max_batch_size=self.GetMaxBatchSize(run_params)) + + def _VerifyGraphDefV2(self, run_params, original_gdef, gdef_to_verify, + graph_state): + if graph_state == GraphState.ORIGINAL: + return + expected_engines = self.ExpectedEnginesToBuild(run_params) + all_op_names = [node.name for node in gdef_to_verify.node] + trt_op_names = [] + for func in gdef_to_verify.library.function: + if not re.search(r"TRTEngineOp_\d{3,}_\d{3,}_native_segment", + func.signature.name): + for node in func.node_def: + all_op_names.append(node.name) + if node.op == "TRTEngineOp": + trt_op_names.append(node.name) + if run_params.dynamic_shape: + self.assertEqual( + self._ToString(node.attr["profile_strategy"].s).lower(), + self._profile_strategy.lower()) + + all_op_names = self._Canonicalize(all_op_names) + trt_op_names = self._RemoveGraphSequenceNumber( + self._Canonicalize(trt_op_names)) + + if isinstance(expected_engines, dict): + # For simplicity we don't verify the connections inside the engine in + # 2.0, but we still make sure that the converted ops are gone from the + # graph. + unexpected_names = set(nest.flatten(expected_engines.values())) + self.assertEmpty( + [name for name in unexpected_names if name in all_op_names]) + expected_engines = set(expected_engines.keys()) + + self.assertEqual(set(expected_engines), trt_op_names) + + def _VerifyGraphDef(self, run_params, original_gdef_or_saved_model_dir, + gdef_or_saved_model_dir_to_verify, graph_state): + original_gdef = self._GetGraphDef(run_params, + original_gdef_or_saved_model_dir) + gdef_to_verify = self._GetGraphDef(run_params, + gdef_or_saved_model_dir_to_verify) + self._WriteGraph(run_params, gdef_to_verify, graph_state) + if run_params.is_v2: + self._VerifyGraphDefV2(run_params, original_gdef, gdef_to_verify, + graph_state) + else: + self._VerifyGraphDefV1(run_params, original_gdef, gdef_to_verify, + graph_state) + + def _GetSavedModelDir(self, run_params, graph_state): + test_tmpdir = os.getenv("TRT_TEST_TMPDIR") + if test_tmpdir: + saved_model_dir = os.path.join( + test_tmpdir, self.__class__.__name__ + "_" + run_params.test_name + + "_" + self._GetGraphStateLabel(graph_state)) + try: + # For TF 1.x we need to make sure the output directory doesn't exist + # before exporting the saved model. + shutil.rmtree(saved_model_dir) + except OSError as e: + if e.errno != errno.ENOENT: + raise + return saved_model_dir + return tempfile.mkdtemp(dir=self.get_temp_dir()) + + def _MakeSavedModelV1(self, run_params): + """Write the saved model as an input for testing.""" + params = self._GetParamsCached() + g = ops.Graph() + with g.as_default(): + inputs = [] + for spec in params.input_specs: + inp = array_ops.placeholder( + dtype=spec.dtype, shape=spec.shape, name=spec.name) + inputs.append(inp) + outputs = params.graph_fn(*inputs) + if not isinstance(outputs, list) and not isinstance(outputs, tuple): + outputs = [outputs] + + signature_def = signature_def_utils.build_signature_def( + inputs={inp.op.name: utils.build_tensor_info(inp) for inp in inputs}, + outputs={out.op.name: utils.build_tensor_info(out) for out in outputs}, + method_name=signature_constants.PREDICT_METHOD_NAME) + + saved_model_dir = self._GetSavedModelDir(run_params, GraphState.ORIGINAL) + saved_model_builder = builder.SavedModelBuilder(saved_model_dir) + with self.session( + graph=g, config=self._GetConfigProto(run_params, + GraphState.ORIGINAL)) as sess: + saved_model_builder.add_meta_graph_and_variables( + sess, [tag_constants.SERVING], + signature_def_map={ + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: + signature_def + }) + saved_model_builder.save() + return saved_model_dir + + def _MakeSavedModelV2(self, run_params): + params = self._GetParamsCached() + root = autotrackable.AutoTrackable() + root.run = def_function.function( + params.graph_fn, input_signature=params.input_specs) + saved_model_dir = self._GetSavedModelDir(run_params, GraphState.ORIGINAL) + logging.info("Saving input SavedModel to %s", saved_model_dir) + save.save(root, saved_model_dir, + {signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: root.run}) + return saved_model_dir + + def _MakeSavedModel(self, run_params): + if run_params.is_v2: + return self._MakeSavedModelV2(run_params) + return self._MakeSavedModelV1(run_params) + + def RunTest(self, run_params): + + with disable_tensorfloat32(): + with trace.Trace(run_params.test_name): + should_run, reason_for_skipping = self.ShouldRunTest(run_params) + if not should_run: + return self.skipTest(reason_for_skipping) + + saved_model_dir = self._MakeSavedModel(run_params) + + np.random.seed(12345) # Fix the seed so the test is deterministic. + inputs_data = [] + input_specs = self._GetParamsCached().input_specs + for dim_list in self._GetParamsCached().input_dims: + assert len(input_specs) == len(dim_list), ( + f"Inconsistent input_specs and dim_list: len({input_specs}) != " + f"len({dim_list}).") + current_input_data = [] + for spec, np_shape in zip(input_specs, dim_list): + np_dtype = spec.dtype.as_numpy_dtype() + if not np.issubdtype(np_dtype, np.bool_): + # Multiply the input by some constant to avoid all zeros input for + # integer types. + scale = 10.0 if np.issubdtype(np_dtype, np.integer) else 1.0 + data = (scale * + np.random.random_sample(np_shape)).astype(np_dtype) + else: + data = np.random.choice(a=[False, True], size=np_shape) + + if run_params.is_v2: + with ops.device("/GPU:0"): + data = ops.convert_to_tensor(data) + current_input_data.append(data) + inputs_data.append(current_input_data) + + # Verify the original graph. + self._VerifyGraphDef(run_params, saved_model_dir, saved_model_dir, + GraphState.ORIGINAL) + + # Run the original graph without TensorRT to get the reference result. + logging.info("Running original graph w/o TensorRT\n") + ref_result = self._RunGraph( + run_params, + saved_model_dir, + inputs_data, + GraphState.ORIGINAL, + num_runs=1) + + # Run calibration if necessary. + if IsQuantizationWithCalibration(run_params): + infer_saved_model_dir = self._GetCalibratedInferGraph( + run_params, saved_model_dir, inputs_data) + self._VerifyGraphDef(run_params, saved_model_dir, + infer_saved_model_dir, GraphState.INFERENCE) + elif not run_params.convert_online: + infer_saved_model_dir = self._GetInferGraph(run_params, + saved_model_dir) + self._VerifyGraphDef(run_params, saved_model_dir, + infer_saved_model_dir, GraphState.INFERENCE) + else: + infer_saved_model_dir = saved_model_dir + + # Run the inference graph, either using the converted graph or the + # original graph with convert_online == True. + logging.info("Running final inference graph\n") + result = self._RunGraph(run_params, infer_saved_model_dir, inputs_data, + GraphState.INFERENCE) + self.assertAllClose( + ref_result, + result, + atol=self.ExpectedAbsoluteTolerance(run_params), + rtol=self.ExpectedRelativeTolerance(run_params)) + + def testIdempotence(self): + # Test that applying tensorrt optimizer or offline conversion tools multiple + # times to the same graph will result in same graph. + # + # TODO(aaroey): implement this. + pass + + +def _GetTestConfigsV1(): + """Returns the config combinations to run the test.""" + convert_online, convert_offline = True, False + dynamic_engine, static_engine = True, False + use_calibration, no_calibration = True, False + implicit_batch = False + + # Add all possible test cases and let the derived test class to decide + # whether to run specific ones with ShouldRunTest(). + # + # Note: INT8 without calibration behaves like FP32/FP16. + opts = list( + itertools.product([FP32, FP16, INT8], [convert_online, convert_offline], + [dynamic_engine, static_engine], [no_calibration], + [implicit_batch])) + # We always run calibration with offline tool. + # TODO(aaroey): static calibration engine is not supported yet. + opts.append( + (INT8, convert_offline, dynamic_engine, use_calibration, implicit_batch)) + return opts + + +def _GetTestConfigsV2(): + """Returns the config combinations to run the test.""" + convert_offline = False + # TODO(laigd): add support for static_engine. + dynamic_engine = True + # TODO(laigd): add support for calibration. + no_calibration = False + use_calibration = True + + # Add all possible test cases and let the derived test class to decide + # whether to run specific ones with ShouldRunTest(). + # + # Note: + # - In TF2.0 the conversion always produce dynamic engine, and we don't test + # the offline mode here. + # - For simplicity we don't test online conversion which requires setting the + # Grappler config in default eager context. + # - INT8 without calibration behaves like FP32/FP16. + opts = list( + itertools.product([FP32, FP16], [convert_offline], [dynamic_engine], + [no_calibration], [False, True])) + # We always run calibration with offline tool. + opts.append((INT8, convert_offline, dynamic_engine, use_calibration, False)) + opts.append((INT8, convert_offline, dynamic_engine, use_calibration, True)) + return opts + + +def _GetTest(run_params): + """Gets a single test method based on the parameters.""" + + def _Test(self): + logging.info(f"Running test `{run_params.test_name}` with parameters: " + f"convert_online={run_params.convert_online}, " + f"precision_mode={run_params.precision_mode}, " + f"dynamic_engine={run_params.dynamic_engine}, " + f"dynamic_shape={run_params.dynamic_shape}") + self.RunTest(run_params) + + return _Test + + +def _AddTestsFor(test_class, is_v2): + """Adds test methods to TfTrtIntegrationTestBase for specific TF version.""" + opts = _GetTestConfigsV2() if is_v2 else _GetTestConfigsV1() + for (precision_mode, convert_online, dynamic_engine, use_calibration, + dynamic_shape) in opts: + conversion = "OnlineConversion" if convert_online else "OfflineConversion" + engine_type = "DynamicEngine" if dynamic_engine else "StaticEngine" + calibration_type = "UseCalibration" if use_calibration else "NoCalibration" + dynamic_shape_type = "DynamicShape" if dynamic_shape else "ImplicitBatch" + test_name = "%s_%s_%s_%s_%s_%s" % ("testTfTrtV2" if is_v2 else "testTfTrt", + conversion, engine_type, precision_mode, + calibration_type, dynamic_shape_type) + run_params = RunParams( + convert_online=convert_online, + precision_mode=precision_mode, + dynamic_engine=dynamic_engine, + test_name=test_name, + use_calibration=use_calibration, + is_v2=is_v2, + dynamic_shape=dynamic_shape) + if is_v2: + setattr(test_class, test_name, + test_util.run_v2_only(_GetTest(run_params))) + else: + setattr(test_class, test_name, + test_util.run_v1_only("", _GetTest(run_params))) + + +def _AddTests(test_class): + """Adds test methods to TfTrtIntegrationTestBase.""" + _AddTestsFor(test_class, is_v2=False) + _AddTestsFor(test_class, is_v2=True) + + +if is_tensorrt_enabled(): + os.environ["TF_TRT_ALLOW_ENGINE_NATIVE_SEGMENT_EXECUTION"] = "False" + _AddTests(TfTrtIntegrationTestBase) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/trt_convert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/trt_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..746f910e4070bda710a503e98abefae46b93b1a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/trt_convert.py @@ -0,0 +1,1855 @@ +# 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. +# ============================================================================= +"""Exposes the Python wrapper conversion to trt_graph.""" + +import collections +from functools import partial # pylint: disable=g-importing-member +import os +import platform +import sys +import tempfile + +import numpy as np +import six as _six + +from tensorflow.core.framework import variable_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.client import session +from tensorflow.python.compiler.tensorrt import utils as trt_utils +from tensorflow.python.eager import context +from tensorflow.python.eager import wrap_function +from tensorflow.python.framework import convert_to_constants +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import importer +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.grappler import tf_optimizer +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import builder +from tensorflow.python.saved_model import load +from tensorflow.python.saved_model import loader +from tensorflow.python.saved_model import save +from tensorflow.python.saved_model import signature_constants +from tensorflow.python.saved_model import tag_constants +from tensorflow.python.trackable import asset +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import resource +from tensorflow.python.training import saver +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util.lazy_loader import LazyLoader +from tensorflow.python.util.tf_export import tf_export + +# Lazily load the op, since it's not available in cpu-only builds. Importing +# this at top will cause tests that imports TF-TRT fail when they're built +# and run without CUDA/GPU. +gen_trt_ops = LazyLoader( + "gen_trt_ops", globals(), + "tensorflow.compiler.tf2tensorrt.ops.gen_trt_ops") + +_pywrap_py_utils = LazyLoader( + "_pywrap_py_utils", globals(), + "tensorflow.compiler.tf2tensorrt._pywrap_py_utils") + +# Register TRT ops in python, so that when users import this module they can +# execute a TRT-converted graph without calling any of the methods in this +# module. +# +# This will call register_op_list() in +# tensorflow/python/framework/op_def_registry.py, but it doesn't register +# the op or the op kernel in C++ runtime. +try: + gen_trt_ops.trt_engine_op # pylint: disable=pointless-statement +except AttributeError: + pass + + +def _to_bytes(s): + """Encode s if it is a sequence of chars.""" + if isinstance(s, _six.text_type): + return s.encode("utf-8", errors="surrogateescape") + return s + + +def _to_string(s): + """Decode s if it is a sequence of bytes.""" + if isinstance(s, _six.binary_type): + return s.decode("utf-8") + return s + + +class TrtPrecisionMode(object): + FP32 = "FP32" + FP16 = "FP16" + INT8 = "INT8" + + @staticmethod + def supported_precision_modes(): + precisions = [ + TrtPrecisionMode.FP32, TrtPrecisionMode.FP16, TrtPrecisionMode.INT8 + ] + return precisions + [p.lower() for p in precisions] + + +# Use a large enough number as the default max_workspace_size for TRT engines, +# so it can produce reasonable performance results with the default. +# For TRT >= 8.4, the recommendation is MAX_INT. +if (_pywrap_py_utils.is_tensorrt_enabled() and + trt_utils.is_loaded_tensorrt_version_greater_equal(8, 4, 0)): + # We must use `sys.maxsize - 512` to avoid overflow during casting. + DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES = sys.maxsize - 512 +else: + DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES = 1 << 30 # 1,073,741,824 + +PROFILE_STRATEGY_RANGE = "Range" +PROFILE_STRATEGY_OPTIMAL = "Optimal" +PROFILE_STRATEGY_RANGE_OPTIMAL = "Range+Optimal" +PROFILE_STRATEGY_IMPLICIT_BATCH_MODE_COMPATIBLE = "ImplicitBatchModeCompatible" + + +def supported_profile_strategies(): + return [ + PROFILE_STRATEGY_RANGE, PROFILE_STRATEGY_OPTIMAL, + PROFILE_STRATEGY_RANGE_OPTIMAL, + PROFILE_STRATEGY_IMPLICIT_BATCH_MODE_COMPATIBLE + ] + + +@tf_export("experimental.tensorrt.ConversionParams", v1=[]) +class TrtConversionParams( + collections.namedtuple("TrtConversionParams", [ + "max_workspace_size_bytes", "precision_mode", "minimum_segment_size", + "maximum_cached_engines", "use_calibration", "allow_build_at_runtime" + ])): + """Parameters that are used for TF-TRT conversion. + + Fields: + max_workspace_size_bytes: the maximum GPU temporary memory that the TRT + engine can use at execution time. This corresponds to the + 'workspaceSize' parameter of nvinfer1::IBuilder::setMaxWorkspaceSize(). + precision_mode: one of the strings in + TrtPrecisionMode.supported_precision_modes(). + minimum_segment_size: the minimum number of nodes required for a subgraph + to be replaced by TRTEngineOp. + maximum_cached_engines: max number of cached TRT engines for dynamic TRT + ops. Created TRT engines for a dynamic dimension are cached. If the + number of cached engines is already at max but none of them supports the + input shapes, the TRTEngineOp will fall back to run the original TF + subgraph that corresponds to the TRTEngineOp. + use_calibration: this argument is ignored if precision_mode is not INT8. + If set to True, a calibration graph will be created to calibrate the + missing ranges. The calibration graph must be converted to an inference + graph by running calibration with calibrate(). If set to False, + quantization nodes will be expected for every tensor in the graph + (excluding those which will be fused). If a range is missing, an error + will occur. Please note that accuracy may be negatively affected if + there is a mismatch between which tensors TRT quantizes and which + tensors were trained with fake quantization. + allow_build_at_runtime: whether to allow building TensorRT engines during + runtime if no prebuilt TensorRT engine can be found that can handle the + given inputs during runtime, then a new TensorRT engine is built at + runtime if allow_build_at_runtime=True, and otherwise native TF is used. + """ + + def __new__(cls, + max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES, + precision_mode=TrtPrecisionMode.FP32, + minimum_segment_size=3, + maximum_cached_engines=1, + use_calibration=True, + allow_build_at_runtime=True): + return super(TrtConversionParams, + cls).__new__(cls, max_workspace_size_bytes, precision_mode, + minimum_segment_size, maximum_cached_engines, + use_calibration, allow_build_at_runtime) + + +DEFAULT_TRT_CONVERSION_PARAMS = TrtConversionParams() + +_TRT_ENGINE_OP_NAME = "TRTEngineOp" + + +def _check_conversion_params(conversion_params, is_v2=False): + """Validate the provided TrtConversionParams. + + Args: + conversion_params: a TrtConversionParams instance. + is_v2: whether we're getting a RewriterConfig for TF 2.0. + + Raises: + TypeError: if any of the parameters are of unexpected type. + ValueError: if any of the parameters are of unexpected value. + """ + supported_precision_modes = TrtPrecisionMode.supported_precision_modes() + if conversion_params.precision_mode not in supported_precision_modes: + raise ValueError( + ("precision mode '{}' is not supported." + "It should be one of {}").format(conversion_params.precision_mode, + supported_precision_modes)) + if (conversion_params.minimum_segment_size <= 0 and + conversion_params.minimum_segment_size != -1): + raise ValueError("minimum segment size should be positive or -1 " + "(to disable main graph conversion).") + + +def _check_trt_version_compatibility(): + """Check compatibility of TensorRT version. + + Raises: + RuntimeError: if the TensorRT library version is incompatible. + """ + + if not _pywrap_py_utils.is_tensorrt_enabled(): + logging.error( + "Tensorflow needs to be built with TensorRT support enabled to allow " + "TF-TRT to operate.") + + raise RuntimeError("Tensorflow has not been built with TensorRT support.") + + if platform.system() == "Windows": + logging.warn( + "Windows support is provided experimentally. No guarantee is made " + "regarding functionality or engineering support. Use at your own risk.") + + linked_version = _pywrap_py_utils.get_linked_tensorrt_version() + loaded_version = _pywrap_py_utils.get_loaded_tensorrt_version() + + logging.info("Linked TensorRT version: %s", str(linked_version)) + logging.info("Loaded TensorRT version: %s", str(loaded_version)) + + def raise_trt_version_deprecated(version_type, trt_version): + assert version_type in [ + "linked", "loaded" + ], ("Incorrect value received for version_type: %s. Accepted: ['linked', " + "'loaded']") % version_type + + logging.error( + "The {version_type} version of TensorRT: `{trt_version}` has now " + "been removed. Please upgrade to TensorRT 7 or more recent.".format( + version_type=version_type, + trt_version=trt_utils.version_tuple_to_string(trt_version))) + + raise RuntimeError("Incompatible %s TensorRT versions" % version_type) + + if not trt_utils.is_linked_tensorrt_version_greater_equal(7, 0, 0): + raise_trt_version_deprecated("linked", linked_version) + + if not trt_utils.is_loaded_tensorrt_version_greater_equal(7, 0, 0): + raise_trt_version_deprecated("loaded", loaded_version) + + if (loaded_version[0] != linked_version[0] or + not trt_utils.is_loaded_tensorrt_version_greater_equal(*linked_version)): + logging.error( + "Loaded TensorRT %s but linked TensorFlow against TensorRT %s. A few " + "requirements must be met:\n" + "\t-It is required to use the same major version of TensorRT during " + "compilation and runtime.\n" + "\t-TensorRT does not support forward compatibility. The loaded " + "version has to be equal or more recent than the linked version.", + trt_utils.version_tuple_to_string(loaded_version), + trt_utils.version_tuple_to_string(linked_version)) + raise RuntimeError("Incompatible TensorRT major version") + + elif loaded_version != linked_version: + logging.info( + "Loaded TensorRT %s and linked TensorFlow against TensorRT %s. This is " + "supported because TensorRT minor/patch upgrades are backward " + "compatible.", trt_utils.version_tuple_to_string(loaded_version), + trt_utils.version_tuple_to_string(linked_version)) + + +def _get_tensorrt_rewriter_config(conversion_params, + is_dynamic_op=None, + max_batch_size=None, + is_v2=False, + disable_non_trt_optimizers=False, + use_implicit_batch=True, + profile_strategy=PROFILE_STRATEGY_RANGE): + """Returns a RewriterConfig proto for TRT transformation. + + Args: + conversion_params: a TrtConversionParams instance. + is_dynamic_op: whether to use dynamic engines. + max_batch_size: maximum batch size for static engines. + is_v2: whether we're getting a RewriterConfig for TF 2.0. + disable_non_trt_optimizers: Turn off all default Grappler optimizers. + use_implicit_batch: Whether to use implicit batch or explicit batch. + profile_strategy: dynamic shape optimization profile strategy. + + Returns: + A RewriterConfig proto which sets a TensorRTOptimizer to run Grappler. + + Raises: + TypeError: if any of the parameters are of unexpected type. + ValueError: if any of the parameters are of unexpected value. + """ + _check_conversion_params(conversion_params, is_v2=is_v2) + if is_v2 and is_dynamic_op is not None and not is_dynamic_op: + raise ValueError("is_dynamic_op is either None or True for TF2") + if not is_v2 and is_dynamic_op is None: + raise ValueError("is_dynamic_op can't be None for TF1") + + if (is_dynamic_op is None or is_dynamic_op) and max_batch_size is not None: + raise ValueError("max_batch_size has to be None for TF2" + " or when is_dynamic_op == True in TF1") + if is_dynamic_op is not None and not is_dynamic_op and not isinstance( + max_batch_size, int): + raise ValueError( + "max_batch_size has to be an integer for is_dynamic_op==False in TF1") + rewriter_config_with_trt = rewriter_config_pb2.RewriterConfig() + # Disable Grappler Remapper to avoid that fused OPs that may not be + # beneficial to TF-TRT and are not supported by TF-TRT. + rewriter_config_with_trt.remapping = False + + # Prevent folding of Const->QDQ chains. + rewriter_config_with_trt. \ + experimental_disable_folding_quantization_emulation = ( + trt_utils.is_linked_tensorrt_version_greater_equal(8, 0, 0) or + trt_utils.is_loaded_tensorrt_version_greater_equal(8, 0, 0)) + + if not disable_non_trt_optimizers: + rewriter_config_with_trt.optimizers.extend([ + "pruning", "debug_stripper", "layout", "dependency", "constfold", + "common_subgraph_elimination" + ]) + + rewriter_config_with_trt.meta_optimizer_iterations = ( + rewriter_config_pb2.RewriterConfig.ONE) + optimizer = rewriter_config_with_trt.custom_optimizers.add() + + if not disable_non_trt_optimizers: + # Add a constfold optimizer to cleanup the unused Const nodes. + rewriter_config_with_trt.custom_optimizers.add().name = "constfold" + + optimizer.name = "TensorRTOptimizer" + optimizer.parameter_map[ + "minimum_segment_size"].i = conversion_params.minimum_segment_size + optimizer.parameter_map["max_workspace_size_bytes"].i = ( + conversion_params.max_workspace_size_bytes) + optimizer.parameter_map["precision_mode"].s = _to_bytes( + conversion_params.precision_mode) + optimizer.parameter_map[ + "maximum_cached_engines"].i = conversion_params.maximum_cached_engines + optimizer.parameter_map[ + "use_calibration"].b = conversion_params.use_calibration + optimizer.parameter_map["is_dynamic_op"].b = is_dynamic_op + optimizer.parameter_map[ + "allow_build_at_runtime"].b = conversion_params.allow_build_at_runtime + if max_batch_size is not None: + optimizer.parameter_map["max_batch_size"].i = max_batch_size + optimizer.parameter_map["use_implicit_batch"].b = use_implicit_batch + # While we accept case insensitive strings from the users, we only pass the + # strings in lower cases to TF-TRT converter. + if not use_implicit_batch: + optimizer.parameter_map["profile_strategy"].s = _to_bytes( + profile_strategy.lower()) + + # Disabling optimizers should happen after defining the TF-TRT grappler pass + # otherwise the template can overwrite the disablement. + if disable_non_trt_optimizers: + trt_utils.disable_non_trt_optimizers_in_rewriter_config( + rewriter_config_with_trt) + + return rewriter_config_with_trt + + +@deprecation.deprecated( + None, "You shouldn't need a rewriter_config with the current TF-TRT APIs.") +def get_tensorrt_rewriter_config(conversion_params, + is_dynamic_op=None, + max_batch_size=None, + is_v2=False, + disable_non_trt_optimizers=False): + return _get_tensorrt_rewriter_config(conversion_params, is_dynamic_op, + max_batch_size, is_v2, + disable_non_trt_optimizers) + + +# Remove all scope prefixes in the node name. In TF 2.0, the same concrete +# function can be initialized multiple times with different prefixes, and +# this will result in the same TRTEngineOp being initialized multiple times +# with different cache and duplicate TRT engines. +# TODO(laigd): this may be caused by the fact that TRTEngineOp is not +# stateful, need to investigate. +# TODO(laigd): we rely on the fact that all functions are fully inlined +# before TF-TRT optimizer is called, as otherwise it may generate the same +# name when optimizing a different function graph. Fix this. +def _get_canonical_engine_name(name): + return name.split("/")[-1] + + +class TrtGraphConverter(object): + """A converter for TF-TRT transformation for TF 1.x GraphDef/SavedModels. + + To run the conversion without quantization calibration (e.g. for FP32/FP16 + precision modes): + + ```python + converter = TrtGraphConverter( + input_saved_model_dir="my_dir", + precision_mode=TrtPrecisionMode.FP16) + converted_graph_def = converter.convert() + converter.save(output_saved_model_dir) + ``` + + To run the conversion with quantization calibration: + + ```python + converter = TrtGraphConverter( + input_saved_model_dir="my_dir", + precision_mode=TrtPrecisionMode.INT8) + converter.convert() + + # Run calibration 10 times. + converted_graph_def = converter.calibrate( + fetch_names=['output:0'], + num_runs=10, + feed_dict_fn=lambda: {'input:0': my_next_data()}) + + converter.save(output_saved_model_dir) + ``` + """ + + def __init__(self, + input_saved_model_dir=None, + input_saved_model_tags=None, + input_saved_model_signature_key=None, + input_graph_def=None, + nodes_denylist=None, + max_batch_size=1, + max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES, + precision_mode=TrtPrecisionMode.FP32, + minimum_segment_size=3, + is_dynamic_op=False, + maximum_cached_engines=1, + use_calibration=True): + """Initializes the converter. + + Args: + input_saved_model_dir: the directory to load the SavedModel which contains + the input graph to transforms. Used only when input_graph_def is None. + input_saved_model_tags: list of tags to load the SavedModel. + input_saved_model_signature_key: the key of the signature to optimize the + graph for. + input_graph_def: a GraphDef object containing a model to be transformed. + If set to None, the graph will be read from the SavedModel loaded from + input_saved_model_dir. + nodes_denylist: list of node names to prevent the converter from touching. + max_batch_size: max size for the input batch. + max_workspace_size_bytes: the maximum GPU temporary memory which the TRT + engine can use at execution time. This corresponds to the + 'workspaceSize' parameter of nvinfer1::IBuilder::setMaxWorkspaceSize(). + precision_mode: one of TrtPrecisionMode.supported_precision_modes(). + minimum_segment_size: the minimum number of nodes required for a subgraph + to be replaced by TRTEngineOp. + is_dynamic_op: whether to generate dynamic TRT ops which will build the + TRT network and engine at run time. + maximum_cached_engines: max number of cached TRT engines in dynamic TRT + ops. If the number of cached engines is already at max but none of them + can serve the input, the TRTEngineOp will fall back to run the TF + function based on which the TRTEngineOp is created. + use_calibration: this argument is ignored if precision_mode is not INT8. + If set to True, a calibration graph will be created to calibrate the + missing ranges. The calibration graph must be converted to an inference + graph by running calibration with calibrate(). If set to False, + quantization nodes will be expected for every tensor in the graph + (excluding those which will be fused). If a range is missing, an error + will occur. Please note that accuracy may be negatively affected if + there is a mismatch between which tensors TRT quantizes and which + tensors were trained with fake quantization. + + Raises: + ValueError: if the combination of the parameters is invalid. + RuntimeError: if this class is used in TF 2.0. + """ + if context.executing_eagerly(): + raise RuntimeError( + "Please use tf.experimental.tensorrt.Converter in TF 2.0.") + + if input_graph_def and input_saved_model_dir: + raise ValueError( + "Can only specify one of input_graph_def and input_saved_model_dir") + if not input_graph_def and not input_saved_model_dir: + raise ValueError("Must specify one of input_graph_def and " + "input_saved_model_dir") + _check_trt_version_compatibility() + + self._input_graph_def = input_graph_def + self._nodes_denylist = nodes_denylist + + self._input_saved_model_dir = input_saved_model_dir + self._converted = False + self._grappler_meta_graph_def = None + + self._input_saved_model_tags = ( + input_saved_model_tags or [tag_constants.SERVING]) + self._input_saved_model_signature_key = ( + input_saved_model_signature_key or + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY) + + # For calibration usage. + self._calibration_graph = None + self._calibration_data_collected = False + self._need_calibration = ( + ((precision_mode == TrtPrecisionMode.INT8) or + (precision_mode == TrtPrecisionMode.INT8.lower())) and use_calibration) + if self._need_calibration and not is_dynamic_op: + logging.warn( + "INT8 precision mode with calibration is supported with " + "dynamic TRT ops only. Disregarding is_dynamic_op parameter.") + is_dynamic_op = True + + self._is_dynamic_op = is_dynamic_op + if is_dynamic_op: + self._max_batch_size = None + if max_batch_size is not None: + logging.warn("When is_dynamic_op==True max_batch_size should be None") + else: + if not isinstance(max_batch_size, int): + raise ValueError("When is_dynamic_op==False max_batch_size should be " + "an integer") + self._max_batch_size = max_batch_size + + self._conversion_params = TrtConversionParams( + max_workspace_size_bytes=max_workspace_size_bytes, + precision_mode=precision_mode, + minimum_segment_size=minimum_segment_size, + maximum_cached_engines=maximum_cached_engines, + use_calibration=use_calibration, + allow_build_at_runtime=True) + _check_conversion_params(self._conversion_params) + + self._test_only_disable_non_trt_optimizers = False + + def _run_conversion(self): + """Run Grappler's OptimizeGraph() tool to convert the graph.""" + # Create custom ConfigProto for Grappler. + grappler_session_config = config_pb2.ConfigProto() + custom_rewriter_config = _get_tensorrt_rewriter_config( + conversion_params=self._conversion_params, + is_dynamic_op=self._is_dynamic_op, + max_batch_size=self._max_batch_size, + disable_non_trt_optimizers=self._test_only_disable_non_trt_optimizers, + use_implicit_batch=True) + grappler_session_config.graph_options.rewrite_options.CopyFrom( + custom_rewriter_config) + + # Run Grappler. + self._converted_graph_def = tf_optimizer.OptimizeGraph( + grappler_session_config, + self._grappler_meta_graph_def, + graph_id=b"tf_graph") + self._converted = True + + def _add_nodes_denylist(self): + if self._nodes_denylist: + collection_def = self._grappler_meta_graph_def.collection_def["train_op"] + denylist = collection_def.node_list.value + for i in self._nodes_denylist: + if isinstance(i, tensor.Tensor): + denylist.append(_to_bytes(i.name)) + else: + denylist.append(_to_bytes(i)) + + def _convert_graph_def(self): + """Convert the input GraphDef.""" + graph = ops.Graph() + with graph.as_default(): + importer.import_graph_def(self._input_graph_def, name="") + self._grappler_meta_graph_def = saver.export_meta_graph( + graph_def=graph.as_graph_def(add_shapes=True), graph=graph) + self._add_nodes_denylist() + + self._run_conversion() + + def _collections_to_keep(self, collection_keys): + # TODO(laigd): currently we use the collection key to filter out + # collections that depend on variable ops, but this may miss some + # other user-defined collections. A better way would be to use + # CollectionDef::NodeList for the filtering. + collections_to_remove = ( + ops.GraphKeys._VARIABLE_COLLECTIONS + [ + ops.GraphKeys.TRAIN_OP, ops.GraphKeys.WHILE_CONTEXT, + ops.GraphKeys.COND_CONTEXT + ]) + return [key for key in collection_keys if key not in collections_to_remove] + + def _convert_saved_model(self): + """Convert the input SavedModel.""" + graph = ops.Graph() + with session.Session(graph=graph) as sess: + input_meta_graph_def = loader.load(sess, self._input_saved_model_tags, + self._input_saved_model_dir) + input_signature_def = input_meta_graph_def.signature_def[ + self._input_saved_model_signature_key] + + def _gather_names(tensor_info): + """Get the node names from a TensorInfo.""" + return {tensor_info[key].name.split(":")[0] for key in tensor_info} + + # Get input and outputs from all SignatureDef. + output_node_names = _gather_names(input_signature_def.inputs).union( + _gather_names(input_signature_def.outputs)) + + # Preserve nodes in collection + for collection_key in self._collections_to_keep( + input_meta_graph_def.collection_def): + for op in sess.graph.get_collection(collection_key): + if isinstance(op, ops.Operation): + output_node_names.add(op.name.split(":")[0]) + + # Freeze the variables in the SavedModel graph and copy the frozen + # graph over. + frozen_graph_def = convert_to_constants.convert_variables_to_constants( + sess, sess.graph.as_graph_def(add_shapes=True), + list(output_node_names)) + self._grappler_meta_graph_def = meta_graph_pb2.MetaGraphDef() + self._grappler_meta_graph_def.graph_def.CopyFrom(frozen_graph_def) + + # Copy the collections that are not variables. + for collection_key in self._collections_to_keep( + input_meta_graph_def.collection_def): + self._grappler_meta_graph_def.collection_def[collection_key].CopyFrom( + input_meta_graph_def.collection_def[collection_key]) + + self._add_nodes_denylist() + + # Copy other information. + self._grappler_meta_graph_def.meta_info_def.CopyFrom( + input_meta_graph_def.meta_info_def) + self._grappler_meta_graph_def.signature_def[ + self._input_saved_model_signature_key].CopyFrom(input_signature_def) + # TODO(laigd): maybe add back AssetFileDef. + + self._run_conversion() + + def convert(self): + """Run the TF-TRT conversion. + + Returns: + The converted GraphDef for TF 1.x. + """ + assert not self._converted + if self._input_graph_def: + self._convert_graph_def() + else: + self._convert_saved_model() + return self._converted_graph_def + + def calibrate(self, + fetch_names, + num_runs, + feed_dict_fn=None, + input_map_fn=None): + """Run the calibration and return the calibrated GraphDef. + + Args: + fetch_names: a list of output tensor name to fetch during calibration. + num_runs: number of runs of the graph during calibration. + feed_dict_fn: a function that returns a dictionary mapping input names (as + strings) in the GraphDef to be calibrated to values (e.g. Python list, + numpy arrays, etc). One and only one of `feed_dict_fn` and + `input_map_fn` should be specified. + input_map_fn: a function that returns a dictionary mapping input names (as + strings) in the GraphDef to be calibrated to Tensor objects. The values + of the named input tensors in the GraphDef to be calibrated will be + re-mapped to the respective `Tensor` values during calibration. One and + only one of `feed_dict_fn` and `input_map_fn` should be specified. + + Raises: + ValueError: if the input combination is invalid. + RuntimeError: if this method is called in eager mode. + + Returns: + The GraphDef after the calibration. + """ + assert self._converted + assert self._need_calibration + assert not self._calibration_data_collected + + if (feed_dict_fn and input_map_fn) or (not feed_dict_fn and + not input_map_fn): + raise ValueError( + "Should specify one and only one of feed_dict_fn and input_map_fn.") + + if input_map_fn: + for k, v in input_map_fn().items(): + if not isinstance(k, str): + raise ValueError("Keys of input_map_fn must be of type str") + if not isinstance(v, tensor.Tensor): + raise ValueError("Values of input_map_fn must be of type tf.Tensor") + + self._calibration_graph = ops.Graph() + with self._calibration_graph.as_default(): + fetches = importer.import_graph_def( + self._converted_graph_def, + input_map=input_map_fn() if input_map_fn else None, + return_elements=fetch_names, + name="") + + calibrate_rewriter_cfg = rewriter_config_pb2.RewriterConfig() + if self._test_only_disable_non_trt_optimizers: + trt_utils.disable_non_trt_optimizers_in_rewriter_config( + calibrate_rewriter_cfg) + + # Set allow_soft_placement=True to run the graph for calibration so that + # OPs supported by TensorRT but don't have a GPU implementation are allowed + # to execute on CPU. + calibrate_config = config_pb2.ConfigProto( + allow_soft_placement=True, + graph_options=config_pb2.GraphOptions( + rewrite_options=calibrate_rewriter_cfg)) + + with session.Session( + graph=self._calibration_graph, + config=calibrate_config) as calibration_sess: + for _ in range(num_runs): + calibration_sess.run( + fetches, feed_dict=feed_dict_fn() if feed_dict_fn else None) + + # Maps device name to the corresponding get_calibration_data. + # + # TODO(laigd): a better way would be to use calibration_sess to list + # all the devices, add one get_calibration_data for each device, and + # fetch each such op for every resource until its found. This can work + # even when the device of the TRTEngineOp is empty or not fully specified. + device_to_get_resource_op_map = {} + + with self._calibration_graph.as_default(): + resource_name_input = array_ops.placeholder(dtypes.string) + + for node in self._converted_graph_def.node: + if node.op == _TRT_ENGINE_OP_NAME: + # Adds the get_calibration_data op for the device if not done + # before. We only add one such op for each device. + # TODO(laigd): What if the device is empty????? + if node.device not in device_to_get_resource_op_map: + with self._calibration_graph.device(node.device): + serialized_resources_output = ( + gen_trt_ops.get_calibration_data_op(resource_name_input)) + device_to_get_resource_op_map[node.device] = ( + serialized_resources_output) + + # Get the calibration resource. + calibration_result = calibration_sess.run( + device_to_get_resource_op_map[node.device], + feed_dict={ + resource_name_input: _get_canonical_engine_name(node.name) + }) + node.attr["calibration_data"].s = calibration_result + + self._calibration_data_collected = True + + return self._converted_graph_def + + def save(self, output_saved_model_dir): + """Save the converted graph as a SavedModel. + + Args: + output_saved_model_dir: construct a SavedModel using the converted + GraphDef and save it to the specified directory. This option only works + when the input graph is loaded from a SavedModel, i.e. when + input_saved_model_dir is specified and input_graph_def is None in + __init__(). + + Raises: + ValueError: if the input to the converter is a GraphDef instead of a + SavedModel. + """ + assert self._converted + if self._need_calibration: + assert self._calibration_data_collected + if self._input_graph_def: + raise ValueError( + "Not able to save to a SavedModel since input is a GraphDef") + + def _restore_collections(dest_graph, src_meta_graph_def, collection_keys): + """Restores collections that we need to keep.""" + scope = "" + for key in collection_keys: + collection_def = src_meta_graph_def.collection_def[key] + kind = collection_def.WhichOneof("kind") + if kind is None: + logging.error( + "Cannot identify data type for collection %s. Skipping.", key) + continue + from_proto = ops.get_from_proto_function(key) + if from_proto and kind == "bytes_list": + proto_type = ops.get_collection_proto_type(key) + # It is assumed that there are no Variables Keys in collections + for value in collection_def.bytes_list.value: + proto = proto_type() + proto.ParseFromString(value) + try: + new_value = from_proto(proto, import_scope=scope) + except: + continue + dest_graph.add_to_collection(key, new_value) + else: + field = getattr(collection_def, kind) + if kind == "node_list": + for value in field.value: + name = ops.prepend_name_scope(value, scope) + # Since the graph has been optimized, the node may no longer + # exists + try: + col_op = dest_graph.as_graph_element(name) + except (TypeError, ValueError, KeyError): + continue + dest_graph.add_to_collection(key, col_op) + elif kind == "int64_list": + # NOTE(opensource): This force conversion is to work around the + # fact that Python2 distinguishes between int and long, while + # Python3 has only int. + for value in field.value: + dest_graph.add_to_collection(key, int(value)) + else: + for value in field.value: + dest_graph.add_to_collection(key, + ops.prepend_name_scope(value, scope)) + + # Write the transformed graphdef as SavedModel. + saved_model_builder = builder.SavedModelBuilder(output_saved_model_dir) + with ops.Graph().as_default(): + importer.import_graph_def(self._converted_graph_def, name="") + _restore_collections( + ops.get_default_graph(), self._grappler_meta_graph_def, + self._collections_to_keep( + self._grappler_meta_graph_def.collection_def)) + # We don't use any specific converter here. + with session.Session() as sess: + saved_model_builder.add_meta_graph_and_variables( + sess, + self._input_saved_model_tags, + signature_def_map=self._grappler_meta_graph_def.signature_def) + # Ignore other meta graphs from the input SavedModel. + saved_model_builder.save() + +def _get_resource_handle(name, device): + with ops.device(device): + return gen_trt_ops.create_trt_resource_handle(resource_name=name) + + +def _remove_native_segments(input_func): + """Remove native segments from the input TF-TRT Converted Function. + + Args: + input_func: provide the concrete function with native segment nodes. The + transformed output func will not contain any native segment nodes. All the + TRTEngineOp references will be deleted and reset to default empty func. + """ + input_graph_def = input_func.graph.as_graph_def() + # Deleting the Native Segment node in each TRTEngineOp node. + nodes_deleted = 0 + for func_id in reversed(range(len(input_graph_def.library.function))): + f = input_graph_def.library.function[func_id] + if "native_segment" in f.signature.name: + nodes_deleted += 1 + while context.context().has_function(f.signature.name): + context.context().remove_function(f.signature.name) + del input_graph_def.library.function[func_id] + + logging.info( + "Found and deleted native segments from " + f"{nodes_deleted} TRTEngineOp nodes." + ) + + # Deleting the references to `_native_segment`s. + # This helps TRTEngineOp constructor to not look for native segment handles + # during construction of graph for inference. + for node in input_graph_def.node: + if node.op == "TRTEngineOp": + del node.attr["segment_func"] + for func in input_graph_def.library.function: + for node in func.node_def: + if node.op == "TRTEngineOp": + del node.attr["segment_func"] + # Reconstruct the converted_func with the new graph + new_func = _construct_function_from_graph_def(input_func, input_graph_def) + + return new_func + + +class _TRTEngineResource(resource.TrackableResource): + """Class to track the serialized engines resource.""" + + def __init__(self, + resource_name, + filename, + maximum_cached_engines, + device="GPU"): + super(_TRTEngineResource, self).__init__(device=device) + self._resource_name = resource_name + # Track the serialized engine file in the SavedModel. + self._filename = self._track_trackable( + asset.Asset(filename), "_serialized_trt_resource_filename") + self._maximum_cached_engines = maximum_cached_engines + + def _create_resource(self): + return _get_resource_handle(self._resource_name, self._resource_device) + + def _initialize(self): + gen_trt_ops.initialize_trt_resource( + self.resource_handle, + self._filename, + max_cached_engines_count=self._maximum_cached_engines) + + def _destroy_resource(self): + handle = _get_resource_handle(self._resource_name, self._resource_device) + with ops.device(self._resource_device): + gen_resource_variable_ops.destroy_resource_op( + handle, ignore_lookup_error=True) + + +def _print_row(fields, positions, print_fn): + """Prints a row.""" + line = "" + for i, field in enumerate(fields): + field = str(field) + end_line_pos = positions[i] + if i > 0: + line = line + " " + line = "{0:{min_length}}".format(line + field, min_length=end_line_pos) + + if len(line) > end_line_pos: + line = line[:(end_line_pos - 4)] + " ..." + + print_fn(line) + + +def _construct_function_from_graph_def(func, graph_def, frozen_func=None): + """Rebuild function from graph_def.""" + if frozen_func is None: + frozen_func = func + + # If a function is converted, then the TF context contains the original + # function while the converted_graph_def contains the converted function. + # Remove the original function from the TF context in this case. + for f in graph_def.library.function: + while context.context().has_function(f.signature.name): + context.context().remove_function(f.signature.name) + + captures = { + c[1].name.split(":")[0]: c[0] + for c in frozen_func.graph.captures + } + new_func = wrap_function.function_from_graph_def( + graph_def, [tensor.name for tensor in frozen_func.inputs], + [tensor.name for tensor in frozen_func.outputs], captures) + new_func.graph.structured_outputs = nest.pack_sequence_as( + func.graph.structured_outputs, new_func.graph.structured_outputs) + new_func._function_type = func.function_type # pylint: disable=protected-access + + # Copy structured input signature from original function (used during + # serialization) + new_func.graph.structured_input_signature = (func.structured_input_signature) + + return new_func + + +def _apply_inlining(func): + """Apply an inlining optimization to the function's graph definition.""" + graph_def = func.graph.as_graph_def() + + # In some cases, a secondary implementation of the function (e.g. for GPU) is + # written to the "api_implements" attribute. (e.g. `tf.keras.layers.LSTM` in + # TF2 produces a CuDNN-based RNN for GPU). + # This function suppose to inline all functions calls, but "api_implements" + # prevents this from happening. Removing the attribute solves the problem. + # To learn more about "api_implements", see: + # tensorflow/core/grappler/optimizers/implementation_selector.h + for function in graph_def.library.function: + if "api_implements" in function.attr: + del function.attr["api_implements"] + + meta_graph = saver.export_meta_graph(graph_def=graph_def, graph=func.graph) + + # Clear the initializer_name for the variables collections, since they are not + # needed after saved to saved_model. + for name in [ + "variables", "model_variables", "trainable_variables", "local_variables" + ]: + raw_list = [] + for raw in meta_graph.collection_def["variables"].bytes_list.value: + variable = variable_pb2.VariableDef() + variable.ParseFromString(raw) + variable.ClearField("initializer_name") + raw_list.append(variable.SerializeToString()) + meta_graph.collection_def[name].bytes_list.value[:] = raw_list + + # Add a collection 'train_op' so that Grappler knows the outputs. + fetch_collection = meta_graph_pb2.CollectionDef() + for array in func.inputs + func.outputs: + fetch_collection.node_list.value.append(array.name) + meta_graph.collection_def["train_op"].CopyFrom(fetch_collection) + + # Initialize RewriterConfig with everything disabled except function inlining. + config = config_pb2.ConfigProto() + rewrite_options = config.graph_options.rewrite_options + rewrite_options.min_graph_nodes = -1 # do not skip small graphs + rewrite_options.optimizers.append("function") + + new_graph_def = tf_optimizer.OptimizeGraph(config, meta_graph) + + return new_graph_def + + +def _annotate_variable_ops(func, graph_def): + """Annotates variable operations with custom `_shape` attribute. + + This is required for the converters and shape inference. The graph + definition is modified in-place. + + Args: + func: Function represented by the graph definition. + graph_def: Graph definition to be annotated in-place. + + Raises: + RuntimeError: if some shapes cannot be annotated. + """ + ph_shape_map = {} + for ph, var in zip(func.graph.internal_captures, func.variables): + ph_shape_map[ph.name] = var.shape + # Construct a mapping of node names to nodes + name_to_node = {node.name: node for node in graph_def.node} + # Go through all the ReadVariableOp nodes in the graph def + for node in graph_def.node: + if node.op == "ReadVariableOp" or node.op == "ResourceGather": + node_ = node + # Go up the chain of identities to find a placeholder + while name_to_node[node_.input[0]].op == "Identity": + node_ = name_to_node[node_.input[0]] + ph_name = node_.input[0] + ":0" + if ph_name in ph_shape_map: + shape = ph_shape_map[ph_name] + node.attr["_shape"].shape.CopyFrom(shape.as_proto()) + else: + raise RuntimeError( + "Not found in the function captures: {}".format(ph_name)) + + +def _save_calibration_table(node): + try: + calibration_table = gen_trt_ops.get_calibration_data_op( + _get_canonical_engine_name(node.name)) + node.attr["calibration_data"].s = calibration_table.numpy() + except (errors.UnknownError, errors.NotFoundError): + logging.warning("Warning calibration error for %s", node.name) + + +def _convert_to_tensor(inp): + try: + if isinstance(inp, dict): + args = [] + kwargs = {k: ops.convert_to_tensor(v) for k, v in inp.items()} + else: + kwargs = {} + if isinstance(inp, (list, tuple)): + args = map(ops.convert_to_tensor, inp) + else: + args = [ops.convert_to_tensor(inp)] + except: + error_msg = "Failed to convert input to tensor." + logging.error(error_msg + "\ninp = `{0}`\n".format(inp)) + raise RuntimeError(error_msg) + + return args, kwargs + + +@tf_export("experimental.tensorrt.Converter", v1=[]) +class TrtGraphConverterV2(object): + """An offline converter for TF-TRT transformation for TF 2.0 SavedModels. + + Windows support is provided experimentally. No guarantee is made regarding + functionality or engineering support. Use at your own risk. + + There are several ways to run the conversion: + + 1. FP32/FP16 precision + + ```python + params = tf.experimental.tensorrt.ConversionParams( + precision_mode='FP16') + converter = tf.experimental.tensorrt.Converter( + input_saved_model_dir="my_dir", conversion_params=params) + converter.convert() + converter.save(output_saved_model_dir) + ``` + + In this case, no TRT engines will be built or saved in the converted + SavedModel. But if input data is available during conversion, we can still + build and save the TRT engines to reduce the cost during inference (see + option 2 below). + + 2. FP32/FP16 precision with pre-built engines + + ```python + params = tf.experimental.tensorrt.ConversionParams( + precision_mode='FP16', + # Set this to a large enough number so it can cache all the engines. + maximum_cached_engines=16) + converter = tf.experimental.tensorrt.Converter( + input_saved_model_dir="my_dir", conversion_params=params) + converter.convert() + + # Define a generator function that yields input data, and use it to execute + # the graph to build TRT engines. + def my_input_fn(): + for _ in range(num_runs): + inp1, inp2 = ... + yield inp1, inp2 + + converter.build(input_fn=my_input_fn) # Generate corresponding TRT engines + converter.save(output_saved_model_dir) # Generated engines will be saved. + ``` + + In this way, one engine will be built/saved for each unique input shapes of + the TRTEngineOp. This is good for applications that cannot afford building + engines during inference but have access to input data that is similar to + the one used in production (for example, that has the same input shapes). + Also, the generated TRT engines is platform dependent, so we need to run + `build()` in an environment that is similar to production (e.g. with + same type of GPU). + + 3. INT8 precision and calibration with pre-built engines + + ```python + params = tf.experimental.tensorrt.ConversionParams( + precision_mode='INT8', + # Currently only one INT8 engine is supported in this mode. + maximum_cached_engines=1, + use_calibration=True) + converter = tf.experimental.tensorrt.Converter( + input_saved_model_dir="my_dir", conversion_params=params) + + # Define a generator function that yields input data, and run INT8 + # calibration with the data. All input data should have the same shape. + # At the end of convert(), the calibration stats (e.g. range information) + # will be saved and can be used to generate more TRT engines with different + # shapes. Also, one TRT engine will be generated (with the same shape as + # the calibration data) for save later. + def my_calibration_input_fn(): + for _ in range(num_runs): + inp1, inp2 = ... + yield inp1, inp2 + + converter.convert(calibration_input_fn=my_calibration_input_fn) + + # (Optional) Generate more TRT engines offline (same as the previous + # option), to avoid the cost of generating them during inference. + def my_input_fn(): + for _ in range(num_runs): + inp1, inp2 = ... + yield inp1, inp2 + converter.build(input_fn=my_input_fn) + + # Save the TRT engine and the engines. + converter.save(output_saved_model_dir) + ``` + 4. To use dynamic shape, we need to call the build method with an input + function to generate profiles. This step is similar to the INT8 calibration + step described above. The converter also needs to be created with + use_dynamic_shape=True and one of the following profile_strategies for + creating profiles based on the inputs produced by the input function: + * `Range`: create one profile that works for inputs with dimension values + in the range of [min_dims, max_dims] where min_dims and max_dims are + derived from the provided inputs. + * `Optimal`: create one profile for each input. The profile only works for + inputs with the same dimensions as the input it is created for. The GPU + engine will be run with optimal performance with such inputs. + * `Range+Optimal`: create the profiles for both `Range` and `Optimal`. + """ + + def _verify_profile_strategy(self, strategy): + supported_strategies = [s.lower() for s in supported_profile_strategies()] + if strategy.lower() not in supported_strategies: + raise ValueError( + ("profile_strategy '{}' is not supported. It should be one of {}" + ).format(strategy, supported_profile_strategies())) + if strategy == "ImplicitBatchModeCompatible": + logging.warn( + "ImplicitBatchModeCompatible strategy is deprecated, and" + " using it may result in errors during engine building. Please" + " consider using a different profile strategy.") + + @deprecation.deprecated_args(None, + "Use individual converter parameters instead", + "conversion_params") + def __init__(self, + input_saved_model_dir=None, + input_saved_model_tags=None, + input_saved_model_signature_key=None, + use_dynamic_shape=None, + dynamic_shape_profile_strategy=None, + max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES, + precision_mode=TrtPrecisionMode.FP32, + minimum_segment_size=3, + maximum_cached_engines=1, + use_calibration=True, + allow_build_at_runtime=True, + conversion_params=None): + """Initialize the converter. + + Args: + input_saved_model_dir: the directory to load the SavedModel which contains + the input graph to transforms. Required. + input_saved_model_tags: list of tags to load the SavedModel. + input_saved_model_signature_key: the key of the signature to optimize the + graph for. + use_dynamic_shape: whether to enable dynamic shape support. None is + equivalent to False in the current implementation. + dynamic_shape_profile_strategy: one of the strings in + supported_profile_strategies(). None is equivalent to Range in the + current implementation. + max_workspace_size_bytes: the maximum GPU temporary memory that the TRT + engine can use at execution time. This corresponds to the + 'workspaceSize' parameter of nvinfer1::IBuilder::setMaxWorkspaceSize(). + precision_mode: one of the strings in + TrtPrecisionMode.supported_precision_modes(). + minimum_segment_size: the minimum number of nodes required for a subgraph + to be replaced by TRTEngineOp. + maximum_cached_engines: max number of cached TRT engines for dynamic TRT + ops. Created TRT engines for a dynamic dimension are cached. If the + number of cached engines is already at max but none of them supports the + input shapes, the TRTEngineOp will fall back to run the original TF + subgraph that corresponds to the TRTEngineOp. + use_calibration: this argument is ignored if precision_mode is not INT8. + If set to True, a calibration graph will be created to calibrate the + missing ranges. The calibration graph must be converted to an inference + graph by running calibration with calibrate(). If set to False, + quantization nodes will be expected for every tensor in the graph + (excluding those which will be fused). If a range is missing, an error + will occur. Please note that accuracy may be negatively affected if + there is a mismatch between which tensors TRT quantizes and which + tensors were trained with fake quantization. + allow_build_at_runtime: whether to allow building TensorRT engines during + runtime if no prebuilt TensorRT engine can be found that can handle the + given inputs during runtime, then a new TensorRT engine is built at + runtime if allow_build_at_runtime=True, and otherwise native TF is used. + conversion_params: a TrtConversionParams instance (deprecated). + + Raises: + ValueError: if the combination of the parameters is invalid. + """ + assert context.executing_eagerly() + if conversion_params is None: + conversion_params = TrtConversionParams( + max_workspace_size_bytes=max_workspace_size_bytes, + precision_mode=precision_mode, + minimum_segment_size=minimum_segment_size, + maximum_cached_engines=maximum_cached_engines, + use_calibration=use_calibration, + allow_build_at_runtime=allow_build_at_runtime) + + _check_trt_version_compatibility() + _check_conversion_params(conversion_params, is_v2=True) + + self._conversion_params = conversion_params + self._input_saved_model_dir = input_saved_model_dir + self._input_saved_model_tags = ( + input_saved_model_tags or [tag_constants.SERVING]) + self._input_saved_model_signature_key = ( + input_saved_model_signature_key or + signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY) + self.freeze = not trt_utils.is_experimental_feature_activated( + "disable_graph_freezing") + + self._need_calibration = (( + (conversion_params.precision_mode == TrtPrecisionMode.INT8) or + (conversion_params.precision_mode == TrtPrecisionMode.INT8.lower())) and + conversion_params.use_calibration) + + self._calibration_input_fn = None + + self._converted = False + self._device = None + self._build_called_once = False + self._calibrated = False + + if use_dynamic_shape is None: + self._use_dynamic_shape = False + else: + self._use_dynamic_shape = use_dynamic_shape + + if not self.freeze and not self._use_dynamic_shape: + logging.warn( + "Disabling graph freezing is only possible in dynamic shape mode." + " The graph will be frozen.") + self.freeze = True + + self._profile_strategy = "Unknown" + if self._use_dynamic_shape: + if dynamic_shape_profile_strategy is None: + self._profile_strategy = PROFILE_STRATEGY_RANGE + else: + self._verify_profile_strategy(dynamic_shape_profile_strategy) + self._profile_strategy = dynamic_shape_profile_strategy + + # Fields to support TF-TRT testing and shouldn't be used for other purpose. + self._test_only_disable_non_trt_optimizers = False + + def _need_trt_profiles(self): + return self._use_dynamic_shape + + def _run_conversion(self, meta_graph_def): + """Run Grappler's OptimizeGraph() tool to convert the graph. + + Args: + meta_graph_def: the MetaGraphDef instance to run the optimizations on. + + Returns: + The optimized GraphDef. + """ + grappler_session_config = config_pb2.ConfigProto() + # Always set `allow_build_at_runtime` for offline TensorRT engine building. + custom_rewriter_config = _get_tensorrt_rewriter_config( + conversion_params=self._conversion_params._replace( + allow_build_at_runtime=True), + is_dynamic_op=True, + max_batch_size=None, + disable_non_trt_optimizers=self._test_only_disable_non_trt_optimizers, + use_implicit_batch=not self._use_dynamic_shape, + profile_strategy=self._profile_strategy) + grappler_session_config.graph_options.rewrite_options.CopyFrom( + custom_rewriter_config) + return tf_optimizer.OptimizeGraph( + grappler_session_config, meta_graph_def, graph_id=b"tf_graph") + + def _for_each_trt_node(self, graph_def, fn): + """Helper method to manipulate all TRTEngineOps in a GraphDef.""" + for node in graph_def.node: + if node.op == _TRT_ENGINE_OP_NAME: + fn(node) + for func in graph_def.library.function: + for node in func.node_def: + if node.op == _TRT_ENGINE_OP_NAME: + fn(node) + + def _execute_calibration(self, calibration_input_fn): + """Run INT8 calibration with the provided input generator function.""" + for inp in calibration_input_fn(): + args, kwargs = _convert_to_tensor(inp) + self._converted_func(*args, **kwargs) + + self._for_each_trt_node(self._converted_graph_def, _save_calibration_table) + + # Rebuild the function since calibration has changed the graph. + self._converted_func = _construct_function_from_graph_def( + self._converted_func, self._converted_graph_def) + self._calibrated = True + + # TODO(laigd): provide a utility function to optimize a ConcreteFunction and + # use it here (b/124792963). + def convert(self, calibration_input_fn=None): + """Convert the input SavedModel in 2.0 format. + + Args: + calibration_input_fn: a generator function that yields input data as a + list or tuple or dict, which will be used to execute the converted + signature for calibration. All the returned input data should have the + same shape. Example: `def input_fn(): yield input1, input2, input3` + + If dynamic_shape_mode==False, (or if the graph has static input shapes) + then we run calibration and build the calibrated engine during + conversion. + + If dynamic_shape_mode==True (and the graph has any unknown input + shape), then the reference to calibration_input_fn is stored, and the + calibration is actually performed when we build the engine (see + build()). + + Raises: + ValueError: if the input combination is invalid. + + Returns: + The TF-TRT converted Function. + """ + assert not self._converted + + # Creating an empty tensor to fetch queried device + device_requested = array_ops.zeros([]).device + + if "gpu" not in device_requested.lower(): + raise ValueError(f"Specified device is not a GPU: {device_requested}") + + if "gpu:0" not in device_requested.lower(): + self._device = device_requested + logging.info(f"Placing imported graph from " + f"`{self._input_saved_model_dir}` on device: {self._device}") + + if (self._need_calibration and not calibration_input_fn): + raise ValueError("Should specify calibration_input_fn because INT8 " + "calibration is needed") + if (not self._need_calibration and calibration_input_fn): + raise ValueError("Should not specify calibration_input_fn because INT8 " + "calibration is not needed") + + self._saved_model = load.load(self._input_saved_model_dir, + self._input_saved_model_tags) + func = self._saved_model.signatures[self._input_saved_model_signature_key] + if self.freeze: + frozen_func = convert_to_constants.convert_variables_to_constants_v2(func) + else: + inlined_graph_def = _apply_inlining(func) + _annotate_variable_ops(func, inlined_graph_def) + frozen_func = _construct_function_from_graph_def(func, inlined_graph_def) + frozen_graph_def = frozen_func.graph.as_graph_def() + + # Clear any prior device assignments + logging.info("Clearing prior device assignments in loaded saved model") + for node in frozen_graph_def.node: + node.device = "" + + if self._device is None: + grappler_meta_graph_def = saver.export_meta_graph( + graph_def=frozen_graph_def, graph=frozen_func.graph) + else: + with ops.Graph().as_default() as graph, ops.device(self._device): + importer.import_graph_def(frozen_graph_def, name="") + grappler_meta_graph_def = saver.export_meta_graph( + graph_def=graph.as_graph_def(), graph=graph) + + # Add a collection 'train_op' so that Grappler knows the outputs. + fetch_collection = meta_graph_pb2.CollectionDef() + for array in frozen_func.inputs + frozen_func.outputs: + fetch_collection.node_list.value.append(array.name) + grappler_meta_graph_def.collection_def["train_op"].CopyFrom( + fetch_collection) + + # Run TRT optimizer in Grappler to convert the graph. + self._converted_graph_def = self._run_conversion(grappler_meta_graph_def) + self._converted_func = _construct_function_from_graph_def( + func, self._converted_graph_def, frozen_func) + + if self._need_calibration: + # Execute calibration here only if not in dynamic shape mode. + if not self._need_trt_profiles(): + self._execute_calibration(calibration_input_fn) + else: + self._calibration_input_fn = calibration_input_fn + + self._converted = True + + graphviz_path = os.environ.get("TF_TRT_EXPORT_GRAPH_VIZ_PATH", default=None) + if graphviz_path is not None: + try: + trt_utils.draw_graphdef_as_graphviz( + graphdef=self._converted_func.graph.as_graph_def(add_shapes=True), + dot_output_filename=graphviz_path) + except Exception as e: + logging.error( + "An Exception occurred during the export of the graph " + f"visualization: {e}" + ) + + return self._converted_func + + def build(self, input_fn): + """Run inference with converted graph in order to build TensorRT engines. + + If the conversion requires INT8 calibration, then a reference to the + calibration function was stored during the call to convert(). Calibration + will be performed while we build the TensorRT engines. + + Args: + input_fn: a generator function that provides the input data as a single + array, OR a list or tuple of the arrays OR a dict, which will be used + to execute the converted signature to generate TRT engines. + Example 1: + `def input_fn(): + # Let's assume a network with 1 input tensor. + # We generate 2 sets of dummy input data: + input_shapes = [(1, 16), # 1st shape + (2, 32)] # 2nd shape + for shapes in input_shapes: + # return an input tensor + yield np.zeros(shape).astype(np.float32)' + + Example 2: + `def input_fn(): + # Let's assume a network with 2 input tensors. + # We generate 3 sets of dummy input data: + input_shapes = [[(1, 16), (2, 16)], # 1st input list + [(2, 32), (4, 32)], # 2nd list of two tensors + [(4, 32), (8, 32)]] # 3rd input list + for shapes in input_shapes: + # return a list of input tensors + yield [np.zeros(x).astype(np.float32) for x in shapes]` + + Raises: + NotImplementedError: build() is already called. + RuntimeError: the input_fx is None. + """ + if self._build_called_once: + raise NotImplementedError("build() is already called. It is not " + "supported to call build() more than once.") + if not input_fn: + raise RuntimeError("input_fn is None. Method build() needs input_fn " + "to be specified in order to build TensorRT engines") + if not self._converted: + raise RuntimeError("Need to call convert() before build()") + if (self._need_calibration and not self._calibrated and + self._calibration_input_fn is None): + raise RuntimeError("Need to provide the calibration_input_fn arg while " + "calling convert().") + + def _set_profile_generation_mode(value, node): + node.attr["_profile_generation_mode"].b = value + + if self._need_trt_profiles(): + # Enable profile generation. + self._for_each_trt_node(self._converted_graph_def, + partial(_set_profile_generation_mode, True)) + # Profile generation is enabled using the _profile_generation_mode + # attribute of the TRTEngineOps. We need to rebuild the function to + # change this attribute. + func = _construct_function_from_graph_def(self._converted_func, + self._converted_graph_def) + else: + func = self._converted_func + + first_input = None + # Run inference: + # Builds TRT engines if self._need_trt_profiles is False. + # Builds TRT optimization profiles if self._need_trt_profiles is True. + for inp in input_fn(): + if first_input is None: + first_input = inp + args, kwargs = _convert_to_tensor(inp) + func(*args, **kwargs) + + if self._need_trt_profiles(): + # Disable profile generation. + self._for_each_trt_node(self._converted_graph_def, + partial(_set_profile_generation_mode, False)) + + # Run calibration if required, this would have been skipped in + # the convert step + if self._need_calibration and not self._calibrated: + self._execute_calibration(self._calibration_input_fn) + # calibration also builds the engine + else: + # Use the first input in explicit batch mode to build TensorRT engines + # after generating all the profiles. The first input is used but any of + # the inputs can be used because the shape of this input does not + # determine the engine and instead the shapes collected in profiles + # determine the engine. + args, kwargs = _convert_to_tensor(first_input) + self._converted_func(*args, **kwargs) + + self._build_called_once = True + + def save(self, + output_saved_model_dir, + save_gpu_specific_engines=True, + options=None): + """Save the converted SavedModel. + + Args: + output_saved_model_dir: directory to saved the converted SavedModel. + save_gpu_specific_engines: whether to save TRT engines that have been + built. When True, all engines are saved and when False, the engines + are not saved and will be rebuilt at inference time. By using + save_gpu_specific_engines=False after doing INT8 calibration, inference + can be done on different GPUs than the GPU that the model was calibrated + and saved on. + options: `tf.saved_model.SaveOptions` object for configuring save options. + Raises: + RuntimeError: if the needed calibration hasn't been done. + """ + assert self._converted + + # 'remove_native_segments': setting this value to True removes native segments + # associated with each TRT engine. This option can be used to reduce the size + # of the converted model. Please note that a converted model without native + # segments can't be used for collecting profiles, building or re-converting. + # The reduced model can only be used for inference when no native segments + # are required for computation. When remove_native_segments flag is set to + # True, the converted_graph_def needs to be reduced before saved_model + # function serialization. + if trt_utils.is_experimental_feature_activated("remove_native_segments"): + logging.info( + "'remove_native_segments' experimental feature is enabled" + " during saving of converted SavedModel." + ) + self._converted_func = _remove_native_segments(self._converted_func) + self._converted_graph_def = self._converted_func.graph.as_graph_def() + + if self._need_calibration and not self._calibrated: + raise RuntimeError("A model that requires INT8 calibration has to be " + "built before saving it. Call build() to build and " + "calibrate the TensorRT engines.") + # Serialize the TRT engines in the cache if any, and create trackable + # resource to track them. + engine_asset_dir = tempfile.mkdtemp() + resource_map = {} + + def _serialize_and_track_engine(node): + """Serialize TRT engines in the cache and track them.""" + # Don't dump the same cache twice. + canonical_engine_name = _get_canonical_engine_name(node.name) + if canonical_engine_name in resource_map: + return + + filename = os.path.join(engine_asset_dir, + "trt-serialized-engine." + canonical_engine_name) + + try: + gen_trt_ops.serialize_trt_resource( + resource_name=canonical_engine_name, + filename=filename, + delete_resource=True, + save_gpu_specific_engines=save_gpu_specific_engines) + except errors.NotFoundError: + logging.info( + "Could not find %s in TF-TRT cache. " + "This can happen if build() is not called, " + "which means TensorRT engines will be built " + "and cached at runtime.", canonical_engine_name) + return + + # TODO(laigd): add an option for the user to choose the device. + resource_map[canonical_engine_name] = _TRTEngineResource( + canonical_engine_name, filename, + self._conversion_params.maximum_cached_engines) + + self._for_each_trt_node(self._converted_graph_def, + _serialize_and_track_engine) + # If the graph is frozen, tracked variables are not needed by the converted model. + trackable = autotrackable.AutoTrackable( + ) if self.freeze else self._saved_model + trackable.trt_engine_resources = resource_map + + # Set allow_build_at_runtime=False if asked by user. + # + # This attribute is set here because build() needs it to be True in order to + # build engines. + if not self._conversion_params.allow_build_at_runtime: + + def _reset_allow_build_at_runtime(node): + node.attr["_allow_build_at_runtime"].b = False + + self._for_each_trt_node(self._converted_graph_def, + _reset_allow_build_at_runtime) + # Rebuild the function since a node attribute changed above + reset_converted_func = wrap_function.function_from_graph_def( + self._converted_graph_def, + [tensor.name for tensor in self._converted_func.inputs], + [tensor.name for tensor in self._converted_func.outputs]) + reset_converted_func.graph.structured_outputs = nest.pack_sequence_as( + self._converted_func.graph.structured_outputs, + reset_converted_func.graph.structured_outputs) + reset_converted_func.graph.structured_input_signature = ( + self._converted_func.structured_input_signature) + self._converted_func = reset_converted_func + + # Rewrite the signature map using the optimized ConcreteFunction. + signatures = {self._input_saved_model_signature_key: self._converted_func} + save.save(trackable, output_saved_model_dir, signatures, options=options) + + def summary(self, line_length=160, detailed=True, print_fn=None): + """This method describes the results of the conversion by TF-TRT. + + It includes information such as the name of the engine, the number of nodes + per engine, the input and output dtype, along with the input shape of each + TRTEngineOp. + + Args: + line_length: Default line length when printing on the console. Minimum 160 + characters long. + detailed: Whether or not to show the nodes inside each TRTEngineOp. + print_fn: Print function to use. Defaults to `print`. It will be called on + each line of the summary. You can set it to a custom function in order + to capture the string summary. + + Raises: + RuntimeError: if the graph is not converted. + """ + if not self._converted: + raise RuntimeError( + f"Impossible to call `{self.__class__.__name__}.summary()` before " + f"calling {self.__class__.__name__}.convert()`.") + + if line_length < 160: + raise ValueError(f"Invalid `line_length` value has been received: " + f"{line_length}. Minimum: 160.") + + if print_fn is None: + print_fn = print + + # positions are percentage of `line_length`. positions[i]+1 is the starting + # position for (i+1)th field. We also make sure that the last char printed + # for each field is a space. + columns = [ + # (column name, column size in % of line) + ("TRTEngineOP Name", .20), # 20% + ("Device", .09), # 29% + ("# Nodes", .05), # 34% + ("# Inputs", .09), # 43% + ("# Outputs", .09), # 52% + ("Input DTypes", .12), # 64% + ("Output Dtypes", .12), # 76% + ("Input Shapes", .12), # 88% + ("Output Shapes", .12) # 100% + ] + + positions = [int(line_length * p) for _, p in columns] + positions = np.cumsum(positions).tolist() + headers = [h for h, _ in columns] + + _print_row(headers, positions, print_fn=print_fn) + print_fn("=" * line_length) + + n_engines = 0 + n_ops_converted = 0 + n_ops_not_converted = 0 + + graphdef = self._converted_func.graph.as_graph_def(add_shapes=True) + + trtengineops_dict = dict() + for node in graphdef.node: + if node.op != "TRTEngineOp": + n_ops_not_converted += 1 + continue + else: + trtengineops_dict[node.name] = node + n_engines += 1 + + for name, node in sorted(trtengineops_dict.items()): + node_device = node.device.split("/")[-1] + in_shapes = trt_utils.get_node_io_shapes(node, "input_shapes") + out_shapes = trt_utils.get_node_io_shapes(node, "_output_shapes") + in_dtypes = trt_utils.get_trtengineop_io_dtypes(node, "InT") + out_dtypes = trt_utils.get_trtengineop_io_dtypes(node, "OutT") + in_nodes_count = trt_utils.get_trtengineop_io_nodes_count(node, "InT") + out_nodes_count = trt_utils.get_trtengineop_io_nodes_count(node, "OutT") + node_count, converted_ops_dict = trt_utils.get_trtengineop_node_op_count( + graphdef, name) + + n_ops_converted += node_count + + if n_engines != 1: + print_fn(f"\n{'-'*40}\n") + + _print_row( + fields=[ + name, node_device, node_count, in_nodes_count, out_nodes_count, + in_dtypes, out_dtypes, in_shapes, out_shapes + ], + positions=positions, + print_fn=print_fn) + + if detailed: + print_fn() + for key, value in sorted(dict(converted_ops_dict).items()): + print_fn(f"\t- {key}: {value}x") + + print_fn(f"\n{'='*line_length}") + print_fn(f"[*] Total number of TensorRT engines: {n_engines}") + total_ops = n_ops_not_converted + n_ops_converted + conversion_ratio = n_ops_converted / total_ops * 100 + print_fn(f"[*] % of OPs Converted: {conversion_ratio:.2f}% " + f"[{n_ops_converted}/{total_ops}]\n") + + +# TODO(laigd): use TrtConversionParams here. +def create_inference_graph( + input_graph_def, + outputs, + max_batch_size=1, + max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES, + precision_mode=TrtPrecisionMode.FP32, + minimum_segment_size=3, + is_dynamic_op=False, + maximum_cached_engines=1, + input_saved_model_dir=None, + input_saved_model_tags=None, + input_saved_model_signature_key=None, + output_saved_model_dir=None): + """Python wrapper for the TRT transformation. + + Args: + input_graph_def: a GraphDef object containing a model to be transformed. If + set to None, the graph will be read from the SavedModel loaded from + input_saved_model_dir. + outputs: list of tensors or node names for the model outputs. Only used when + input_graph_def is not None. + max_batch_size: max size for the input batch. + max_workspace_size_bytes: the maximum GPU temporary memory which the TRT + engine can use at execution time. This corresponds to the 'workspaceSize' + parameter of nvinfer1::IBuilder::setMaxWorkspaceSize(). + precision_mode: one of TrtPrecisionMode.supported_precision_modes(). + minimum_segment_size: the minimum number of nodes required for a subgraph to + be replaced by TRTEngineOp. + is_dynamic_op: whether to generate dynamic TRT ops which will build the TRT + network and engine at run time. + maximum_cached_engines: max number of cached TRT engines in dynamic TRT ops. + If the number of cached engines is already at max but none of them can + serve the input, the TRTEngineOp will fall back to run the TF function + based on which the TRTEngineOp is created. + input_saved_model_dir: the directory to load the SavedModel which contains + the input graph to transforms. Used only when input_graph_def is None. + input_saved_model_tags: list of tags to load the SavedModel. + input_saved_model_signature_key: the key of the signature to optimize the + graph for. + output_saved_model_dir: if not None, construct a SavedModel using the + returned GraphDef and save it to the specified directory. This option only + works when the input graph is loaded from a SavedModel, i.e. when + input_saved_model_dir is specified and input_graph_def is None. + + Returns: + A GraphDef transformed from input_graph_def (or the SavedModel graph def + loaded from input_saved_model_dir, if input_graph_def is not present), where + all TRT compatible subgraphs are replaced with TRTEngineOps, and a TF + function is added for each of the subgraphs. + + If is_dynamic_op is True, each TRTEngineOp will contain a serialized + subgraph GraphDef, which will be converted to a TRT engine at execution time + and the TRT engine will be cached for future usage. A new TRT engine will be + created each time when none of the cached engines match the input shapes. If + it fails to execute the TRT engine or the number of cached engines reaches + maximum_cached_engines, the op will fall back to call the corresponding TF + function. + + If is_dynamic_op is False, each TRTEngineOp will contain a serialized TRT + engine created from the corresponding subgraph. No more engines will be + created on the fly, and the op will fall back to call the corresponding TF + function when it fails to execute the engine. + + Raises: + ValueError: if the combination of the parameters is invalid. + """ + trt_converter = TrtGraphConverter( + input_saved_model_dir=input_saved_model_dir, + input_saved_model_tags=input_saved_model_tags, + input_saved_model_signature_key=input_saved_model_signature_key, + input_graph_def=input_graph_def, + nodes_denylist=outputs, + max_batch_size=max_batch_size, + max_workspace_size_bytes=max_workspace_size_bytes, + precision_mode=precision_mode, + minimum_segment_size=minimum_segment_size, + is_dynamic_op=is_dynamic_op, + maximum_cached_engines=maximum_cached_engines, + use_calibration=False) + converted_graph_def = trt_converter.convert() + if output_saved_model_dir: + trt_converter.save(output_saved_model_dir) + return converted_graph_def diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a908f920b149968987ce7a887896f8ec551942d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/tensorrt/utils.py @@ -0,0 +1,259 @@ +# 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. +# ============================================================================= +"""Exposes the Python wrapper conversion to trt_graph.""" + +import collections +import os +import re + +from packaging import version + +from tensorflow.compiler.tf2tensorrt import _pywrap_py_utils +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.framework import dtypes + + +def disable_non_trt_optimizers_in_rewriter_config(rewriter_config): + """Modifies rewriter_config to disable all non-TRT optimizations.""" + off = rewriter_config_pb2.RewriterConfig.OFF + + rewriter_config.arithmetic_optimization = off + rewriter_config.auto_mixed_precision = off + rewriter_config.auto_parallel.enable = False + rewriter_config.constant_folding = off + rewriter_config.debug_stripper = off + rewriter_config.dependency_optimization = off + # This one needs to be ON to allow TF-TRT + rewriter_config.disable_meta_optimizer = False + rewriter_config.disable_model_pruning = True + rewriter_config.function_optimization = off + rewriter_config.implementation_selector = off + rewriter_config.layout_optimizer = off + rewriter_config.loop_optimization = off + rewriter_config.memory_optimization = ( + rewriter_config_pb2.RewriterConfig.NO_MEM_OPT) + rewriter_config.min_graph_nodes = -1 + rewriter_config.pin_to_host_optimization = off + rewriter_config.remapping = off + rewriter_config.scoped_allocator_optimization = off + rewriter_config.shape_optimization = off + + +def version_tuple_to_string(ver_tuple): + assert isinstance(ver_tuple, tuple) + assert len(ver_tuple) == 3 + + ver_tuple = [str(x) for x in ver_tuple] + return ".".join(ver_tuple) + + +def _is_tensorrt_version_greater_equal(trt_ver, target_ver): + trt_ver = version.Version(version_tuple_to_string(trt_ver)) + target_ver = version.Version(version_tuple_to_string(target_ver)) + + return trt_ver >= target_ver + + +def is_linked_tensorrt_version_greater_equal(major, minor=0, patch=0): + ver = _pywrap_py_utils.get_linked_tensorrt_version() + return _is_tensorrt_version_greater_equal(ver, (major, minor, patch)) + + +def is_loaded_tensorrt_version_greater_equal(major, minor=0, patch=0): + ver = _pywrap_py_utils.get_loaded_tensorrt_version() + return _is_tensorrt_version_greater_equal(ver, (major, minor, patch)) + + +def is_experimental_feature_activated(feature_name): + """Determines if a TF-TRT experimental feature is enabled. + + This helper function checks if an experimental feature was enabled using + the environment variable `TF_TRT_EXPERIMENTAL_FEATURES=feature_1,feature_2`. + + Args: + feature_name: Name of the feature being tested for activation. + """ + + return (feature_name + in os.environ.get("TF_TRT_EXPERIMENTAL_FEATURES", + default="").split(",")) + + +def _convert_dtype_id_to_str(dtype): + """Helper function to convert a dtype id to a corresponding string name.""" + if isinstance(dtype, int): + return dtypes._TYPE_TO_STRING[dtype] + else: + return [dtypes._TYPE_TO_STRING[d] for d in dtype] + + +def get_node_compute_dtype(node): + """Returns the compute DType of a GraphDef Node.""" + # Note: Order is important, by default TF Node compute dtype is mentioned + # under `T` key, unless these nodes are one of ["TRTEngineOP", "Cast", "Plh"]. + for type_key in [ + "precision_mode", # TRTEngineOp + "DstT", # Cast Nodes + "dtype", # Placeholder + "T", # Everything Else + ]: + try: + precision_val = node.attr[type_key] + if type_key == "precision_mode": + precision_val = precision_val.s.decode("utf-8") + if precision_val == "": + continue + if precision_val == "FP32": + return "float32" + elif precision_val == "FP16": + return "float16" + elif precision_val == "INT8": + return "int8" + else: + return "unknown" + else: + return _convert_dtype_id_to_str(precision_val.type) + except Exception as e: + continue + + +def get_node_io_shapes(node, key): + """Returns the input/output shapes of a GraphDef Node.""" + out_shape = [] + for shape in node.attr[key].list.shape: + out_shape.append([dim.size for dim in shape.dim]) + return out_shape + + +def get_trtengineop_io_dtypes(node, key): + """Returns the input/output dtypes of a TRTEngineOp.""" + return _convert_dtype_id_to_str(node.attr[key].list.type) + + +def get_trtengineop_io_nodes_count(node, key): + """Returns the number of input/output nodes of a TRTEngineOp.""" + return len(node.attr[key].list.type) + + +def get_trtengineop_node_op_count(graphdef, node_name): + """Counts the number of nodes and OP types of a given TRTEngineOp.""" + ops_in_engine = collections.defaultdict(int) + for func in graphdef.library.function: + if f"{node_name}_native_segment" == func.signature.name: + node_count = len(func.node_def) + for node in func.node_def: + ops_in_engine[node.op] += 1 + break + return node_count, ops_in_engine + + +class DTypeIndex(dict): + """Helper class to create an index of dtypes with incremental values.""" + + def get_dtype_index(self, dtype): + if dtype not in self: + self[dtype] = len(self) + 1 + return self[dtype] + + +def draw_graphdef_as_graphviz(graphdef, dot_output_filename): + """Exports a GraphDef to GraphViz format. + + - Step 1: Drawing Each Node of the compute GraphDef. + - Step 2: Create nodes for each collected dtype in the graph. + - Step 3: Creating invisible links to align properly the legend. + + Each node consequently mentions: + - Op Type + - Compute Dtype + - Compute Device + """ + + dtype_index = DTypeIndex() + + with open(dot_output_filename, "w") as f: + print("digraph tftrt_converted_graph {", file=f) + + print(" graph [fontsize=10 fontname=\"Verdana\"];", file=f) + # ColorScheme Documentation: https://graphviz.org/doc/info/colors.html + print( + " node [style=filled height=0.55 colorscheme=set312 shape=box];", + file=f) + + # Step 1: Parsing the graph and drawing OPs one by one. + print("\n subgraph tensorflow_graph {", file=f) + print(" node [width=1.35];", file=f) + nodes_with_no_inputs = [] + for node in graphdef.node: + output_name = node.name + + node_precision = get_node_compute_dtype(node) + color_idx = dtype_index.get_dtype_index(node_precision) + + device_key = node.device.split("/")[-1] + if not device_key: + device_key = "device:Unspecified" + + if node.op == "TRTEngineOp": + node_count, _ = get_trtengineop_node_op_count(graphdef, output_name) + node_label = f"{output_name} [{node_count}]" + else: + node_label = f"{node.op}" + + # Note: double space before
is necessary for formatting. + node_label = f"{node_label}
{device_key}" + + print( + f" \"{output_name}\" [label=<{node_label}> " + f"fillcolor={color_idx}];", + file=f) + + if len(node.input): + for input_full_name in node.input: + parts = input_full_name.split(":") + input_name = re.sub(r"^\^", "", parts[0]) + print(f" \"{input_name}\" -> \"{output_name}\";", file=f) + else: + nodes_with_no_inputs.append(output_name) + print(" }", file=f) + + # Step 2: Creating the DType Nodes previously found in Step 1. + print("\n subgraph cluster_legend {", file=f) + print(" label=\"Compute Dtype Legend\";", file=f) + print(" margin=\"30\";", file=f) + print(" node [width=2];", file=f) + + for dtype, color_idx in dtype_index.items(): + print( + f" {dtype} [fillcolor={color_idx} label=<{dtype}>];", + file=f) + + print(" }", file=f) + + # Step 3: Alignement of the legend with the graph. + print("\n edge[style=\"invisible\", dir=\"none\"];", file=f) + for dtype in dtype_index.keys(): + for node_name in nodes_with_no_inputs: + print(f" \"{dtype}\" -> \"{node_name}\"", file=f) + + print("}", file=f) + + print("\n===================================================================") + print(f"Graph Visualization Exported to: `{dot_output_filename}`.") + print("We recommend using https://edotor.net/ to visualize the .dot file.") + print("You can also use `graphviz` utility to convert them to PNG format:") + print(" - `sudo apt install -y graphviz`") + print(" - `dot -Tpng .dot -o .png`") + print("===================================================================\n") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e46488a5cc068df7ca8931757a1ac81ebfb8e023 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/__init__.py @@ -0,0 +1,20 @@ +# 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 module for controlling the Tensorflow/XLA JIT compiler.""" + +# pylint: disable=unused-import +from tensorflow.python.compiler.xla import jit +from tensorflow.python.compiler.xla import xla +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/experimental/xla_sharding.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/experimental/xla_sharding.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a6df557442452dc956a5c1c247b8df8f61c93c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/experimental/xla_sharding.py @@ -0,0 +1,587 @@ +# 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. +# ====================================== +"""Experimental support for defining XLA shardings.""" + +import numpy as _np # Avoids becoming a part of public Tensorflow API. + +from tensorflow.compiler.tf2xla.python import xla as tf2xla +from tensorflow.compiler.xla import xla_data_pb2 +from tensorflow.core.framework import attr_value_pb2 + + +class Sharding(object): + """A class to support adding sharding attributes to Ops. + + Use the factory constructors and then call apply_to_tensor: + Sharding.replicate().apply_to_tensor(tensor) + """ + + def __init__(self, proto=None): + """Do not use this constructor; use the factory functions below.""" + self._proto = proto + + @classmethod + def replicate(cls): + """Returns a replicated sharding attribute. + + This causes an op to be computed in its entirety independently on all + cores in the XLA device. + """ + return Sharding( + proto=xla_data_pb2.OpSharding(type=xla_data_pb2.OpSharding.REPLICATED)) + + @classmethod + def manual(cls): + """Returns a manuall sharding attribute. + + This means the op is manually partitioned by the user and XLA will not + change the shapes. + """ + return Sharding( + proto=xla_data_pb2.OpSharding(type=xla_data_pb2.OpSharding.MANUAL)) + + @classmethod + def assign_device(cls, core): + """Returns an AssignDevice sharding attribute. + + This causes an op to be computed in its entirety only on one core in + the XLA device. + Args: + core: The core to assign this Op to. + """ + return Sharding( + proto=xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.MAXIMAL, + tile_assignment_dimensions=[1], + tile_assignment_devices=[core])) + + @classmethod + def tile(cls, tile_assignment): + """Returns a Tiled sharding attribute. + + This causes an op to be partially computed on multiple cores in the + XLA device. + + Args: + tile_assignment: An np.ndarray describing the topology of the tiling and + which device will compute which part of the topology. + + Raises: + TypeError: tile_assignment was not of np.array type. + + TODO(jmolloy): This concept is nefarious and is not + something we really want to expose to users (especially as the + contract for tile_assignment is very strict). + """ + if not isinstance(tile_assignment, _np.ndarray): + raise TypeError('Tile assignment must be of type np.ndarray') + dims = list(tile_assignment.shape) + flattened_devices = tile_assignment.reshape(-1, order='C') + return Sharding( + proto=xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.OTHER, + tile_assignment_dimensions=dims, + tile_assignment_devices=list(flattened_devices))) + + @classmethod + def subgroup_tile(cls, tile_assignment, subgroup_modes): + """Returns a subgroup manual sharding attribute. + + This is similar to tile(), but tile_assignment has one or more dimension + than the tensor, and subgroup_modes define the sharding types in the last + dimensions of tile_assignment. + + Args: + tile_assignment: An np.ndarray describing the topology of the tiling and + which device will compute which part of the topology. + subgroup_modes: sharding types for the dimension more than the tensor + shape rank. + + Raises: + TypeError: tile_assignment was not of np.array type or subgroup_modes + has unsupported sharding type. + """ + if not isinstance(tile_assignment, _np.ndarray): + raise TypeError('SubgroupTile assignment must be of type np.ndarray') + + if not isinstance(subgroup_modes, list): + raise TypeError('subgroup_modes in subgroup manual must be of type list') + + if len(tile_assignment.shape) < len(subgroup_modes): + raise TypeError('SubgroupTile assignment must have rank larger than' + ' length of subgroup_modes') + + for sharding_type in subgroup_modes: + if sharding_type not in [ + xla_data_pb2.OpSharding.REPLICATED, xla_data_pb2.OpSharding.MANUAL + ]: + raise TypeError( + 'Each sharding_type in subgroup_modes in subgroup manual must ' + 'be of type xla_data_pb2.OpSharding.REPLICATED' + ' or xla_data_pb2.OpSharding.MANUAL') + dims = list(tile_assignment.shape) + flattened_devices = tile_assignment.reshape(-1, order='C') + return Sharding( + proto=xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.OTHER, + tile_assignment_dimensions=dims, + tile_assignment_devices=list(flattened_devices), + last_tile_dims=list(subgroup_modes))) + + @classmethod + def partial_tile(cls, tile_assignment): + """Returns a partially tiled sharding attribute. + + This is similar to tile(), but tile_assignment has one more dimension than + the tensor, and tiles in the last dimension of tile_assignment are + replicated. + + Args: + tile_assignment: An np.ndarray describing the topology of the tiling and + which device will compute which part of the topology. + + Raises: + TypeError: tile_assignment was not of np.array type. + """ + if not isinstance(tile_assignment, _np.ndarray): + raise TypeError('PartialTile assignment must be of type np.ndarray') + dims = list(tile_assignment.shape) + flattened_devices = tile_assignment.reshape(-1, order='C') + return Sharding( + proto=xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.OTHER, + tile_assignment_dimensions=dims, + tile_assignment_devices=list(flattened_devices), + replicate_on_last_tile_dim=True)) + + @classmethod + def split(cls, tensor, split_dimension, num_devices, input_shape=None): + """Returns a Sharding that splits a tensor across a dimension. + + This creates a Tiled attribute, similar to tile(), but easier to use for the + common case of tiling a tensor N ways in one dimension. + + Args: + tensor: A tf.Tensor to split. + split_dimension: The dimension number to split. + num_devices: The number of cores to split `tensor` over. + input_shape: The shape of the original tensor. + + Raises: + ValueError: The tensor to split was smaller in the split dimension than + the number of devices to split over. + """ + if input_shape: + shape = input_shape + else: + shape = tensor.shape.as_list() + if (shape[split_dimension] is not None and + shape[split_dimension] < num_devices): + raise ValueError('Split dimension was smaller than the required number ' + 'of splits: shape=%r, dimension=%r, num_devices=%r' % + (shape, split_dimension, num_devices)) + + tile_assignment_dims = [1] * len(shape) + tile_assignment_dims[split_dimension] = num_devices + + return Sharding( + proto=xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.OTHER, + tile_assignment_dimensions=tile_assignment_dims, + tile_assignment_devices=range(num_devices))) + + def apply_to_tensor(self, + tensor, + assign_tuple_sharding=False, + use_sharding_op=False, + unspecified_dims=None): + """Applies this Sharding attribute to `tensor`. + + Args: + tensor: A tf.Tensor to split. + assign_tuple_sharding: If the sharding type should be a tuple. + use_sharding_op: Whether to create a sharding op on `tensor`. + unspecified_dims: An optional list of dimensions unspecified. + + Returns: + The tensor with Sharding attribute. + """ + if unspecified_dims: + assert use_sharding_op and not assign_tuple_sharding + proto = self._proto + if use_sharding_op: + if assign_tuple_sharding: + proto = self._create_tuple_proto(num_outputs=1) + tensor = tf2xla.sharding(tensor, sharding=proto.SerializeToString()) + else: + tensor = tf2xla.sharding( + tensor, + sharding=proto.SerializeToString(), + unspecified_dims=unspecified_dims or []) + elif assign_tuple_sharding or len(tensor.op.outputs) > 1: + proto = self._get_or_create_tuple_proto(tensor.op) + # We can't mutate an element of old_proto.tuple_shardings, so create + # a new proto. + tuple_shardings = list(proto.tuple_shardings) + tuple_shardings[tensor.value_index] = self._proto + proto = xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.TUPLE, tuple_shardings=tuple_shardings) + + # TODO(jmolloy): This need to be seriously revisited before declaring this + # API available for public use. + # pylint: disable=protected-access + tensor.op._set_attr('_XlaSharding', + attr_value_pb2.AttrValue(s=proto.SerializeToString())) + return tensor + + def apply_to_operation(self, operation): + """Applies this Sharding attribute to `operation`. + + Args: + operation: A tf.Operation to add sharding annotation. + """ + attr_value = attr_value_pb2.AttrValue(s=self._proto.SerializeToString()) + # pylint: disable=protected-access + operation._set_attr('_XlaSharding', attr_value) + + @property + def proto(self): + """Return the sharding protobuf of type xla_data_pb2.OpSharding.""" + return self._proto + + def _get_or_create_tuple_proto(self, op): + try: + attr = op.get_attr('_XlaSharding') + proto = xla_data_pb2.OpSharding() + proto.ParseFromString(attr) + return proto + except ValueError: + return self._create_tuple_proto(len(op.outputs)) + + def _create_tuple_proto(self, num_outputs): + shardings = [ + xla_data_pb2.OpSharding(type=xla_data_pb2.OpSharding.REPLICATED) + ] * num_outputs + return xla_data_pb2.OpSharding( + type=xla_data_pb2.OpSharding.TUPLE, tuple_shardings=shardings) + + +def copy_sharding(from_tensor, to_tensor, use_sharding_op=False): + """Copies the a tensor's sharding to another. + + Args: + from_tensor: Source tensor. Must be the sole output of an op. + to_tensor: the tensor the annotate with the copy. + use_sharding_op: whether to create a sharding op on `to_tensor`. + + Returns: + A tensor with sharding annotation copied from `from_tensor`. + """ + sharding = get_tensor_sharding(from_tensor) + if sharding is None: + return to_tensor + + if use_sharding_op: + to_tensor = tf2xla.sharding(to_tensor, sharding=sharding) + attr_value = attr_value_pb2.AttrValue(s=sharding) + # pylint: disable=protected-access + to_tensor.op._set_attr('_XlaSharding', attr_value) + return to_tensor + +# Helpers for the above factory functions that allow easy application of +# shardings, for example: +# tensor = xla_sharding.replicate(tensor) + + +def replicate(tensor, assign_tuple_sharding=False, use_sharding_op=False): + return Sharding.replicate().apply_to_tensor( + tensor, + assign_tuple_sharding=assign_tuple_sharding, + use_sharding_op=use_sharding_op) + + +def assign_device(tensor, + device, + assign_tuple_sharding=False, + use_sharding_op=False): + """Returns a tensor that has AssignDevice sharding attribute.""" + return Sharding.assign_device(device).apply_to_tensor( + tensor, + assign_tuple_sharding=assign_tuple_sharding, + use_sharding_op=use_sharding_op) + + +def tile(tensor, + tile_assignment, + assign_tuple_sharding=False, + use_sharding_op=False, + unspecified_dims=None): + """Returns a tensor that has tiled sharding. + + Args: + tensor: A tf.Tensor to shard. + tile_assignment: An np.ndarray describing the topology of the tiling and + which device will compute which part of the topology. + assign_tuple_sharding: If the sharding type should be a tuple. + use_sharding_op: If true, adds a sharding op to set the sharding. + unspecified_dims: An optional list of dimensions unspecified. + """ + return Sharding.tile(tile_assignment).apply_to_tensor( + tensor, + assign_tuple_sharding=assign_tuple_sharding, + use_sharding_op=use_sharding_op, + unspecified_dims=unspecified_dims or []) + + +def split(tensor, + split_dimension, + num_devices, + assign_tuple_sharding=False, + use_sharding_op=False, + input_shape=None): + """Returns a tensor that is split along the given dimension. + + Args: + tensor: A tf.Tensor to split. + split_dimension: The dimension to split. + num_devices: The number of devices to partition the dimension. + assign_tuple_sharding: If the sharding type should be a tuple. + use_sharding_op: If true, adds a sharding op to set the sharding. + input_shape: The full shape of the input tensor. + """ + return Sharding.split(tensor, split_dimension, num_devices, + input_shape).apply_to_tensor( + tensor, + assign_tuple_sharding=assign_tuple_sharding, + use_sharding_op=use_sharding_op) + + +def partial_tile(tensor, + tile_assignment, + use_sharding_op=False, + unspecified_dims=None): + """Returns a tensor that has tiled sharding. + + Args: + tensor: A tf.Tensor to shard. + tile_assignment: An np.ndarray describing the topology of the tiling and + which device will compute which part of the topology. It must have one + more dimension than tensor, and the last dimension represents partially + replicated tiles. + use_sharding_op: If true, adds a sharding op to set the sharding. + unspecified_dims: An optional list of dimensions unspecified. + """ + return Sharding.partial_tile(tile_assignment).apply_to_tensor( + tensor, + use_sharding_op=use_sharding_op, + unspecified_dims=unspecified_dims or []) + + +def get_op_sharding(op): + """Returns sharding attribute of an op. + + Args: + op: a TensorFlow op. + + Returns: + The attribute representing XLA sharding on this op. + """ + try: + return op.get_attr('_XlaSharding') + except ValueError: + return None + except AttributeError: + # AttributeError: 'DistributedVarOp' object has no attribute 'get_attr'. + return None + + +def get_tensor_sharding(tensor): + """Returns sharding attribute of a Tensor. + + Args: + tensor: a Tensor. + + Returns: + The attribute representing XLA sharding on tensor's op. + """ + try: + return get_op_sharding(tensor.op) + except AttributeError: + # AttributeError: Tensor.op is meaningless when eager execution is enabled. + return None + + +def get_sharding_tile_shape(sharding): + """Returns the tile assignment shape for a sharded Tensor. + + Args: + sharding: a serialized OpSharding message describing the layout of a + sharded Tensor. + + Returns: + A list, for each dimension of the sharded Tensor, of the number of shards + into which it has been split. Returns None if the input indicates no tile + assignments. + """ + if sharding is None: + return None + sharding_message = xla_data_pb2.OpSharding() + sharding_message.ParseFromString(sharding) + if sharding_message.tile_assignment_dimensions: + return sharding_message.tile_assignment_dimensions + else: + return None + + +def auto_to_manual_spmd_partition(tensor, + manual_sharding, + single_dim=-1, + unspecified_dims=None): + """Switches from automatic SPMD partitioning to manual partitioning. + + Converts a full-shaped tensor (to be automatically partitioned by SPMD + partitioner) to a shard-shaped tensor to be consumed by manually partitioned + ops. + + Args: + tensor: A tf.Tensor in full shape. + manual_sharding: A serialized string of OpSharding to be used in manual + partitioning. + single_dim: If >= 0, the conversion will happen only on this dim in + subgroups. + unspecified_dims: An optional list of dimensions unspecified. + + Returns: + A shard-shaped tensor to be consumed by manually partitioned ops. + """ + return tf2xla.spmd_full_to_shard_shape( + tensor, + manual_sharding=manual_sharding, + dim=single_dim, + unspecified_dims=unspecified_dims or []) + + +def manual_to_auto_spmd_partition(tensor, + manual_sharding, + full_shape, + single_dim=-1, + unspecified_dims=None): + """Switches from manual partitioning to automatic SPMD partitioning. + + Converts a shard-shaped tensor (manually partitioned in SPMD-style) to a + full-shaped tensor to be partitioned automatically by the SPMD partitioner. + + Args: + tensor: A tf.Tensor in shard shape. + manual_sharding: a serialized string of OpSharding to be used in manual + partitioning. + full_shape: the shape of tensor before partitioning. + single_dim: If >= 0, the conversion will happen only on this dim in + subgroups. + unspecified_dims: An optional list of dimensions unspecified. + + Returns: + A full-shaped tensor to be partitioned automatically by the SPMD + partitioner. + """ + return tf2xla.spmd_shard_to_full_shape( + tensor, + manual_sharding=manual_sharding, + full_shape=full_shape, + dim=single_dim, + unspecified_dims=unspecified_dims or []) + + +def mesh_split_sharding(device_mesh, + tensor_split_dims_mapping, + manual_mesh_dims=None): + """Returns a Sharding object representing sharding along multiple dimensions. + + Args: + device_mesh: An np.ndarray describing the topology of the device mesh and + each element is the ID of the device in the topology. + tensor_split_dims_mapping: A list of integers that map each tensor axis to + the device mesh axis along which it is sharded. Its length is the tensor + rank, and tensor_split_dims_mapping[i] is device mesh axis for tensor + dimension i. Use -1 for tensor dimensions that are not sharded. + manual_mesh_dims: An optional list of mesh dims for manual subgroups. + + Raises: + ValueError: The number of tensor split dimensions is larger than device mesh + rank. + """ + manual_mesh_dims = manual_mesh_dims or [] + permutation = [d for d in tensor_split_dims_mapping if d >= 0 + ] + manual_mesh_dims + if len(permutation) > len(device_mesh.shape): + raise ValueError( + 'Number of tensor split dimensions (%r) is larger than device mesh ' + 'rank (%r). tensor_split_dims_mapping: %r, device_mesh.shape: %r' % + (len(permutation), len( + device_mesh.shape), tensor_split_dims_mapping, device_mesh.shape)) + # Append replicated dimensions to the end. + transpose_permutation = permutation + [ + d for d in range(len(device_mesh.shape)) if d not in permutation + ] + tile_assignment = _np.transpose(device_mesh, transpose_permutation) + tile_shape = [ + 1 if d < 0 else device_mesh.shape[d] + for d in (tensor_split_dims_mapping + manual_mesh_dims) + ] + subgroup_modes = [xla_data_pb2.OpSharding.MANUAL] * len(manual_mesh_dims) + partial = len(permutation) < len(device_mesh.shape) + if partial: + tile_shape.append(_np.prod(device_mesh.shape) // _np.prod(tile_shape)) + subgroup_modes.append(xla_data_pb2.OpSharding.REPLICATED) + tile_assignment = _np.reshape(tile_assignment, tile_shape) + + if manual_mesh_dims: + return Sharding.subgroup_tile(tile_assignment, subgroup_modes) + + if partial: + return Sharding.partial_tile(tile_assignment) + return Sharding.tile(tile_assignment) + + +def mesh_split(tensor, + device_mesh, + tensor_split_dims_mapping, + use_sharding_op=False, + manual_mesh_dims=None, + unspecified_dims=None): + """Returns a tensor that is split along multiple dimensions in a device mesh. + + Args: + tensor: A tf.Tensor to split. + device_mesh: An np.ndarray describing the topology of the device mesh and + each element is the ID of the device in the topology. + tensor_split_dims_mapping: A list of integers that map each tensor axis to + the device mesh axis along which it is sharded. Its length is the tensor + rank, and tensor_split_dims_mapping[i] is device mesh axis for tensor + dimension i. Use -1 for tensor dimensions that are not sharded. + use_sharding_op: If true, adds a sharding op to set the sharding. + manual_mesh_dims: An optional list of mesh dims for manual subgroups. + unspecified_dims: An optional list of dimensions unspecified. + + Raises: + ValueError: The number of tensor split dimensions is larger than device mesh + rank. + """ + sharding = mesh_split_sharding(device_mesh, tensor_split_dims_mapping, + manual_mesh_dims) + return sharding.apply_to_tensor( + tensor, + use_sharding_op=use_sharding_op, + unspecified_dims=unspecified_dims or []) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/jit.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/jit.py new file mode 100644 index 0000000000000000000000000000000000000000..90d63dacefc3c359c98ad37f43bc081cd752d043 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/jit.py @@ -0,0 +1,156 @@ +# 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. +# ============================================================================== +"""Library for controlling the Tensorflow/XLA JIT compiler.""" + +import contextlib + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.util.tf_export import tf_export + + +_XLA_SCOPE_KEY = ("__xla_scope",) + + +class _XlaScope(object): + """Keeps track of previous XLA scope calls, and depth of current call.""" + + def __init__(self, count, depth): + self.count = count + self.depth = depth + + +@contextlib.contextmanager +@tf_export("xla.experimental.jit_scope") +def experimental_jit_scope(compile_ops=True, separate_compiled_gradients=False): + """Enable or disable JIT compilation of operators within the scope. + + NOTE: This is an experimental feature. + + The compilation is a hint and only supported on a best-effort basis. + + Example usage: + + ```python + with tf.xla.experimental.jit_scope(): + c = tf.matmul(a, b) # compiled + with tf.xla.experimental.jit_scope(compile_ops=False): + d = tf.matmul(a, c) # not compiled + with tf.xla.experimental.jit_scope( + compile_ops=lambda node_def: 'matmul' in node_def.op.lower()): + e = tf.matmul(a, b) + d # matmul is compiled, the addition is not. + ``` + + Example of `separate_compiled_gradients`: + + ```python + # In the example below, the computations for f, g and h will all be compiled + # in separate scopes. + with tf.xla.experimental.jit_scope( + separate_compiled_gradients=True): + f = tf.matmul(a, b) + g = tf.gradients([f], [a, b], name='mygrads1') + h = tf.gradients([f], [a, b], name='mygrads2') + ``` + + Ops that are not in the scope may be clustered and compiled with ops in + the scope with `compile_ops=True`, while the ops in the scope with + `compile_ops=False` will never be compiled. + + For example: + + ```python + # In the example below, x and loss may be clustered and compiled together, + # while y will not be compiled. + with tf.xla.experimental.jit_scope(): + x = tf.matmul(a, b) + with tf.xla.experimental.jit_scope(compile_ops=False): + y = tf.matmul(c, d) + loss = x + y + ``` + + If you want to only compile the ops in the scope with `compile_ops=True`, + consider adding an outer `jit_scope(compile_ops=False)`: + + ```python + # In the example below, only x will be compiled. + with tf.xla.experimental.jit_scope(compile_ops=False): + with tf.xla.experimental.jit_scope(): + x = tf.matmul(a, b) + y = tf.matmul(c, d) + loss = x + y + ``` + + Args: + compile_ops: Whether to enable or disable compilation in the scope. + Either a Python bool, or a callable that accepts the parameter + `node_def` and returns a python bool. + separate_compiled_gradients: If true put each gradient subgraph into a + separate compilation scope. This gives fine-grained control over which + portions of the graph will be compiled as a single unit. Compiling + gradients separately may yield better performance for some graphs. + The scope is named based on the scope of the forward computation as well + as the name of the gradients. As a result, the gradients will be compiled + in a scope that is separate from both the forward computation, and from + other gradients. + Raises: + RuntimeError: if called when eager execution is enabled. + Yields: + The current scope, enabling or disabling compilation. + """ + if context.executing_eagerly(): + raise RuntimeError("xla.experimental.jit_scope is not supported when eager " + "execution is enabled. Try use it inside tf.function.") + + if callable(compile_ops): + def xla_compile(node_def): + return attr_value_pb2.AttrValue(b=compile_ops(node_def)) + else: + xla_compile = attr_value_pb2.AttrValue(b=compile_ops) + + attrs = { + "_XlaCompile": + xla_compile, + "_XlaSeparateCompiledGradients": + attr_value_pb2.AttrValue(b=bool(separate_compiled_gradients)) + } + + # Find the singleton counter for the current scoped graph. If it + # doesn't exist, create one. + xla_scope_counter = ops.get_collection(_XLA_SCOPE_KEY) + if not xla_scope_counter: + xla_scope_counter = _XlaScope(0, 0) + ops.add_to_collection(_XLA_SCOPE_KEY, xla_scope_counter) + else: + xla_scope_counter = xla_scope_counter[0] + + if xla_scope_counter.depth == 0: + # If we're at the root xla scope, we can increase the counter so + # future calls to jit_scope use a different scope value. + # If we're already within a scope, we'll be fusing using the scope + # controlled by the parent. + attrs["_XlaScope"] = attr_value_pb2.AttrValue( + s=("jit_scope_%d" % xla_scope_counter.count).encode()) + xla_scope_counter.count += 1 + + xla_scope_counter.depth += 1 + + # pylint: disable=protected-access + with ops.get_default_graph()._attr_scope(attrs): + yield + # pylint: enable=protected-access + + xla_scope_counter.depth -= 1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/xla.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2312dfd0589116c547f5d1c37f4b9defd0fcca --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/compiler/xla/xla.py @@ -0,0 +1,635 @@ +# 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. +# ============================================================================= +"""xla is an experimental library that provides XLA support APIs.""" + +import contextlib + + +from tensorflow.compiler.jit.ops import xla_ops +from tensorflow.compiler.jit.ops import xla_ops_grad # pylint: disable=unused-import +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.distribute import summary_op_util +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export + +_XLA_COMPILE_ATTR = '_xla_compile_id' +_MAX_WARNING_LINES = 5 + +# Operations that indicate some error in the users graph. For example, XLA +# computation should not have any Placeholder op. +_DENYLISTED_OPS = set([ + 'Placeholder', +]) + +# XLA doesn't currently support reading of intermediate tensors, thus some ops +# are not supported. +_UNSUPPORTED_OPS = set([ + 'AudioSummary', + 'AudioSummaryV2', + 'HistogramSummary', + 'ImageSummary', + 'MergeSummary', + 'Print', + 'ScalarSummary', + 'TensorSummary', + 'TensorSummaryV2', +]) + + +@tf_export('xla.experimental.compile') +@deprecated( + None, 'xla.experimental.compile is deprecated. Consider using ' + '`@tf.function(jit_compile=True)`.', + warn_once=True) +def compile(computation, inputs=None): # pylint: disable=redefined-builtin + """Builds an operator that compiles and runs `computation` with XLA. + + NOTE: In eager mode, `computation` will have `@tf.function` semantics. + + Args: + computation: A Python function that builds a computation to apply to the + input. If the function takes n inputs, 'inputs' should be a list of n + `Tensor`s. + + `computation` may return a list of `Tensor`s and `Operation`s. + `Tensor`s must come before `Operation`s in the returned list. + + All `Operation`s returned from `computation` will be executed when + evaluating any of the returned output tensors. + inputs: A list of inputs or `None` (equivalent to an empty list). Each input + can be a nested structure containing values that can be converted to + `Tensor`s. Note that passing an N-dimension list of compatible values will + result in an N-dimension list of scalar `Tensor`s rather than a single + Rank-N `Tensor`. If you need a different behavior, convert parts of + `inputs` to `Tensor`s with `tf.convert_to_tensor`. + + Returns: + List of `Tensor`s corresponding to the `Tensor`s from + the output of `computation` i.e. the same return value as if + computation(*inputs) is called directly, with the following exceptions: + * None output: a NoOp would be returned with a control dependency on + `computation`. + * Single value output: a tuple containing the value would be returned. + * Operation-only outputs: a NoOp would be returned with a control + dependency on `computation`. + TODO(b/121383831): Investigate into removing these special cases. + + Raises: + RuntimeError: When eager execution is enabled. + + Known issues: + When a tf.random operation is built with XLA, the implementation doesn't + pass the user provided seed to the XLA compiler. As such, the XLA compiler + generates a random number and uses it as a seed when compiling the + operation. This implementation causes a violation of the Tensorflow + defined semantics in two aspects. First, changing the value of the user + defined seed doesn't change the numbers generated by the operation. + Second, when a seed is not specified, running the program multiple times + will generate the same numbers. + """ + if context.executing_eagerly(): + + @def_function.function + def xla_compile_wrapper(): + return _compile_internal(computation, inputs) + + return xla_compile_wrapper() + + return _compile_internal(computation, inputs) + + +class XLACompileContext(control_flow_ops.XLAControlFlowContext): + """A `ControlFlowContext` for nodes inside an XLA computation cluster. + + THIS IS ONLY FOR TENSORFLOW INTERNAL IMPLEMENTATION, DO NO USE DIRECTLY. + + The primary role of `XLACompileContext` is to mark operators inside a + xla.compile() computation with attribute "_xla_compile_id=XYZ", where XYZ is + a unique name. + + `ControlFlowContext` is used to perform the annotation since it integrates + with Tensorflow constructs like ResourceVariables. For example, if a + `ResourceVariable` is constructed inside a xla.compile() block, the + `ResourceVariable` implementation can use + `with ops.control_dependencies(None)` to build the variable's definition + outside the compiled computation. + """ + + def __init__(self, name, pivot): + """Builds a new XLACompileContext. + + Args: + name: a unique name for the context, used to populate the + `_xla_compile_id` attribute. + pivot: a pivot node. Nodes in the XLACompileContext that do not have any + inputs will have a control dependency on the pivot node. This ensures + that nodes are correctly included in any enclosing control flow + contexts. + """ + super(XLACompileContext, self).__init__() + self._name = name + self._name_as_bytes = compat.as_bytes(name) + self._unsupported_ops = [] + self._pivot = pivot + + def report_unsupported_operations(self): + if self._unsupported_ops: + op_str = '\n'.join([ + ' %s (%s)' % (op.type, op.name) + for op in self._unsupported_ops[:_MAX_WARNING_LINES] + ]) + logging.warning('%d unsupported operations found: \n%s', + len(self._unsupported_ops), op_str) + if len(self._unsupported_ops) > _MAX_WARNING_LINES: + logging.warning('... and %d more', + len(self._unsupported_ops) - _MAX_WARNING_LINES) + + def _RemoveExternalControlEdges(self, op: ops.Operation): + """Remove any external control dependency on this op.""" + internal_control_inputs = [] + external_control_inputs = [] + for x in op.control_inputs: + # pylint: disable=protected-access + is_internal_op = False + ctxt = x._get_control_flow_context() + while ctxt is not None: + if ctxt == self: + is_internal_op = True + break + ctxt = ctxt._outer_context + if is_internal_op: + internal_control_inputs.append(x) + else: + external_control_inputs.append(x) + # pylint: enable=protected-access + # pylint: disable=protected-access + op._remove_all_control_inputs() + op._add_control_inputs(internal_control_inputs) + # pylint: enable=protected-access + return internal_control_inputs, external_control_inputs + + def AddOp(self, op: ops.Operation): + """Create op in XLACompileContext and notifies outer context recursively.""" + # pylint: disable=protected-access + if op.type in _DENYLISTED_OPS: + logging.error( + 'Operation of type %s (%s) is not supported in XLA. Execution will ' + 'fail if this op is used in the graph. ', op.type, op.name) + + # TODO(ycao): Automatically disable summaries instead of reporting them. + if op.type in _UNSUPPORTED_OPS: + self._unsupported_ops.append(op) + + if any(x.dtype._is_ref_dtype for x in op.inputs): + raise NotImplementedError( + 'Non-resource Variables are not supported inside XLA computations ' + '(operator name: %s)' % op.name) + + if _XLA_COMPILE_ATTR in op.node_def.attr: + raise ValueError('XLA compiled computations cannot be nested, (operator ' + 'name: %s)' % op.name) + + op._set_attr( + _XLA_COMPILE_ATTR, attr_value_pb2.AttrValue(s=self._name_as_bytes)) + + op.graph.prevent_feeding(op) + op.graph.prevent_fetching(op) + + # Remove any control edges from outer control flow contexts. These may cause + # mismatched frame errors. An example is when one of op's inputs is + # generated in a different While control flow context. + (internal_control_inputs, + external_control_inputs) = self._RemoveExternalControlEdges(op) + + if not op.inputs: + # Add a control edge from the control pivot to this op. + if not internal_control_inputs: + # pylint: disable=protected-access + op._add_control_input(self._pivot) + # pylint: enable=protected-access + else: + for index in range(len(op.inputs)): + x = op.inputs[index] + real_x = self.AddValue(x) + if real_x is not x: + op._update_input(index, real_x) # pylint: disable=protected-access + + if external_control_inputs: + # Use an identity to pull control inputs as data inputs. Note that we + # ignore ops which don't have outputs. TODO(phawkins): fix that. + with ops.control_dependencies(None): + self.Enter() + external_control_inputs = [ + array_ops.identity(x.outputs[0]).op + for x in external_control_inputs + if x.outputs + ] + self.Exit() + # pylint: disable=protected-access + op._add_control_inputs(external_control_inputs) + # pylint: enable=protected-access + + # Mark op's outputs as seen by this context and any outer contexts. + output_names = [x.name for x in op.outputs] + context = self + while context is not None: + # pylint: disable=protected-access + context._values.update(output_names) + context = context._outer_context + # pylint: enable=protected-access + + if self._outer_context: + self._outer_context.AddInnerOp(op) + + def AddValue(self, val): + """Add `val` to the current context and its outer context recursively.""" + if val.name in self._values: + # Use the real value if it comes from outer context. + result = self._external_values.get(val.name) + return val if result is None else result + + result = val + self._values.add(val.name) + if self._outer_context: + result = self._outer_context.AddValue(val) + self._values.add(result.name) + + self._external_values[val.name] = result + + return result + + def AddInnerOp(self, op: ops.Operation): + self.AddOp(op) + if self._outer_context: + self._outer_context.AddInnerOp(op) + + @property + def grad_state(self): + # Define the gradient loop state associated with the XLACompileContext to + # be None as the XLACompileContext does not get nested nor does the + # grad_state outside the XLACompileContext affect the graph inside so the + # grad_state should be as if this is the top-level gradient state. + return None + + @property + def back_prop(self): + """Forwards to the enclosing while context, if any.""" + if self.GetWhileContext(): + return self.GetWhileContext().back_prop + return False + + +def _compile_internal(computation, inputs=None): + """Builds graph operators that compiles and symbolically executes computation. + + Args: + computation: A Python function that builds the computation to compile and + execute. + inputs: A list of inputs or `None` (equivalent to an empty list). Each input + can be a nested structure containing values that are convertible to + tensors. Note that passing an N-dimension list of compatible values will + result in a N-dimension list of scalar tensors rather than a single Rank-N + tensors. If you need different behavior, convert part of inputs to tensors + with `tf.convert_to_tensor`. + + Returns: + Same data structure as if computation(*inputs) is called directly with some + exceptions for correctness. Exceptions include: 1) None output 2) Single + value output 3) Operation-only outputs + Raises: + ValueError: If any element in computation outputs is neither an operations + or a value that can be converted to tensor. + ValueError: If computation outputs is non-flat and contains any Operations. + TypeError: If `inputs` is not a list or tuple. + """ + if inputs is None: + inputs = [] + + if not isinstance(inputs, collections_abc.Sequence): + raise TypeError('inputs must be a list') + + # Flatten inputs. + flat_inputs = nest.flatten(inputs) + # Converts inputs to Tensors. + flat_inputs = [ops.convert_to_tensor(x) for x in flat_inputs] + + cluster_name = ops.get_default_graph().unique_name('cluster') + pivot = control_flow_ops.no_op(name=cluster_name + '/pivot') + context = XLACompileContext(name=cluster_name, pivot=pivot) + try: + context.Enter() + + # Add identity ops so even unused inputs are 'consumed' by the + # computation. + flat_inputs = [ + array_ops.identity(x, name='input_{}'.format(i)) + for i, x in enumerate(flat_inputs) + ] + + # Re-pack flat_inputs in same structure as 'inputs'. + computation_inputs = nest.pack_sequence_as( + structure=inputs, flat_sequence=flat_inputs) + + # Only resource variables work inside an XLA computation, so turn on + # resource variables for the computation. + vscope = variable_scope.get_variable_scope() + saved_use_resource = vscope.use_resource + vscope.set_use_resource(True) + + with _disable_summary_context(): + outputs = computation(*computation_inputs) + + # Restore variable scope after computation. + vscope.set_use_resource(saved_use_resource) + + outputs_is_flat = is_flat(outputs) + if outputs_is_flat: + output_tensors, control_deps = _postprocess_flat_outputs(outputs) + else: + output_tensors, control_deps = _postprocess_non_flat_outputs(outputs) + + context.ExitResult(output_tensors) + finally: + context.report_unsupported_operations() + context.Exit() + + # When XLA computation returns only operations and no tensors, a NoOp + # dependent on the operations in outputs is returned. Otherwise final + # outputs would be empty and there is no way to trigger returned + # operations. + if not output_tensors: + return control_flow_ops.group(control_deps, name='output_0') + + output_tensors = [ + xla_ops.xla_cluster_output(o, name='output{}'.format(i)) + for i, o in enumerate(output_tensors) + ] + + with ops.control_dependencies(control_deps): + # Wraps the outputs in identity operators that carries control + # dependencies. + output_tensors = [ + array_ops.identity(o, name='output_%d' % i) + for i, o in enumerate(output_tensors) + ] + + # If `computation` returned non-flat output structure, pack output tensors + # back into same structure. + if not outputs_is_flat: + output_tensors = nest.pack_sequence_as( + structure=outputs, flat_sequence=output_tensors) + + return output_tensors + + +def is_flat(outputs): + """Checks if outputs is a flat structure. + + Following structures and values are considered flat: + 1) None + 2) A single object + 3) A list or tuple of Tensors/Operations + + The only structures that this function understands are sequences, + dictionaries and types defined using the attrs library. E.g. this means + that if outputs contains a single user-defined Object, it is considered to + be flat. Errors are raised later on if that Object cannot be converted to a + Tensor. + + Args: + outputs: Output from `computation` inside `xla.compile`. + + Returns: + A boolean indicates whether outputs is flat. + """ + # If outputs is a list or tuple, check if it has any nested structure. If + # there is, then outputs is non-flat. + if isinstance(outputs, collections_abc.Sequence): + for o in outputs: + if (isinstance(o, collections_abc.Sequence) or + isinstance(o, collections_abc.Mapping) or + hasattr(o.__class__, '__attrs_attrs__')): + return False + + # If outputs is a dict, it is non-flat. + if isinstance(outputs, collections_abc.Mapping): + return False + + # If outputs is from the attrs library, it is non-flat. + if hasattr(outputs.__class__, '__attrs_attrs__'): + return False + + # Getting here means either outputs itself is a single non-structured value + # or it is a flat list of single non-structured values. + return True + + +def _postprocess_flat_outputs(outputs): + """Validates flat outputs and adds back device assignments. + + Args: + outputs: Output from `computation` inside `xla.compile`. + + Returns: + Tensors and Operations extracted from outputs. + """ + # Following code segment is to preserve legacy behavior. Previously we only + # supported flat outputs and thus for consistency it was nice to convert even + # single element into a tuple. But now that we support arbitrary output + # structure, this is no longer necessary. + # TODO(b/121383831): Migrate all legacy use cases and delete this special + # case. + # If the computation returns `None`, make it an empty tuple. + if outputs is None: + outputs = tuple() + # If the computation only returned one value, make it a tuple. + if not isinstance(outputs, collections_abc.Sequence): + outputs = (outputs,) + + # Append `no_op` here so that return value of this function always contains + # at least one op that can trigger XlaLaunch node. + outputs += (control_flow_ops.no_op(),) + try: + outputs = [ + o if isinstance(o, ops.Operation) else ops.convert_to_tensor(o) + for o in outputs + ] + except Exception as e: + raise ValueError( + 'XLA computation function return values must all either be Operations' + ' or convertible to Tensors. Got error: "%s"' % str(e)) + + # Separates the returned Operations and Tensors. + output_operations = [o for o in outputs if isinstance(o, ops.Operation)] + output_tensors = [o for o in outputs if not isinstance(o, ops.Operation)] + + if outputs != output_tensors + output_operations: + raise ValueError( + 'XLA computation function must return zero or more Tensor values ' + 'followed by zero or more Operations.') + + new_output_tensors = [] + for t in output_tensors: + with ops.device(t.device if t.device else ''): + new_output_tensors.append(array_ops.identity(t)) + + return new_output_tensors, output_operations + + +def _postprocess_non_flat_outputs(outputs): + """Validates non-flat outputs and adds back device assignments. + + Args: + outputs: Output from `computation` inside `xla.compile`. + + Returns: + Tensors extracted from outputs and an empty list because Operations are not + allowed in non-flat outputs.. + """ + # Convert all non-Operation outputs to Tensors. + new_output_tensors = [] + for o in nest.flatten(outputs): + if isinstance(o, ops.Operation): + raise ValueError( + 'xla.compile does not support Operation as return value in non-flat ' + 'output structure. You can set returned Operations as control ' + 'dependencies of returned Tensors so Operations are triggered when ' + 'Tensors are evaluated. Operation found: "%s"' % o.name) + + try: + o = ops.convert_to_tensor(o) + except Exception as e: + raise ValueError( + 'XLA computation function return values must all either be ' + 'Operations or convertible to Tensors. Got error: "%s"' % str(e)) + + # Makes sure even pass-through inputs/outputs are touched in compile + # context by creating an Identity node inside compile context. + with ops.device(o.device if o.device else ''): + new_output_tensors.append(array_ops.identity(o)) + + return new_output_tensors, [] + + +@contextlib.contextmanager +def _disable_summary_context(): + """Enters a context where all summary ops are skipped. + + Summaries are not yet supported in xla.compile(). So we provide this context + manager that can skip creating summary ops. This is a temporary workaround due + to XLA not supporting summary ops. + + Yields: + None. + """ + original_skip_summary_func = summary_op_util.skip_summary + summary_op_util.skip_summary = lambda: True + + try: + yield + finally: + summary_op_util.skip_summary = original_skip_summary_func + + +class _CapturedObject(object): + """A placeholder to capture an object.""" + + def __init__(self): + self._object = None + + def capture(self, o): + if self._object: + raise RuntimeError( + 'InternalError: _CapturedObject can capture only once. Please file ' + 'bug.') + + self._object = o + + def get(self): + return self._object + + +def _get_scaffold(captured_scaffold_fn): + """Retrieves the Scaffold from `captured_scaffold_fn`.""" + scaffold_fn = captured_scaffold_fn.get() + + if not scaffold_fn: + return None + + scaffold = scaffold_fn() + if scaffold is None: + raise ValueError( + 'TPUEstimatorSpec.scaffold_fn returns None, which is not allowed') + + return scaffold + + +def check_function_argument_count(func, input_arity, infeed_queue): + """Validate the number of input arguments to an XLA function. + + Args: + func: the Python function that will be called to generate the body of an XLA + computation graph. + input_arity: the number of explicit arguments supplied by the caller. + infeed_queue: if not None, the infeed queue that will supply + additional arguments to the function. + + Returns: + None if function can be called with the supplied number of + arguments, or an error string if it cannot. + """ + def format_error(complaint, quantity): + return '%s %d argument%s' % (complaint, quantity, '' + if quantity == 1 else 's') + + num_args_supplied = input_arity + if infeed_queue is not None: + num_args_supplied += infeed_queue.number_of_tuple_elements + arg_spec = tf_inspect.getargspec(func) + num_func_args = len(arg_spec.args) + if arg_spec.defaults is None: + num_func_defaults = 0 + else: + num_func_defaults = len(arg_spec.defaults) + min_func_args = num_func_args - num_func_defaults + if num_args_supplied < min_func_args: + # The required number of arguments is not enough to call the function. + if num_func_defaults == 0 and arg_spec.varargs is None: + return format_error('exactly', num_func_args) + else: + return format_error('at least', min_func_args) + if arg_spec.varargs is None and num_args_supplied > num_func_args: + # The required number of arguments is too many to call the function. + if num_func_defaults == 0: + return format_error('exactly', num_func_args) + else: + return format_error('at most', num_func_args) + # Reaching here means either + # 1) There are varargs, func can accept any number of arguments greater than + # the minimum. + # 2) Number of supplied arguments falls in range of acceptable argument count + # of func. + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25602d92e590a38fc40060d6f017185209d4c0b3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/__init__.py @@ -0,0 +1,33 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""`tf.data.Dataset` API for input pipelines. + +See [Importing Data](https://tensorflow.org/guide/data) for an overview. +""" + +# pylint: disable=unused-import +from tensorflow.python.data import experimental +from tensorflow.python.data.ops.dataset_ops import AUTOTUNE +from tensorflow.python.data.ops.dataset_ops import Dataset +from tensorflow.python.data.ops.dataset_ops import INFINITE as INFINITE_CARDINALITY +from tensorflow.python.data.ops.dataset_ops import make_initializable_iterator +from tensorflow.python.data.ops.dataset_ops import make_one_shot_iterator +from tensorflow.python.data.ops.dataset_ops import UNKNOWN as UNKNOWN_CARDINALITY +from tensorflow.python.data.ops.iterator_ops import Iterator +from tensorflow.python.data.ops.options import Options +from tensorflow.python.data.ops.readers import FixedLengthRecordDataset +from tensorflow.python.data.ops.readers import TextLineDataset +from tensorflow.python.data.ops.readers import TFRecordDataset +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/benchmarks/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/benchmarks/benchmark_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/benchmarks/benchmark_base.py new file mode 100644 index 0000000000000000000000000000000000000000..9db8219589501de0219efdda21fee5db1d89b317 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/benchmarks/benchmark_base.py @@ -0,0 +1,250 @@ +# 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. +# ============================================================================== +"""Test utilities for tf.data benchmarking functionality.""" +import time + +import numpy as np + +from tensorflow.python.client import session +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.data.util import nest +from tensorflow.python.eager import context +from tensorflow.python.platform import test + + +class DatasetBenchmarkBase(test.Benchmark): + """Base class for dataset benchmarks.""" + + def _run_eager_benchmark(self, iterable, iters, warmup): + """Benchmark the iterable in eager mode. + + Runs the iterable `iters` times. In each iteration, the benchmark measures + the time it takes to go execute the iterable. + + Args: + iterable: The tf op or tf.data Dataset to benchmark. + iters: Number of times to repeat the timing. + warmup: If true, warms up the session caches by running an untimed run. + + Returns: + A float, representing the median time (with respect to `iters`) + it takes for the iterable to be executed `iters` num of times. + + Raises: + RuntimeError: When executed in graph mode. + """ + + deltas = [] + if not context.executing_eagerly(): + raise RuntimeError( + "Eager mode benchmarking is not supported in graph mode.") + + for _ in range(iters): + if warmup: + iterator = iter(iterable) + next(iterator) + + iterator = iter(iterable) + start = time.time() + next(iterator) + end = time.time() + deltas.append(end - start) + return np.median(deltas) + + def _run_graph_benchmark(self, + iterable, + iters, + warmup, + session_config, + initializer=None): + """Benchmarks the iterable in graph mode. + + Runs the iterable `iters` times. In each iteration, the benchmark measures + the time it takes to go execute the iterable. + + Args: + iterable: The tf op or tf.data Dataset to benchmark. + iters: Number of times to repeat the timing. + warmup: If true, warms up the session caches by running an untimed run. + session_config: A ConfigProto protocol buffer with configuration options + for the session. Applicable only for benchmarking in graph mode. + initializer: The initializer op required to initialize the iterable. + + Returns: + A float, representing the median time (with respect to `iters`) + it takes for the iterable to be executed `iters` num of times. + + Raises: + RuntimeError: When executed in eager mode. + """ + + deltas = [] + if context.executing_eagerly(): + raise RuntimeError( + "Graph mode benchmarking is not supported in eager mode.") + + for _ in range(iters): + with session.Session(config=session_config) as sess: + if warmup: + # Run once to warm up the session caches. + if initializer: + sess.run(initializer) + sess.run(iterable) + + if initializer: + sess.run(initializer) + start = time.time() + sess.run(iterable) + end = time.time() + deltas.append(end - start) + return np.median(deltas) + + def run_op_benchmark(self, op, iters=1, warmup=True, session_config=None): + """Benchmarks the op. + + Runs the op `iters` times. In each iteration, the benchmark measures + the time it takes to go execute the op. + + Args: + op: The tf op to benchmark. + iters: Number of times to repeat the timing. + warmup: If true, warms up the session caches by running an untimed run. + session_config: A ConfigProto protocol buffer with configuration options + for the session. Applicable only for benchmarking in graph mode. + + Returns: + A float, representing the per-execution wall time of the op in seconds. + This is the median time (with respect to `iters`) it takes for the op + to be executed `iters` num of times. + """ + + if context.executing_eagerly(): + return self._run_eager_benchmark(iterable=op, iters=iters, warmup=warmup) + + return self._run_graph_benchmark( + iterable=op, iters=iters, warmup=warmup, session_config=session_config) + + def run_benchmark(self, + dataset, + num_elements, + iters=1, + warmup=True, + apply_default_optimizations=False, + session_config=None): + """Benchmarks the dataset. + + Runs the dataset `iters` times. In each iteration, the benchmark measures + the time it takes to go through `num_elements` elements of the dataset. + + Args: + dataset: Dataset to benchmark. + num_elements: Number of dataset elements to iterate through each benchmark + iteration. + iters: Number of times to repeat the timing. + warmup: If true, warms up the session caches by running an untimed run. + apply_default_optimizations: Determines whether default optimizations + should be applied. + session_config: A ConfigProto protocol buffer with configuration options + for the session. Applicable only for benchmarking in graph mode. + + Returns: + A float, representing the per-element wall time of the dataset in seconds. + This is the median time (with respect to `iters`) it takes for the dataset + to go through `num_elements` elements, divided by `num_elements.` + """ + + # The options that have been applied to the dataset are preserved so that + # they are not overwritten while benchmarking. + options = options_lib.Options() + options.experimental_optimization.apply_default_optimizations = ( + apply_default_optimizations) + dataset = dataset.with_options(options) + + # NOTE: We use `dataset.skip()` to perform the iterations in C++, avoiding + # the overhead of having to execute a TensorFlow op for each step of the + # input pipeline. Note that this relies on the underlying implementation of + # `skip` to execute upstream computation. If it is optimized in the future, + # we will have to change this code. + dataset = dataset.skip(num_elements - 1) + + if context.executing_eagerly(): + median_duration = self._run_eager_benchmark( + iterable=dataset, iters=iters, warmup=warmup) + return median_duration / float(num_elements) + + iterator = dataset_ops.make_initializable_iterator(dataset) + next_element = iterator.get_next() + op = nest.flatten(next_element)[0].op + median_duration = self._run_graph_benchmark( + iterable=op, + iters=iters, + warmup=warmup, + session_config=session_config, + initializer=iterator.initializer) + return median_duration / float(num_elements) + + def run_and_report_benchmark(self, + dataset, + num_elements, + name, + iters=5, + extras=None, + warmup=True, + apply_default_optimizations=False, + session_config=None): + """Benchmarks the dataset and reports the stats. + + Runs the dataset `iters` times. In each iteration, the benchmark measures + the time it takes to go through `num_elements` elements of the dataset. + This is followed by logging/printing the benchmark stats. + + Args: + dataset: Dataset to benchmark. + num_elements: Number of dataset elements to iterate through each benchmark + iteration. + name: Name of the benchmark. + iters: Number of times to repeat the timing. + extras: A dict which maps string keys to additional benchmark info. + warmup: If true, warms up the session caches by running an untimed run. + apply_default_optimizations: Determines whether default optimizations + should be applied. + session_config: A ConfigProto protocol buffer with configuration options + for the session. Applicable only for benchmarking in graph mode. + + Returns: + A float, representing the per-element wall time of the dataset in seconds. + This is the median time (with respect to `iters`) it takes for the dataset + to go through `num_elements` elements, divided by `num_elements.` + """ + wall_time = self.run_benchmark( + dataset=dataset, + num_elements=num_elements, + iters=iters, + warmup=warmup, + apply_default_optimizations=apply_default_optimizations, + session_config=session_config) + if extras is None: + extras = {} + if context.executing_eagerly(): + name = "{}.eager".format(name) + extras["implementation"] = "eager" + else: + name = "{}.graph".format(name) + extras["implementation"] = "graph" + extras["num_elements"] = num_elements + self.report_benchmark( + wall_time=wall_time, iters=iters, name=name, extras=extras) + return wall_time diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3965ab53b77d95a85cb56fec0fdde8be69013c1e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/__init__.py @@ -0,0 +1,174 @@ +# 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. +# ============================================================================== +"""Experimental API for building input pipelines. + +This module contains experimental `Dataset` sources and transformations that can +be used in conjunction with the `tf.data.Dataset` API. Note that the +`tf.data.experimental` API is not subject to the same backwards compatibility +guarantees as `tf.data`, but we will provide deprecation advice in advance of +removing existing functionality. + +See [Importing Data](https://tensorflow.org/guide/datasets) for an overview. + +@@AutoShardPolicy +@@AutotuneAlgorithm +@@AutotuneOptions +@@CheckpointInputPipelineHook +@@Counter +@@CsvDataset +@@DatasetInitializer +@@DatasetStructure +@@DistributeOptions +@@ExternalStatePolicy +@@OptimizationOptions +@@Optional +@@OptionalStructure +@@RaggedTensorStructure +@@RandomDataset +@@Reducer +@@SparseTensorStructure +@@SqlDataset +@@Structure +@@TFRecordWriter +@@TensorArrayStructure +@@TensorStructure +@@ThreadingOptions + +@@assert_cardinality +@@at +@@bucket_by_sequence_length +@@cardinality +@@choose_from_datasets +@@copy_to_device +@@dense_to_ragged_batch +@@dense_to_sparse_batch +@@distribute +@@enable_debug_mode +@@enumerate_dataset +@@from_list +@@from_variant +@@get_next_as_optional +@@get_single_element +@@get_structure +@@group_by_reducer +@@group_by_window +@@ignore_errors +@@index_table_from_dataset +@@load +@@make_batched_features_dataset +@@make_csv_dataset +@@make_saveable_from_iterator +@@map_and_batch +@@map_and_batch_with_legacy_function +@@pad_to_cardinality +@@parallel_interleave +@@parse_example_dataset +@@prefetch_to_device +@@rejection_resample +@@sample_from_datasets +@@save +@@scan +@@shuffle_and_repeat +@@snapshot +@@table_from_dataset +@@take_while +@@to_variant +@@unbatch +@@unique + +@@AUTOTUNE +@@INFINITE_CARDINALITY +@@SHARD_HINT +@@UNKNOWN_CARDINALITY +""" + +# pylint: disable=unused-import +from tensorflow.python.data.experimental import service +from tensorflow.python.data.experimental.ops.batching import dense_to_ragged_batch +from tensorflow.python.data.experimental.ops.batching import dense_to_sparse_batch +from tensorflow.python.data.experimental.ops.batching import map_and_batch +from tensorflow.python.data.experimental.ops.batching import map_and_batch_with_legacy_function +from tensorflow.python.data.experimental.ops.batching import unbatch +from tensorflow.python.data.experimental.ops.cardinality import assert_cardinality +from tensorflow.python.data.experimental.ops.cardinality import cardinality +from tensorflow.python.data.experimental.ops.cardinality import INFINITE as INFINITE_CARDINALITY +from tensorflow.python.data.experimental.ops.cardinality import UNKNOWN as UNKNOWN_CARDINALITY +from tensorflow.python.data.experimental.ops.counter import Counter +from tensorflow.python.data.experimental.ops.distribute import SHARD_HINT +from tensorflow.python.data.experimental.ops.enumerate_ops import enumerate_dataset +from tensorflow.python.data.experimental.ops.error_ops import ignore_errors +from tensorflow.python.data.experimental.ops.from_list import from_list +from tensorflow.python.data.experimental.ops.get_single_element import get_single_element +from tensorflow.python.data.experimental.ops.grouping import bucket_by_sequence_length +from tensorflow.python.data.experimental.ops.grouping import group_by_reducer +from tensorflow.python.data.experimental.ops.grouping import group_by_window +from tensorflow.python.data.experimental.ops.grouping import Reducer +from tensorflow.python.data.experimental.ops.interleave_ops import choose_from_datasets +from tensorflow.python.data.experimental.ops.interleave_ops import parallel_interleave +from tensorflow.python.data.experimental.ops.interleave_ops import sample_from_datasets +from tensorflow.python.data.experimental.ops.io import load +from tensorflow.python.data.experimental.ops.io import save +from tensorflow.python.data.experimental.ops.iterator_ops import CheckpointInputPipelineHook +from tensorflow.python.data.experimental.ops.iterator_ops import make_saveable_from_iterator +from tensorflow.python.data.experimental.ops.lookup_ops import DatasetInitializer +from tensorflow.python.data.experimental.ops.lookup_ops import index_table_from_dataset +from tensorflow.python.data.experimental.ops.lookup_ops import table_from_dataset +from tensorflow.python.data.experimental.ops.pad_to_cardinality import pad_to_cardinality +from tensorflow.python.data.experimental.ops.parsing_ops import parse_example_dataset +from tensorflow.python.data.experimental.ops.prefetching_ops import copy_to_device +from tensorflow.python.data.experimental.ops.prefetching_ops import prefetch_to_device +from tensorflow.python.data.experimental.ops.random_access import at +from tensorflow.python.data.experimental.ops.random_ops import RandomDataset +from tensorflow.python.data.experimental.ops.readers import CsvDataset +from tensorflow.python.data.experimental.ops.readers import make_batched_features_dataset +from tensorflow.python.data.experimental.ops.readers import make_csv_dataset +from tensorflow.python.data.experimental.ops.readers import SqlDataset +from tensorflow.python.data.experimental.ops.resampling import rejection_resample +from tensorflow.python.data.experimental.ops.scan_ops import scan +from tensorflow.python.data.experimental.ops.shuffle_ops import shuffle_and_repeat +from tensorflow.python.data.experimental.ops.snapshot import snapshot +from tensorflow.python.data.experimental.ops.take_while_ops import take_while +from tensorflow.python.data.experimental.ops.unique import unique +from tensorflow.python.data.experimental.ops.writers import TFRecordWriter +from tensorflow.python.data.ops.dataset_ops import AUTOTUNE +from tensorflow.python.data.ops.dataset_ops import DatasetSpec as DatasetStructure +from tensorflow.python.data.ops.dataset_ops import from_variant +from tensorflow.python.data.ops.dataset_ops import get_structure +from tensorflow.python.data.ops.dataset_ops import to_variant +from tensorflow.python.data.ops.debug_mode import enable_debug_mode +from tensorflow.python.data.ops.iterator_ops import get_next_as_optional +from tensorflow.python.data.ops.optional_ops import Optional +from tensorflow.python.data.ops.optional_ops import OptionalSpec as OptionalStructure +from tensorflow.python.data.ops.options import AutoShardPolicy +from tensorflow.python.data.ops.options import AutotuneAlgorithm +from tensorflow.python.data.ops.options import AutotuneOptions +from tensorflow.python.data.ops.options import DistributeOptions +from tensorflow.python.data.ops.options import ExternalStatePolicy +from tensorflow.python.data.ops.options import OptimizationOptions +from tensorflow.python.data.ops.options import ThreadingOptions +from tensorflow.python.data.util.structure import _RaggedTensorStructure as RaggedTensorStructure +from tensorflow.python.data.util.structure import _SparseTensorStructure as SparseTensorStructure +from tensorflow.python.data.util.structure import _TensorArrayStructure as TensorArrayStructure +from tensorflow.python.data.util.structure import _TensorStructure as TensorStructure +from tensorflow.python.framework.type_spec import TypeSpec as Structure +# pylint: enable=unused-import + +from tensorflow.python.util.all_util import remove_undocumented + +_allowed_symbols = [ + "service", +] + +remove_undocumented(__name__, _allowed_symbols) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/multi_process_cluster.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/multi_process_cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..e70586188b50dbca6cbd1a411fe02df5d3eca404 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/multi_process_cluster.py @@ -0,0 +1,165 @@ +# 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. +# ============================================================================== +"""tf.data service test-cluster with local and remote workers.""" + +import tempfile + +from tensorflow.core.protobuf import data_service_pb2 +from tensorflow.core.protobuf import service_config_pb2 +from tensorflow.python.data.experimental.kernel_tests.service import test_base as data_service_test_base +from tensorflow.python.data.experimental.service import server_lib +from tensorflow.python.distribute import multi_process_lib +from tensorflow.python.framework import test_util +from tensorflow.python.platform import googletest + +_WORKER_SHUTDOWN_QUIET_PERIOD_MS = 100 + + +# pylint: disable=protected-access +class _RemoteWorkerProcess(multi_process_lib.Process): + """Runs a worker server in a new process to simulate a remote worker.""" + + def __init__(self, dispatcher_address, port, worker_tags, pipe_writer): + super(_RemoteWorkerProcess, self).__init__() + self._dispatcher_address = dispatcher_address + self._port = port + self._worker_tags = worker_tags + self._pipe_writer = pipe_writer + + def run(self): + self.start_worker() + + def start_worker(self): + self._worker = data_service_test_base.TestWorker( + self._dispatcher_address, + _WORKER_SHUTDOWN_QUIET_PERIOD_MS, + port=self._port, + worker_tags=self._worker_tags) + self._worker.start() + self._pipe_writer.send(self._worker.worker_address()) + self._worker.join() + + +class MultiProcessCluster: + """tf.data service cluster with local and remote workers. + + Represents a cluster with a dispatcher, `num_local_workers` local workers, and + `num_remote_workers` remote workers. Remote workers run in separate processes. + This is useful to test reading from local in-process workers. For example: + + ``` + cluster = multi_process_cluster.MultiProcessCluster( + num_local_workers=1, num_remote_workers=3) + num_elements = 10 + dataset = self.make_distributed_range_dataset( + num_elements, cluster, target_workers="LOCAL") + self.assertDatasetProduces(dataset, list(range(num_elements))) + ``` + """ + + def __init__(self, + num_local_workers, + num_remote_workers, + worker_tags=None, + worker_addresses=None, + deployment_mode=data_service_pb2.DEPLOYMENT_MODE_COLOCATED): + self._work_dir = tempfile.mkdtemp(dir=googletest.GetTempDir()) + self._deployment_mode = deployment_mode + self._start_dispatcher(worker_addresses) + self._start_local_workers(num_local_workers, worker_tags) + self._start_remote_workers(num_remote_workers, worker_tags) + + def _start_dispatcher(self, worker_addresses, port=0): + if port == 0: + port = test_util.pick_unused_port() + self._dispatcher = server_lib.DispatchServer( + service_config_pb2.DispatcherConfig( + port=port, + protocol="grpc", + work_dir=self._work_dir, + fault_tolerant_mode=True, + worker_addresses=worker_addresses, + deployment_mode=self._deployment_mode), + start=True) + + def _start_local_workers(self, num_workers, worker_tags=None): + self._local_workers = [] + for _ in range(num_workers): + self.start_local_worker(worker_tags) + + def _start_remote_workers(self, num_workers, worker_tags=None): + # List of (worker address, remote worker process) tuples. + self._remote_workers = [] + for _ in range(num_workers): + self.start_remote_worker(worker_tags) + + def start_local_worker(self, worker_tags=None): + worker = data_service_test_base.TestWorker( + self.dispatcher_address(), + _WORKER_SHUTDOWN_QUIET_PERIOD_MS, + port=test_util.pick_unused_port(), + worker_tags=worker_tags) + worker.start() + self._local_workers.append(worker) + + def start_remote_worker(self, worker_tags=None): + """Runs a tf.data service worker in a remote process.""" + + pipe_reader, pipe_writer = multi_process_lib.multiprocessing.Pipe( + duplex=False) + worker_process = _RemoteWorkerProcess( + self.dispatcher_address(), + port=test_util.pick_unused_port(), + worker_tags=worker_tags, + pipe_writer=pipe_writer) + worker_process.start() + worker_address = pipe_reader.recv() + self._remote_workers.append((worker_address, worker_process)) + + def restart_dispatcher(self): + port = int(self.dispatcher_address().split(":")[1]) + self._dispatcher._stop() + self._start_dispatcher( + worker_addresses=(self.local_worker_addresses() + + self.remote_worker_addresses()), + port=port) + + def restart_local_workers(self): + for worker in self._local_workers: + worker.restart() + + def dispatcher_address(self): + return self._dispatcher._address + + def local_worker_addresses(self): + return [worker.worker_address() for worker in self._local_workers] + + def remote_worker_addresses(self): + return [worker_address for (worker_address, _) in self._remote_workers] + + def _stop(self): + for worker in self._local_workers: + worker.stop() + for (_, worker_process) in self._remote_workers: + worker_process.kill() + self._dispatcher._stop() + + def __del__(self): + self._stop() + + +def test_main(): + """Main function to be called within `__main__` of a test file.""" + multi_process_lib.test_main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..4758ba8d24a31746de0a7ad6dfbb2c2daf8f8357 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/kernel_tests/service/test_base.py @@ -0,0 +1,431 @@ +# 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. +# ============================================================================== +"""Test base for tf.data service tests.""" +import tempfile + +from tensorflow.core.protobuf import service_config_pb2 +from tensorflow.python.data.experimental.ops import data_service_ops +from tensorflow.python.data.experimental.service import server_lib +from tensorflow.python.data.kernel_tests import test_base +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import combinations +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + +# This will be resolved to a tmp directory by `start_dispatch_server`. +TMP_WORK_DIR = "tmp_work_dir_placeholder" +# `""` indicates not to use a work directory. +NO_WORK_DIR = "" +# We use a faster than normal heartbeat interval so that tests run faster. +TEST_HEARTBEAT_INTERVAL_MS = 100 +TEST_DISPATCHER_TIMEOUT_MS = 5000 +TEST_WORKER_TIMEOUT_MS = 200 +TEST_JOB_GC_CHECK_INTERNAL_MS = 1000 +TEST_SNAPSHOT_MAX_CHUNK_SIZE_BYTES = 16 << 10 # 16 KB +PROTOCOL = "grpc" + + +def all_cluster_configurations(): + with_work_dir = combinations.combine( + work_dir=TMP_WORK_DIR, fault_tolerant_mode=[True, False]) + without_work_dir = combinations.combine( + work_dir=NO_WORK_DIR, fault_tolerant_mode=False) + return with_work_dir + without_work_dir + + +def _make_worker( + dispatcher_address, + protocol, + data_transfer_protocol, + shutdown_quiet_period_ms=0, + port=0, + worker_tags=None, + cross_trainer_cache_size_bytes=None, + snapshot_max_chunk_size_bytes=TEST_SNAPSHOT_MAX_CHUNK_SIZE_BYTES, +): + """Creates a worker server.""" + defaults = server_lib.WorkerConfig(dispatcher_address=dispatcher_address) + config_proto = service_config_pb2.WorkerConfig( + dispatcher_address=dispatcher_address, + worker_address=defaults.worker_address, + port=port, + protocol=protocol, + worker_tags=worker_tags, + heartbeat_interval_ms=TEST_HEARTBEAT_INTERVAL_MS, + dispatcher_timeout_ms=TEST_DISPATCHER_TIMEOUT_MS, + data_transfer_protocol=data_transfer_protocol, + data_transfer_address=defaults.worker_address, + shutdown_quiet_period_ms=shutdown_quiet_period_ms, + cross_trainer_cache_size_bytes=cross_trainer_cache_size_bytes, + snapshot_max_chunk_size_bytes=snapshot_max_chunk_size_bytes, + ) + return server_lib.WorkerServer(config_proto, start=False) + + +# pylint: disable=protected-access +class TestWorker: + """A tf.data service worker.""" + + def __init__( + self, + dispatcher_address, + shutdown_quiet_period_ms, + protocol=PROTOCOL, + data_transfer_protocol=None, + port=0, + worker_tags=None, + cross_trainer_cache_size_bytes=None, + snapshot_max_chunk_size_bytes=TEST_SNAPSHOT_MAX_CHUNK_SIZE_BYTES, + ): + self._dispatcher_address = dispatcher_address + self._shutdown_quiet_period_ms = shutdown_quiet_period_ms + self._server = _make_worker( + dispatcher_address, + protocol, + data_transfer_protocol, + shutdown_quiet_period_ms, + port=port, + worker_tags=worker_tags, + cross_trainer_cache_size_bytes=cross_trainer_cache_size_bytes, + snapshot_max_chunk_size_bytes=snapshot_max_chunk_size_bytes, + ) + self._running = False + self._protocol = protocol + self._data_transfer_protocol = data_transfer_protocol + + def stop(self): + self._server._stop() + self._running = False + + def start(self): + self._server.start() + self._port = int(self._server._address.split(":")[1]) + self._running = True + + def restart(self, use_same_port=True): + """Restarts the worker, stopping it first if it is already running.""" + if self._running: + self.stop() + port = 0 + if use_same_port: + port = self._port + self._server = _make_worker(self._dispatcher_address, + self._protocol, + self._data_transfer_protocol, + self._shutdown_quiet_period_ms, port) + self._server.start() + self._port = int(self._server._address.split(":")[1]) + self._running = True + + def join(self): + self._server.join() + + def num_tasks(self): + return self._server._num_tasks() + + def snapshot_task_progresses(self): + return self._server._snapshot_task_progresses() + + def worker_address(self): + return self._server._address + + +class TestCluster: + """Test tf.data service cluster.""" + + def __init__( + self, + num_workers, + dispatcher_port=0, + work_dir=TMP_WORK_DIR, + fault_tolerant_mode=True, + job_gc_check_interval_ms=TEST_JOB_GC_CHECK_INTERNAL_MS, + job_gc_timeout_ms=None, + worker_timeout_ms=TEST_WORKER_TIMEOUT_MS, + worker_shutdown_quiet_period_ms=0, + snapshot_max_chunk_size_bytes=TEST_SNAPSHOT_MAX_CHUNK_SIZE_BYTES, + worker_max_concurrent_snapshots=0, + start=True, + protocol=PROTOCOL, + data_transfer_protocol=None, + ): + """Creates a tf.data service test cluster. + + Args: + num_workers: The number of workers to initially add to the cluster. + dispatcher_port: The port to use for the dispatcher. + work_dir: The work directory to use for the dispatcher. If set to + `TMP_WORK_DIR`, the cluster will create a new temporary directory to use + as the work directory. If set to `NO_WORK_DIR`, no work directory will + be used. + fault_tolerant_mode: Whether the dispatcher should write its state to a + journal so that it can recover from restarts. + job_gc_check_interval_ms: How often the dispatcher should scan through to + delete old and unused jobs, in milliseconds. + job_gc_timeout_ms: How long a job needs to be unused before it becomes a + candidate for garbage collection, in milliseconds. + worker_timeout_ms: How long to wait for a worker to heartbeat before + considering it missing, in milliseconds. + worker_shutdown_quiet_period_ms: When shutting down a worker, how long to + wait for the gRPC server to process the final requests. + snapshot_max_chunk_size_bytes: The maximum size of a distributed snapshot + chunk file. + worker_max_concurrent_snapshots: The maximum number of snapshots a worker + can concurrently process. + start: Whether to immediately start the servers in the cluster. If + `False`, the servers can be started later by calling + `start_dispatcher()` and `start_workers()`. + protocol: The protocol to use for communicating with the tf.data service, + e.g. "grpc". + data_transfer_protocol: (Optional.) The protocol to use for transferring + data with the tf.data service. + """ + if work_dir == TMP_WORK_DIR: + work_dir = tempfile.mkdtemp(dir=googletest.GetTempDir()) + self._worker_shutdown_quiet_period_ms = worker_shutdown_quiet_period_ms + self._snapshot_max_chunk_size_bytes = snapshot_max_chunk_size_bytes + self._protocol = protocol + self._data_transfer_protocol = data_transfer_protocol + self._job_gc_check_interval_ms = job_gc_check_interval_ms + self._job_gc_timeout_ms = job_gc_timeout_ms + self._worker_timeout_ms = worker_timeout_ms + self._worker_max_concurrent_snapshots = worker_max_concurrent_snapshots + self.dispatcher = server_lib.DispatchServer( + server_lib.DispatcherConfig( + port=dispatcher_port, + work_dir=work_dir, + protocol=protocol, + fault_tolerant_mode=fault_tolerant_mode, + job_gc_check_interval_ms=job_gc_check_interval_ms, + job_gc_timeout_ms=job_gc_timeout_ms, + worker_timeout_ms=worker_timeout_ms, + worker_max_concurrent_snapshots=worker_max_concurrent_snapshots, + ), + start=start, + ) + + self.workers = [] + for _ in range(num_workers): + self.add_worker(start=start) + + def dispatcher_address(self): + return self.dispatcher.target.split("://")[1] + + def add_worker(self, start=True): + worker = TestWorker( + self.dispatcher_address(), + self._worker_shutdown_quiet_period_ms, + self._protocol, + self._data_transfer_protocol, + snapshot_max_chunk_size_bytes=self._snapshot_max_chunk_size_bytes, + ) + if start: + worker.start() + self.workers.append(worker) + + def start_dispatcher(self): + self.dispatcher.start() + + def start_workers(self): + for worker in self.workers: + worker.start() + + def stop_dispatcher(self): + # pylint: disable=protected-access + self.dispatcher._stop() + + def restart_worker(self, index): + self.workers[index].restart() + + def stop_worker(self, index): + self.workers[index].stop() + + def stop_workers(self): + for worker in self.workers: + worker.stop() + + # pylint: disable=protected-access + def restart_dispatcher(self): + """Stops `dispatcher` and creates a new dispatcher with the same port. + + Restarting is supported only when the dispatcher is configured with + `fault_tolerant_mode=True`. + """ + if not self.dispatcher._config.fault_tolerant_mode: + raise ValueError( + "Trying to restart the dispatcher without fault-tolerance.") + port = int(self.dispatcher_address().split(":")[1]) + self.dispatcher._stop() + self.dispatcher = server_lib.DispatchServer( + server_lib.DispatcherConfig( + port=port, + work_dir=self.dispatcher._config.work_dir, + protocol=self._protocol, + fault_tolerant_mode=self.dispatcher._config.fault_tolerant_mode, + job_gc_check_interval_ms=self._job_gc_check_interval_ms, + job_gc_timeout_ms=self._job_gc_timeout_ms, + worker_timeout_ms=self._worker_timeout_ms, + worker_max_concurrent_snapshots= + self._worker_max_concurrent_snapshots, + ) + ) + + def num_registered_workers(self): + return self.dispatcher._num_workers() + + def num_tasks_on_workers(self): + return sum(worker.num_tasks() for worker in self.workers) + + def snapshot_streams(self, path): + return self.dispatcher._snapshot_streams(path) + + def __del__(self): + # Destroy workers before the dispatcher for clean shutdown. + self.workers.clear() + del self.dispatcher + + +class TestBase(test_base.DatasetTestBase): + """Base class for tf.data service tests.""" + + def setUp(self): + self.default_data_transfer_protocol = None + self.default_compression = "AUTO" + + def set_default_data_transfer_protocol(self, protocol): + self.default_data_transfer_protocol = protocol + + def set_default_compression(self, compression): + self.default_compression = compression + + def make_test_cluster(self, *args, **kwargs): + if "data_transfer_protocol" not in kwargs: + kwargs["data_transfer_protocol"] = self.default_data_transfer_protocol + return TestCluster(*args, **kwargs) + + def make_distributed_dataset(self, + dataset, + cluster, + processing_mode="parallel_epochs", + **kwargs): + kwargs["task_refresh_interval_hint_ms"] = 20 + if "data_transfer_protocol" not in kwargs: + kwargs["data_transfer_protocol"] = self.default_data_transfer_protocol + if "compression" not in kwargs: + kwargs["compression"] = self.default_compression + + # pylint: disable=protected-access + return dataset.apply( + data_service_ops._distribute( + processing_mode, + cluster.dispatcher_address(), + **kwargs)) + + def make_distributed_range_dataset(self, + num_elements, + cluster, + **kwargs): + dataset = dataset_ops.Dataset.range(num_elements) + return self.make_distributed_dataset(dataset, cluster, **kwargs) + + def make_coordinated_read_dataset( + self, + cluster, + num_consumers, + sharding_policy=data_service_ops.ShardingPolicy.OFF): + """Creates a dataset that performs coordinated reads. + + The dataset simulates `num_consumers` consumers by using parallel + interleave to read with `num_consumers` threads, one for each consumer. The + nth element of the dataset is produced by consumer `n % num_consumers`. + + The dataset executed on each worker will produce groups of `num_consumers` + sequentially increasing numbers. For example, if `num_consumers=3` a worker + dataset could produce [0, 1, 2, 9, 10, 11, 21, 22, 23]. This enables + `checkCoordinatedReadGroups` below to assess whether the values received in + each step came from the same group. + + Args: + cluster: A tf.data service `TestCluster`. + num_consumers: The number of consumers to simulate. + sharding_policy: The sharding policy to use. Currently only OFF and + DYNAMIC are supported. + + Returns: + A dataset that simulates reading with `num_consumers` consumers. + """ + if sharding_policy not in [ + data_service_ops.ShardingPolicy.OFF, + data_service_ops.ShardingPolicy.DYNAMIC + ]: + raise ValueError(f"Unsupported sharding policy: {sharding_policy}") + # Start from 0 so that we can detect when a new worker is added with + # ShardingPolicy.OFF. + ds = dataset_ops.Dataset.from_tensors(math_ops.cast(0, dtypes.int64)) + ds = ds.concatenate(dataset_ops.Dataset.random()) + # Ensure that all elements in the same group are consecutive. + def make_group(x): + # Avoid overflowing an int64 in (x+1)*num_consumers below. + x = x % (2**32) + return dataset_ops.Dataset.range(x*num_consumers, (x+1)*num_consumers) + ds = ds.flat_map(make_group) + consumers = [] + for consumer_index in range(num_consumers): + consumers.append( + self.make_distributed_dataset( + ds, + cluster, + job_name="test", + processing_mode=sharding_policy, + consumer_index=consumer_index, + num_consumers=num_consumers)) + # Use parallel interleave to read from consumers in parallel. + ds = dataset_ops.Dataset.from_tensor_slices(consumers) + ds = ds.interleave( + lambda x: x, + cycle_length=num_consumers, + num_parallel_calls=num_consumers) + return ds + + def checkCoordinatedReadGroups(self, results, num_consumers): + """Validates results from a `make_coordinted_read_dataset` dataset. + + Each group of `num_consumers` results should be consecutive, indicating that + they were produced by the same worker. + + Args: + results: The elements produced by the dataset. + num_consumers: The number of consumers. + """ + groups = [ + results[start:start + num_consumers] + for start in range(0, len(results), num_consumers) + ] + incorrect_groups = [] + for group in groups: + # Check that each group of `num_consumers` results are consecutive. + for offset in range(1, len(group)): + if group[0] + offset != group[offset]: + incorrect_groups.append(group) + break + self.assertEmpty( + incorrect_groups, + "Incorrect groups: {}.\nAll groups: {}".format(incorrect_groups, + groups)) + + def read(self, get_next, results, count): + for _ in range(count): + results.append(self.evaluate(get_next())) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/batching.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/batching.py new file mode 100644 index 0000000000000000000000000000000000000000..9b07a6b4471e0092f477e52920a3365a909a228e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/batching.py @@ -0,0 +1,379 @@ +# 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. +# ============================================================================== +"""Batching dataset transformations.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import convert +from tensorflow.python.data.util import nest +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.dense_to_ragged_batch") +@deprecation.deprecated(None, "Use `tf.data.Dataset.ragged_batch` instead.") +def dense_to_ragged_batch(batch_size, + drop_remainder=False, + row_splits_dtype=dtypes.int64): + """A transformation that batches ragged elements into `tf.RaggedTensor`s. + + This transformation combines multiple consecutive elements of the input + dataset into a single element. + + Like `tf.data.Dataset.batch`, the components of the resulting element will + have an additional outer dimension, which will be `batch_size` (or + `N % batch_size` for the last element if `batch_size` does not divide the + number of input elements `N` evenly and `drop_remainder` is `False`). If + your program depends on the batches having the same outer dimension, you + should set the `drop_remainder` argument to `True` to prevent the smaller + batch from being produced. + + Unlike `tf.data.Dataset.batch`, the input elements to be batched may have + different shapes: + + * If an input element is a `tf.Tensor` whose static `tf.TensorShape` is + fully defined, then it is batched as normal. + * If an input element is a `tf.Tensor` whose static `tf.TensorShape` contains + one or more axes with unknown size (i.e., `shape[i]=None`), then the output + will contain a `tf.RaggedTensor` that is ragged up to any of such + dimensions. + * If an input element is a `tf.RaggedTensor` or any other type, then it is + batched as normal. + + Example: + + >>> dataset = tf.data.Dataset.from_tensor_slices(np.arange(6)) + >>> dataset = dataset.map(lambda x: tf.range(x)) + >>> dataset.element_spec.shape + TensorShape([None]) + >>> dataset = dataset.apply( + ... tf.data.experimental.dense_to_ragged_batch(batch_size=2)) + >>> for batch in dataset: + ... print(batch) + + + + + Args: + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size` elements; the default behavior is not to drop the smaller + batch. + row_splits_dtype: The dtype that should be used for the `row_splits` of any + new ragged tensors. Existing `tf.RaggedTensor` elements do not have their + row_splits dtype changed. + + Returns: + Dataset: A `Dataset`. + """ + def _apply_fn(dataset): + return dataset.ragged_batch(batch_size, drop_remainder, row_splits_dtype) + + return _apply_fn + + +@tf_export("data.experimental.dense_to_sparse_batch") +@deprecation.deprecated(None, "Use `tf.data.Dataset.sparse_batch` instead.") +def dense_to_sparse_batch(batch_size, row_shape): + """A transformation that batches ragged elements into `tf.sparse.SparseTensor`s. + + Like `Dataset.padded_batch()`, this transformation combines multiple + consecutive elements of the dataset, which might have different + shapes, into a single element. The resulting element has three + components (`indices`, `values`, and `dense_shape`), which + comprise a `tf.sparse.SparseTensor` that represents the same data. The + `row_shape` represents the dense shape of each row in the + resulting `tf.sparse.SparseTensor`, to which the effective batch size is + prepended. For example: + + ```python + # NOTE: The following examples use `{ ... }` to represent the + # contents of a dataset. + a = { ['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c', 'd'] } + + a.apply(tf.data.experimental.dense_to_sparse_batch( + batch_size=2, row_shape=[6])) == + { + ([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], # indices + ['a', 'b', 'c', 'a', 'b'], # values + [2, 6]), # dense_shape + ([[0, 0], [0, 1], [0, 2], [0, 3]], + ['a', 'b', 'c', 'd'], + [1, 6]) + } + ``` + + Args: + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + row_shape: A `tf.TensorShape` or `tf.int64` vector tensor-like object + representing the equivalent dense shape of a row in the resulting + `tf.sparse.SparseTensor`. Each element of this dataset must have the same + rank as `row_shape`, and must have size less than or equal to `row_shape` + in each dimension. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return dataset.sparse_batch(batch_size, row_shape) + + return _apply_fn + + +@deprecation.deprecated(None, "Use `tf.data.experimental.map_and_batch()") +@tf_export(v1=["data.experimental.map_and_batch_with_legacy_function"]) +def map_and_batch_with_legacy_function(map_func, + batch_size, + num_parallel_batches=None, + drop_remainder=False, + num_parallel_calls=None): + """Fused implementation of `map` and `batch`. + + NOTE: This is an escape hatch for existing uses of `map_and_batch` that do not + work with V2 functions. New uses are strongly discouraged and existing uses + should migrate to `map_and_batch` as this method will not be removed in V2. + + Args: + map_func: A function mapping a nested structure of tensors to another + nested structure of tensors. + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + num_parallel_batches: (Optional.) A `tf.int64` scalar `tf.Tensor`, + representing the number of batches to create in parallel. On one hand, + higher values can help mitigate the effect of stragglers. On the other + hand, higher values can increase contention if CPU is scarce. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in case its size is smaller than + desired; the default behavior is not to drop the smaller batch. + num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`, + representing the number of elements to process in parallel. If not + specified, `batch_size * num_parallel_batches` elements will be processed + in parallel. If the value `tf.data.AUTOTUNE` is used, then + the number of parallel calls is set dynamically based on available CPU. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + + Raises: + ValueError: If both `num_parallel_batches` and `num_parallel_calls` are + specified. + """ + + if num_parallel_batches is None and num_parallel_calls is None: + num_parallel_calls = batch_size + elif num_parallel_batches is not None and num_parallel_calls is None: + num_parallel_calls = batch_size * num_parallel_batches + elif num_parallel_batches is not None and num_parallel_calls is not None: + raise ValueError( + "`map_and_batch_with_legacy_function` allows only one of " + "`num_parallel_batches` and " + "`num_parallel_calls` to be set, but " + f"`num_parallel_batches` was set to {num_parallel_batches} " + f"and `num_parallel_calls` as set to {num_parallel_calls}.") + + def _apply_fn(dataset): + return _MapAndBatchDataset(dataset, map_func, batch_size, + num_parallel_calls, drop_remainder, + use_legacy_function=True) + + return _apply_fn + + +@deprecation.deprecated( + None, + "Use `tf.data.Dataset.map(map_func, num_parallel_calls)` followed by " + "`tf.data.Dataset.batch(batch_size, drop_remainder)`. Static tf.data " + "optimizations will take care of using the fused implementation.") +@tf_export("data.experimental.map_and_batch") +def map_and_batch(map_func, + batch_size, + num_parallel_batches=None, + drop_remainder=False, + num_parallel_calls=None): + """Fused implementation of `map` and `batch`. + + Maps `map_func` across `batch_size` consecutive elements of this dataset + and then combines them into a batch. Functionally, it is equivalent to `map` + followed by `batch`. This API is temporary and deprecated since input pipeline + optimization now fuses consecutive `map` and `batch` operations automatically. + + Args: + map_func: A function mapping a nested structure of tensors to another + nested structure of tensors. + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + num_parallel_batches: (Optional.) A `tf.int64` scalar `tf.Tensor`, + representing the number of batches to create in parallel. On one hand, + higher values can help mitigate the effect of stragglers. On the other + hand, higher values can increase contention if CPU is scarce. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in case its size is smaller than + desired; the default behavior is not to drop the smaller batch. + num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`, + representing the number of elements to process in parallel. If not + specified, `batch_size * num_parallel_batches` elements will be processed + in parallel. If the value `tf.data.AUTOTUNE` is used, then + the number of parallel calls is set dynamically based on available CPU. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + + Raises: + ValueError: If both `num_parallel_batches` and `num_parallel_calls` are + specified. + """ + + if num_parallel_batches is None and num_parallel_calls is None: + num_parallel_calls = batch_size + elif num_parallel_batches is not None and num_parallel_calls is None: + num_parallel_calls = batch_size * num_parallel_batches + elif num_parallel_batches is not None and num_parallel_calls is not None: + raise ValueError( + "`map_and_batch` allows only one of `num_parallel_batches` and " + "`num_parallel_calls` to be set, but " + f"`num_parallel_batches` was set to {num_parallel_batches} " + f"and `num_parallel_calls` as set to {num_parallel_calls}.") + + def _apply_fn(dataset): + return _MapAndBatchDataset(dataset, map_func, batch_size, + num_parallel_calls, drop_remainder) + + return _apply_fn + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.unbatch()`.") +@tf_export("data.experimental.unbatch") +def unbatch(): + """Splits elements of a dataset into multiple elements on the batch dimension. + + For example, if elements of the dataset are shaped `[B, a0, a1, ...]`, + where `B` may vary for each input element, then for each element in the + dataset, the unbatched dataset will contain `B` consecutive elements + of shape `[a0, a1, ...]`. + + ```python + # NOTE: The following example uses `{ ... }` to represent the contents + # of a dataset. + a = { ['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c', 'd'] } + + a.unbatch() == { + 'a', 'b', 'c', 'a', 'b', 'a', 'b', 'c', 'd'} + ``` + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return dataset.unbatch() + + return _apply_fn + + +class _DenseToSparseBatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that batches ragged dense elements into `tf.sparse.SparseTensor`s.""" + + def __init__(self, input_dataset, batch_size, row_shape): + """See `Dataset.dense_to_sparse_batch()` for more details.""" + if not isinstance( + dataset_ops.get_legacy_output_types(input_dataset), dtypes.DType): + raise TypeError("`dense_to_sparse_batch` requires an input dataset whose " + "elements have a single component, but the given dataset " + "has the following component types: " + f"{dataset_ops.get_legacy_output_types(input_dataset)}.") + self._input_dataset = input_dataset + self._batch_size = batch_size + self._row_shape = row_shape + self._element_spec = sparse_tensor.SparseTensorSpec( + tensor_shape.TensorShape([None]).concatenate(self._row_shape), + dataset_ops.get_legacy_output_types(input_dataset)) + + variant_tensor = ged_ops.dense_to_sparse_batch_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._batch_size, + row_shape=convert.partial_shape_to_tensor(self._row_shape), + **self._flat_structure) + super(_DenseToSparseBatchDataset, self).__init__(input_dataset, + variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +class _MapAndBatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over a batch of elements.""" + + def __init__(self, input_dataset, map_func, batch_size, num_parallel_calls, + drop_remainder, use_legacy_function=False): + self._input_dataset = input_dataset + + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, + "tf.data.experimental.map_and_batch()", + dataset=input_dataset, + use_legacy_function=use_legacy_function) + self._batch_size_t = ops.convert_to_tensor( + batch_size, dtype=dtypes.int64, name="batch_size") + self._num_parallel_calls_t = ops.convert_to_tensor( + num_parallel_calls, dtype=dtypes.int64, name="num_parallel_calls") + self._drop_remainder_t = ops.convert_to_tensor( + drop_remainder, dtype=dtypes.bool, name="drop_remainder") + + constant_drop_remainder = tensor_util.constant_value(self._drop_remainder_t) + # pylint: disable=protected-access + if constant_drop_remainder: + # NOTE(mrry): `constant_drop_remainder` may be `None` (unknown statically) + # or `False` (explicitly retaining the remainder). + # pylint: disable=g-long-lambda + self._element_spec = nest.map_structure( + lambda component_spec: component_spec._batch( + tensor_util.constant_value(self._batch_size_t)), + self._map_func.output_structure) + else: + self._element_spec = nest.map_structure( + lambda component_spec: component_spec._batch(None), + self._map_func.output_structure) + # pylint: enable=protected-access + variant_tensor = ged_ops.map_and_batch_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, + f=self._map_func.function, + batch_size=self._batch_size_t, + num_parallel_calls=self._num_parallel_calls_t, + drop_remainder=self._drop_remainder_t, + preserve_cardinality=True, + **self._flat_structure) + super(_MapAndBatchDataset, self).__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._element_spec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/cardinality.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/cardinality.py new file mode 100644 index 0000000000000000000000000000000000000000..6525e565f368627d8673ee859ac7ee04adc9563c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/cardinality.py @@ -0,0 +1,113 @@ +# 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. +# ============================================================================== +"""Cardinality analysis of `Dataset` objects.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.util.tf_export import tf_export + + +INFINITE = -1 +UNKNOWN = -2 +tf_export("data.experimental.INFINITE_CARDINALITY").export_constant( + __name__, "INFINITE") +tf_export("data.experimental.UNKNOWN_CARDINALITY").export_constant( + __name__, "UNKNOWN") + + +# TODO(b/157691652): Deprecate this method after migrating users to the new API. +@tf_export("data.experimental.cardinality") +def cardinality(dataset): + """Returns the cardinality of `dataset`, if known. + + The operation returns the cardinality of `dataset`. The operation may return + `tf.data.experimental.INFINITE_CARDINALITY` if `dataset` contains an infinite + number of elements or `tf.data.experimental.UNKNOWN_CARDINALITY` if the + analysis fails to determine the number of elements in `dataset` (e.g. when the + dataset source is a file). + + >>> dataset = tf.data.Dataset.range(42) + >>> print(tf.data.experimental.cardinality(dataset).numpy()) + 42 + >>> dataset = dataset.repeat() + >>> cardinality = tf.data.experimental.cardinality(dataset) + >>> print((cardinality == tf.data.experimental.INFINITE_CARDINALITY).numpy()) + True + >>> dataset = dataset.filter(lambda x: True) + >>> cardinality = tf.data.experimental.cardinality(dataset) + >>> print((cardinality == tf.data.experimental.UNKNOWN_CARDINALITY).numpy()) + True + + Args: + dataset: A `tf.data.Dataset` for which to determine cardinality. + + Returns: + A scalar `tf.int64` `Tensor` representing the cardinality of `dataset`. If + the cardinality is infinite or unknown, the operation returns the named + constant `INFINITE_CARDINALITY` and `UNKNOWN_CARDINALITY` respectively. + """ + + return gen_dataset_ops.dataset_cardinality(dataset._variant_tensor) # pylint: disable=protected-access + + +@tf_export("data.experimental.assert_cardinality") +def assert_cardinality(expected_cardinality): + """Asserts the cardinality of the input dataset. + + NOTE: The following assumes that "examples.tfrecord" contains 42 records. + + >>> dataset = tf.data.TFRecordDataset("examples.tfrecord") + >>> cardinality = tf.data.experimental.cardinality(dataset) + >>> print((cardinality == tf.data.experimental.UNKNOWN_CARDINALITY).numpy()) + True + >>> dataset = dataset.apply(tf.data.experimental.assert_cardinality(42)) + >>> print(tf.data.experimental.cardinality(dataset).numpy()) + 42 + + Args: + expected_cardinality: The expected cardinality of the input dataset. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + + Raises: + FailedPreconditionError: The assertion is checked at runtime (when iterating + the dataset) and an error is raised if the actual and expected cardinality + differ. + """ + def _apply_fn(dataset): + return _AssertCardinalityDataset(dataset, expected_cardinality) + + return _apply_fn + + +class _AssertCardinalityDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that assert the cardinality of its input.""" + + def __init__(self, input_dataset, expected_cardinality): + self._input_dataset = input_dataset + self._expected_cardinality = ops.convert_to_tensor( + expected_cardinality, dtype=dtypes.int64, name="expected_cardinality") + + # pylint: enable=protected-access + variant_tensor = ged_ops.assert_cardinality_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._expected_cardinality, + **self._flat_structure) + super(_AssertCardinalityDataset, self).__init__(input_dataset, + variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/compression_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/compression_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..67213a0729638892bb652eb55ca9a4bb09d39bbc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/compression_ops.py @@ -0,0 +1,51 @@ +# 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. +# ============================================================================== +"""Ops for compressing and uncompressing dataset elements.""" +from tensorflow.python.data.util import structure +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def compress(element): + """Compress a dataset element. + + Args: + element: A nested structure of types supported by Tensorflow. + + Returns: + A variant tensor representing the compressed element. This variant can be + passed to `uncompress` to get back the original element. + """ + element_spec = structure.type_spec_from_value(element) + tensor_list = structure.to_tensor_list(element_spec, element) + return ged_ops.compress_element(tensor_list) + + +def uncompress(element, output_spec): + """Uncompress a compressed dataset element. + + Args: + element: A scalar variant tensor to uncompress. The element should have been + created by calling `compress`. + output_spec: A nested structure of `tf.TypeSpec` representing the type(s) of + the uncompressed element. + + Returns: + The uncompressed element. + """ + flat_types = structure.get_flat_tensor_types(output_spec) + flat_shapes = structure.get_flat_tensor_shapes(output_spec) + tensor_list = ged_ops.uncompress_element( + element, output_types=flat_types, output_shapes=flat_shapes) + return structure.from_tensor_list(output_spec, tensor_list) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/counter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/counter.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8eaaae76afaaf507d86301f87e7313ae730c30 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/counter.py @@ -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. +# ============================================================================== +"""The Counter Dataset.""" +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.Counter", v1=[]) +@deprecation.deprecated(None, "Use `tf.data.Dataset.counter(...)` instead.") +def CounterV2(start=0, step=1, dtype=dtypes.int64): + """Creates a `Dataset` that counts from `start` in steps of size `step`. + + Unlike `tf.data.Dataset.range` which will stop at some ending number, + `Counter` will produce elements indefinitely. + + >>> dataset = tf.data.experimental.Counter().take(5) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 2, 3, 4] + >>> dataset.element_spec + TensorSpec(shape=(), dtype=tf.int64, name=None) + >>> dataset = tf.data.experimental.Counter(dtype=tf.int32) + >>> dataset.element_spec + TensorSpec(shape=(), dtype=tf.int32, name=None) + >>> dataset = tf.data.experimental.Counter(start=2).take(5) + >>> list(dataset.as_numpy_iterator()) + [2, 3, 4, 5, 6] + >>> dataset = tf.data.experimental.Counter(start=2, step=5).take(5) + >>> list(dataset.as_numpy_iterator()) + [2, 7, 12, 17, 22] + >>> dataset = tf.data.experimental.Counter(start=10, step=-1).take(5) + >>> list(dataset.as_numpy_iterator()) + [10, 9, 8, 7, 6] + + Args: + start: (Optional.) The starting value for the counter. Defaults to 0. + step: (Optional.) The step size for the counter. Defaults to 1. + dtype: (Optional.) The data type for counter elements. Defaults to + `tf.int64`. + + Returns: + A `Dataset` of scalar `dtype` elements. + """ + return dataset_ops.Dataset.counter(start, step, dtype) + + +@tf_export(v1=["data.experimental.Counter"]) +@deprecation.deprecated(None, "Use `tf.data.Dataset.counter(...)` instead.") +def CounterV1(start=0, step=1, dtype=dtypes.int64): + return dataset_ops.DatasetV1Adapter(CounterV2(start, step, dtype)) + + +CounterV1.__doc__ = CounterV2.__doc__ + +if tf2.enabled(): + Counter = CounterV2 +else: + Counter = CounterV1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/data_service_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/data_service_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..baf0862379cd4feeb7ec70e68c19ab909aa67c42 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/data_service_ops.py @@ -0,0 +1,1170 @@ +# 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. +# ============================================================================== +"""Python API for executing a tf.data.Dataset using a tf.data service.""" + +import enum +import functools + +from tensorflow.core.protobuf import data_service_pb2 +from tensorflow.python import tf2 +from tensorflow.python.data.experimental.ops import compression_ops +from tensorflow.python.data.experimental.service import _pywrap_server_lib +from tensorflow.python.data.experimental.service import _pywrap_utils +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.ops.options import AutoShardPolicy +from tensorflow.python.data.ops.options import ExternalStatePolicy +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util.tf_export import tf_export + +COMPRESSION_AUTO = "AUTO" +COMPRESSION_NONE = None +_PARALLEL_EPOCHS = "parallel_epochs" +_DISTRIBUTED_EPOCH = "distributed_epoch" + + +@tf_export("data.experimental.service.ShardingPolicy") +class ShardingPolicy(enum.IntEnum): + """Specifies how to shard data among tf.data service workers. + + OFF: No sharding will be performed. Each worker produces the entire dataset + without any sharding. With this mode, the best practice is to shuffle the + dataset nondeterministically so that workers process the dataset in different + orders. If workers are restarted or join the cluster mid-job, they will begin + processing the dataset from the beginning. + + DYNAMIC: The input dataset is dynamically split among workers at runtime. Each + worker gets the next split when it reads data from the dispatcher. Data is + produced non-deterministically in this mode. Dynamic sharding works well with + varying-sized tf.data service clusters, e.g., when you need to auto-scale your + workers. Dynamic sharding provides at-most once visitation guarantees. No + examples will be repeated, but some may be missed if a tf.data service worker + gets restarted while processing a file. + + The following are static sharding policies. The semantics are similar to + `tf.data.experimental.AutoShardPolicy`. These policies require: + * The tf.data service cluster is configured with a fixed list of workers + in DispatcherConfig. + * Each client only reads from the local tf.data service worker. + + If a worker is restarted while performing static sharding, the worker will + begin processing its shard again from the beginning. + + FILE: Shards by input files (i.e. each worker will get a fixed 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. + + 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 partition the dataset elements, the dataset needs to + produce elements in a deterministic order. + + FILE_OR_DATA: Attempts FILE-based sharding, falling back to DATA-based + sharding on failure. + + HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated as a + placeholder to replace with `shard(num_workers, worker_index)`. + """ + + # LINT.IfChange(tf_data_service_sharding_policy) + OFF = 0 + DYNAMIC = 1 + FILE = 2 + DATA = 3 + FILE_OR_DATA = 4 + HINT = 5 + # LINT.ThenChange() + + def _to_proto(self) -> data_service_pb2.ProcessingModeDef.ShardingPolicy: + """Converts the policy to ProcessingModeDef proto enum.""" + + if self == ShardingPolicy.OFF: + return data_service_pb2.ProcessingModeDef.OFF + if self == ShardingPolicy.DYNAMIC: + return data_service_pb2.ProcessingModeDef.DYNAMIC + if self == ShardingPolicy.FILE: + return data_service_pb2.ProcessingModeDef.FILE + if self == ShardingPolicy.DATA: + return data_service_pb2.ProcessingModeDef.DATA + if self == ShardingPolicy.FILE_OR_DATA: + return data_service_pb2.ProcessingModeDef.FILE_OR_DATA + if self == ShardingPolicy.HINT: + return data_service_pb2.ProcessingModeDef.HINT + raise ValueError(f"Unable to convert sharding policy {self!r} to proto.") + + +@tf_export("data.experimental.service.CrossTrainerCache") +class CrossTrainerCache: + """Options related to the tf.data service cross trainer cache. + + This is used to enable cross-trainer cache when distributing a dataset. For + example: + + ``` + dataset = dataset.apply(tf.data.experimental.service.distribute( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + job_name="job", + cross_trainer_cache=data_service_ops.CrossTrainerCache( + trainer_id=trainer_id()))) + ``` + + For more details, refer to + https://www.tensorflow.org/api_docs/python/tf/data/experimental/service#sharing_tfdata_service_with_concurrent_trainers. + """ + + def __init__(self, trainer_id): + """Constructs a CrossTrainerCache. + + Args: + trainer_id: Each training job has a unique ID. Once a job has consumed + data, the data remains in the cache and is re-used by jobs with different + `trainer_id`s. Requests with the same `trainer_id` do not re-use data. + + Raises: + ValueError if `trainer_id` is empty. + """ + if not trainer_id: + raise ValueError( + "tf.data service cross-trainer cache requires a non-empty trainer ID." + ) + self.trainer_id = trainer_id + + def _to_proto(self) -> data_service_pb2.CrossTrainerCacheOptions: + return data_service_pb2.CrossTrainerCacheOptions(trainer_id=self.trainer_id) + + +def _get_validated_sharding_policy(processing_mode) -> ShardingPolicy: + """Validates `processing_mode` and converts it to ShardingPolicy.""" + + if isinstance(processing_mode, ShardingPolicy): + return processing_mode + if processing_mode == _PARALLEL_EPOCHS: + return ShardingPolicy.OFF + if processing_mode == _DISTRIBUTED_EPOCH: + return ShardingPolicy.DYNAMIC + + raise ValueError("tf.data service processing mode should be a " + "`tf.data.experimental.service.ShardingPolicy`, " + "`\"parallel_epochs\"`, or `\"distributed_epoch\"`. Got " + f"{processing_mode!r}.") + + +def _validate_job_name(job_name) -> None: + if job_name is None: + return + if not isinstance(job_name, str): + raise ValueError("`job_name` must be a string, but `job_name` was of type " + f"{type(job_name)}. job_name={job_name}") + if not job_name: + raise ValueError("`job_name` must not be empty") + + +def _validate_compression(compression) -> None: + valid_compressions = [COMPRESSION_AUTO, COMPRESSION_NONE] + if compression not in valid_compressions: + raise ValueError(f"Invalid `compression` argument: {compression}. " + f"Must be one of {valid_compressions}.") + + +def _get_compression_proto( + compression) -> data_service_pb2.DataServiceMetadata.Compression: + if compression == COMPRESSION_AUTO: + return data_service_pb2.DataServiceMetadata.COMPRESSION_SNAPPY + if compression == COMPRESSION_NONE: + return data_service_pb2.DataServiceMetadata.COMPRESSION_OFF + raise ValueError(f"Invalid `compression` argument: {compression}. " + f"Must be one of {[COMPRESSION_AUTO, COMPRESSION_NONE]}.") + + +def _to_tensor(dataset_id) -> tensor.Tensor: + """Converts `dataset_id` to Tensor.""" + + if isinstance(dataset_id, tensor.Tensor): + return dataset_id + if isinstance(dataset_id, str) or isinstance(dataset_id, bytes): + return ops.convert_to_tensor( + dataset_id, dtype=dtypes.string, name="dataset_id") + return ops.convert_to_tensor( + dataset_id, dtype=dtypes.int64, name="dataset_id") + + +def _to_string(dataset_id) -> str: + """Converts `dataset_id` to string.""" + + if isinstance(dataset_id, tensor.Tensor): + return (dataset_id if dataset_id.dtype == dtypes.string else + string_ops.as_string(dataset_id)) + return (dataset_id.decode() + if isinstance(dataset_id, bytes) else str(dataset_id)) + + +class _DataServiceDatasetV2(dataset_ops.DatasetSource): + """A `Dataset` that reads elements from the tf.data service.""" + + def __init__(self, + dataset_id, + processing_mode, + address, + element_spec, + protocol, + data_transfer_protocol, + job_name=None, + consumer_index=None, + num_consumers=None, + max_outstanding_requests=None, + task_refresh_interval_hint_ms=None, + cross_trainer_cache=None, + target_workers="AUTO"): + """Constructs a _DataServiceDatasetV2. + + Args: + dataset_id: The dataset id for the dataset to read from. + processing_mode: A `tf.data.experimental.service.ShardingPolicy` + specifying how to shard the dataset among tf.data workers. See + `tf.data.experimental.service.ShardingPolicy` for details. For backwards + compatibility, `processing_mode` may also be set to the strings + `"parallel_epochs"` or `"distributed_epoch"`, which are respectively + equivalent to `ShardingPolicy.OFF` and `ShardingPolicy.DYNAMIC`. + address: The tf.data service address, e.g. "localhost:5000". + element_spec: The dataset element spec for the dataset to read from. + protocol: The protocol to use for communicating with the tf.data service, + e.g. "grpc". + data_transfer_protocol: (Optional.) The protocol to use for transferring + data with the tf.data service. By default, data is transferred using + gRPC. + job_name: (Optional.) The name of the job. If provided, it must be a + non-empty string or Tensor. This argument makes it possible for multiple + datasets to share the same job. The default behavior is that the dataset + creates anonymous, exclusively owned jobs. + consumer_index: (Optional.) The index of the consumer in the range from + `0` to `num_consumers`. Must be specified alongside `num_consumers`. + When specified, consumers will read from the job in a strict round-robin + order, instead of the default first-come-first-served order. + num_consumers: (Optional.) The number of consumers which will consume from + the job. Must be specified alongside `consumer_index`. When specified, + consumers will read from the job in a strict round-robin order, instead + of the default first-come-first-served order. When `num_consumers` is + specified, the dataset must have infinite cardinality to prevent a + producer from running out of data early and causing consumers to go out + of sync. + max_outstanding_requests: (Optional.) A limit on how many elements may be + requested at the same time. You can use this option to control the + amount of memory used, since `distribute` won't use more than + `element_size` * `max_outstanding_requests` of memory. + task_refresh_interval_hint_ms: (Optional.) A hint for how often to query + the dispatcher for task changes. + cross_trainer_cache: (Optional.) If a `CrossTrainerCache` object is + provided, dataset iteration will be shared across concurrently running + trainers. See + https://www.tensorflow.org/api_docs/python/tf/data/experimental/service#sharing_tfdata_service_with_concurrent_trainers + for details. + target_workers: (Optional.) Which workers to read from. If `"AUTO"`, + tf.data runtime decides which workers to read from. If `"ANY"`, reads + from any tf.data service workers. If `"LOCAL"`, only reads from local + in-processs tf.data service workers. `"AUTO"` works well for most cases, + while users can specify other targets. For example, `"LOCAL"` helps + avoid RPCs and data copy if every TF worker colocates with a tf.data + service worker. Consumers of a shared job must use the same + `target_workers`. Defaults to `"AUTO"`. + """ + if consumer_index is None != num_consumers is None: + raise ValueError( + "Must either set both `consumer_index` and `num_consumers`, " + "or neither. ", + f"consumer_index={consumer_index}, num_consumers={num_consumers}") + if num_consumers is not None and job_name is None: + raise ValueError("`job_name` must be set when setting `num_consumers`. " + f"num_consumers was set to {num_consumers}.") + + processing_mode_def = data_service_pb2.ProcessingModeDef( + sharding_policy=_get_validated_sharding_policy( + processing_mode)._to_proto()) + if job_name is None: + job_name = "" + if max_outstanding_requests is None: + max_outstanding_requests = dataset_ops.AUTOTUNE + if task_refresh_interval_hint_ms is None: + task_refresh_interval_hint_ms = dataset_ops.AUTOTUNE + + self._dataset_id = _to_tensor(dataset_id) + self._processing_mode = ops.convert_to_tensor( + processing_mode_def.SerializeToString(), + dtype=dtypes.string, + name="processing_mode") + self._address = ops.convert_to_tensor( + address, dtype=dtypes.string, name="address") + self._protocol = ops.convert_to_tensor( + protocol, dtype=dtypes.string, name="protocol") + self._job_name = ops.convert_to_tensor( + job_name, dtype=dtypes.string, name="job_name") + self._consumer_index = ops.convert_to_tensor( + -1 if consumer_index is None else consumer_index, + dtype=dtypes.int64, + name="consumer_index") + self._num_consumers = ops.convert_to_tensor( + -1 if num_consumers is None else num_consumers, + dtype=dtypes.int64, + name="num_consumers") + self._max_outstanding_requests = ops.convert_to_tensor( + max_outstanding_requests, + dtype=dtypes.int64, + name="max_outstanding_requests") + self._element_spec = element_spec + uncompress_func = structured_function.StructuredFunctionWrapper( + lambda x: compression_ops.uncompress(x, output_spec=element_spec), + transformation_name="DataServiceDataset.uncompress()", + input_structure=tensor.TensorSpec(shape=(), dtype=dtypes.variant)) + cross_trainer_cache_options = ( + cross_trainer_cache._to_proto().SerializeToString() + if cross_trainer_cache else None) + + compat_kwargs = {} + if data_transfer_protocol is not None: + compat_kwargs["data_transfer_protocol"] = data_transfer_protocol + + # If `uncompress` is `True`, the dataset will query the servers to find + # out the actual compression used. It is always set to `True` the first + # time the graph is built, and set to false when serializing, so we will + # uncompress at most once. + uncompress = True + variant_tensor = gen_experimental_dataset_ops.data_service_dataset_v4( + dataset_id=self._dataset_id, + processing_mode=self._processing_mode, + address=self._address, + protocol=self._protocol, + job_name=self._job_name, + consumer_index=self._consumer_index, + num_consumers=self._num_consumers, + max_outstanding_requests=self._max_outstanding_requests, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + iteration_counter=( + gen_experimental_dataset_ops.dummy_iteration_counter()), + target_workers=target_workers, + uncompress=uncompress, + uncompress_fn=uncompress_func.function, + cross_trainer_cache_options=cross_trainer_cache_options, + **compat_kwargs, + **self._flat_structure) + super(_DataServiceDatasetV2, self).__init__(variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +class _DataServiceDatasetV1(dataset_ops.DatasetV1Adapter): + """A `Dataset` that executes its input through the tf.data service.""" + + @functools.wraps(_DataServiceDatasetV2.__init__) + def __init__(self, dataset_id, processing_mode, address, element_spec, + protocol, data_transfer_protocol, job_name, consumer_index, + num_consumers, max_outstanding_requests, + task_refresh_interval_hint_ms, cross_trainer_cache, + target_workers): + + self._wrapped = _DataServiceDatasetV2( + dataset_id=dataset_id, + processing_mode=processing_mode, + address=address, + element_spec=element_spec, + protocol=protocol, + data_transfer_protocol=data_transfer_protocol, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + cross_trainer_cache=cross_trainer_cache, + target_workers=target_workers) + super(_DataServiceDatasetV1, self).__init__(self._wrapped) + + +if tf2.enabled(): + _DataServiceDataset = _DataServiceDatasetV2 +else: + _DataServiceDataset = _DataServiceDatasetV1 + + +def _parse_service(service) -> tuple[str, str]: + """Converts a tf.data service string into a (protocol, address) tuple. + + Args: + service: A string in the format "protocol://address" or just "address". If + the string is only an address, the default protocol will be used. + + Returns: + The (protocol, address) tuple + """ + if not isinstance(service, str): + raise ValueError("`service` must be a string, but `service` was of type " + f"{type(service)}. service={service}") + if not service: + raise ValueError("`service` must not be empty") + parts = service.split("://") + if len(parts) == 2: + protocol, address = parts + elif len(parts) == 1: + address = parts[0] + protocol = _pywrap_utils.TF_DATA_DefaultProtocol() + else: + raise ValueError("Malformed `service` string has multiple '://': " + f"{service}.") + # TODO(aaudibert): Considering validating reachability of address here. + return (protocol, address) + + +def _distribute(processing_mode, + service, + job_name=None, + consumer_index=None, + num_consumers=None, + max_outstanding_requests=None, + task_refresh_interval_hint_ms=None, + data_transfer_protocol=None, + compression="AUTO", + cross_trainer_cache=None, + target_workers="AUTO") -> dataset_ops.Dataset: + """A transformation that moves dataset processing to the tf.data service. + + This transformation is similar to `distribute`, but supports additional + parameters which we do not yet want to add to the public Python API. + + Args: + processing_mode: A `tf.data.experimental.service.ShardingPolicy` specifying + how to shard the dataset among tf.data workers. See + `tf.data.experimental.service.ShardingPolicy` for details. For backwards + compatibility, `processing_mode` may also be set to the strings + `"parallel_epochs"` or `"distributed_epoch"`, which are respectively + equivalent to `ShardingPolicy.OFF` and `ShardingPolicy.DYNAMIC`. + service: A string or a tuple indicating how to connect to the tf.data + service. If it's a string, it should be in the format + `[://]
`, where `
` identifies the dispatcher + address and `` can optionally be used to override the default + protocol to use. If it's a tuple, it should be (protocol, address). + job_name: (Optional.) The name of the job. If provided, it must be a + non-empty string. This argument makes it possible for multiple datasets to + share the same job. The default behavior is that the dataset creates + anonymous, exclusively owned jobs. + consumer_index: (Optional.) The index of the consumer in the range from `0` + to `num_consumers`. Must be specified alongside `num_consumers`. When + specified, consumers will read from the job in a strict round-robin order, + instead of the default first-come-first-served order. + num_consumers: (Optional.) The number of consumers which will consume from + the job. Must be specified alongside `consumer_index`. When specified, + consumers will read from the job in a strict round-robin order, instead of + the default first-come-first-served order. When `num_consumers` is + specified, the dataset must have infinite cardinality to prevent a + producer from running out of data early and causing consumers to go out of + sync. + max_outstanding_requests: (Optional.) A limit on how many elements may be + requested at the same time. You can use this option to control the amount + of memory used, since `distribute` won't use more than `element_size` * + `max_outstanding_requests` of memory. + task_refresh_interval_hint_ms: (Optional.) A hint for how often to query the + dispatcher for task changes. + data_transfer_protocol: (Optional.) The protocol to use for transferring + data with the tf.data service. By default, data is transferred using gRPC. + compression: How to compress the dataset's elements before transferring them + over the network. "AUTO" leaves the decision of how to compress up to the + tf.data service runtime. `None` indicates not to compress. + cross_trainer_cache: (Optional.) If a `CrossTrainerCache` object is + provided, dataset iteration will be shared across concurrently running + trainers. See + https://www.tensorflow.org/api_docs/python/tf/data/experimental/service#sharing_tfdata_service_with_concurrent_trainers + for details. + target_workers: (Optional.) Which workers to read from. If `"AUTO"`, tf.data + runtime decides which workers to read from. If `"ANY"`, reads from any + tf.data service workers. If `"LOCAL"`, only reads from local in-processs + tf.data service workers. `"AUTO"` works well for most cases, while users + can specify other targets. For example, `"LOCAL"` helps avoid RPCs and + data copy if every TF worker colocates with a tf.data service worker. + Consumers of a shared job must use the same `target_workers`. Defaults to + `"AUTO"`. + + Returns: + Dataset: A `Dataset` of the elements produced by the data service. + """ + processing_mode = _get_validated_sharding_policy(processing_mode) + _validate_compression(compression) + + def _apply_fn(dataset) -> dataset_ops.Dataset: # pylint: disable=missing-docstring + dataset_id = _register_dataset(service, dataset, compression=compression) + return _from_dataset_id( + processing_mode, + service, + dataset_id, + dataset.element_spec, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + data_transfer_protocol=data_transfer_protocol, + cross_trainer_cache=cross_trainer_cache, + target_workers=target_workers) + + return _apply_fn + + +@tf_export("data.experimental.service.distribute") +def distribute(processing_mode, + service, + job_name=None, + consumer_index=None, + num_consumers=None, + max_outstanding_requests=None, + data_transfer_protocol=None, + compression="AUTO", + cross_trainer_cache=None, + target_workers="AUTO") -> dataset_ops.Dataset: + """A transformation that moves dataset processing to the tf.data service. + + When you iterate over a dataset containing the `distribute` transformation, + the tf.data service creates a "job" which produces data for the dataset + iteration. + + The tf.data service uses a cluster of workers to prepare data for training + your model. + The `processing_mode` argument to `tf.data.experimental.service.distribute` + describes how to leverage multiple workers to process the input dataset. + Currently, there are two processing modes to choose from: "distributed_epoch" + and "parallel_epochs". + + "distributed_epoch" means that the dataset will be split across all tf.data + service workers. + The dispatcher produces "splits" for the dataset and sends them to workers for + further processing. For example, if a dataset begins with a list of filenames, + the dispatcher will iterate through the filenames and send the filenames to + tf.data workers, which will perform the rest of the dataset transformations on + those files. "distributed_epoch" is useful when your model needs to see each + element of the dataset exactly once, or if it needs to see the data in a + generally-sequential order. "distributed_epoch" only works for datasets with + splittable sources, such as `Dataset.from_tensor_slices`, + `Dataset.list_files`, or `Dataset.range`. + + "parallel_epochs" means that the entire input dataset will be processed + independently by each of the tf.data service workers. + For this reason, it is important to shuffle data (e.g. filenames) + non-deterministically, so that each worker will process the elements of the + dataset in a different order. "parallel_epochs" can be used to distribute + datasets that aren't splittable. + + With two workers, "parallel_epochs" will produce every element of the dataset + twice: + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> # Start two workers + >>> workers = [ + ... tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) for _ in range(2) + ... ] + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.apply(tf.data.experimental.service.distribute( + ... processing_mode="parallel_epochs", service=dispatcher.target)) + >>> print(sorted(list(dataset.as_numpy_iterator()))) + [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9] + + "distributed_epoch", on the other hand, will still produce each element once: + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> workers = [ + ... tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) for _ in range(2) + ... ] + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.apply(tf.data.experimental.service.distribute( + ... processing_mode="distributed_epoch", service=dispatcher.target)) + >>> print(sorted(list(dataset.as_numpy_iterator()))) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + When using `apply(tf.data.experimental.service.distribute(...))`, the dataset + before the `apply` transformation executes within the tf.data service, while + the operations after `apply` happen within the local process. + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> workers = [ + ... tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) for _ in range(2) + ... ] + >>> dataset = tf.data.Dataset.range(5) + >>> dataset = dataset.map(lambda x: x*x) + >>> dataset = dataset.apply( + ... tf.data.experimental.service.distribute("parallel_epochs", + ... dispatcher.target)) + >>> dataset = dataset.map(lambda x: x+1) + >>> print(sorted(list(dataset.as_numpy_iterator()))) + [1, 1, 2, 2, 5, 5, 10, 10, 17, 17] + + In the above example, the dataset operations (before applying the `distribute` + function on the elements) will be executed on the tf.data workers, + and the elements are provided over RPC. The remaining transformations + (after the call to `distribute`) will be executed locally. The dispatcher + and the workers will bind to usused free ports (which are chosen at random), + in order to communicate with each other. However, to bind them to specific + ports, the `port` parameter can be passed. + + The `job_name` argument allows jobs to be shared across multiple + datasets. Instead of each dataset creating its own job, all + datasets with the same `job_name` will consume from the same job. A new job + will be created for each iteration of the dataset (with each repetition of + `Dataset.repeat` counting as a new iteration). Suppose the `DispatchServer` + is serving on `localhost:5000` and two training workers (in either a single + client or multi-client setup) iterate over the below dataset, and there is a + single tf.data worker: + + ``` + range5_dataset = tf.data.Dataset.range(5) + dataset = range5_dataset.apply(tf.data.experimental.service.distribute( + "parallel_epochs", "localhost:5000", job_name="my_job_name")) + for iteration in range(3): + print(list(dataset)) + ``` + + The elements of each job will be split between the two processes, with + elements being consumed by the processes on a first-come first-served basis. + One possible result is that process 1 prints + + ``` + [0, 2, 4] + [0, 1, 3] + [1] + ``` + + and process 2 prints + + ``` + [1, 3] + [2, 4] + [0, 2, 3, 4] + ``` + + Job names must not be re-used across different training jobs within the + lifetime of the tf.data service. In general, the tf.data service is expected + to live for the duration of a single training job. + To use the tf.data service with multiple training jobs, make sure to use + different job names to avoid conflicts. For example, suppose a training job + calls `distribute` with `job_name="job"` and reads until end of input. If + another independent job connects to the same tf.data service and tries to read + from `job_name="job"`, it will immediately receive end of input, without + getting any data. + + **Coordinated data read** + + By default, when multiple consumers read from the same job, they receive data + on a first-come first-served basis. In some use cases, it is advantageous to + coordinate the consumers. At each step, consumers read data from the same + worker. + + For example, the tf.data service can be used to coordinate example sizes + across a cluster during synchronous training, so that during each step all + replicas train on similar-sized elements. To achieve this, define a dataset + which generates rounds of `num_consumers` consecutive similar-sized batches, + then enable coordinated reads by setting `consumer_index` and `num_consumers`. + + NOTE: To keep consumers in sync, round robin data consumption requires that + the dataset have infinite cardinality. You can get this by adding `.repeat()` + at the end of the dataset definition. + + **Keras and Distribution Strategies** + + The dataset produced by the `distribute` transformation can be passed to + Keras' `Model.fit` or Distribution Strategy's + `tf.distribute.Strategy.experimental_distribute_dataset` like any other + `tf.data.Dataset`. We recommend setting a `job_name` on the call to + `distribute` so that if there are multiple workers, they read data from the + same job. Note that the autosharding normally performed by + `experimental_distribute_dataset` will be disabled when setting a `job_name`, + since sharing the job already results in splitting data across the workers. + When using a shared job, data will be dynamically balanced across workers, so + that they reach end of input about the same time. This results in better + worker utilization than with autosharding, where each worker processes an + independent set of files, and some workers may run out of data earlier than + others. + + Args: + processing_mode: A `tf.data.experimental.service.ShardingPolicy` specifying + how to shard the dataset among tf.data workers. See + `tf.data.experimental.service.ShardingPolicy` for details. For backwards + compatibility, `processing_mode` may also be set to the strings + `"parallel_epochs"` or `"distributed_epoch"`, which are respectively + equivalent to `ShardingPolicy.OFF` and `ShardingPolicy.DYNAMIC`. + service: A string or a tuple indicating how to connect to the tf.data + service. If it's a string, it should be in the format + `[://]
`, where `
` identifies the dispatcher + address and `` can optionally be used to override the default + protocol to use. If it's a tuple, it should be (protocol, address). + job_name: (Optional.) The name of the job. If provided, it must be a + non-empty string. This argument makes it possible for multiple datasets to + share the same job. The default behavior is that the dataset creates + anonymous, exclusively owned jobs. + consumer_index: (Optional.) The index of the consumer in the range from `0` + to `num_consumers`. Must be specified alongside `num_consumers`. When + specified, consumers will read from the job in a strict round-robin order, + instead of the default first-come-first-served order. + num_consumers: (Optional.) The number of consumers which will consume from + the job. Must be specified alongside `consumer_index`. When specified, + consumers will read from the job in a strict round-robin order, instead of + the default first-come-first-served order. When `num_consumers` is + specified, the dataset must have infinite cardinality to prevent a + producer from running out of data early and causing consumers to go out of + sync. + max_outstanding_requests: (Optional.) A limit on how many elements may be + requested at the same time. You can use this option to control the amount + of memory used, since `distribute` won't use more than `element_size` * + `max_outstanding_requests` of memory. + data_transfer_protocol: (Optional.) The protocol to use for transferring + data with the tf.data service. By default, data is transferred using gRPC. + compression: How to compress the dataset's elements before transferring them + over the network. "AUTO" leaves the decision of how to compress up to the + tf.data service runtime. `None` indicates not to compress. + cross_trainer_cache: (Optional.) If a `CrossTrainerCache` object is + provided, dataset iteration will be shared across concurrently running + trainers. See + https://www.tensorflow.org/api_docs/python/tf/data/experimental/service#sharing_tfdata_service_with_concurrent_trainers + for details. + target_workers: (Optional.) Which workers to read from. If `"AUTO"`, tf.data + runtime decides which workers to read from. If `"ANY"`, reads from any + tf.data service workers. If `"LOCAL"`, only reads from local in-processs + tf.data service workers. `"AUTO"` works well for most cases, while users + can specify other targets. For example, `"LOCAL"` helps avoid RPCs and + data copy if every TF worker colocates with a tf.data service worker. + Consumers of a shared job must use the same `target_workers`. Defaults to + `"AUTO"`. + + Returns: + Dataset: A `Dataset` of the elements produced by the data service. + """ + _validate_job_name(job_name) + return _distribute( + processing_mode=processing_mode, + service=service, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + data_transfer_protocol=data_transfer_protocol, + compression=compression, + cross_trainer_cache=cross_trainer_cache, + target_workers=target_workers) + + +def _register_dataset( + service, dataset, compression, dataset_id=None) -> tensor.Tensor: + """Registers a dataset with the tf.data service. + + This transformation is similar to `register_dataset`, but supports additional + parameters which we do not yet want to add to the public Python API. + + Args: + service: A string or a tuple indicating how to connect to the tf.data + service. If it's a string, it should be in the format + `[://]
`, where `
` identifies the dispatcher + address and `` can optionally be used to override the default + protocol to use. If it's a tuple, it should be (protocol, address). + dataset: A `tf.data.Dataset` to register with the tf.data service. + compression: How to compress the dataset's elements before transferring them + over the network. "AUTO" leaves the decision of how to compress up to the + tf.data service runtime. `None` indicates not to compress. + dataset_id: (Optional.) By default, tf.data service generates a unique + (string) ID for each registered dataset. If a `dataset_id` is provided, it + will use the specified ID. If a dataset with a matching ID already exists, + no new dataset is registered. This is useful if multiple training jobs + want to (re)use the same dataset for training. In this case, they can + register the dataset with the same dataset ID. + + Returns: + A scalar string tensor representing the dataset ID. + """ + _validate_compression(compression) + if isinstance(service, tuple): + protocol, address = service + else: + protocol, address = _parse_service(service) + external_state_policy = dataset.options().experimental_external_state_policy + if external_state_policy is None: + external_state_policy = ExternalStatePolicy.WARN + + encoded_spec = None + if context.executing_eagerly(): + encoded_spec = nested_structure_coder.encode_structure( + dataset.element_spec).SerializeToString() + + if compression == COMPRESSION_AUTO: + dataset = dataset.map( + lambda *x: compression_ops.compress(x), + num_parallel_calls=dataset_ops.AUTOTUNE) + dataset = dataset._apply_debug_options() # pylint: disable=protected-access + + metadata = data_service_pb2.DataServiceMetadata( + element_spec=encoded_spec, + compression=_get_compression_proto(compression)) + + return gen_experimental_dataset_ops.register_dataset_v2( + dataset._variant_tensor, # pylint: disable=protected-access + address=address, + protocol=protocol, + external_state_policy=external_state_policy.value, + requested_dataset_id=dataset_id, + metadata=metadata.SerializeToString()) + + +@tf_export("data.experimental.service.register_dataset") +def register_dataset( + service, dataset, compression="AUTO", dataset_id=None) -> tensor.Tensor: + """Registers a dataset with the tf.data service. + + `register_dataset` registers a dataset with the tf.data service so that + datasets can be created later with + `tf.data.experimental.service.from_dataset_id`. This is useful when the + dataset + is registered by one process, then used in another process. When the same + process is both registering and reading from the dataset, it is simpler to use + `tf.data.experimental.service.distribute` instead. + + If the dataset is already registered with the tf.data service, + `register_dataset` returns the already-registered dataset's id. + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> worker = tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) + >>> dataset = tf.data.Dataset.range(10) + >>> dataset_id = tf.data.experimental.service.register_dataset( + ... dispatcher.target, dataset) + >>> dataset = tf.data.experimental.service.from_dataset_id( + ... processing_mode="parallel_epochs", + ... service=dispatcher.target, + ... dataset_id=dataset_id, + ... element_spec=dataset.element_spec) + >>> print(list(dataset.as_numpy_iterator())) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + Args: + service: A string or a tuple indicating how to connect to the tf.data + service. If it's a string, it should be in the format + `[://]
`, where `
` identifies the dispatcher + address and `` can optionally be used to override the default + protocol to use. If it's a tuple, it should be (protocol, address). + dataset: A `tf.data.Dataset` to register with the tf.data service. + compression: (Optional.) How to compress the dataset's elements before + transferring them over the network. "AUTO" leaves the decision of how to + compress up to the tf.data service runtime. `None` indicates not to + compress. + dataset_id: (Optional.) By default, tf.data service generates a unique + (string) ID for each registered dataset. If a `dataset_id` is provided, it + will use the specified ID. If a dataset with a matching ID already exists, + no new dataset is registered. This is useful if multiple training jobs + want to (re)use the same dataset for training. In this case, they can + register the dataset with the same dataset ID. + + Returns: + A scalar string tensor representing the dataset ID. + """ + return _register_dataset(service, dataset, compression, dataset_id) + + +def _from_dataset_id(processing_mode, + service, + dataset_id, + element_spec, + job_name=None, + consumer_index=None, + num_consumers=None, + max_outstanding_requests=None, + task_refresh_interval_hint_ms=None, + data_transfer_protocol=None, + cross_trainer_cache=None, + target_workers="AUTO") -> dataset_ops.Dataset: + """Creates a dataset which reads data from the tf.data service. + + This transformation is similar to `from_dataset_id`, but supports additional + parameters which we do not yet want to add to the public Python API. + + Args: + processing_mode: A `tf.data.experimental.service.ShardingPolicy` specifying + how to shard the dataset among tf.data workers. See + `tf.data.experimental.service.ShardingPolicy` for details. For backwards + compatibility, `processing_mode` may also be set to the strings + `"parallel_epochs"` or `"distributed_epoch"`, which are respectively + equivalent to `ShardingPolicy.OFF` and `ShardingPolicy.DYNAMIC`. + service: A string or a tuple indicating how to connect to the tf.data + service. If it's a string, it should be in the format + `[://]
`, where `
` identifies the dispatcher + address and `` can optionally be used to override the default + protocol to use. If it's a tuple, it should be (protocol, address). + dataset_id: The id of the dataset to read from. This id is returned by + `register_dataset` when the dataset is registered with the tf.data + service. + element_spec: A nested structure of `tf.TypeSpec`s representing the type of + elements produced by the dataset. This argument is only required inside a + tf.function. Use `tf.data.Dataset.element_spec` to get the element spec + for a given dataset. + job_name: (Optional.) The name of the job. If provided, it must be a + non-empty string or tensor. This argument makes it possible for multiple + datasets to share the same job. The default behavior is that the dataset + creates anonymous, exclusively owned jobs. + consumer_index: (Optional.) The index of the consumer in the range from `0` + to `num_consumers`. Must be specified alongside `num_consumers`. When + specified, consumers will read from the job in a strict round-robin order, + instead of the default first-come-first-served order. + num_consumers: (Optional.) The number of consumers which will consume from + the job. Must be specified alongside `consumer_index`. When specified, + consumers will read from the job in a strict round-robin order, instead of + the default first-come-first-served order. When `num_consumers` is + specified, the dataset must have infinite cardinality to prevent a + producer from running out of data early and causing consumers to go out of + sync. + max_outstanding_requests: (Optional.) A limit on how many elements may be + requested at the same time. You can use this option to control the amount + of memory used, since `distribute` won't use more than `element_size` * + `max_outstanding_requests` of memory. + task_refresh_interval_hint_ms: (Optional.) A hint for how often to query the + dispatcher for task changes. + data_transfer_protocol: (Optional.) The protocol to use for transferring + data with the tf.data service. By default, data is transferred using gRPC. + cross_trainer_cache: (Optional.) If a `CrossTrainerCache` object is + provided, dataset iteration will be shared across concurrently running + trainers. See + https://www.tensorflow.org/api_docs/python/tf/data/experimental/service#sharing_tfdata_service_with_concurrent_trainers + for details. + target_workers: (Optional.) Which workers to read from. If `"AUTO"`, tf.data + runtime decides which workers to read from. If `"ANY"`, reads from any + tf.data service workers. If `"LOCAL"`, only reads from local in-processs + tf.data service workers. `"AUTO"` works well for most cases, while users + can specify other targets. For example, `"LOCAL"` helps avoid RPCs and + data copy if every TF worker colocates with a tf.data service worker. + Consumers of a shared job must use the same `target_workers`. Defaults to + `"AUTO"`. + + Returns: + A `tf.data.Dataset` which reads from the tf.data service. + """ + def _get_element_spec(): + """Fetches the element spec from the server.""" + data_service_metadata = None + dataset_id_val = tensor_util.constant_value(dataset_id) + try: + data_service_metadata = ( + _pywrap_server_lib.TF_DATA_GetDataServiceMetadataByID( + dataset_id_val, address, protocol + ) + ) + except NotImplementedError as err: + raise ValueError( + "The tf.data service is running an earlier version of TensorFlow " + "that requires specifying `element_spec` as an argument to " + "`from_dataset_id`. Please either supply an element spec or update " + "the tf.data service to the latest version.") from err + except RuntimeError: + # This error results from dataset ID not found. A more appropriate error + # will be raised when the dataset is created. + pass + + if not data_service_metadata or not data_service_metadata.element_spec: + dataset_id_val = tensor_util.constant_value(dataset_id) + raise ValueError( + f"Failed to fetch element spec for dataset id {dataset_id_val} from " + "tf.data service. If the dataset was registered in graph mode or " + "inside a tf.function, the `element_spec` must be specified as an " + "argument to `from_dataset_id`.") + + struct_pb = nested_structure_coder.struct_pb2.StructuredValue() + struct_pb.ParseFromString(data_service_metadata.element_spec) + return nested_structure_coder.decode_proto(struct_pb) + + processing_mode = _get_validated_sharding_policy(processing_mode) + if isinstance(service, tuple): + protocol, address = service + else: + protocol, address = _parse_service(service) + if job_name is not None: + if not isinstance(job_name, str) and not isinstance( + job_name, tensor.Tensor): + raise ValueError( + "`job_name` must be a string or Tensor, but `job_name` was of type " + f"{type(job_name)}. job_name={job_name}.") + + if not element_spec: + if not context.executing_eagerly(): + raise ValueError( + "In graph mode `element_spec` must be provided manually.") + element_spec = _get_element_spec() + + dataset = _DataServiceDataset( + dataset_id=dataset_id, + processing_mode=processing_mode, + address=address, + element_spec=element_spec, + protocol=protocol, + data_transfer_protocol=data_transfer_protocol, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, + cross_trainer_cache=cross_trainer_cache, + target_workers=target_workers) + + # Disable autosharding for shared jobs. + if job_name is not None: + options = options_lib.Options() + options.experimental_distribute.auto_shard_policy = AutoShardPolicy.OFF + dataset = dataset.with_options(options) + return dataset + + +@tf_export("data.experimental.service.from_dataset_id") +def from_dataset_id(processing_mode, + service, + dataset_id, + element_spec=None, + job_name=None, + consumer_index=None, + num_consumers=None, + max_outstanding_requests=None, + data_transfer_protocol=None, + cross_trainer_cache=None, + target_workers="AUTO") -> dataset_ops.Dataset: + """Creates a dataset which reads data from the tf.data service. + + This is useful when the dataset is registered by one process, then used in + another process. When the same process is both registering and reading from + the dataset, it is simpler to use `tf.data.experimental.service.distribute` + instead. + + Before using `from_dataset_id`, the dataset must have been registered with the + tf.data service using `tf.data.experimental.service.register_dataset`. + `register_dataset` returns a dataset id for the registered dataset. That is + the `dataset_id` which should be passed to `from_dataset_id`. + + The `element_spec` argument indicates the `tf.TypeSpec`s for the elements + produced by the dataset. Currently `element_spec` must be explicitly + specified, and match the dataset registered under `dataset_id`. `element_spec` + defaults to `None` so that in the future we can support automatically + discovering the `element_spec` by querying the tf.data service. + + `tf.data.experimental.service.distribute` is a convenience method which + combines `register_dataset` and `from_dataset_id` into a dataset + transformation. + See the documentation for `tf.data.experimental.service.distribute` for more + detail about how `from_dataset_id` works. + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> worker = tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) + >>> dataset = tf.data.Dataset.range(10) + >>> dataset_id = tf.data.experimental.service.register_dataset( + ... dispatcher.target, dataset) + >>> dataset = tf.data.experimental.service.from_dataset_id( + ... processing_mode="parallel_epochs", + ... service=dispatcher.target, + ... dataset_id=dataset_id, + ... element_spec=dataset.element_spec) + >>> print(list(dataset.as_numpy_iterator())) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + Args: + processing_mode: A `tf.data.experimental.service.ShardingPolicy` specifying + how to shard the dataset among tf.data workers. See + `tf.data.experimental.service.ShardingPolicy` for details. For backwards + compatibility, `processing_mode` may also be set to the strings + `"parallel_epochs"` or `"distributed_epoch"`, which are respectively + equivalent to `ShardingPolicy.OFF` and `ShardingPolicy.DYNAMIC`. + service: A string or a tuple indicating how to connect to the tf.data + service. If it's a string, it should be in the format + `[://]
`, where `
` identifies the dispatcher + address and `` can optionally be used to override the default + protocol to use. If it's a tuple, it should be (protocol, address). + dataset_id: The id of the dataset to read from. This id is returned by + `register_dataset` when the dataset is registered with the tf.data + service. + element_spec: A nested structure of `tf.TypeSpec`s representing the type of + elements produced by the dataset. This argument is only required inside a + tf.function. Use `tf.data.Dataset.element_spec` to get the element spec + for a given dataset. + job_name: (Optional.) The name of the job. If provided, it must be a + non-empty string. This argument makes it possible for multiple datasets to + share the same job. The default behavior is that the dataset creates + anonymous, exclusively owned jobs. + consumer_index: (Optional.) The index of the consumer in the range from `0` + to `num_consumers`. Must be specified alongside `num_consumers`. When + specified, consumers will read from the job in a strict round-robin order, + instead of the default first-come-first-served order. + num_consumers: (Optional.) The number of consumers which will consume from + the job. Must be specified alongside `consumer_index`. When specified, + consumers will read from the job in a strict round-robin order, instead of + the default first-come-first-served order. When `num_consumers` is + specified, the dataset must have infinite cardinality to prevent a + producer from running out of data early and causing consumers to go out of + sync. + max_outstanding_requests: (Optional.) A limit on how many elements may be + requested at the same time. You can use this option to control the amount + of memory used, since `distribute` won't use more than `element_size` * + `max_outstanding_requests` of memory. + data_transfer_protocol: (Optional.) The protocol to use for transferring + data with the tf.data service. By default, data is transferred using gRPC. + cross_trainer_cache: (Optional.) If a `CrossTrainerCache` object is + provided, dataset iteration will be shared across concurrently running + trainers. See + https://www.tensorflow.org/api_docs/python/tf/data/experimental/service#sharing_tfdata_service_with_concurrent_trainers + for details. + target_workers: (Optional.) Which workers to read from. If `"AUTO"`, tf.data + runtime decides which workers to read from. If `"ANY"`, reads from any + tf.data service workers. If `"LOCAL"`, only reads from local in-processs + tf.data service workers. `"AUTO"` works well for most cases, while users + can specify other targets. For example, `"LOCAL"` helps avoid RPCs and + data copy if every TF worker colocates with a tf.data service worker. + Consumers of a shared job must use the same `target_workers`. Defaults to + `"AUTO"`. + + Returns: + A `tf.data.Dataset` which reads from the tf.data service. + """ + _validate_job_name(job_name) + if job_name is not None: + job_name = string_ops.string_join( + ["dataset_id=", _to_string(dataset_id), job_name], "/") + + return _from_dataset_id( + processing_mode=processing_mode, + service=service, + dataset_id=dataset_id, + element_spec=element_spec, + job_name=job_name, + consumer_index=consumer_index, + num_consumers=num_consumers, + max_outstanding_requests=max_outstanding_requests, + data_transfer_protocol=data_transfer_protocol, + cross_trainer_cache=cross_trainer_cache, + target_workers=target_workers) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/distribute.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/distribute.py new file mode 100644 index 0000000000000000000000000000000000000000..1eb3672d5dc2c11190777846f31bf97d726076ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/distribute.py @@ -0,0 +1,399 @@ +# 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. +# ============================================================================== +"""Distribution Strategy-related dataset transformations.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops.options import ExternalStatePolicy +from tensorflow.python.data.util import nest +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.types import data as data_types +from tensorflow.python.util.tf_export import tf_export + +SHARD_HINT = -1 +tf_export("data.experimental.SHARD_HINT").export_constant( + __name__, "SHARD_HINT") + + +class _AutoShardDataset(dataset_ops.UnaryDataset): + """A `Dataset` that shards the `Dataset` automatically. + + This dataset takes in an existing dataset and tries to automatically figure + out how to shard the dataset in a multi-worker scenario using graph rewrites. + + If the AutoShardPolicy is set to FILE, it walks up the dataset graph until + it finds a reader dataset, then inserts a ShardDataset op before that node + so that each worker only sees some files. + + If the AutoShardPolicy is set to DATA, it inserts a ShardDataset op at the + end of the input pipeline, before any terminal PrefetchDataset if there is + one. Additionally, if there is a RebatchDatasetV2 in the input pipeline, it + is written to legacy RebatchDataset for correctness reasons, since + RebatchDatasetV2 is incompatible with data sharding. + + If the AutoShardPolicy is set to AUTO, it tries to do file-based sharding. + If it cannot find a reader dataset, it falls back to doing data-based + sharding. + + If the AutoShardPolicy is set to OFF, it does nothing. + + Attributes: + num_workers: Total number of workers to shard this dataset across. + index: The current worker index (out of the total number of workers) this + dataset is for. + num_replicas: The total number of replicas across all workers. This is used + only when sharding by data (either DATA or AUTO) in order to rewrite + RebatchDatasetV2 to RebatchDataset. + + Raises: + NotFoundError: If we cannot find a suitable reader dataset to begin + automatically sharding the dataset. + """ + + def __init__(self, input_dataset, num_workers, index, num_replicas=None): + self._input_dataset = input_dataset + + self._element_spec = input_dataset.element_spec + variant_tensor = ged_ops.auto_shard_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + num_workers=num_workers, + index=index, + auto_shard_policy=int( + input_dataset.options().experimental_distribute.auto_shard_policy), + num_replicas=num_replicas, + **self._flat_structure) + super(_AutoShardDataset, self).__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +def _AutoShardDatasetV1(input_dataset, num_workers, index, num_replicas=None): # pylint: disable=invalid-name + return dataset_ops.DatasetV1Adapter( + _AutoShardDataset(input_dataset, num_workers, index, num_replicas)) + + +class _LegacyRebatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that divides its input batches into `num_replicas` sub-batches. + + For each batch in the input dataset, _LegacyRebatchDataset will produce + `num_replicas` smaller batches whose sizes add up to the original batch size. + + For example: + + ```python + ds = tf.data.Dataset.range(8) + ds = ds.batch(4) + ds = _LegacyRebatchDataset(ds, num_replicas=3) + for elem in ds: + print(elem) + >> [0, 1], [2, 3], [], [4, 5], [6, 7], [] + ``` + """ + + def __init__(self, input_dataset, num_replicas): + """Creates a _LegacyRebatchDataset. + + Args: + input_dataset: `Dataset` to rebatch. + num_replicas: A `tf.int64` scalar, representing the number of sub-batches + to split each batch from `input_dataset` into. + """ + + def recalculate_batch_size(type_spec): + """Recalculates the output_shape after dividing it by num_replicas.""" + output_shape = type_spec._to_legacy_output_shapes() # pylint: disable=protected-access + if not isinstance(output_shape, tensor_shape.TensorShape): + return None + + # If the output shape is unknown, we set the batch dimension to unknown. + if output_shape.rank is None: + return None + + if len(output_shape) < 1: + raise ValueError( + "Invalid `input_dataset`. Expected a dataset whose elements " + "have rank >= 1 but found a dataset whose elements are scalars. " + "Fix the issue by adding the `batch` transformation to the " + "dataset.") + output_dims = [d.value for d in output_shape.dims] + + if output_dims[0] is not None and output_dims[0] % num_replicas == 0: + return output_dims[0] // num_replicas + + # Set the batch dimension to unknown. If the global batch size does not + # divide num_replicas evenly, the minibatches may have different sizes. + return None + + def rebatch(type_spec): + # pylint: disable=protected-access + batch_size = recalculate_batch_size(type_spec) + return type_spec._unbatch()._batch(batch_size) + # pylint: enable=protected-access + + self._element_spec = nest.map_structure( + rebatch, dataset_ops.get_structure(input_dataset)) + + # auto_shard rewrite assumes that there's normalize_to_dense before + # rebatch_dataset. + # LINT.IfChange + input_dataset = dataset_ops.normalize_to_dense(input_dataset) + variant_tensor = ged_ops.rebatch_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + num_replicas=num_replicas, + **self._flat_structure) + # LINT.ThenChange(//tensorflow/core/grappler/optimizers/data/auto_shard.cc) + super(_LegacyRebatchDataset, self).__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +class _RemoteDataset(dataset_ops.DatasetSource): + """Creates a dataset on a given `device` given a graph def.""" + + def __init__(self, graph_def, device, element_spec): + self._elem_spec = element_spec + with ops.device(device): + variant_tensor = ged_ops.dataset_from_graph(graph_def) + super(_RemoteDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return self._elem_spec + + +def replicate(dataset, devices): + """A transformation that replicates `dataset` onto a list of devices. + + Args: + dataset: A `tf.data.Dataset` object. + devices: A list of devices to replicate the dataset on. + + Returns: + A dictionary mapping device name to a dataset on that device. + """ + if not isinstance(dataset, data_types.DatasetV2): + raise TypeError( + f"Invalid `dataset`. Expected a `tf.data.Dataset` object but " + f"got {type(dataset)}.") + + # pylint: disable=protected-access + dataset_device = dataset._variant_tensor.device + + datasets = {} + if len(devices) == 1 and devices[0] == dataset_device: + datasets[devices[0]] = dataset + return datasets + + with ops.colocate_with(dataset._variant_tensor): + dataset = dataset._apply_debug_options() + graph_def = dataset._as_serialized_graph( + strip_device_assignment=True, + external_state_policy=ExternalStatePolicy.WARN) + for device in devices: + ds = _RemoteDataset(graph_def, device, dataset.element_spec) + datasets[device] = ds + return datasets + + +def batch_sizes_for_worker(global_batch_size, num_workers, + num_replicas_per_worker, worker_index): + """Determines how to rebatch a dataset for the given worker. + + Given the global batch size, number of workers, number of replicas per worker, + and worker index, returns the correct batch sizes for rebatching a dataset + on worker `worker_index` of `num_workers`, such that each global step (across + all workers and replicas) will consume global_batch_size elements. The + returned value should be passed as the `batch_sizes` input parameter to + `tf.data.experimental.rebatch()`. The returned batch sizes meet the following + constraints: + + Let G = global_batch_size, W = num_workers, R = num_replicas_per_worker + (A) for any worker, len(batch_sizes) = W * R + (B) for any worker, sum(batch_sizes) == G + (C) for any global step (i.e. R iterations on each worker), the sum of batches + consumed by replicas across all workers is G. + (D) any two batch sizes of any two replicas differs by at most one. + + For example, suppose we have G = 7, W = 2, R = 2, and suppose we have two + files which each contain 7 elements: + + ```python + # WORKER 0 + batch_sizes_0 = batch_sizes_for_worker(global_batch_size=global_batch_size, + num_workers=2, + num_replicas_per_worker=2, + worker_index=0) + print(batch_sizes_0) + >> [2, 2, 2, 1] + + dataset_0 = tf.data.Dataset.from_tensor_slices(["file_a", "file_b"]) + dataset_0 = dataset_0.shard(num_shards, index=0) + dataset_0 = dataset_0.batch(7) + dataset_0 = dataset_0.apply(tf.data.experimental.rebatch(batch_sizes_0)) + for elem in dataset_0: + print(elem) + >> [[A0, A1], [A2, A3], [A4, A5], [A6]] + + # WORKER 1 + batch_sizes_1 = batch_sizes_for_worker(global_batch_size=global_batch_size, + num_workers=2, + num_replicas_per_worker=2, + worker_index=1) + print(batch_sizes_1) + >> [2, 1, 2, 2] + + dataset_1 = tf.data.Dataset.from_tensor_slices(["file_a", "file_b"]) + dataset_1 = dataset_1.shard(num_shards, index=1) + dataset_1 = dataset_1.batch(7) + dataset_1 = dataset_1.apply(tf.data.experimental.rebatch(batch_sizes_1)) + for elem in dataset_1: + print(elem) + >> [[B0, B1], [B2], [B3, B4], [B5, B6]] + ``` + + The above example will produce the following elements: + + Step 1: + Worker 0 Replica 0: [A0, A1] + Worker 0 Replica 1: [A2, A3] + Worker 1 Replica 0: [B0, B1] + Worker 1 Replica 1: [B2] + Total batch size = 7 + + Step 2: + Worker 0 Replica 0: [A4, A5] + Worker 0 Replica 1: [A6] + Worker 1 Replica 0: [B3, B4] + Worker 1 Replica 1: [B5, B6] + Total batch size = 7 + + Args: + global_batch_size: A `tf.int64` scalar, representing the global batch size. + num_workers: An integer representing the number of workers the dataset will + be distributed across. + num_replicas_per_worker: An integer representing the number of replicas per + worker. All workers are assumed to have the same number of replicas. + worker_index: An integer index of the worker to be rebatched. + + Returns: + A `tf.int64` vector, representing the batch sizes to rebatch the dataset + into. + """ + # Constraint (A) + num_subbatches = num_workers * num_replicas_per_worker + + offset = worker_index * num_replicas_per_worker + + const_value = tensor_util.constant_value(global_batch_size) + if const_value is not None: + # Use the constant global batch size for further calculations + global_batch_size = const_value + + # Let N = W * R. Constraint (B) and (D) jointly mean that the iterations + # should have batch size either floor(B/N) or ceil(B/N). Namely, of the N + # subbatches a batch is split into, B - N * floor(B/N) of them will have size + # ceil(B/N), and the rest will have size floor(B/N). + floor = global_batch_size // num_subbatches + num_ceil = global_batch_size - (num_subbatches * floor) + + # For worker 0, we assign the first num_ceil subbatches to have size + # ceil(B/N), and the remainder to have size floor(B/N). The other workers will + # each be offset by R * worker_index in order to meet constraint (C). + if const_value is not None: + # If the global batch size is a known constant value, we return a constant + # tensor directly instead of manipulating it with TF ops. This allows for + # better downstream shape inference. + worker_0 = [floor + 1] * num_ceil + [floor] * (num_subbatches - num_ceil) + return ops.convert_to_tensor( + worker_0[offset:] + worker_0[:offset], + dtype=dtypes.int64, + name="batch_sizes") + + worker_0 = array_ops.ones(num_subbatches, dtype=dtypes.int64) + worker_0 = floor * worker_0 + array_ops.concat([ + array_ops.ones(num_ceil, dtype=dtypes.int64), + array_ops.zeros(num_subbatches - num_ceil, dtype=dtypes.int64) + ], + axis=0) + + return array_ops.concat([worker_0[offset:], worker_0[:offset]], axis=0) + + +def compute_batch_size(dataset): + """An operation that returns the batch size of the dataset. + + This op tries to infer the batch size statically by walking up the dataset + tree from the final dataset node and returning the batch size of the first + batching dataset (such as from .batch() and .padded_batch()) that it + encounters. This differs from using the `element_spec` of a dataset in that it + does not account for partial batches. + + This operation may fail if it encounters contradictory batch sizes (for + example, if the dataset is created by zipping together two datasets with + different batch sizes), if there are no explicit batching transformations, or + if there are operations downstream from the batching transformation that may + modify its batch size. In these cases, it returns a -1. + + Args: + dataset: A `tf.data.Dataset` object. + + Returns: + A `tf.int64` Tensor representing the batch size of the dataset sans partial + batches. If this cannot be inferred statically, the value of this tensor + will be -1. + """ + + def get_static_batch_dim(type_spec): + try: + output_shape = type_spec._to_legacy_output_shapes() # pylint: disable=protected-access + except NotImplementedError: + return None + if not isinstance(output_shape, tensor_shape.TensorShape): + return None + if output_shape.rank is None: + return None + return output_shape.dims[0].value + + batch_dims = [ + get_static_batch_dim(type_spec) + for type_spec in nest.flatten(dataset_ops.get_structure(dataset)) + ] + + if all(d is not None for d in batch_dims): + + if all(d == batch_dims[0] for d in batch_dims): + # If all batch dimensions are known and equal, return that directly. + batch_dim = batch_dims[0] + else: + # If all batch dimensions are known but not all equal, return -1. + batch_dim = -1 + + return constant_op.constant( + batch_dim, dtype=dtypes.int64, name="static_batch_size") + + # If any batch dimensions are unknown, use compute_batch_size op. + return ged_ops.compute_batch_size(dataset._variant_tensor) # pylint: disable=protected-access + + +_AutoShardDatasetV1.__doc__ = _AutoShardDataset.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/distributed_save_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/distributed_save_op.py new file mode 100644 index 0000000000000000000000000000000000000000..3e986a72681309237024eb910ce2af40c04fa37d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/distributed_save_op.py @@ -0,0 +1,61 @@ +# 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. +# ============================================================================== +"""Distributed saving of a dataset to disk.""" + +from tensorflow.core.protobuf import snapshot_pb2 +from tensorflow.python.ops import gen_experimental_dataset_ops +# TODO(b/238903802): Use TypeSpec serialization methods directly. +from tensorflow.python.saved_model import nested_structure_coder + + +# TODO(b/250921378): Add example to docstring and export to TF API. +def distributed_save(dataset, path, dispatcher_address, compression="AUTO"): + """Initiates the process of distributedly saving a dataset to disk. + + Args: + dataset: The `tf.data.Dataset` to save. + path: A string indicating the filepath of the directory to which to save + `dataset`. + dispatcher_address: A string indicating the address of the dispatcher for + the tf.data service instance used to save `dataset`. + compression: (Optional.) A string indicating whether and how to compress the + `dataset` materialization. If `"AUTO"`, the tf.data runtime decides which + algorithm to use. If `"GZIP"` or `"SNAPPY"`, that specific algorithm is + used. If `None`, the `dataset` materialization is not compressed. + + Returns: + An operation which when executed performs the distributed save. + + Raises: + ValueError: If `dispatcher_address` is invalid. + """ + if not isinstance(dispatcher_address, str): + raise ValueError("`dispatcher_address` must be a string, but is a " + f"{type(dispatcher_address)} ({dispatcher_address}") + if not dispatcher_address: + raise ValueError("`dispatcher_address` must not be empty") + + metadata = snapshot_pb2.DistributedSnapshotMetadata( + element_spec=nested_structure_coder.encode_structure( + dataset.element_spec).SerializeToString(), + compression=compression, + ) + + return gen_experimental_dataset_ops.distributed_save( + dataset._variant_tensor, # pylint: disable=protected-access + directory=path, + address=dispatcher_address, + metadata=metadata.SerializeToString(), + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/enumerate_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/enumerate_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7d73e748156c44d34c4923bf0a57d00b8213a3cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/enumerate_ops.py @@ -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. +# ============================================================================== +"""Enumerate dataset transformations.""" +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.enumerate()`.") +@tf_export("data.experimental.enumerate_dataset") +def enumerate_dataset(start=0): + """A transformation that enumerates the elements of a dataset. + + It is similar to python's `enumerate`. + For example: + + ```python + # NOTE: The following examples use `{ ... }` to represent the + # contents of a dataset. + a = { 1, 2, 3 } + b = { (7, 8), (9, 10) } + + # The nested structure of the `datasets` argument determines the + # structure of elements in the resulting dataset. + a.apply(tf.data.experimental.enumerate_dataset(start=5)) + => { (5, 1), (6, 2), (7, 3) } + b.apply(tf.data.experimental.enumerate_dataset()) + => { (0, (7, 8)), (1, (9, 10)) } + ``` + + Args: + start: A `tf.int64` scalar `tf.Tensor`, representing the start value for + enumeration. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return dataset.enumerate(start) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/error_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/error_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..263de71deb9b0a284a34acd65786c1980cc95b3c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/error_ops.py @@ -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. +# ============================================================================== +"""Ignore_errors dataset transformations.""" +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.ignore_errors") +@deprecation.deprecated(None, "Use `tf.data.Dataset.ignore_errors` instead.") +def ignore_errors(log_warning=False): + """Creates a `Dataset` from another `Dataset` and silently ignores any errors. + + Use this transformation to produce a dataset that contains the same elements + as the input, but silently drops any elements that caused an error. For + example: + + ```python + dataset = tf.data.Dataset.from_tensor_slices([1., 2., 0., 4.]) + + # Computing `tf.debugging.check_numerics(1. / 0.)` will raise an + InvalidArgumentError. + dataset = dataset.map(lambda x: tf.debugging.check_numerics(1. / x, "error")) + + # Using `ignore_errors()` will drop the element that causes an error. + dataset = + dataset.apply(tf.data.experimental.ignore_errors()) # ==> {1., 0.5, 0.2} + ``` + Args: + log_warning: (Optional.) A 'tf.bool' scalar indicating whether ignored + errors should be logged to stderr. Defaults to 'False'. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + def _apply_fn(dataset): + return dataset.ignore_errors(log_warning) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/from_list.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/from_list.py new file mode 100644 index 0000000000000000000000000000000000000000..9725d54c1b65a83ee8884f14bcac7df3db434494 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/from_list.py @@ -0,0 +1,119 @@ +# 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. +# ============================================================================== +"""Python API for creating a dataset from a list.""" + +import itertools + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.util.tf_export import tf_export + + +class _ListDataset(dataset_ops.DatasetSource): + """A `Dataset` of elements from a list.""" + + def __init__(self, elements, name=None): + if not elements: + raise ValueError("Invalid `elements`. `elements` should not be empty.") + if not isinstance(elements, list): + raise ValueError("Invalid `elements`. `elements` must be a list.") + + elements = [structure.normalize_element(element) for element in elements] + type_specs = [ + structure.type_spec_from_value(element) for element in elements + ] + + # Check that elements have same nested structure. + num_elements = len(elements) + for i in range(1, num_elements): + nest.assert_same_structure(type_specs[0], type_specs[i]) + + # Infer elements' supershape. + flattened_type_specs = [nest.flatten(type_spec) for type_spec in type_specs] + num_tensors_per_element = len(flattened_type_specs[0]) + flattened_structure = [None] * num_tensors_per_element + for i in range(num_tensors_per_element): + flattened_structure[i] = flattened_type_specs[0][i] + for j in range(1, num_elements): + flattened_structure[i] = flattened_structure[ + i].most_specific_common_supertype([flattened_type_specs[j][i]]) + + if not isinstance(type_specs[0], dataset_ops.DatasetSpec): + self._tensors = list( + itertools.chain.from_iterable( + [nest.flatten(element) for element in elements])) + else: + self._tensors = [x._variant_tensor for x in elements] + self._structure = nest.pack_sequence_as(type_specs[0], flattened_structure) + self._name = name + variant_tensor = gen_experimental_dataset_ops.list_dataset( + self._tensors, + output_types=self._flat_types, + output_shapes=self._flat_shapes, + metadata=self._metadata.SerializeToString()) + super(_ListDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return self._structure + + +@tf_export("data.experimental.from_list") +def from_list(elements, name=None): + """Creates a `Dataset` comprising the given list of elements. + + The returned dataset will produce the items in the list one by one. The + functionality is identical to `Dataset.from_tensor_slices` when elements are + scalars, but different when elements have structure. Consider the following + example. + + >>> dataset = tf.data.experimental.from_list([(1, 'a'), (2, 'b'), (3, 'c')]) + >>> list(dataset.as_numpy_iterator()) + [(1, b'a'), (2, b'b'), (3, b'c')] + + To get the same output with `from_tensor_slices`, the data needs to be + reorganized: + + >>> dataset = tf.data.Dataset.from_tensor_slices(([1, 2, 3], ['a', 'b', 'c'])) + >>> list(dataset.as_numpy_iterator()) + [(1, b'a'), (2, b'b'), (3, b'c')] + + Unlike `from_tensor_slices`, `from_list` supports non-rectangular input: + + >>> dataset = tf.data.experimental.from_list([[1], [2, 3]]) + >>> list(dataset.as_numpy_iterator()) + [array([1], dtype=int32), array([2, 3], dtype=int32)] + + Achieving the same with `from_tensor_slices` requires the use of ragged + tensors. + + `from_list` can be more performant than `from_tensor_slices` in some cases, + since it avoids the need for data slicing each epoch. However, it can also be + less performant, because data is stored as many small tensors rather than a + few large tensors as in `from_tensor_slices`. The general guidance is to + prefer `from_list` from a performance perspective when the number of elements + is small (less than 1000). + + Args: + elements: A list of elements whose components have the same nested + structure. + name: (Optional.) A name for the tf.data operation. + + Returns: + Dataset: A `Dataset` of the `elements`. + """ + return _ListDataset(elements, name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/get_single_element.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/get_single_element.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8d65e036b101d60d61f195b2fb2f9e131aa95f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/get_single_element.py @@ -0,0 +1,147 @@ +# 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. +# ============================================================================== +"""Python wrappers for Datasets and Iterators.""" +from tensorflow.python.types import data as data_types +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.get_single_element()`.") +@tf_export("data.experimental.get_single_element") +def get_single_element(dataset): + """Returns the single element of the `dataset` as a nested structure of tensors. + + The function enables you to use a `tf.data.Dataset` in a stateless + "tensor-in tensor-out" expression, without creating an iterator. + This facilitates the ease of data transformation on tensors using the + optimized `tf.data.Dataset` abstraction on top of them. + + For example, lets consider a `preprocessing_fn` which would take as an + input the raw features and returns the processed feature along with + it's label. + + ```python + def preprocessing_fn(raw_feature): + # ... the raw_feature is preprocessed as per the use-case + return feature + + raw_features = ... # input batch of BATCH_SIZE elements. + dataset = (tf.data.Dataset.from_tensor_slices(raw_features) + .map(preprocessing_fn, num_parallel_calls=BATCH_SIZE) + .batch(BATCH_SIZE)) + + processed_features = tf.data.experimental.get_single_element(dataset) + ``` + + In the above example, the `raw_features` tensor of length=BATCH_SIZE + was converted to a `tf.data.Dataset`. Next, each of the `raw_feature` was + mapped using the `preprocessing_fn` and the processed features were + grouped into a single batch. The final `dataset` contains only one element + which is a batch of all the processed features. + + NOTE: The `dataset` should contain only one element. + + Now, instead of creating an iterator for the `dataset` and retrieving the + batch of features, the `tf.data.experimental.get_single_element()` function + is used to skip the iterator creation process and directly output the batch + of features. + + This can be particularly useful when your tensor transformations are + expressed as `tf.data.Dataset` operations, and you want to use those + transformations while serving your model. + + # Keras + + ```python + + model = ... # A pre-built or custom model + + class PreprocessingModel(tf.keras.Model): + def __init__(self, model): + super().__init__(self) + self.model = model + + @tf.function(input_signature=[...]) + def serving_fn(self, data): + ds = tf.data.Dataset.from_tensor_slices(data) + ds = ds.map(preprocessing_fn, num_parallel_calls=BATCH_SIZE) + ds = ds.batch(batch_size=BATCH_SIZE) + return tf.argmax( + self.model(tf.data.experimental.get_single_element(ds)), + axis=-1 + ) + + preprocessing_model = PreprocessingModel(model) + your_exported_model_dir = ... # save the model to this path. + tf.saved_model.save(preprocessing_model, your_exported_model_dir, + signatures={'serving_default': preprocessing_model.serving_fn}) + ``` + + # Estimator + + In the case of estimators, you need to generally define a `serving_input_fn` + which would require the features to be processed by the model while + inferencing. + + ```python + def serving_input_fn(): + + raw_feature_spec = ... # Spec for the raw_features + input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn( + raw_feature_spec, default_batch_size=None) + ) + serving_input_receiver = input_fn() + raw_features = serving_input_receiver.features + + def preprocessing_fn(raw_feature): + # ... the raw_feature is preprocessed as per the use-case + return feature + + dataset = (tf.data.Dataset.from_tensor_slices(raw_features) + .map(preprocessing_fn, num_parallel_calls=BATCH_SIZE) + .batch(BATCH_SIZE)) + + processed_features = tf.data.experimental.get_single_element(dataset) + + # Please note that the value of `BATCH_SIZE` should be equal to + # the size of the leading dimension of `raw_features`. This ensures + # that `dataset` has only element, which is a pre-requisite for + # using `tf.data.experimental.get_single_element(dataset)`. + + return tf.estimator.export.ServingInputReceiver( + processed_features, serving_input_receiver.receiver_tensors) + + estimator = ... # A pre-built or custom estimator + estimator.export_saved_model(your_exported_model_dir, serving_input_fn) + ``` + + Args: + dataset: A `tf.data.Dataset` object containing a single element. + + Returns: + A nested structure of `tf.Tensor` objects, corresponding to the single + element of `dataset`. + + Raises: + TypeError: if `dataset` is not a `tf.data.Dataset` object. + InvalidArgumentError: (at runtime) if `dataset` does not contain exactly + one element. + """ + if not isinstance(dataset, data_types.DatasetV2): + raise TypeError( + f"Invalid `dataset`. Expected a `tf.data.Dataset` object " + f"but got {type(dataset)}.") + + return dataset.get_single_element() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/grouping.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/grouping.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc0890fe442fc5fc0988e227b5fd1b49832d05a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/grouping.py @@ -0,0 +1,428 @@ +# 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. +# ============================================================================== +"""Grouping dataset transformations.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.group_by_reducer") +def group_by_reducer(key_func, reducer): + """A transformation that groups elements and performs a reduction. + + This transformation maps element of a dataset to a key using `key_func` and + groups the elements by key. The `reducer` is used to process each group; its + `init_func` is used to initialize state for each group when it is created, the + `reduce_func` is used to update the state every time an element is mapped to + the matching group, and the `finalize_func` is used to map the final state to + an output value. + + Args: + key_func: A function mapping a nested structure of tensors + (having shapes and types defined by `self.output_shapes` and + `self.output_types`) to a scalar `tf.int64` tensor. + reducer: An instance of `Reducer`, which captures the reduction logic using + the `init_func`, `reduce_func`, and `finalize_func` functions. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + return _GroupByReducerDataset(dataset, key_func, reducer) + + return _apply_fn + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.group_by_window(...)`.") +@tf_export("data.experimental.group_by_window") +def group_by_window(key_func, + reduce_func, + window_size=None, + window_size_func=None): + """A transformation that groups windows of elements by key and reduces them. + + This transformation maps each consecutive element in a dataset to a key + using `key_func` and groups the elements by key. It then applies + `reduce_func` to at most `window_size_func(key)` elements matching the same + key. All except the final window for each key will contain + `window_size_func(key)` elements; the final window may be smaller. + + You may provide either a constant `window_size` or a window size determined by + the key through `window_size_func`. + + Args: + key_func: A function mapping a nested structure of tensors + (having shapes and types defined by `self.output_shapes` and + `self.output_types`) to a scalar `tf.int64` tensor. + reduce_func: A function mapping a key and a dataset of up to `window_size` + consecutive elements matching that key to another dataset. + window_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements matching the same key to combine in a single + batch, which will be passed to `reduce_func`. Mutually exclusive with + `window_size_func`. + window_size_func: A function mapping a key to a `tf.int64` scalar + `tf.Tensor`, representing the number of consecutive elements matching + the same key to combine in a single batch, which will be passed to + `reduce_func`. Mutually exclusive with `window_size`. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + + Raises: + ValueError: if neither or both of {`window_size`, `window_size_func`} are + passed. + """ + + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + return dataset.group_by_window( + key_func=key_func, + reduce_func=reduce_func, + window_size=window_size, + window_size_func=window_size_func) + + return _apply_fn + + +@deprecation.deprecated(None, + "Use `tf.data.Dataset.bucket_by_sequence_length(...)`.") +@tf_export("data.experimental.bucket_by_sequence_length") +def bucket_by_sequence_length(element_length_func, + bucket_boundaries, + bucket_batch_sizes, + padded_shapes=None, + padding_values=None, + pad_to_bucket_boundary=False, + no_padding=False, + drop_remainder=False): + """A transformation that buckets elements in a `Dataset` by length. + + Elements of the `Dataset` are grouped together by length and then are padded + and batched. + + This is useful for sequence tasks in which the elements have variable length. + Grouping together elements that have similar lengths reduces the total + fraction of padding in a batch which increases training step efficiency. + + Below is an example to bucketize the input data to the 3 buckets + "[0, 3), [3, 5), [5, inf)" based on sequence length, with batch size 2. + + >>> elements = [ + ... [0], [1, 2, 3, 4], [5, 6, 7], + ... [7, 8, 9, 10, 11], [13, 14, 15, 16, 19, 20], [21, 22]] + + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: elements, tf.int64, output_shapes=[None]) + + >>> dataset = dataset.apply( + ... tf.data.experimental.bucket_by_sequence_length( + ... element_length_func=lambda elem: tf.shape(elem)[0], + ... bucket_boundaries=[3, 5], + ... bucket_batch_sizes=[2, 2, 2])) + + >>> for elem in dataset.as_numpy_iterator(): + ... print(elem) + [[1 2 3 4] + [5 6 7 0]] + [[ 7 8 9 10 11 0] + [13 14 15 16 19 20]] + [[ 0 0] + [21 22]] + + There is also a possibility to pad the dataset till the bucket boundary. + You can also provide which value to be used while padding the data. + Below example uses `-1` as padding and it also shows the input data + being bucketizied to two buckets "[0,3], [4,6]". + + >>> elements = [ + ... [0], [1, 2, 3, 4], [5, 6, 7], + ... [7, 8, 9, 10, 11], [13, 14, 15, 16, 19, 20], [21, 22]] + + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: elements, tf.int32, output_shapes=[None]) + + >>> dataset = dataset.apply( + ... tf.data.experimental.bucket_by_sequence_length( + ... element_length_func=lambda elem: tf.shape(elem)[0], + ... bucket_boundaries=[4, 7], + ... bucket_batch_sizes=[2, 2, 2], + ... pad_to_bucket_boundary=True, + ... padding_values=-1)) + + >>> for elem in dataset.as_numpy_iterator(): + ... print(elem) + [[ 0 -1 -1] + [ 5 6 7]] + [[ 1 2 3 4 -1 -1] + [ 7 8 9 10 11 -1]] + [[21 22 -1]] + [[13 14 15 16 19 20]] + + When using `pad_to_bucket_boundary` option, it can be seen that it is + not always possible to maintain the bucket batch size. + You can drop the batches that do not maintain the bucket batch size by + using the option `drop_remainder`. Using the same input data as in the + above example you get the following result. + + >>> elements = [ + ... [0], [1, 2, 3, 4], [5, 6, 7], + ... [7, 8, 9, 10, 11], [13, 14, 15, 16, 19, 20], [21, 22]] + + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: elements, tf.int32, output_shapes=[None]) + + >>> dataset = dataset.apply( + ... tf.data.experimental.bucket_by_sequence_length( + ... element_length_func=lambda elem: tf.shape(elem)[0], + ... bucket_boundaries=[4, 7], + ... bucket_batch_sizes=[2, 2, 2], + ... pad_to_bucket_boundary=True, + ... padding_values=-1, + ... drop_remainder=True)) + + >>> for elem in dataset.as_numpy_iterator(): + ... print(elem) + [[ 0 -1 -1] + [ 5 6 7]] + [[ 1 2 3 4 -1 -1] + [ 7 8 9 10 11 -1]] + + Args: + element_length_func: function from element in `Dataset` to `tf.int32`, + determines the length of the element, which will determine the bucket it + goes into. + bucket_boundaries: `list`, upper length boundaries of the buckets. + bucket_batch_sizes: `list`, batch size per bucket. Length should be + `len(bucket_boundaries) + 1`. + padded_shapes: Nested structure of `tf.TensorShape` to pass to + `tf.data.Dataset.padded_batch`. If not provided, will use + `dataset.output_shapes`, which will result in variable length dimensions + being padded out to the maximum length in each batch. + padding_values: Values to pad with, passed to + `tf.data.Dataset.padded_batch`. Defaults to padding with 0. + pad_to_bucket_boundary: bool, if `False`, will pad dimensions with unknown + size to maximum length in batch. If `True`, will pad dimensions with + unknown size to bucket boundary minus 1 (i.e., the maximum length in each + bucket), and caller must ensure that the source `Dataset` does not contain + any elements with length longer than `max(bucket_boundaries)`. + no_padding: `bool`, indicates whether to pad the batch features (features + need to be either of type `tf.sparse.SparseTensor` or of same shape). + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size` elements; the default behavior is not to drop the smaller + batch. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + + Raises: + ValueError: if `len(bucket_batch_sizes) != len(bucket_boundaries) + 1`. + """ + + def _apply_fn(dataset): + return dataset.bucket_by_sequence_length( + element_length_func=element_length_func, + bucket_boundaries=bucket_boundaries, + bucket_batch_sizes=bucket_batch_sizes, + padded_shapes=padded_shapes, + padding_values=padding_values, + pad_to_bucket_boundary=pad_to_bucket_boundary, + no_padding=no_padding, + drop_remainder=drop_remainder) + + return _apply_fn + + +class _GroupByReducerDataset(dataset_ops.UnaryDataset): + """A `Dataset` that groups its input and performs a reduction.""" + + def __init__(self, input_dataset, key_func, reducer): + """See `group_by_reducer()` for details.""" + self._input_dataset = input_dataset + self._make_key_func(key_func, input_dataset) + self._make_init_func(reducer.init_func) + self._make_reduce_func(reducer.reduce_func, input_dataset) + self._make_finalize_func(reducer.finalize_func) + variant_tensor = ged_ops.experimental_group_by_reducer_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._key_func.function.captured_inputs, + self._init_func.function.captured_inputs, + self._reduce_func.function.captured_inputs, + self._finalize_func.function.captured_inputs, + key_func=self._key_func.function, + init_func=self._init_func.function, + reduce_func=self._reduce_func.function, + finalize_func=self._finalize_func.function, + **self._flat_structure) + super(_GroupByReducerDataset, self).__init__(input_dataset, variant_tensor) + + def _make_key_func(self, key_func, input_dataset): + """Make wrapping defun for key_func.""" + self._key_func = structured_function.StructuredFunctionWrapper( + key_func, self._transformation_name(), dataset=input_dataset) + if not self._key_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.int64)): + raise ValueError( + f"Invalid `key_func`. Expected `key_func` to return a scalar " + f"tf.int64 tensor, but instead `key_func` has output " + f"types={self._key_func.output_types} " + f"and shapes={self._key_func.output_shapes}." + ) + + def _make_init_func(self, init_func): + """Make wrapping defun for init_func.""" + self._init_func = structured_function.StructuredFunctionWrapper( + init_func, + self._transformation_name(), + input_structure=tensor_spec.TensorSpec([], dtypes.int64)) + + def _make_reduce_func(self, reduce_func, input_dataset): + """Make wrapping defun for reduce_func.""" + + # Iteratively rerun the reduce function until reaching a fixed point on + # `self._state_structure`. + self._state_structure = self._init_func.output_structure + state_types = self._init_func.output_types + state_shapes = self._init_func.output_shapes + state_classes = self._init_func.output_classes + need_to_rerun = True + while need_to_rerun: + + wrapped_func = structured_function.StructuredFunctionWrapper( + reduce_func, + self._transformation_name(), + input_structure=(self._state_structure, input_dataset.element_spec), + add_to_graph=False) + + # Extract and validate class information from the returned values. + for new_state_class, state_class in zip( + nest.flatten(wrapped_func.output_classes), + nest.flatten(state_classes)): + if not issubclass(new_state_class, state_class): + raise TypeError( + f"Invalid `reducer`. The output class of the " + f"`reducer.reduce_func` {wrapped_func.output_classes}, " + f"does not match the class of the reduce state " + f"{self._state_classes}.") + + # Extract and validate type information from the returned values. + for new_state_type, state_type in zip( + nest.flatten(wrapped_func.output_types), nest.flatten(state_types)): + if new_state_type != state_type: + raise TypeError( + f"Invalid `reducer`. The element types for the new state " + f"{wrapped_func.output_types} do not match the element types " + f"of the old state {self._init_func.output_types}." + ) + + # Extract shape information from the returned values. + flat_state_shapes = nest.flatten(state_shapes) + flat_new_state_shapes = nest.flatten(wrapped_func.output_shapes) + weakened_state_shapes = [ + original.most_specific_compatible_shape(new) + for original, new in zip(flat_state_shapes, flat_new_state_shapes) + ] + + need_to_rerun = False + for original_shape, weakened_shape in zip(flat_state_shapes, + weakened_state_shapes): + if original_shape.ndims is not None and ( + weakened_shape.ndims is None or + original_shape.as_list() != weakened_shape.as_list()): + need_to_rerun = True + break + + if need_to_rerun: + state_shapes = nest.pack_sequence_as( + self._init_func.output_shapes, weakened_state_shapes) + self._state_structure = structure.convert_legacy_structure( + state_types, state_shapes, state_classes) + + self._reduce_func = wrapped_func + self._reduce_func.function.add_to_graph(ops.get_default_graph()) + + def _make_finalize_func(self, finalize_func): + """Make wrapping defun for finalize_func.""" + self._finalize_func = structured_function.StructuredFunctionWrapper( + finalize_func, + self._transformation_name(), + input_structure=self._state_structure) + + @property + def element_spec(self): + return self._finalize_func.output_structure + + def _functions(self): + return [ + self._key_func, self._init_func, self._reduce_func, self._finalize_func + ] + + def _transformation_name(self): + return "tf.data.experimental.group_by_reducer()" + + +@tf_export("data.experimental.Reducer") +class Reducer: + """A reducer is used for reducing a set of elements. + + A reducer is represented as a tuple of the three functions: + - init_func - to define initial value: key => initial state + - reducer_func - operation to perform on values with same key: (old state, input) => new state + - finalize_func - value to return in the end: state => result + + For example, + + ``` + def init_func(_): + return (0.0, 0.0) + + def reduce_func(state, value): + return (state[0] + value['features'], state[1] + 1) + + def finalize_func(s, n): + return s / n + + reducer = tf.data.experimental.Reducer(init_func, reduce_func, finalize_func) + ``` + """ + + def __init__(self, init_func, reduce_func, finalize_func): + self._init_func = init_func + self._reduce_func = reduce_func + self._finalize_func = finalize_func + + @property + def init_func(self): + return self._init_func + + @property + def reduce_func(self): + return self._reduce_func + + @property + def finalize_func(self): + return self._finalize_func diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/interleave_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/interleave_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf61f9d5c7f9bb27b1d0ed9ebdec462fa7909d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/interleave_ops.py @@ -0,0 +1,247 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Non-deterministic dataset transformations.""" +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import readers +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated( + None, + "Use `tf.data.Dataset.interleave(map_func, cycle_length, block_length, " + "num_parallel_calls=tf.data.AUTOTUNE)` instead. If sloppy " + "execution is desired, use `tf.data.Options.deterministic`.") +@tf_export("data.experimental.parallel_interleave") +def parallel_interleave(map_func, + cycle_length, + block_length=1, + sloppy=False, + buffer_output_elements=None, + prefetch_input_elements=None): + """A parallel version of the `Dataset.interleave()` transformation. + + `parallel_interleave()` maps `map_func` across its input to produce nested + datasets, and outputs their elements interleaved. Unlike + `tf.data.Dataset.interleave`, it gets elements from `cycle_length` nested + datasets in parallel, which increases the throughput, especially in the + presence of stragglers. Furthermore, the `sloppy` argument can be used to + improve performance, by relaxing the requirement that the outputs are produced + in a deterministic order, and allowing the implementation to skip over nested + datasets whose elements are not readily available when requested. + + Example usage: + + ```python + # Preprocess 4 files concurrently. + filenames = tf.data.Dataset.list_files("/path/to/data/train*.tfrecords") + dataset = filenames.apply( + tf.data.experimental.parallel_interleave( + lambda filename: tf.data.TFRecordDataset(filename), + cycle_length=4)) + ``` + + WARNING: If `sloppy` is `True`, the order of produced elements is not + deterministic. + + Args: + map_func: A function mapping a nested structure of tensors to a `Dataset`. + cycle_length: The number of input `Dataset`s to interleave from in parallel. + block_length: The number of consecutive elements to pull from an input + `Dataset` before advancing to the next input `Dataset`. + sloppy: A boolean controlling whether determinism should be traded for + performance by allowing elements to be produced out of order. If `sloppy` + is `None`, the `tf.data.Options.deterministic` dataset option (`True` by + default) is used to decide whether to enforce a deterministic order. + buffer_output_elements: The number of elements each iterator being + interleaved should buffer (similar to the `.prefetch()` transformation for + each interleaved iterator). + prefetch_input_elements: The number of input elements to transform to + iterators before they are needed for interleaving. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return readers.ParallelInterleaveDataset(dataset, map_func, cycle_length, + block_length, sloppy, + buffer_output_elements, + prefetch_input_elements) + + return _apply_fn + + +@deprecation.deprecated(None, + "Use `tf.data.Dataset.sample_from_datasets(...)`.") +@tf_export("data.experimental.sample_from_datasets", v1=[]) +def sample_from_datasets_v2(datasets, + weights=None, + seed=None, + stop_on_empty_dataset=False): + """Samples elements at random from the datasets in `datasets`. + + Creates a dataset by interleaving elements of `datasets` with `weight[i]` + probability of picking an element from dataset `i`. Sampling is done without + replacement. For example, suppose we have 2 datasets: + + ```python + dataset1 = tf.data.Dataset.range(0, 3) + dataset2 = tf.data.Dataset.range(100, 103) + ``` + + Suppose also that we sample from these 2 datasets with the following weights: + + ```python + sample_dataset = tf.data.Dataset.sample_from_datasets( + [dataset1, dataset2], weights=[0.5, 0.5]) + ``` + + One possible outcome of elements in sample_dataset is: + + ``` + print(list(sample_dataset.as_numpy_iterator())) + # [100, 0, 1, 101, 2, 102] + ``` + + Args: + datasets: A non-empty list of `tf.data.Dataset` objects with compatible + structure. + weights: (Optional.) A list or Tensor of `len(datasets)` floating-point + values where `weights[i]` represents the probability to sample from + `datasets[i]`, or a `tf.data.Dataset` object where each element is such a + list. Defaults to a uniform distribution across `datasets`. + seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random + seed that will be used to create the distribution. See + `tf.random.set_seed` for behavior. + stop_on_empty_dataset: If `True`, sampling stops if it encounters an empty + dataset. If `False`, it skips empty datasets. It is recommended to set it + to `True`. Otherwise, the distribution of samples starts off as the user + intends, but may change as input datasets become empty. This can be + difficult to detect since the dataset starts off looking correct. Default + to `False` for backward compatibility. + + Returns: + A dataset that interleaves elements from `datasets` at random, according to + `weights` if provided, otherwise with uniform probability. + + Raises: + TypeError: If the `datasets` or `weights` arguments have the wrong type. + ValueError: + - If `datasets` is empty, or + - If `weights` is specified and does not match the length of `datasets`. + """ + return dataset_ops.Dataset.sample_from_datasets( + datasets=datasets, + weights=weights, + seed=seed, + stop_on_empty_dataset=stop_on_empty_dataset) + + +@deprecation.deprecated(None, + "Use `tf.data.Dataset.sample_from_datasets(...)`.") +@tf_export(v1=["data.experimental.sample_from_datasets"]) +def sample_from_datasets_v1(datasets, + weights=None, + seed=None, + stop_on_empty_dataset=False): + return dataset_ops.DatasetV1Adapter( + sample_from_datasets_v2(datasets, weights, seed, stop_on_empty_dataset)) + + +sample_from_datasets_v1.__doc__ = sample_from_datasets_v2.__doc__ + + +@deprecation.deprecated( + None, "Use `tf.data.Dataset.choose_from_datasets(...)` instead. Note that, " + "unlike the experimental endpoint, the non-experimental endpoint " + "sets `stop_on_empty_dataset=True` by default. You should set this " + "argument explicitly in case you would like to match the behavior of the " + "experimental endpoint.") +@tf_export("data.experimental.choose_from_datasets", v1=[]) +def choose_from_datasets_v2(datasets, + choice_dataset, + stop_on_empty_dataset=False): + """Creates a dataset that deterministically chooses elements from `datasets`. + + For example, given the following datasets: + + ```python + datasets = [tf.data.Dataset.from_tensors("foo").repeat(), + tf.data.Dataset.from_tensors("bar").repeat(), + tf.data.Dataset.from_tensors("baz").repeat()] + + # Define a dataset containing `[0, 1, 2, 0, 1, 2, 0, 1, 2]`. + choice_dataset = tf.data.Dataset.range(3).repeat(3) + + result = tf.data.experimental.choose_from_datasets(datasets, choice_dataset) + ``` + + The elements of `result` will be: + + ``` + "foo", "bar", "baz", "foo", "bar", "baz", "foo", "bar", "baz" + ``` + + Args: + datasets: A non-empty list of `tf.data.Dataset` objects with compatible + structure. + choice_dataset: A `tf.data.Dataset` of scalar `tf.int64` tensors between `0` + and `len(datasets) - 1`. + stop_on_empty_dataset: If `True`, selection stops if it encounters an empty + dataset. If `False`, it skips empty datasets. It is recommended to set it + to `True`. Otherwise, the selected elements start off as the user intends, + but may change as input datasets become empty. This can be difficult to + detect since the dataset starts off looking correct. Default to `False` + for backward compatibility. + + Returns: + A dataset that interleaves elements from `datasets` according to the values + of `choice_dataset`. + + Raises: + TypeError: If `datasets` or `choice_dataset` has the wrong type. + ValueError: If `datasets` is empty. + """ + return dataset_ops.Dataset.choose_from_datasets( + datasets=datasets, + choice_dataset=choice_dataset, + stop_on_empty_dataset=stop_on_empty_dataset) + + +@deprecation.deprecated( + None, "Use `tf.data.Dataset.choose_from_datasets(...)` instead. Note that, " + "unlike the experimental endpoint, the non-experimental endpoint " + "sets `stop_on_empty_dataset=True` by default. You should set this " + "argument explicitly in case you would like to match the behavior of the " + "experimental endpoint.") +@tf_export(v1=["data.experimental.choose_from_datasets"]) +def choose_from_datasets_v1(datasets, + choice_dataset, + stop_on_empty_dataset=False): + return dataset_ops.DatasetV1Adapter( + choose_from_datasets_v2(datasets, choice_dataset, stop_on_empty_dataset)) + + +choose_from_datasets_v1.__doc__ = choose_from_datasets_v2.__doc__ + +if tf2.enabled(): + choose_from_datasets = choose_from_datasets_v2 + sample_from_datasets = sample_from_datasets_v2 +else: + choose_from_datasets = choose_from_datasets_v1 + sample_from_datasets = sample_from_datasets_v1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/io.py new file mode 100644 index 0000000000000000000000000000000000000000..35554a1464c953a23d54406dde78f85ad90ab7be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/io.py @@ -0,0 +1,166 @@ +# 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. +# ============================================================================== +"""Python API for save and loading a dataset.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +COMPRESSION_GZIP = "GZIP" +COMPRESSION_SNAPPY = "NONE" +DATASET_SPEC_FILENAME = "dataset_spec.pb" + + +@tf_export("data.experimental.save", v1=[]) +@deprecation.deprecated(None, "Use `tf.data.Dataset.save(...)` instead.") +def save(dataset, + path, + compression=None, + shard_func=None, + checkpoint_args=None): + """Saves the content of the given dataset. + + Example usage: + + >>> import tempfile + >>> path = os.path.join(tempfile.gettempdir(), "saved_data") + >>> # Save a dataset + >>> dataset = tf.data.Dataset.range(2) + >>> tf.data.experimental.save(dataset, path) + >>> new_dataset = tf.data.experimental.load(path) + >>> for elem in new_dataset: + ... print(elem) + tf.Tensor(0, shape=(), dtype=int64) + tf.Tensor(1, shape=(), dtype=int64) + + The saved dataset is saved in multiple file "shards". By default, the dataset + output is divided to shards in a round-robin fashion but custom sharding can + be specified via the `shard_func` function. For example, you can save the + dataset to using a single shard as follows: + + ```python + dataset = make_dataset() + def custom_shard_func(element): + return np.int64(0) + dataset = tf.data.experimental.save( + path="/path/to/data", ..., shard_func=custom_shard_func) + ``` + + To enable checkpointing, pass in `checkpoint_args` to the `save` method + as follows: + + ```python + dataset = tf.data.Dataset.range(100) + save_dir = "..." + checkpoint_prefix = "..." + step_counter = tf.Variable(0, trainable=False) + checkpoint_args = { + "checkpoint_interval": 50, + "step_counter": step_counter, + "directory": checkpoint_prefix, + "max_to_keep": 20, + } + dataset.save(dataset, save_dir, checkpoint_args=checkpoint_args) + ``` + + NOTE: The directory layout and file format used for saving the dataset is + considered an implementation detail and may change. For this reason, datasets + saved through `tf.data.experimental.save` should only be consumed through + `tf.data.experimental.load`, which is guaranteed to be backwards compatible. + + Args: + dataset: The dataset to save. + path: Required. A directory to use for saving the dataset. + compression: Optional. The algorithm to use to compress data when writing + it. Supported options are `GZIP` and `NONE`. Defaults to `NONE`. + shard_func: Optional. A function to control the mapping of dataset elements + to file shards. The function is expected to map elements of the input + dataset to int64 shard IDs. If present, the function will be traced and + executed as graph computation. + checkpoint_args: Optional args for checkpointing which will be passed into + the `tf.train.CheckpointManager`. If `checkpoint_args` are not specified, + then checkpointing will not be performed. The `save()` implementation + creates a `tf.train.Checkpoint` object internally, so users should not + set the `checkpoint` argument in `checkpoint_args`. + + Returns: + An operation which when executed performs the save. When writing + checkpoints, returns None. The return value is useful in unit tests. + + Raises: + ValueError if `checkpoint` is passed into `checkpoint_args`. + """ + return dataset.save(path, compression, shard_func, checkpoint_args) + + +@tf_export("data.experimental.load", v1=[]) +@deprecation.deprecated(None, "Use `tf.data.Dataset.load(...)` instead.") +def load(path, element_spec=None, compression=None, reader_func=None): + """Loads a previously saved dataset. + + Example usage: + + >>> import tempfile + >>> path = os.path.join(tempfile.gettempdir(), "saved_data") + >>> # Save a dataset + >>> dataset = tf.data.Dataset.range(2) + >>> tf.data.experimental.save(dataset, path) + >>> new_dataset = tf.data.experimental.load(path) + >>> for elem in new_dataset: + ... print(elem) + tf.Tensor(0, shape=(), dtype=int64) + tf.Tensor(1, shape=(), dtype=int64) + + + If the default option of sharding the saved dataset was used, the element + order of the saved dataset will be preserved when loading it. + + The `reader_func` argument can be used to specify a custom order in which + elements should be loaded from the individual shards. The `reader_func` is + expected to take a single argument -- a dataset of datasets, each containing + elements of one of the shards -- and return a dataset of elements. For + example, the order of shards can be shuffled when loading them as follows: + + ```python + def custom_reader_func(datasets): + datasets = datasets.shuffle(NUM_SHARDS) + return datasets.interleave(lambda x: x, num_parallel_calls=AUTOTUNE) + + dataset = tf.data.experimental.load( + path="/path/to/data", ..., reader_func=custom_reader_func) + ``` + + Args: + path: Required. A path pointing to a previously saved dataset. + element_spec: Optional. A nested structure of `tf.TypeSpec` objects matching + the structure of an element of the saved dataset and specifying the type + of individual element components. If not provided, the nested structure of + `tf.TypeSpec` saved with the saved dataset is used. Note that this + argument is required in graph mode. + compression: Optional. The algorithm to use to decompress the data when + reading it. Supported options are `GZIP` and `NONE`. Defaults to `NONE`. + reader_func: Optional. A function to control how to read data from shards. + If present, the function will be traced and executed as graph computation. + + Returns: + A `tf.data.Dataset` instance. + + Raises: + FileNotFoundError: If `element_spec` is not specified and the saved nested + structure of `tf.TypeSpec` can not be located with the saved dataset. + ValueError: If `element_spec` is not specified and the method is executed + in graph mode. + """ + return dataset_ops.Dataset.load(path, element_spec, compression, reader_func) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/iterator_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/iterator_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..12a8643923fe91b701e01736c7833c5d91f2a8b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/iterator_ops.py @@ -0,0 +1,321 @@ +# 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. +# ============================================================================== +"""Iterator ops.""" + +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.framework import ops +from tensorflow.python.training import basic_session_run_hooks +from tensorflow.python.training import saver as saver_lib +from tensorflow.python.training import session_run_hook +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +def _convert_external_state_policy_to_enum(external_state_policy): + if isinstance(external_state_policy, options_lib.ExternalStatePolicy): + return external_state_policy + if external_state_policy == "warn": + return options_lib.ExternalStatePolicy.WARN + if external_state_policy == "ignore": + return options_lib.ExternalStatePolicy.IGNORE + if external_state_policy == "fail": + return options_lib.ExternalStatePolicy.FAIL + raise ValueError( + f"Invalid `ExternalStatePolicy.` Supported values include 'warn', " + f"'ignore', and 'fail.' Received {external_state_policy}." + ) + + +@tf_export("data.experimental.make_saveable_from_iterator") +@deprecation.deprecated( + None, "`make_saveable_from_iterator` is intended for use in TF1 with " + "`tf.compat.v1.Saver`. In TF2, use `tf.train.Checkpoint` instead.") +def make_saveable_from_iterator(iterator, external_state_policy=None): + """Returns a SaveableObject for saving/restoring iterator state using Saver. + + Args: + iterator: Iterator. + external_state_policy: A string that identifies how to handle input + pipelines that depend on external state. Possible values are + 'ignore': The external state is silently ignored. + 'warn': The external state is ignored, logging a warning. + 'fail': The operation fails upon encountering external state. + By default we set it to 'fail'. + + Returns: + A SaveableObject for saving/restoring iterator state using Saver. + + Raises: + ValueError: If iterator does not support checkpointing. + ValueError: If `external_state_policy` is not one of 'warn', 'ignore' or + 'fail'. + + For example: + + ```python + with tf.Graph().as_default(): + ds = tf.data.Dataset.range(10) + iterator = ds.make_initializable_iterator() + # Build the iterator SaveableObject. + saveable_obj = tf.data.experimental.make_saveable_from_iterator(iterator) + # Add the SaveableObject to the SAVEABLE_OBJECTS collection so + # it can be automatically saved using Saver. + tf.compat.v1.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, saveable_obj) + saver = tf.compat.v1.train.Saver() + + while continue_training: + ... Perform training ... + if should_save_checkpoint: + saver.save() + ``` + + Note: When restoring the iterator, the existing iterator state is completely + discarded. This means that any changes you may have made to the Dataset + graph will be discarded as well! This includes the new Dataset graph + that you may have built during validation. So, while running validation, + make sure to run the initializer for the validation input pipeline after + restoring the checkpoint. + + Note: Not all iterators support checkpointing yet. Attempting to save the + state of an unsupported iterator will throw an error. + """ + if external_state_policy is None: + external_state_policy = "fail" + policy_enum = _convert_external_state_policy_to_enum(external_state_policy) + return iterator_ops._IteratorSaveable( # pylint: disable=protected-access + iterator._iterator_resource, # pylint: disable=protected-access + iterator._iterator_resource.name, # pylint: disable=protected-access + external_state_policy=policy_enum) + + +@tf_export("data.experimental.CheckpointInputPipelineHook") +class CheckpointInputPipelineHook(session_run_hook.SessionRunHook): + """Checkpoints input pipeline state every N steps or seconds. + + This hook saves the state of the iterators in the `Graph` so that when + training is resumed the input pipeline continues from where it left off. + This could potentially avoid overfitting in certain pipelines where the + number of training steps per eval are small compared to the dataset + size or if the training pipeline is pre-empted. + + Differences from `CheckpointSaverHook`: + 1. Saves only the input pipelines in the "iterators" collection and not the + global variables or other saveable objects. + 2. Does not write the `GraphDef` and `MetaGraphDef` to the summary. + + Example of checkpointing the training pipeline: + + ```python + est = tf.estimator.Estimator(model_fn) + while True: + est.train( + train_input_fn, + hooks=[tf.data.experimental.CheckpointInputPipelineHook(est)], + steps=train_steps_per_eval) + # Note: We do not pass the hook here. + metrics = est.evaluate(eval_input_fn) + if should_stop_the_training(metrics): + break + ``` + + This hook should be used if the input pipeline state needs to be saved + separate from the model checkpoint. Doing so may be useful for a few reasons: + 1. The input pipeline checkpoint may be large, if there are large shuffle + or prefetch buffers for instance, and may bloat the checkpoint size. + 2. If the input pipeline is shared between training and validation, restoring + the checkpoint during validation may override the validation input + pipeline. + + For saving the input pipeline checkpoint alongside the model weights use + `tf.data.experimental.make_saveable_from_iterator` directly to create a + `SaveableObject` and add to the `SAVEABLE_OBJECTS` collection. Note, however, + that you will need to be careful not to restore the training iterator during + eval. You can do that by not adding the iterator to the SAVEABLE_OBJECTS + collector when building the eval graph. + """ + + def __init__(self, estimator, external_state_policy=None): + """Initializes a `CheckpointInputPipelineHook`. + + If the input pipeline depends on external state (e.g. seeds for + RandomUniform) beyond the input pipeline, this hook would be unable to + serialize and deserialize that state. If its acceptable to ignore that state + change the external_state_policy argument to 'warn' or 'ignore'. For e.g. + + ```python + est = tf.estimator.Estimator(model_fn) + while True: + est.train( + train_input_fn, + hooks=[tf.data.experimental.CheckpointInputPipelineHook( + est, external_state_policy='warn')], + steps=train_steps_per_eval) + # Note: We do not pass the hook here. + metrics = est.evaluate(eval_input_fn) + if should_stop_the_training(metrics): + break + ``` + + Args: + estimator: Estimator. + external_state_policy: A string that identifies how to handle input + pipelines that depend on external state. Possible values are + 'ignore': The external state is silently ignored. + 'warn': The external state is ignored, logging a warning. + 'fail': The operation fails upon encountering external state. + By default we set it to 'fail'. + + Raises: + ValueError: One of `save_steps` or `save_secs` should be set. + ValueError: At most one of saver or scaffold should be set. + ValueError: If `external_state_policy` is not one of 'warn', 'ignore' or + 'fail'. + """ + if external_state_policy is None: + external_state_policy = "fail" + self._external_state_policy = _convert_external_state_policy_to_enum( + external_state_policy) + # `checkpoint_basename` is "input.ckpt" for non-distributed pipelines or + # of the form "input__.ckpt" for distributed pipelines. + # Note: The default `checkpoint_basename` used by `CheckpointSaverHook` is + # "model.ckpt". We intentionally choose the input pipeline checkpoint prefix + # to be different to avoid conflicts with the model checkpoint. + + # pylint: disable=protected-access + checkpoint_prefix = "input" + if estimator._config.num_worker_replicas > 1: + # Distributed setting. + suffix = "_{}_{}".format(estimator._config.task_type, + estimator._config.task_id) + checkpoint_prefix += suffix + # pylint: enable=protected-access + + # We use a composition paradigm instead of inheriting from + # `CheckpointSaverHook` because `Estimator` does an `isinstance` check + # to check whether a `CheckpointSaverHook` is already present in the list + # of hooks and if not, adds one. Inheriting from `CheckpointSaverHook` + # would thwart this behavior. This hook checkpoints *only the iterators* + # and not the graph variables. + self._checkpoint_saver_hook = basic_session_run_hooks.CheckpointSaverHook( + estimator.model_dir, + save_secs=estimator._config.save_checkpoints_secs, # pylint: disable=protected-access + save_steps=estimator._config.save_checkpoints_steps, # pylint: disable=protected-access + checkpoint_basename=checkpoint_prefix + ".ckpt") + + # Name for the protocol buffer file that will contain the list of most + # recent checkpoints stored as a `CheckpointState` protocol buffer. + # This file, kept in the same directory as the checkpoint files, is + # automatically managed by the `Saver` to keep track of recent checkpoints. + # The default name used by the `Saver` for this file is "checkpoint". Here + # we use the name "checkpoint_" so that in case the + # `checkpoint_dir` is the same as the model checkpoint directory, there are + # no conflicts during restore. + self._latest_filename = "checkpoint_" + checkpoint_prefix + + def begin(self): + # Build a Saver that saves all iterators in the `GLOBAL_ITERATORS` + # collection if no `Saver` or `Scaffold` is provided. + # pylint: disable=protected-access + if (self._checkpoint_saver_hook._saver is None and + self._checkpoint_saver_hook._scaffold is None): + iterators = ops.get_collection(iterator_ops.GLOBAL_ITERATORS) + saveables = [ + iterator_ops._IteratorSaveable( + i, i.name, external_state_policy=self._external_state_policy) + for i in iterators + ] + self._checkpoint_saver_hook._saver = _CustomSaver( + saveables, self._latest_filename, sharded=True) + # pylint: enable=protected-access + self._checkpoint_saver_hook.begin() + + def after_create_session(self, session, coord): + # If a new session was created, we set _first_run to True so that we can + # restore if needed. + self._first_run = True + + def _restore_or_save_initial_ckpt(self, session): + # Ideally this should be run in after_create_session but is not for the + # following reason: + # Currently there is no way of enforcing an order of running the + # `SessionRunHooks`. Hence it is possible that the `_DatasetInitializerHook` + # is run *after* this hook. That is troublesome because + # 1. If a checkpoint exists and this hook restores it, the initializer hook + # will override it. + # 2. If no checkpoint exists, this hook will try to save an uninitialized + # iterator which will result in an exception. + # + # As a temporary fix we enter the following implicit contract between this + # hook and the _DatasetInitializerHook. + # 1. The _DatasetInitializerHook initializes the iterator in the call to + # after_create_session. + # 2. This hook saves the iterator on the first call to `before_run()`, which + # is guaranteed to happen after `after_create_session()` of all hooks + # have been run. + + # Check if there is an existing checkpoint. If so, restore from it. + # pylint: disable=protected-access + latest_checkpoint_path = checkpoint_management.latest_checkpoint( + self._checkpoint_saver_hook._checkpoint_dir, + latest_filename=self._latest_filename) + if latest_checkpoint_path: + self._checkpoint_saver_hook._get_saver().restore(session, + latest_checkpoint_path) + else: + # The checkpoint saved here is the state at step "global_step". + # Note: We do not save the GraphDef or MetaGraphDef here. + global_step = session.run(self._checkpoint_saver_hook._global_step_tensor) + self._checkpoint_saver_hook._save(session, global_step) + self._checkpoint_saver_hook._timer.update_last_triggered_step(global_step) + # pylint: enable=protected-access + + def before_run(self, run_context): + if self._first_run: + self._restore_or_save_initial_ckpt(run_context.session) + self._first_run = False + return self._checkpoint_saver_hook.before_run(run_context) + + def after_run(self, run_context, run_values): + self._checkpoint_saver_hook.after_run(run_context, run_values) + + def end(self, session): + self._checkpoint_saver_hook.end(session) + + +class _CustomSaver(saver_lib.Saver): + """`Saver` with a different default `latest_filename`. + + This is used in the `CheckpointInputPipelineHook` to avoid conflicts with + the model ckpt saved by the `CheckpointSaverHook`. + """ + + def __init__(self, var_list, latest_filename, sharded=False): + super(_CustomSaver, self).__init__(var_list, sharded=sharded) + self._latest_filename = latest_filename + + def save(self, + sess, + save_path, + global_step=None, + latest_filename=None, + meta_graph_suffix="meta", + write_meta_graph=True, + write_state=True, + strip_default_attrs=False): + return super(_CustomSaver, self).save( + sess, save_path, global_step, latest_filename or self._latest_filename, + meta_graph_suffix, write_meta_graph, write_state, strip_default_attrs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/lookup_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/lookup_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..aef2902813eca123686a13119be2b29772d61fee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/lookup_ops.py @@ -0,0 +1,238 @@ +# 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. +#============================================================================== +"""Lookup operations.""" + +from tensorflow.python.data.experimental.ops.cardinality import assert_cardinality +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util.tf_export import tf_export + + +def _check_table_initializer_element_spec(element_spec): + """Raises an error if the given table initializer element spec is invalid.""" + base_error = ("Datasets used to initialize lookup tables must " + "produce elements in the form (key, value), where " + "the keys and values are scalar tensors. ") + specific_error = None + if len(element_spec) != 2: + raise ValueError(base_error + "However, the given dataset produces " + f"{len(element_spec)} components instead of two " + "(key, value) components. Full dataset element spec: " + f"{element_spec}.") + if not isinstance(element_spec[0], tensor.TensorSpec): + raise ValueError(base_error + "However, the given dataset produces " + f"non-Tensor keys of type {type(element_spec[0])}.") + if not isinstance(element_spec[1], tensor.TensorSpec): + raise ValueError(base_error + "However, the given dataset produces " + f"non-Tensor values of type {type(element_spec[1])}.") + if element_spec[0].shape.rank not in (None, 0): + raise ValueError( + base_error + "However, the given dataset produces " + f"non-scalar key Tensors of rank {element_spec[0].shape.rank}.") + if element_spec[1].shape.rank not in (None, 0): + raise ValueError( + base_error + "However, the given dataset produces " + f"non-scalar value Tensors of rank {element_spec[1].shape.rank}.") + + +@tf_export("data.experimental.DatasetInitializer") +class DatasetInitializer(lookup_ops.TableInitializerBase): + """Creates a table initializer from a `tf.data.Dataset`. + + Sample usage: + + >>> keys = tf.data.Dataset.range(100) + >>> values = tf.data.Dataset.range(100).map( + ... lambda x: tf.strings.as_string(x * 2)) + >>> ds = tf.data.Dataset.zip((keys, values)) + >>> init = tf.data.experimental.DatasetInitializer(ds) + >>> table = tf.lookup.StaticHashTable(init, "") + >>> table.lookup(tf.constant([0, 1, 2], dtype=tf.int64)).numpy() + array([b'0', b'2', b'4'], dtype=object) + + Attributes: + dataset: A `tf.data.Dataset` object that produces tuples of scalars. The + first scalar is treated as a key and the second as value. + Raises: ValueError if `dataset` doesn't conform to specifications. + """ + + def __init__(self, dataset): + """Creates a table initializer from a `tf.data.Dataset`. + + Args: + dataset: A `tf.data.Dataset` object that produces tuples of scalars. The + first scalar is treated as a key and the second as value. + Raises: ValueError if `dataset` doesn't conform to specifications. + Returns: A `DatasetInitializer` object + """ + # Assert that the dataset element spec is a tuple of TensorSpecs where + # each tensor is a scalar. + self.dataset = dataset + elem_spec = self.dataset.element_spec + _check_table_initializer_element_spec(elem_spec) + + key_type = elem_spec[0].dtype + value_type = elem_spec[1].dtype + super(DatasetInitializer, self).__init__(key_type, value_type) + + def initialize(self, table): + lookup_ops.check_table_dtypes(table, self._key_dtype, self._value_dtype) + init_op = ged_ops.initialize_table_from_dataset( + table.resource_handle, self.dataset._variant_tensor) # pylint: disable=protected-access + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op) + return init_op + + +@tf_export("data.experimental.table_from_dataset") +def table_from_dataset(dataset=None, + num_oov_buckets=0, + vocab_size=None, + default_value=None, + hasher_spec=lookup_ops.FastHashSpec, + key_dtype=dtypes.string, + name=None): + """Returns a lookup table based on the given dataset. + + This operation constructs a lookup table based on the given dataset of pairs + of (key, value). + + Any lookup of an out-of-vocabulary token will return a bucket ID based on its + hash if `num_oov_buckets` is greater than zero. Otherwise it is assigned the + `default_value`. + The bucket ID range is + `[vocabulary size, vocabulary size + num_oov_buckets - 1]`. + + Sample Usages: + + >>> keys = tf.data.Dataset.range(100) + >>> values = tf.data.Dataset.range(100).map( + ... lambda x: tf.strings.as_string(x * 2)) + >>> ds = tf.data.Dataset.zip((keys, values)) + >>> table = tf.data.experimental.table_from_dataset( + ... ds, default_value='n/a', key_dtype=tf.int64) + >>> table.lookup(tf.constant([0, 1, 2], dtype=tf.int64)).numpy() + array([b'0', b'2', b'4'], dtype=object) + + Args: + dataset: A dataset containing (key, value) pairs. + num_oov_buckets: The number of out-of-vocabulary buckets. + vocab_size: Number of the elements in the vocabulary, if known. + default_value: The value to use for out-of-vocabulary feature values. + Defaults to -1. + hasher_spec: A `HasherSpec` to specify the hash function to use for + assignation of out-of-vocabulary buckets. + key_dtype: The `key` data type. + name: A name for this op (optional). + + Returns: + The lookup table based on the given dataset. + + Raises: + ValueError: If + * `dataset` does not contain pairs + * The 2nd item in the `dataset` pairs has a dtype which is incompatible + with `default_value` + * `num_oov_buckets` is negative + * `vocab_size` is not greater than zero + * The `key_dtype` is not integer or string + """ + elem_spec = dataset.element_spec + _check_table_initializer_element_spec(elem_spec) + if default_value is None: + default_value = -1 + if not (elem_spec[1].dtype.is_integer or elem_spec[1].dtype.is_floating): + raise ValueError("`default_value` must be specified when creating a " + "table from a dataset that produces values of type " + f"{elem_spec[1].dtype}.") + if num_oov_buckets < 0: + raise ValueError("`num_oov_buckets` must be greater than or equal to 0, " + f"got {num_oov_buckets}.") + if (not isinstance(vocab_size, tensor.Tensor) and vocab_size is not None and + vocab_size < 1): + raise ValueError(f"`vocab_size` must be greater than 0, got {vocab_size}.") + if (not key_dtype.is_integer) and (dtypes.string != key_dtype.base_dtype): + raise TypeError("`key_dtype` must be either an integer or string type, " + f"but got {key_dtype}") + if vocab_size is not None: + if isinstance(vocab_size, tensor.Tensor): + vocab_size = math_ops.cast(vocab_size, dtypes.int64) + dataset = dataset.take(vocab_size) + dataset = dataset.apply(assert_cardinality(vocab_size)) + with ops.name_scope(name, "string_to_index"): + initializer = DatasetInitializer(dataset) + with ops.name_scope(None, "hash_table"): + table = lookup_ops.StaticHashTableV1(initializer, default_value) + if num_oov_buckets: + table = lookup_ops.IdTableWithHashBuckets( + table, + num_oov_buckets=num_oov_buckets, + hasher_spec=hasher_spec, + key_dtype=key_dtype) + return table + + +@tf_export("data.experimental.index_table_from_dataset") +def index_table_from_dataset(dataset=None, + num_oov_buckets=0, + vocab_size=None, + default_value=-1, + hasher_spec=lookup_ops.FastHashSpec, + key_dtype=dtypes.string, + name=None): + """Returns an index lookup table based on the given dataset. + + This operation constructs a lookup table based on the given dataset of keys. + + Any lookup of an out-of-vocabulary token will return a bucket ID based on its + hash if `num_oov_buckets` is greater than zero. Otherwise it is assigned the + `default_value`. + The bucket ID range is + `[vocabulary size, vocabulary size + num_oov_buckets - 1]`. + + Sample Usages: + + >>> ds = tf.data.Dataset.range(100).map(lambda x: tf.strings.as_string(x * 2)) + >>> table = tf.data.experimental.index_table_from_dataset( + ... ds, key_dtype=dtypes.int64) + >>> table.lookup(tf.constant(['0', '2', '4'], dtype=tf.string)).numpy() + array([0, 1, 2]) + + Args: + dataset: A dataset of keys. + num_oov_buckets: The number of out-of-vocabulary buckets. + vocab_size: Number of the elements in the vocabulary, if known. + default_value: The value to use for out-of-vocabulary feature values. + Defaults to -1. + hasher_spec: A `HasherSpec` to specify the hash function to use for + assignation of out-of-vocabulary buckets. + key_dtype: The `key` data type. + name: A name for this op (optional). + + Returns: + The lookup table based on the given dataset. + + Raises: + ValueError: If + * `num_oov_buckets` is negative + * `vocab_size` is not greater than zero + * The `key_dtype` is not integer or string + """ + return table_from_dataset(dataset.enumerate().map(lambda v, k: (k, v)), + num_oov_buckets, vocab_size, default_value, + hasher_spec, key_dtype, name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/map_defun.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/map_defun.py new file mode 100644 index 0000000000000000000000000000000000000000..86848b507aa9c61a47c876f0bd6d83afbfdfdac2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/map_defun.py @@ -0,0 +1,65 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Experimental API for optimizing `tf.data` pipelines.""" + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import gen_dataset_ops + + +def map_defun(fn, + elems, + output_dtypes, + output_shapes, + max_intra_op_parallelism=1): + """Map a function on the list of tensors unpacked from `elems` on dimension 0. + + Args: + fn: A function (`function.defun`) that takes a list of tensors and returns + another list of tensors. The output list has the same types as + output_dtypes. The elements of the output list have the same dimension 0 + as `elems`, and the remaining dimensions correspond to those of + `fn_output_shapes`. + elems: A list of tensors. + output_dtypes: A list of dtypes corresponding to the output types of the + function. + output_shapes: A list of `TensorShape`s corresponding to the output shapes + from each invocation of the function on slices of inputs. + max_intra_op_parallelism: An integer. If positive, sets the max parallelism + limit of each function call to this. + + Raises: + ValueError: if any of the inputs are malformed. + + Returns: + A list of `Tensor` objects with the same types as `output_dtypes`. + """ + if not isinstance(elems, list): + raise ValueError(f"`elems` must be a list of tensors, but was {elems}.") + if not isinstance(output_dtypes, list): + raise ValueError("`output_dtypes` must be a list of `tf.DType` objects, " + f"but was {output_dtypes}.") + if not isinstance(output_shapes, list): + raise ValueError("`output_shapes` must be a list of `tf.TensorShape` " + f"objects, but was {output_shapes}.") + + concrete_fn = fn.get_concrete_function() # pylint: disable=protected-access + # TODO(shivaniagrawal/rachelim): what about functions created without + # input_signature. + elems = [ops.convert_to_tensor(e) for e in elems] + output_shapes = [tensor_shape.TensorShape(s) for s in output_shapes] + return gen_dataset_ops.map_defun(elems, concrete_fn.captured_inputs, + output_dtypes, output_shapes, concrete_fn, + max_intra_op_parallelism) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/matching_files.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/matching_files.py new file mode 100644 index 0000000000000000000000000000000000000000..deb934126cd5c982b03ed3c3118681074db2edc6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/matching_files.py @@ -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. +# ============================================================================== +"""Experimental API for matching input filenames.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +class MatchingFilesDataset(dataset_ops.DatasetSource): + """A `Dataset` that list the files according to the input patterns.""" + + def __init__(self, patterns): + self._patterns = ops.convert_to_tensor( + patterns, dtype=dtypes.string, name="patterns") + variant_tensor = ged_ops.matching_files_dataset(self._patterns) + super(MatchingFilesDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/pad_to_cardinality.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/pad_to_cardinality.py new file mode 100644 index 0000000000000000000000000000000000000000..e98ddb887331708e2531d76ed0f43543a122a66c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/pad_to_cardinality.py @@ -0,0 +1,105 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.experimental.pad_to_cardinality`.""" + +from collections.abc import Mapping + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.eager import context +from tensorflow.python.ops import array_ops +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.pad_to_cardinality") +def pad_to_cardinality(cardinality, mask_key="valid"): + """Pads a dataset with fake elements to reach the desired cardinality. + + The dataset to pad must have a known and finite cardinality and contain + dictionary elements. The `mask_key` will be added to differentiate between + real and padding elements -- real elements will have a `=True` entry + while padding elements will have a `=False` entry. + + Example usage: + + >>> ds = tf.data.Dataset.from_tensor_slices({'a': [1, 2]}) + >>> ds = ds.apply(tf.data.experimental.pad_to_cardinality(3)) + >>> list(ds.as_numpy_iterator()) + [{'a': 1, 'valid': True}, {'a': 2, 'valid': True}, {'a': 0, 'valid': False}] + + This can be useful, e.g. during eval, when partial batches are undesirable but + it is also important not to drop any data. + + ``` + ds = ... + # Round up to the next full batch. + target_cardinality = -(-ds.cardinality() // batch_size) * batch_size + ds = ds.apply(tf.data.experimental.pad_to_cardinality(target_cardinality)) + # Set `drop_remainder` so that batch shape will be known statically. No data + # will actually be dropped since the batch size divides the cardinality. + ds = ds.batch(batch_size, drop_remainder=True) + ``` + + Args: + cardinality: The cardinality to pad the dataset to. + mask_key: The key to use for identifying real vs padding elements. + + Returns: + A dataset transformation that can be applied via `Dataset.apply()`. + """ + + def make_filler_dataset(ds): + padding = cardinality - ds.cardinality() + + filler_element = nest.map_structure( + lambda spec: array_ops.zeros(spec.shape, spec.dtype), ds.element_spec + ) + filler_element[mask_key] = False + filler_dataset = dataset_ops.Dataset.from_tensors(filler_element) + filler_dataset = filler_dataset.repeat(padding) + return filler_dataset + + def apply_valid_mask(x): + x[mask_key] = True + return x + + def _apply_fn(dataset): + # The cardinality tensor is unknown during tracing, so we only check it + # in eager mode. + if context.executing_eagerly(): + if dataset.cardinality() < 0: + raise ValueError( + "The dataset passed into `pad_to_cardinality` must " + "have a known cardinalty, but has cardinality " + f"{dataset.cardinality()}" + ) + if dataset.cardinality() > cardinality: + raise ValueError( + "The dataset passed into `pad_to_cardinality` must " + "have a cardinalty less than the target cardinality " + f"({cardinality}), but has cardinality " + f"{dataset.cardinality()}" + ) + if not isinstance(dataset.element_spec, Mapping): + raise ValueError( + "`pad_to_cardinality` requires its input dataset to " + "be a dictionary." + ) + filler = make_filler_dataset(dataset) + dataset = dataset.map(apply_valid_mask) + dataset = dataset.concatenate(filler) + return dataset + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/parsing_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/parsing_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd14d63bd3762c17fa7e3dcacedaf8df58e486e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/parsing_ops.py @@ -0,0 +1,161 @@ +# 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. +# ============================================================================== +"""Experimental `dataset` API for parsing example.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import structure +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +class _ParseExampleDataset(dataset_ops.UnaryDataset): + """A `Dataset` that parses `example` dataset into a `dict` dataset.""" + + def __init__(self, input_dataset, features, num_parallel_calls, + deterministic): + self._input_dataset = input_dataset + if not structure.are_compatible( + input_dataset.element_spec, + tensor_spec.TensorSpec([None], dtypes.string)): + raise TypeError("Input dataset should be a dataset of vectors of " + f"strings. Instead it is `{input_dataset.element_spec}`.") + self._num_parallel_calls = num_parallel_calls + if deterministic is None: + self._deterministic = "default" + elif deterministic: + self._deterministic = "true" + else: + self._deterministic = "false" + # pylint: disable=protected-access + self._features = parsing_ops._prepend_none_dimension(features) + params = parsing_ops._ParseOpParams.from_features(self._features, [ + parsing_ops.VarLenFeature, parsing_ops.SparseFeature, + parsing_ops.FixedLenFeature, parsing_ops.FixedLenSequenceFeature, + parsing_ops.RaggedFeature + ]) + # pylint: enable=protected-access + self._sparse_keys = params.sparse_keys + self._sparse_types = params.sparse_types + self._ragged_keys = params.ragged_keys + self._ragged_value_types = params.ragged_value_types + self._ragged_split_types = params.ragged_split_types + self._dense_keys = params.dense_keys + self._dense_defaults = params.dense_defaults_vec + self._dense_shapes = params.dense_shapes_as_proto + self._dense_types = params.dense_types + input_dataset_shape = dataset_ops.get_legacy_output_shapes( + self._input_dataset) + + self._element_spec = {} + + for (key, value_type) in zip(params.sparse_keys, params.sparse_types): + self._element_spec[key] = sparse_tensor.SparseTensorSpec( + input_dataset_shape.concatenate([None]), value_type) + + for (key, value_type, dense_shape) in zip(params.dense_keys, + params.dense_types, + params.dense_shapes): + self._element_spec[key] = tensor_spec.TensorSpec( + input_dataset_shape.concatenate(dense_shape), value_type) + + for (key, value_type, splits_type) in zip(params.ragged_keys, + params.ragged_value_types, + params.ragged_split_types): + self._element_spec[key] = ragged_tensor.RaggedTensorSpec( + input_dataset_shape.concatenate([None]), value_type, 1, splits_type) + + variant_tensor = ( + gen_experimental_dataset_ops.parse_example_dataset_v2( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._num_parallel_calls, + self._dense_defaults, + self._sparse_keys, + self._dense_keys, + self._sparse_types, + self._dense_shapes, + deterministic=self._deterministic, + ragged_keys=self._ragged_keys, + ragged_value_types=self._ragged_value_types, + ragged_split_types=self._ragged_split_types, + **self._flat_structure)) + super(_ParseExampleDataset, self).__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +@tf_export("data.experimental.parse_example_dataset") +@deprecation.deprecated( + None, "Use `tf.data.Dataset.map(tf.io.parse_example(...))` instead.") +def parse_example_dataset(features, num_parallel_calls=1, deterministic=None): + """A transformation that parses `Example` protos into a `dict` of tensors. + + Parses a number of serialized `Example` protos given in `serialized`. We refer + to `serialized` as a batch with `batch_size` many entries of individual + `Example` protos. + + This op parses serialized examples into a dictionary mapping keys to `Tensor`, + `SparseTensor`, and `RaggedTensor` objects. `features` is a dict from keys to + `VarLenFeature`, `RaggedFeature`, `SparseFeature`, and `FixedLenFeature` + objects. Each `VarLenFeature` and `SparseFeature` is mapped to a + `SparseTensor`; each `RaggedFeature` is mapped to a `RaggedTensor`; and each + `FixedLenFeature` is mapped to a `Tensor`. See `tf.io.parse_example` for more + details about feature dictionaries. + + Args: + features: A `dict` mapping feature keys to `FixedLenFeature`, + `VarLenFeature`, `RaggedFeature`, and `SparseFeature` values. + num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`, + representing the number of parsing processes to call in parallel. + deterministic: (Optional.) A boolean controlling whether determinism + should be traded for performance by allowing elements to be produced out + of order if some parsing calls complete faster than others. If + `deterministic` is `None`, the + `tf.data.Options.deterministic` dataset option (`True` by default) is used + to decide whether to produce elements deterministically. + + Returns: + A dataset transformation function, which can be passed to + `tf.data.Dataset.apply`. + + Raises: + ValueError: if features argument is None. + """ + if features is None: + raise ValueError("Argument `features` is required, but not specified.") + + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + out_dataset = _ParseExampleDataset(dataset, features, num_parallel_calls, + deterministic) + if any( + isinstance(feature, parsing_ops.SparseFeature) or + isinstance(feature, parsing_ops.RaggedFeature) + for feature in features.values()): + # pylint: disable=protected-access + # pylint: disable=g-long-lambda + out_dataset = out_dataset.map( + lambda x: parsing_ops._construct_tensors_for_composite_features( + features, x), + num_parallel_calls=num_parallel_calls) + return out_dataset + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/prefetching_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/prefetching_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..5335de4c5a4acd6b0b5d35ab900ab215ef40c051 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/prefetching_ops.py @@ -0,0 +1,287 @@ +# 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. +# ============================================================================== +"""Python wrapper for prefetching_ops.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import structure +from tensorflow.python.eager import def_function +from tensorflow.python.framework import device as framework_device +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import functional_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.prefetch_to_device") +def prefetch_to_device(device, buffer_size=None): + """A transformation that prefetches dataset values to the given `device`. + + NOTE: Although the transformation creates a `tf.data.Dataset`, the + transformation must be the final `Dataset` in the input pipeline. + + For example, + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> dataset = dataset.apply(tf.data.experimental.prefetch_to_device("/cpu:0")) + >>> for element in dataset: + ... print(f'Tensor {element} is on device {element.device}') + Tensor 1 is on device /job:localhost/replica:0/task:0/device:CPU:0 + Tensor 2 is on device /job:localhost/replica:0/task:0/device:CPU:0 + Tensor 3 is on device /job:localhost/replica:0/task:0/device:CPU:0 + + Args: + device: A string. The name of a device to which elements will be prefetched. + buffer_size: (Optional.) The number of elements to buffer on `device`. + Defaults to an automatically chosen value. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + def _apply_fn(dataset): + return dataset.apply( + copy_to_device(target_device=device)).prefetch(buffer_size) + + return _apply_fn + + +@tf_export("data.experimental.copy_to_device") +def copy_to_device(target_device, source_device="/cpu:0"): + """A transformation that copies dataset elements to the given `target_device`. + + Args: + target_device: The name of a device to which elements will be copied. + source_device: The original device on which `input_dataset` will be placed. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return _CopyToDeviceDataset( + dataset, target_device=target_device, source_device=source_device) + + return _apply_fn + + +# TODO(rohanj): Use the _input_hostmem attr on the RemoteCall ops to indicate +# all inputs to the Op are in host memory, thereby avoiding some unnecessary +# Sends and Recvs. +class _CopyToDeviceDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that copies elements to another device.""" + + def __init__(self, input_dataset, target_device, source_device="/cpu:0"): + """Constructs a _CopyToDeviceDataset. + + Args: + input_dataset: `Dataset` to be copied + target_device: The name of the device to which elements would be copied. + source_device: Device where input_dataset would be placed. + """ + self._input_dataset = input_dataset._apply_debug_options() # pylint: disable=protected-access + self._target_device = target_device + spec = framework_device.DeviceSpec().from_string(self._target_device) + self._is_gpu_target = (spec.device_type == "GPU") + self._source_device_string = source_device + self._source_device = ops.convert_to_tensor(source_device) + + wrap_ds_variant = gen_dataset_ops.wrap_dataset_variant( + self._input_dataset._variant_tensor) # pylint: disable=protected-access + + @def_function.function() + def _init_func(): + """Creates an iterator for the input dataset. + + Returns: + A `string` tensor that encapsulates the iterator created. + """ + ds_variant = gen_dataset_ops.unwrap_dataset_variant(wrap_ds_variant) + resource = gen_dataset_ops.anonymous_iterator( + **self._input_dataset._flat_structure) # pylint: disable=protected-access + with ops.control_dependencies( + [gen_dataset_ops.make_iterator(ds_variant, resource)]): + return gen_dataset_ops.iterator_to_string_handle(resource) + + init_func_concrete = _init_func.get_concrete_function() # pylint: disable=protected-access + + @def_function.function() + def _remote_init_func(): + return functional_ops.remote_call( + target=self._source_device, + args=init_func_concrete.captured_inputs, + Tout=[dtypes.string], + f=init_func_concrete) + + self._init_func = _remote_init_func.get_concrete_function() # pylint: disable=protected-access + self._init_captured_args = self._init_func.captured_inputs + + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)]) + def _next_func(string_handle): + """Calls get_next for created iterator. + + Args: + string_handle: An iterator string handle created by _init_func + Returns: + The elements generated from `input_dataset` + """ + with ops.device(self._source_device_string): + iterator = iterator_ops.Iterator.from_string_handle( + string_handle, + dataset_ops.get_legacy_output_types(self), + dataset_ops.get_legacy_output_shapes(self), + dataset_ops.get_legacy_output_classes(self)) + return structure.to_tensor_list(self.element_spec, iterator.get_next()) + + next_func_concrete = _next_func.get_concrete_function() # pylint: disable=protected-access + + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)], + experimental_attributes={"experimental_ints_on_device": True}) + def _remote_next_func(string_handle): + return functional_ops.remote_call( + target=self._source_device, + args=[string_handle] + next_func_concrete.captured_inputs, + Tout=self._input_dataset._flat_types, # pylint: disable=protected-access + f=next_func_concrete) + + self._next_func = _remote_next_func.get_concrete_function() + self._next_captured_args = self._next_func.captured_inputs + + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)]) + def _finalize_func(string_handle): + """Destroys the iterator resource created. + + Args: + string_handle: An iterator string handle created by _init_func + Returns: + Tensor constant 0 + """ + iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2( + string_handle, + **self._input_dataset._flat_structure) # pylint: disable=protected-access + with ops.control_dependencies([ + resource_variable_ops.destroy_resource_op( + iterator_resource, ignore_lookup_error=True)]): + return array_ops.constant(0, dtypes.int64) + + finalize_func_concrete = _finalize_func.get_concrete_function() # pylint: disable=protected-access + + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)]) + def _remote_finalize_func(string_handle): + return functional_ops.remote_call( + target=self._source_device, + args=[string_handle] + finalize_func_concrete.captured_inputs, + Tout=[dtypes.int64], + f=finalize_func_concrete) + + self._finalize_func = _remote_finalize_func.get_concrete_function( # pylint: disable=protected-access + ) + self._finalize_captured_args = self._finalize_func.captured_inputs + + g = ops.get_default_graph() + self._init_func.add_to_graph(g) + self._next_func.add_to_graph(g) + self._finalize_func.add_to_graph(g) + # pylint: enable=protected-scope + + with ops.device(self._target_device): + variant_tensor = gen_dataset_ops.generator_dataset( + self._init_captured_args, + self._next_captured_args, + self._finalize_captured_args, + init_func=self._init_func, + next_func=self._next_func, + finalize_func=self._finalize_func, + **self._input_dataset._flat_structure) # pylint: disable=protected-access + super(_CopyToDeviceDataset, self).__init__(input_dataset, variant_tensor) + + # The one_shot_iterator implementation needs a 0 arg _make_dataset function + # that thereby captures all the inputs required to create the dataset. Since + # there are strings that are inputs to the GeneratorDataset which can't be + # placed on a GPU, this fails for the GPU case. Therefore, disabling it for + # GPU + def make_one_shot_iterator(self): + if self._is_gpu_target: + raise ValueError( + "`make_one_shot_iterator` is not compatible with GPU execution. " + "Please use `Dataset.make_initializable_iterator()` instead." + ) + else: + return super(_CopyToDeviceDataset, self).make_one_shot_iterator() + + +class _MapOnGpuDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over elements in its using a GPU.""" + + def __init__(self, input_dataset, map_func, use_inter_op_parallelism=True): + """See `Dataset.map()` for details.""" + self._input_dataset = input_dataset + self._use_inter_op_parallelism = use_inter_op_parallelism + + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, + self._transformation_name(), + dataset=input_dataset, + defun_kwargs={"experimental_ints_on_device": True}) + variant_tensor = ged_ops.experimental_map_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, + f=self._map_func.function, + use_inter_op_parallelism=self._use_inter_op_parallelism, + **self._flat_structure) + super(_MapOnGpuDataset, self).__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._map_func.output_structure + + def _transformation_name(self): + return "map_on_gpu()" + + +def map_on_gpu(map_func): + """Maps `map_func` across the elements of this dataset. + + NOTE: This is a highly experimental version of `tf.data.Dataset.map` that runs + `map_func` on GPU. It must be used after applying the + `tf.data.experimental.copy_to_device` transformation with a GPU device + argument. + + Args: + map_func: A function mapping a nested structure of tensors (having shapes + and types defined by `self.output_shapes` and `self.output_types`) to + another nested structure of tensors. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return _MapOnGpuDataset(dataset, map_func) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/random_access.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/random_access.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a14b0f9b9d0e47b164bcfd6c1e11c3b710d95b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/random_access.py @@ -0,0 +1,73 @@ +# 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. +# ============================================================================== +"""Python API for random indexing into a dataset.""" + +from tensorflow.python.data.util import structure +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.at", v1=[]) +def at(dataset, index): + """Returns the element at a specific index in a datasest. + + Currently, random access is supported for the following tf.data operations: + + - `tf.data.Dataset.from_tensor_slices`, + - `tf.data.Dataset.from_tensors`, + - `tf.data.Dataset.shuffle`, + - `tf.data.Dataset.batch`, + - `tf.data.Dataset.shard`, + - `tf.data.Dataset.map`, + - `tf.data.Dataset.range`, + - `tf.data.Dataset.zip`, + - `tf.data.Dataset.skip`, + - `tf.data.Dataset.repeat`, + - `tf.data.Dataset.list_files`, + - `tf.data.Dataset.SSTableDataset`, + - `tf.data.Dataset.concatenate`, + - `tf.data.Dataset.enumerate`, + - `tf.data.Dataset.parallel_map`, + - `tf.data.Dataset.prefetch`, + - `tf.data.Dataset.take`, + - `tf.data.Dataset.cache` (in-memory only) + + Users can use the cache operation to enable random access for any dataset, + even one comprised of transformations which are not on this list. + E.g., to get the third element of a TFDS dataset: + + ```python + ds = tfds.load("mnist", split="train").cache() + elem = tf.data.Dataset.experimental.at(ds, 3) + ``` + + Args: + dataset: A `tf.data.Dataset` to determine whether it supports random access. + index: The index at which to fetch the element. + + Returns: + A (nested) structure of values matching `tf.data.Dataset.element_spec`. + + Raises: + UnimplementedError: If random access is not yet supported for a dataset. + """ + # pylint: disable=protected-access + return structure.from_tensor_list( + dataset.element_spec, + gen_experimental_dataset_ops.get_element_at_index( + dataset._variant_tensor, + index, + output_types=structure.get_flat_tensor_types(dataset.element_spec), + output_shapes=structure.get_flat_tensor_shapes(dataset.element_spec))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/random_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/random_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8e951ea962c3d9265c26be0d374fb6fe0cbf26a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/random_ops.py @@ -0,0 +1,46 @@ +# 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. +# ============================================================================== +"""Datasets for random number generators.""" +import functools + +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import random_op +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +# TODO(b/260143413): Migrate users to `tf.data.Dataset.random`. +@deprecation.deprecated(None, "Use `tf.data.Dataset.random(...)`.") +@tf_export("data.experimental.RandomDataset", v1=[]) +class RandomDatasetV2(random_op._RandomDataset): # pylint: disable=protected-access + """A `Dataset` of pseudorandom values.""" + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.random(...)`.") +@tf_export(v1=["data.experimental.RandomDataset"]) +class RandomDatasetV1(dataset_ops.DatasetV1Adapter): + """A `Dataset` of pseudorandom values.""" + + @functools.wraps(RandomDatasetV2.__init__) + def __init__(self, seed=None): + wrapped = RandomDatasetV2(seed) + super(RandomDatasetV1, self).__init__(wrapped) + + +if tf2.enabled(): + RandomDataset = RandomDatasetV2 +else: + RandomDataset = RandomDatasetV1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/readers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/readers.py new file mode 100644 index 0000000000000000000000000000000000000000..1ae47f4c9c8e703164e63a56d56d5f63cca22c55 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/readers.py @@ -0,0 +1,1222 @@ +# 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. +# ============================================================================== +"""Python wrappers for reader Datasets.""" +import collections +import csv +import functools +import gzip + +import numpy as np + +from tensorflow.python import tf2 +from tensorflow.python.data.experimental.ops import error_ops +from tensorflow.python.data.experimental.ops import parsing_ops +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import map_op +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.data.ops import readers as core_readers +from tensorflow.python.data.util import convert +from tensorflow.python.data.util import nest +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.platform import gfile +from tensorflow.python.util.tf_export import tf_export + +_ACCEPTABLE_CSV_TYPES = (dtypes.float32, dtypes.float64, dtypes.int32, + dtypes.int64, dtypes.string) + + +def _is_valid_int32(str_val): + try: + # Checks equality to prevent int32 overflow + return dtypes.int32.as_numpy_dtype(str_val) == dtypes.int64.as_numpy_dtype( + str_val) + except (ValueError, OverflowError): + return False + + +def _is_valid_int64(str_val): + try: + dtypes.int64.as_numpy_dtype(str_val) + return True + except (ValueError, OverflowError): + return False + + +def _is_valid_float(str_val, float_dtype): + try: + return float_dtype.as_numpy_dtype(str_val) < np.inf + except ValueError: + return False + + +def _infer_type(str_val, na_value, prev_type): + """Given a string, infers its tensor type. + + Infers the type of a value by picking the least 'permissive' type possible, + while still allowing the previous type inference for this column to be valid. + + Args: + str_val: String value to infer the type of. + na_value: Additional string to recognize as a NA/NaN CSV value. + prev_type: Type previously inferred based on values of this column that + we've seen up till now. + Returns: + Inferred dtype. + """ + if str_val in ("", na_value): + # If the field is null, it gives no extra information about its type + return prev_type + + type_list = [ + dtypes.int32, dtypes.int64, dtypes.float32, dtypes.float64, dtypes.string + ] # list of types to try, ordered from least permissive to most + + type_functions = [ + _is_valid_int32, + _is_valid_int64, + lambda str_val: _is_valid_float(str_val, dtypes.float32), + lambda str_val: _is_valid_float(str_val, dtypes.float64), + lambda str_val: True, + ] # Corresponding list of validation functions + + for i in range(len(type_list)): + validation_fn = type_functions[i] + if validation_fn(str_val) and (prev_type is None or + prev_type in type_list[:i + 1]): + return type_list[i] + + +def _next_csv_row(filenames, num_cols, field_delim, use_quote_delim, header, + file_io_fn): + """Generator that yields rows of CSV file(s) in order.""" + for fn in filenames: + with file_io_fn(fn) as f: + rdr = csv.reader( + f, + delimiter=field_delim, + quoting=csv.QUOTE_MINIMAL if use_quote_delim else csv.QUOTE_NONE) + row_num = 1 + if header: + next(rdr) # Skip header lines + row_num += 1 + + for csv_row in rdr: + if len(csv_row) != num_cols: + raise ValueError( + f"Problem inferring types: CSV row {row_num} has {len(csv_row)} " + f"number of fields. Expected: {num_cols}.") + row_num += 1 + yield csv_row + + +def _infer_column_defaults(filenames, num_cols, field_delim, use_quote_delim, + na_value, header, num_rows_for_inference, + select_columns, file_io_fn): + """Infers column types from the first N valid CSV records of files.""" + if select_columns is None: + select_columns = range(num_cols) + inferred_types = [None] * len(select_columns) + + for i, csv_row in enumerate( + _next_csv_row(filenames, num_cols, field_delim, use_quote_delim, header, + file_io_fn)): + if num_rows_for_inference is not None and i >= num_rows_for_inference: + break + + for j, col_index in enumerate(select_columns): + inferred_types[j] = _infer_type(csv_row[col_index], na_value, + inferred_types[j]) + + # Replace None's with a default type + inferred_types = [t or dtypes.string for t in inferred_types] + # Default to 0 or '' for null values + return [ + constant_op.constant([0 if t is not dtypes.string else ""], dtype=t) + for t in inferred_types + ] + + +def _infer_column_names(filenames, field_delim, use_quote_delim, file_io_fn): + """Infers column names from first rows of files.""" + csv_kwargs = { + "delimiter": field_delim, + "quoting": csv.QUOTE_MINIMAL if use_quote_delim else csv.QUOTE_NONE + } + with file_io_fn(filenames[0]) as f: + try: + column_names = next(csv.reader(f, **csv_kwargs)) + except StopIteration: + raise ValueError("Failed when reading the header line of " + f"{filenames[0]}. Is it an empty file?") + + for name in filenames[1:]: + with file_io_fn(name) as f: + try: + if next(csv.reader(f, **csv_kwargs)) != column_names: + raise ValueError( + "All input CSV files should have the same column names in the " + f"header row. File {name} has different column names.") + except StopIteration: + raise ValueError("Failed when reading the header line of " + f"{name}. Is it an empty file?") + return column_names + + +def _get_sorted_col_indices(select_columns, column_names): + """Transforms select_columns argument into sorted column indices.""" + names_to_indices = {n: i for i, n in enumerate(column_names)} + num_cols = len(column_names) + + results = [] + for v in select_columns: + # If value is already an int, check if it's valid. + if isinstance(v, int): + if v < 0 or v >= num_cols: + raise ValueError( + f"Column index {v} specified in `select_columns` should be > 0 " + f" and <= {num_cols}, which is the number of columns.") + results.append(v) + # Otherwise, check that it's a valid column name and convert to the + # the relevant column index. + elif v not in names_to_indices: + raise ValueError( + f"Column {v} specified in `select_columns` must be of one of the " + f"columns: {names_to_indices.keys()}.") + else: + results.append(names_to_indices[v]) + + # Sort and ensure there are no duplicates + results = sorted(set(results)) + if len(results) != len(select_columns): + sorted_names = sorted(results) + duplicate_columns = set([a for a, b in zip( + sorted_names[:-1], sorted_names[1:]) if a == b]) + raise ValueError("The `select_columns` argument contains duplicate " + f"columns: {duplicate_columns}.") + return results + + +def _maybe_shuffle_and_repeat( + dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed): + """Optionally shuffle and repeat dataset, as requested.""" + if shuffle: + dataset = dataset.shuffle(shuffle_buffer_size, shuffle_seed) + if num_epochs != 1: + dataset = dataset.repeat(num_epochs) + return dataset + + +def make_tf_record_dataset(file_pattern, + batch_size, + parser_fn=None, + num_epochs=None, + shuffle=True, + shuffle_buffer_size=None, + shuffle_seed=None, + prefetch_buffer_size=None, + num_parallel_reads=None, + num_parallel_parser_calls=None, + drop_final_batch=False): + """Reads and optionally parses TFRecord files into a dataset. + + Provides common functionality such as batching, optional parsing, shuffling, + and performant defaults. + + Args: + file_pattern: List of files or patterns of TFRecord file paths. + See `tf.io.gfile.glob` for pattern rules. + batch_size: An int representing the number of records to combine + in a single batch. + parser_fn: (Optional.) A function accepting string input to parse + and process the record contents. This function must map records + to components of a fixed shape, so they may be batched. By + default, uses the record contents unmodified. + num_epochs: (Optional.) An int specifying the number of times this + dataset is repeated. If None (the default), cycles through the + dataset forever. + shuffle: (Optional.) A bool that indicates whether the input + should be shuffled. Defaults to `True`. + shuffle_buffer_size: (Optional.) Buffer size to use for + shuffling. A large buffer size ensures better shuffling, but + increases memory usage and startup time. + shuffle_seed: (Optional.) Randomization seed to use for shuffling. + prefetch_buffer_size: (Optional.) An int specifying the number of + feature batches to prefetch for performance improvement. + Defaults to auto-tune. Set to 0 to disable prefetching. + num_parallel_reads: (Optional.) Number of threads used to read + records from files. By default or if set to a value >1, the + results will be interleaved. Defaults to `24`. + num_parallel_parser_calls: (Optional.) Number of parallel + records to parse in parallel. Defaults to `batch_size`. + drop_final_batch: (Optional.) Whether the last batch should be + dropped in case its size is smaller than `batch_size`; the + default behavior is not to drop the smaller batch. + + Returns: + A dataset, where each element matches the output of `parser_fn` + except it will have an additional leading `batch-size` dimension, + or a `batch_size`-length 1-D tensor of strings if `parser_fn` is + unspecified. + """ + if num_parallel_reads is None: + # NOTE: We considered auto-tuning this value, but there is a concern + # that this affects the mixing of records from different files, which + # could affect training convergence/accuracy, so we are defaulting to + # a constant for now. + num_parallel_reads = 24 + + if num_parallel_parser_calls is None: + # TODO(josh11b): if num_parallel_parser_calls is None, use some function + # of num cores instead of `batch_size`. + num_parallel_parser_calls = batch_size + + if prefetch_buffer_size is None: + prefetch_buffer_size = dataset_ops.AUTOTUNE + + files = dataset_ops.Dataset.list_files( + file_pattern, shuffle=shuffle, seed=shuffle_seed) + + dataset = core_readers.TFRecordDataset( + files, num_parallel_reads=num_parallel_reads) + + if shuffle_buffer_size is None: + # TODO(josh11b): Auto-tune this value when not specified + shuffle_buffer_size = 10000 + dataset = _maybe_shuffle_and_repeat( + dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed) + + # NOTE(mrry): We set `drop_final_batch=True` when `num_epochs is None` to + # improve the shape inference, because it makes the batch dimension static. + # It is safe to do this because in that case we are repeating the input + # indefinitely, and all batches will be full-sized. + drop_final_batch = drop_final_batch or num_epochs is None + + if parser_fn is None: + dataset = dataset.batch(batch_size, drop_remainder=drop_final_batch) + else: + dataset = dataset.map( + parser_fn, num_parallel_calls=num_parallel_parser_calls) + dataset = dataset.batch(batch_size, drop_remainder=drop_final_batch) + + if prefetch_buffer_size == 0: + return dataset + else: + return dataset.prefetch(buffer_size=prefetch_buffer_size) + + +@tf_export("data.experimental.make_csv_dataset", v1=[]) +def make_csv_dataset_v2( + file_pattern, + batch_size, + column_names=None, + column_defaults=None, + label_name=None, + select_columns=None, + field_delim=",", + use_quote_delim=True, + na_value="", + header=True, + num_epochs=None, # TODO(aaudibert): Change default to 1 when graduating. + shuffle=True, + shuffle_buffer_size=10000, + shuffle_seed=None, + prefetch_buffer_size=None, + num_parallel_reads=None, + sloppy=False, + num_rows_for_inference=100, + compression_type=None, + ignore_errors=False, + encoding="utf-8", +): + """Reads CSV files into a dataset. + + Reads CSV files into a dataset, where each element of the dataset is a + (features, labels) tuple that corresponds to a batch of CSV rows. The features + dictionary maps feature column names to `Tensor`s containing the corresponding + feature data, and labels is a `Tensor` containing the batch's label data. + + By default, the first rows of the CSV files are expected to be headers listing + the column names. If the first rows are not headers, set `header=False` and + provide the column names with the `column_names` argument. + + By default, the dataset is repeated indefinitely, reshuffling the order each + time. This behavior can be modified by setting the `num_epochs` and `shuffle` + arguments. + + For example, suppose you have a CSV file containing + + | Feature_A | Feature_B | + | --------- | --------- | + | 1 | "a" | + | 2 | "b" | + | 3 | "c" | + | 4 | "d" | + + ``` + # No label column specified + dataset = tf.data.experimental.make_csv_dataset(filename, batch_size=2) + iterator = dataset.as_numpy_iterator() + print(dict(next(iterator))) + # prints a dictionary of batched features: + # OrderedDict([('Feature_A', array([1, 4], dtype=int32)), + # ('Feature_B', array([b'a', b'd'], dtype=object))]) + ``` + + ``` + # Set Feature_B as label column + dataset = tf.data.experimental.make_csv_dataset( + filename, batch_size=2, label_name="Feature_B") + iterator = dataset.as_numpy_iterator() + print(next(iterator)) + # prints (features, labels) tuple: + # (OrderedDict([('Feature_A', array([1, 2], dtype=int32))]), + # array([b'a', b'b'], dtype=object)) + ``` + + See the + [Load CSV data guide](https://www.tensorflow.org/tutorials/load_data/csv) for + more examples of using `make_csv_dataset` to read CSV data. + + Args: + file_pattern: List of files or patterns of file paths containing CSV + records. See `tf.io.gfile.glob` for pattern rules. + batch_size: An int representing the number of records to combine + in a single batch. + column_names: An optional list of strings that corresponds to the CSV + columns, in order. One per column of the input record. If this is not + provided, infers the column names from the first row of the records. + These names will be the keys of the features dict of each dataset element. + column_defaults: A optional list of default values for the CSV fields. One + item per selected column of the input record. Each item in the list is + either a valid CSV dtype (float32, float64, int32, int64, or string), or a + `Tensor` with one of the aforementioned types. The tensor can either be + a scalar default value (if the column is optional), or an empty tensor (if + the column is required). If a dtype is provided instead of a tensor, the + column is also treated as required. If this list is not provided, tries + to infer types based on reading the first num_rows_for_inference rows of + files specified, and assumes all columns are optional, defaulting to `0` + for numeric values and `""` for string values. If both this and + `select_columns` are specified, these must have the same lengths, and + `column_defaults` is assumed to be sorted in order of increasing column + index. + label_name: A optional string corresponding to the label column. If + provided, the data for this column is returned as a separate `Tensor` from + the features dictionary, so that the dataset complies with the format + expected by a `tf.Estimator.train` or `tf.Estimator.evaluate` input + function. + select_columns: An optional list of integer indices or string column + names, that specifies a subset of columns of CSV data to select. If + column names are provided, these must correspond to names provided in + `column_names` or inferred from the file header lines. When this argument + is specified, only a subset of CSV columns will be parsed and returned, + corresponding to the columns specified. Using this results in faster + parsing and lower memory usage. If both this and `column_defaults` are + specified, these must have the same lengths, and `column_defaults` is + assumed to be sorted in order of increasing column index. + field_delim: An optional `string`. Defaults to `","`. Char delimiter to + separate fields in a record. + use_quote_delim: An optional bool. Defaults to `True`. If false, treats + double quotation marks as regular characters inside of the string fields. + na_value: Additional string to recognize as NA/NaN. + header: A bool that indicates whether the first rows of provided CSV files + correspond to header lines with column names, and should not be included + in the data. + num_epochs: An int specifying the number of times this dataset is repeated. + If None, cycles through the dataset forever. + shuffle: A bool that indicates whether the input should be shuffled. + shuffle_buffer_size: Buffer size to use for shuffling. A large buffer size + ensures better shuffling, but increases memory usage and startup time. + shuffle_seed: Randomization seed to use for shuffling. + prefetch_buffer_size: An int specifying the number of feature + batches to prefetch for performance improvement. Recommended value is the + number of batches consumed per training step. Defaults to auto-tune. + num_parallel_reads: Number of threads used to read CSV records from files. + If >1, the results will be interleaved. Defaults to `1`. + sloppy: If `True`, reading performance will be improved at + the cost of non-deterministic ordering. If `False`, the order of elements + produced is deterministic prior to shuffling (elements are still + randomized if `shuffle=True`. Note that if the seed is set, then order + of elements after shuffling is deterministic). Defaults to `False`. + num_rows_for_inference: Number of rows of a file to use for type inference + if record_defaults is not provided. If None, reads all the rows of all + the files. Defaults to 100. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. Defaults to no compression. + ignore_errors: (Optional.) If `True`, ignores errors with CSV file parsing, + such as malformed data or empty lines, and moves on to the next valid + CSV record. Otherwise, the dataset raises an error and stops processing + when encountering any invalid records. Defaults to `False`. + encoding: Encoding to use when reading. Defaults to `UTF-8`. + + Returns: + A dataset, where each element is a (features, labels) tuple that corresponds + to a batch of `batch_size` CSV rows. The features dictionary maps feature + column names to `Tensor`s containing the corresponding column data, and + labels is a `Tensor` containing the column data for the label column + specified by `label_name`. + + Raises: + ValueError: If any of the arguments is malformed. + """ + if num_parallel_reads is None: + num_parallel_reads = 1 + + if prefetch_buffer_size is None: + prefetch_buffer_size = dataset_ops.AUTOTUNE + + # Create dataset of all matching filenames + filenames = _get_file_names(file_pattern, False) + dataset = dataset_ops.Dataset.from_tensor_slices(filenames) + if shuffle: + dataset = dataset.shuffle(len(filenames), shuffle_seed) + + # Clean arguments; figure out column names and defaults + if column_names is None or column_defaults is None: + # Find out which io function to open the file + file_io_fn = lambda filename: file_io.FileIO( # pylint: disable=g-long-lambda + filename, "r", encoding=encoding) + if compression_type is not None: + compression_type_value = tensor_util.constant_value(compression_type) + if compression_type_value is None: + raise ValueError( + f"Received unknown `compression_type` {compression_type}. " + "Expected: GZIP, ZLIB or "" (empty string).") + if compression_type_value == "GZIP": + file_io_fn = lambda filename: gzip.open( # pylint: disable=g-long-lambda + filename, "rt", encoding=encoding) + elif compression_type_value == "ZLIB": + raise ValueError( + f"`compression_type` {compression_type} is not supported for " + "probing columns.") + elif compression_type_value != "": + raise ValueError( + f"Received unknown `compression_type` {compression_type}. " + "Expected: GZIP, ZLIB or " + " (empty string).") + if column_names is None: + if not header: + raise ValueError("Expected `column_names` or `header` arguments. Neither " + "is provided.") + # If column names are not provided, infer from the header lines + column_names = _infer_column_names(filenames, field_delim, use_quote_delim, + file_io_fn) + if len(column_names) != len(set(column_names)): + sorted_names = sorted(column_names) + duplicate_columns = set([a for a, b in zip( + sorted_names[:-1], sorted_names[1:]) if a == b]) + raise ValueError( + "Either `column_names` argument or CSV header row contains duplicate " + f"column names: {duplicate_columns}.") + + if select_columns is not None: + select_columns = _get_sorted_col_indices(select_columns, column_names) + + if column_defaults is not None: + column_defaults = [ + constant_op.constant([], dtype=x) + if not tensor_util.is_tf_type(x) and x in _ACCEPTABLE_CSV_TYPES else x + for x in column_defaults + ] + else: + # If column defaults are not provided, infer from records at graph + # construction time + column_defaults = _infer_column_defaults(filenames, len(column_names), + field_delim, use_quote_delim, + na_value, header, + num_rows_for_inference, + select_columns, file_io_fn) + + if select_columns is not None and len(column_defaults) != len(select_columns): + raise ValueError( + "If specified, `column_defaults` and `select_columns` must have the " + f"same length: `column_defaults` has length {len(column_defaults)}, " + f"`select_columns` has length {len(select_columns)}.") + if select_columns is not None and len(column_names) > len(select_columns): + # Pick the relevant subset of column names + column_names = [column_names[i] for i in select_columns] + + if label_name is not None and label_name not in column_names: + raise ValueError("`label_name` provided must be one of the columns: " + f"{column_names}. Received: {label_name}.") + + def filename_to_dataset(filename): + dataset = CsvDataset( + filename, + record_defaults=column_defaults, + field_delim=field_delim, + use_quote_delim=use_quote_delim, + na_value=na_value, + select_cols=select_columns, + header=header, + compression_type=compression_type + ) + if ignore_errors: + dataset = dataset.apply(error_ops.ignore_errors()) + return dataset + + def map_fn(*columns): + """Organizes columns into a features dictionary. + + Args: + *columns: list of `Tensor`s corresponding to one csv record. + Returns: + An OrderedDict of feature names to values for that particular record. If + label_name is provided, extracts the label feature to be returned as the + second element of the tuple. + """ + features = collections.OrderedDict(zip(column_names, columns)) + if label_name is not None: + label = features.pop(label_name) + return features, label + return features + + if num_parallel_reads == dataset_ops.AUTOTUNE: + dataset = dataset.interleave( + filename_to_dataset, num_parallel_calls=num_parallel_reads) + options = options_lib.Options() + options.deterministic = not sloppy + dataset = dataset.with_options(options) + else: + # Read files sequentially (if num_parallel_reads=1) or in parallel + def apply_fn(dataset): + return core_readers.ParallelInterleaveDataset( + dataset, + filename_to_dataset, + cycle_length=num_parallel_reads, + block_length=1, + sloppy=sloppy, + buffer_output_elements=None, + prefetch_input_elements=None) + + dataset = dataset.apply(apply_fn) + + dataset = _maybe_shuffle_and_repeat( + dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed) + + # Apply batch before map for perf, because map has high overhead relative + # to the size of the computation in each map. + # NOTE(mrry): We set `drop_remainder=True` when `num_epochs is None` to + # improve the shape inference, because it makes the batch dimension static. + # It is safe to do this because in that case we are repeating the input + # indefinitely, and all batches will be full-sized. + dataset = dataset.batch(batch_size=batch_size, + drop_remainder=num_epochs is None) + dataset = map_op._MapDataset( # pylint: disable=protected-access + dataset, map_fn, use_inter_op_parallelism=False) + dataset = dataset.prefetch(prefetch_buffer_size) + + return dataset + + +@tf_export(v1=["data.experimental.make_csv_dataset"]) +def make_csv_dataset_v1( + file_pattern, + batch_size, + column_names=None, + column_defaults=None, + label_name=None, + select_columns=None, + field_delim=",", + use_quote_delim=True, + na_value="", + header=True, + num_epochs=None, + shuffle=True, + shuffle_buffer_size=10000, + shuffle_seed=None, + prefetch_buffer_size=None, + num_parallel_reads=None, + sloppy=False, + num_rows_for_inference=100, + compression_type=None, + ignore_errors=False, + encoding="utf-8", +): # pylint: disable=missing-docstring + return dataset_ops.DatasetV1Adapter( + make_csv_dataset_v2(file_pattern, batch_size, column_names, + column_defaults, label_name, select_columns, + field_delim, use_quote_delim, na_value, header, + num_epochs, shuffle, shuffle_buffer_size, + shuffle_seed, prefetch_buffer_size, + num_parallel_reads, sloppy, num_rows_for_inference, + compression_type, ignore_errors, encoding)) +make_csv_dataset_v1.__doc__ = make_csv_dataset_v2.__doc__ + + +_DEFAULT_READER_BUFFER_SIZE_BYTES = 4 * 1024 * 1024 # 4 MB + + +@tf_export("data.experimental.CsvDataset", v1=[]) +class CsvDatasetV2(dataset_ops.DatasetSource): + r"""A Dataset comprising lines from one or more CSV files. + + The `tf.data.experimental.CsvDataset` class provides a minimal CSV Dataset + interface. There is also a richer `tf.data.experimental.make_csv_dataset` + function which provides additional convenience features such as column header + parsing, column type-inference, automatic shuffling, and file interleaving. + + The elements of this dataset correspond to records from the file(s). + RFC 4180 format is expected for CSV files + (https://tools.ietf.org/html/rfc4180) + Note that we allow leading and trailing spaces for int or float fields. + + For example, suppose we have a file 'my_file0.csv' with four CSV columns of + different data types: + + >>> with open('/tmp/my_file0.csv', 'w') as f: + ... f.write('abcdefg,4.28E10,5.55E6,12\n') + ... f.write('hijklmn,-5.3E14,,2\n') + + We can construct a CsvDataset from it as follows: + + >>> dataset = tf.data.experimental.CsvDataset( + ... "/tmp/my_file0.csv", + ... [tf.float32, # Required field, use dtype or empty tensor + ... tf.constant([0.0], dtype=tf.float32), # Optional field, default to 0.0 + ... tf.int32, # Required field, use dtype or empty tensor + ... ], + ... select_cols=[1,2,3] # Only parse last three columns + ... ) + + The expected output of its iterations is: + + >>> for element in dataset.as_numpy_iterator(): + ... print(element) + (4.28e10, 5.55e6, 12) + (-5.3e14, 0.0, 2) + + See + https://www.tensorflow.org/tutorials/load_data/csv#tfdataexperimentalcsvdataset + for more in-depth example usage. + """ + + def __init__(self, + filenames, + record_defaults, + compression_type=None, + buffer_size=None, + header=False, + field_delim=",", + use_quote_delim=True, + na_value="", + select_cols=None, + exclude_cols=None): + """Creates a `CsvDataset` by reading and decoding CSV files. + + Args: + filenames: A `tf.string` tensor containing one or more filenames. + record_defaults: A list of default values for the CSV fields. Each item in + the list is either a valid CSV `DType` (float32, float64, int32, int64, + string), or a `Tensor` object with one of the above types. One per + column of CSV data, with either a scalar `Tensor` default value for the + column if it is optional, or `DType` or empty `Tensor` if required. If + both this and `select_columns` are specified, these must have the same + lengths, and `column_defaults` is assumed to be sorted in order of + increasing column index. If both this and 'exclude_cols' are specified, + the sum of lengths of record_defaults and exclude_cols should equal + the total number of columns in the CSV file. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. Defaults to no + compression. + buffer_size: (Optional.) A `tf.int64` scalar denoting the number of bytes + to buffer while reading files. Defaults to 4MB. + header: (Optional.) A `tf.bool` scalar indicating whether the CSV file(s) + have header line(s) that should be skipped when parsing. Defaults to + `False`. + field_delim: (Optional.) A `tf.string` scalar containing the delimiter + character that separates fields in a record. Defaults to `","`. + use_quote_delim: (Optional.) A `tf.bool` scalar. If `False`, treats + double quotation marks as regular characters inside of string fields + (ignoring RFC 4180, Section 2, Bullet 5). Defaults to `True`. + na_value: (Optional.) A `tf.string` scalar indicating a value that will + be treated as NA/NaN. + select_cols: (Optional.) A sorted list of column indices to select from + the input data. If specified, only this subset of columns will be + parsed. Defaults to parsing all columns. At most one of `select_cols` + and `exclude_cols` can be specified. + exclude_cols: (Optional.) A sorted list of column indices to exclude from + the input data. If specified, only the complement of this set of column + will be parsed. Defaults to parsing all columns. At most one of + `select_cols` and `exclude_cols` can be specified. + + Raises: + InvalidArgumentError: If exclude_cols is not None and + len(exclude_cols) + len(record_defaults) does not match the total + number of columns in the file(s) + + + """ + self._filenames = ops.convert_to_tensor( + filenames, dtype=dtypes.string, name="filenames") + self._compression_type = convert.optional_param_to_tensor( + "compression_type", + compression_type, + argument_default="", + argument_dtype=dtypes.string) + record_defaults = [ + constant_op.constant([], dtype=x) + if not tensor_util.is_tf_type(x) and x in _ACCEPTABLE_CSV_TYPES else x + for x in record_defaults + ] + self._record_defaults = ops.convert_n_to_tensor( + record_defaults, name="record_defaults") + self._buffer_size = convert.optional_param_to_tensor( + "buffer_size", buffer_size, _DEFAULT_READER_BUFFER_SIZE_BYTES) + self._header = ops.convert_to_tensor( + header, dtype=dtypes.bool, name="header") + self._field_delim = ops.convert_to_tensor( + field_delim, dtype=dtypes.string, name="field_delim") + self._use_quote_delim = ops.convert_to_tensor( + use_quote_delim, dtype=dtypes.bool, name="use_quote_delim") + self._na_value = ops.convert_to_tensor( + na_value, dtype=dtypes.string, name="na_value") + self._select_cols = convert.optional_param_to_tensor( + "select_cols", + select_cols, + argument_default=[], + argument_dtype=dtypes.int64, + ) + self._exclude_cols = convert.optional_param_to_tensor( + "exclude_cols", + exclude_cols, + argument_default=[], + argument_dtype=dtypes.int64, + ) + self._element_spec = tuple( + tensor_spec.TensorSpec([], d.dtype) for d in self._record_defaults) + variant_tensor = gen_experimental_dataset_ops.csv_dataset_v2( + filenames=self._filenames, + record_defaults=self._record_defaults, + buffer_size=self._buffer_size, + header=self._header, + output_shapes=self._flat_shapes, + field_delim=self._field_delim, + use_quote_delim=self._use_quote_delim, + na_value=self._na_value, + select_cols=self._select_cols, + exclude_cols=self._exclude_cols, + compression_type=self._compression_type) + super(CsvDatasetV2, self).__init__(variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +@tf_export(v1=["data.experimental.CsvDataset"]) +class CsvDatasetV1(dataset_ops.DatasetV1Adapter): + """A Dataset comprising lines from one or more CSV files.""" + + @functools.wraps(CsvDatasetV2.__init__, ("__module__", "__name__")) + def __init__(self, + filenames, + record_defaults, + compression_type=None, + buffer_size=None, + header=False, + field_delim=",", + use_quote_delim=True, + na_value="", + select_cols=None): + """Creates a `CsvDataset` by reading and decoding CSV files. + + The elements of this dataset correspond to records from the file(s). + RFC 4180 format is expected for CSV files + (https://tools.ietf.org/html/rfc4180) + Note that we allow leading and trailing spaces with int or float field. + + + For example, suppose we have a file 'my_file0.csv' with four CSV columns of + different data types: + ``` + abcdefg,4.28E10,5.55E6,12 + hijklmn,-5.3E14,,2 + ``` + + We can construct a CsvDataset from it as follows: + + ```python + dataset = tf.data.experimental.CsvDataset( + "my_file*.csv", + [tf.float32, # Required field, use dtype or empty tensor + tf.constant([0.0], dtype=tf.float32), # Optional field, default to 0.0 + tf.int32, # Required field, use dtype or empty tensor + ], + select_cols=[1,2,3] # Only parse last three columns + ) + ``` + + The expected output of its iterations is: + + ```python + for element in dataset: + print(element) + + >> (4.28e10, 5.55e6, 12) + >> (-5.3e14, 0.0, 2) + ``` + + Args: + filenames: A `tf.string` tensor containing one or more filenames. + record_defaults: A list of default values for the CSV fields. Each item in + the list is either a valid CSV `DType` (float32, float64, int32, int64, + string), or a `Tensor` object with one of the above types. One per + column of CSV data, with either a scalar `Tensor` default value for the + column if it is optional, or `DType` or empty `Tensor` if required. If + both this and `select_columns` are specified, these must have the same + lengths, and `column_defaults` is assumed to be sorted in order of + increasing column index. If both this and 'exclude_cols' are specified, + the sum of lengths of record_defaults and exclude_cols should equal the + total number of columns in the CSV file. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. Defaults to no + compression. + buffer_size: (Optional.) A `tf.int64` scalar denoting the number of bytes + to buffer while reading files. Defaults to 4MB. + header: (Optional.) A `tf.bool` scalar indicating whether the CSV file(s) + have header line(s) that should be skipped when parsing. Defaults to + `False`. + field_delim: (Optional.) A `tf.string` scalar containing the delimiter + character that separates fields in a record. Defaults to `","`. + use_quote_delim: (Optional.) A `tf.bool` scalar. If `False`, treats double + quotation marks as regular characters inside of string fields (ignoring + RFC 4180, Section 2, Bullet 5). Defaults to `True`. + na_value: (Optional.) A `tf.string` scalar indicating a value that will be + treated as NA/NaN. + select_cols: (Optional.) A sorted list of column indices to select from + the input data. If specified, only this subset of columns will be + parsed. Defaults to parsing all columns. At most one of `select_cols` + and `exclude_cols` can be specified. + """ + wrapped = CsvDatasetV2(filenames, record_defaults, compression_type, + buffer_size, header, field_delim, use_quote_delim, + na_value, select_cols) + super(CsvDatasetV1, self).__init__(wrapped) + + +@tf_export("data.experimental.make_batched_features_dataset", v1=[]) +def make_batched_features_dataset_v2(file_pattern, + batch_size, + features, + reader=None, + label_key=None, + reader_args=None, + num_epochs=None, + shuffle=True, + shuffle_buffer_size=10000, + shuffle_seed=None, + prefetch_buffer_size=None, + reader_num_threads=None, + parser_num_threads=None, + sloppy_ordering=False, + drop_final_batch=False): + """Returns a `Dataset` of feature dictionaries from `Example` protos. + + If label_key argument is provided, returns a `Dataset` of tuple + comprising of feature dictionaries and label. + + Example: + + ``` + serialized_examples = [ + features { + feature { key: "age" value { int64_list { value: [ 0 ] } } } + feature { key: "gender" value { bytes_list { value: [ "f" ] } } } + feature { key: "kws" value { bytes_list { value: [ "code", "art" ] } } } + }, + features { + feature { key: "age" value { int64_list { value: [] } } } + feature { key: "gender" value { bytes_list { value: [ "f" ] } } } + feature { key: "kws" value { bytes_list { value: [ "sports" ] } } } + } + ] + ``` + + We can use arguments: + + ``` + features: { + "age": FixedLenFeature([], dtype=tf.int64, default_value=-1), + "gender": FixedLenFeature([], dtype=tf.string), + "kws": VarLenFeature(dtype=tf.string), + } + ``` + + And the expected output is: + + ```python + { + "age": [[0], [-1]], + "gender": [["f"], ["f"]], + "kws": SparseTensor( + indices=[[0, 0], [0, 1], [1, 0]], + values=["code", "art", "sports"] + dense_shape=[2, 2]), + } + ``` + + Args: + file_pattern: List of files or patterns of file paths containing + `Example` records. See `tf.io.gfile.glob` for pattern rules. + batch_size: An int representing the number of records to combine + in a single batch. + features: A `dict` mapping feature keys to `FixedLenFeature` or + `VarLenFeature` values. See `tf.io.parse_example`. + reader: A function or class that can be + called with a `filenames` tensor and (optional) `reader_args` and returns + a `Dataset` of `Example` tensors. Defaults to `tf.data.TFRecordDataset`. + label_key: (Optional) A string corresponding to the key labels are stored in + `tf.Examples`. If provided, it must be one of the `features` key, + otherwise results in `ValueError`. + reader_args: Additional arguments to pass to the reader class. + num_epochs: Integer specifying the number of times to read through the + dataset. If None, cycles through the dataset forever. Defaults to `None`. + shuffle: A boolean, indicates whether the input should be shuffled. Defaults + to `True`. + shuffle_buffer_size: Buffer size of the ShuffleDataset. A large capacity + ensures better shuffling but would increase memory usage and startup time. + shuffle_seed: Randomization seed to use for shuffling. + prefetch_buffer_size: Number of feature batches to prefetch in order to + improve performance. Recommended value is the number of batches consumed + per training step. Defaults to auto-tune. + reader_num_threads: Number of threads used to read `Example` records. If >1, + the results will be interleaved. Defaults to `1`. + parser_num_threads: Number of threads to use for parsing `Example` tensors + into a dictionary of `Feature` tensors. Defaults to `2`. + sloppy_ordering: If `True`, reading performance will be improved at + the cost of non-deterministic ordering. If `False`, the order of elements + produced is deterministic prior to shuffling (elements are still + randomized if `shuffle=True`. Note that if the seed is set, then order + of elements after shuffling is deterministic). Defaults to `False`. + drop_final_batch: If `True`, and the batch size does not evenly divide the + input dataset size, the final smaller batch will be dropped. Defaults to + `False`. + + Returns: + A dataset of `dict` elements, (or a tuple of `dict` elements and label). + Each `dict` maps feature keys to `Tensor` or `SparseTensor` objects. + + Raises: + TypeError: If `reader` is of the wrong type. + ValueError: If `label_key` is not one of the `features` keys. + """ + if reader is None: + reader = core_readers.TFRecordDataset + + if reader_num_threads is None: + reader_num_threads = 1 + if parser_num_threads is None: + parser_num_threads = 2 + if prefetch_buffer_size is None: + prefetch_buffer_size = dataset_ops.AUTOTUNE + + # Create dataset of all matching filenames + dataset = dataset_ops.Dataset.list_files( + file_pattern, shuffle=shuffle, seed=shuffle_seed) + + if isinstance(reader, type) and issubclass(reader, io_ops.ReaderBase): + raise TypeError("The `reader` argument must return a `Dataset` object. " + "`tf.ReaderBase` subclasses are not supported. For " + "example, pass `tf.data.TFRecordDataset` instead of " + "`tf.TFRecordReader`.") + + # Read `Example` records from files as tensor objects. + if reader_args is None: + reader_args = [] + + if reader_num_threads == dataset_ops.AUTOTUNE: + dataset = dataset.interleave( + lambda filename: reader(filename, *reader_args), + num_parallel_calls=reader_num_threads) + options = options_lib.Options() + options.deterministic = not sloppy_ordering + dataset = dataset.with_options(options) + else: + # Read files sequentially (if reader_num_threads=1) or in parallel + def apply_fn(dataset): + return core_readers.ParallelInterleaveDataset( + dataset, + lambda filename: reader(filename, *reader_args), + cycle_length=reader_num_threads, + block_length=1, + sloppy=sloppy_ordering, + buffer_output_elements=None, + prefetch_input_elements=None) + + dataset = dataset.apply(apply_fn) + + # Extract values if the `Example` tensors are stored as key-value tuples. + if dataset_ops.get_legacy_output_types(dataset) == ( + dtypes.string, dtypes.string): + dataset = map_op._MapDataset( # pylint: disable=protected-access + dataset, lambda _, v: v, use_inter_op_parallelism=False) + + # Apply dataset repeat and shuffle transformations. + dataset = _maybe_shuffle_and_repeat( + dataset, num_epochs, shuffle, shuffle_buffer_size, shuffle_seed) + + # NOTE(mrry): We set `drop_remainder=True` when `num_epochs is None` to + # improve the shape inference, because it makes the batch dimension static. + # It is safe to do this because in that case we are repeating the input + # indefinitely, and all batches will be full-sized. + dataset = dataset.batch( + batch_size, drop_remainder=drop_final_batch or num_epochs is None) + + # Parse `Example` tensors to a dictionary of `Feature` tensors. + dataset = dataset.apply( + parsing_ops.parse_example_dataset( + features, num_parallel_calls=parser_num_threads)) + + if label_key: + if label_key not in features: + raise ValueError( + f"The `label_key` provided ({label_key}) must be one of the " + f"`features` keys: {features.keys()}.") + dataset = dataset.map(lambda x: (x, x.pop(label_key))) + + dataset = dataset.prefetch(prefetch_buffer_size) + return dataset + + +@tf_export(v1=["data.experimental.make_batched_features_dataset"]) +def make_batched_features_dataset_v1(file_pattern, # pylint: disable=missing-docstring + batch_size, + features, + reader=None, + label_key=None, + reader_args=None, + num_epochs=None, + shuffle=True, + shuffle_buffer_size=10000, + shuffle_seed=None, + prefetch_buffer_size=None, + reader_num_threads=None, + parser_num_threads=None, + sloppy_ordering=False, + drop_final_batch=False): + return dataset_ops.DatasetV1Adapter(make_batched_features_dataset_v2( + file_pattern, batch_size, features, reader, label_key, reader_args, + num_epochs, shuffle, shuffle_buffer_size, shuffle_seed, + prefetch_buffer_size, reader_num_threads, parser_num_threads, + sloppy_ordering, drop_final_batch)) +make_batched_features_dataset_v1.__doc__ = ( + make_batched_features_dataset_v2.__doc__) + + +def _get_file_names(file_pattern, shuffle): + """Parse list of file names from pattern, optionally shuffled. + + Args: + file_pattern: File glob pattern, or list of glob patterns. + shuffle: Whether to shuffle the order of file names. + + Returns: + List of file names matching `file_pattern`. + + Raises: + ValueError: If `file_pattern` is empty, or pattern matches no files. + """ + if isinstance(file_pattern, list): + if not file_pattern: + raise ValueError("Argument `file_pattern` should not be empty.") + file_names = [] + for entry in file_pattern: + file_names.extend(gfile.Glob(entry)) + else: + file_names = list(gfile.Glob(file_pattern)) + + if not file_names: + raise ValueError(f"No files match `file_pattern` {file_pattern}.") + + # Sort files so it will be deterministic for unit tests. + if not shuffle: + file_names = sorted(file_names) + return file_names + + +@tf_export("data.experimental.SqlDataset", v1=[]) +class SqlDatasetV2(dataset_ops.DatasetSource): + """A `Dataset` consisting of the results from a SQL query. + + `SqlDataset` allows a user to read data from the result set of a SQL query. + For example: + + ```python + dataset = tf.data.experimental.SqlDataset("sqlite", "/foo/bar.sqlite3", + "SELECT name, age FROM people", + (tf.string, tf.int32)) + # Prints the rows of the result set of the above query. + for element in dataset: + print(element) + ``` + """ + + def __init__(self, driver_name, data_source_name, query, output_types): + """Creates a `SqlDataset`. + + Args: + driver_name: A 0-D `tf.string` tensor containing the database type. + Currently, the only supported value is 'sqlite'. + data_source_name: A 0-D `tf.string` tensor containing a connection string + to connect to the database. + query: A 0-D `tf.string` tensor containing the SQL query to execute. + output_types: A tuple of `tf.DType` objects representing the types of the + columns returned by `query`. + """ + self._driver_name = ops.convert_to_tensor( + driver_name, dtype=dtypes.string, name="driver_name") + self._data_source_name = ops.convert_to_tensor( + data_source_name, dtype=dtypes.string, name="data_source_name") + self._query = ops.convert_to_tensor( + query, dtype=dtypes.string, name="query") + self._element_spec = nest.map_structure( + lambda dtype: tensor_spec.TensorSpec([], dtype), output_types) + variant_tensor = gen_experimental_dataset_ops.sql_dataset( + self._driver_name, self._data_source_name, self._query, + **self._flat_structure) + super(SqlDatasetV2, self).__init__(variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +@tf_export(v1=["data.experimental.SqlDataset"]) +class SqlDatasetV1(dataset_ops.DatasetV1Adapter): + """A `Dataset` consisting of the results from a SQL query.""" + + @functools.wraps(SqlDatasetV2.__init__) + def __init__(self, driver_name, data_source_name, query, output_types): + wrapped = SqlDatasetV2(driver_name, data_source_name, query, output_types) + super(SqlDatasetV1, self).__init__(wrapped) + + +if tf2.enabled(): + CsvDataset = CsvDatasetV2 + SqlDataset = SqlDatasetV2 + make_batched_features_dataset = make_batched_features_dataset_v2 + make_csv_dataset = make_csv_dataset_v2 +else: + CsvDataset = CsvDatasetV1 + SqlDataset = SqlDatasetV1 + make_batched_features_dataset = make_batched_features_dataset_v1 + make_csv_dataset = make_csv_dataset_v1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/resampling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/resampling.py new file mode 100644 index 0000000000000000000000000000000000000000..e233adc9b22c4398d7a8beae60c358df0f7d7c2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/resampling.py @@ -0,0 +1,50 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Resampling dataset transformations.""" +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.rejection_resample(...)`.") +@tf_export("data.experimental.rejection_resample") +def rejection_resample(class_func, target_dist, initial_dist=None, seed=None): + """A transformation that resamples a dataset to achieve a target distribution. + + **NOTE** Resampling is performed via rejection sampling; some fraction + of the input values will be dropped. + + Args: + class_func: A function mapping an element of the input dataset to a scalar + `tf.int32` tensor. Values should be in `[0, num_classes)`. + target_dist: A floating point type tensor, shaped `[num_classes]`. + initial_dist: (Optional.) A floating point type tensor, shaped + `[num_classes]`. If not provided, the true class distribution is + estimated live in a streaming fashion. + seed: (Optional.) Python integer seed for the resampler. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + + return dataset.rejection_resample( + class_func=class_func, + target_dist=target_dist, + initial_dist=initial_dist, + seed=seed) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/scan_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/scan_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..85eba7551a75f8dd5e2b620f4a1be22dd7b60c8e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/scan_ops.py @@ -0,0 +1,45 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Scan dataset transformation.""" +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.scan(...) instead") +@tf_export("data.experimental.scan") +def scan(initial_state, scan_func): + """A transformation that scans a function across an input dataset. + + This transformation is a stateful relative of `tf.data.Dataset.map`. + In addition to mapping `scan_func` across the elements of the input dataset, + `scan()` accumulates one or more state tensors, whose initial values are + `initial_state`. + + Args: + initial_state: A nested structure of tensors, representing the initial state + of the accumulator. + scan_func: A function that maps `(old_state, input_element)` to + `(new_state, output_element)`. It must take two arguments and return a + pair of nested structures of tensors. The `new_state` must match the + structure of `initial_state`. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + def _apply_fn(dataset): + return dataset.scan(initial_state=initial_state, scan_func=scan_func) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/shuffle_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/shuffle_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..ba4d36578020df20d75eb5da9ffcdf629aba9f0f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/shuffle_ops.py @@ -0,0 +1,272 @@ +# 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. +# ============================================================================== +"""Experimental shuffle ops.""" + +import functools +import numpy as np + +from tensorflow.python.data.experimental.ops import random_access +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import random_seed +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +class _ShuffleAndRepeatDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that fuses `shuffle` and `repeat`.""" + + def __init__(self, input_dataset, buffer_size, count=None, seed=None): + self._input_dataset = input_dataset + self._buffer_size = ops.convert_to_tensor( + buffer_size, dtype=dtypes.int64, name="buffer_size") + if count is None: + self._count = constant_op.constant(-1, dtype=dtypes.int64, name="count") + else: + self._count = ops.convert_to_tensor( + count, dtype=dtypes.int64, name="count") + self._seed, self._seed2 = random_seed.get_seed(seed) + variant_tensor = gen_dataset_ops.shuffle_and_repeat_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + buffer_size=self._buffer_size, + count=self._count, + seed=self._seed, + seed2=self._seed2, + **self._flat_structure) + super(_ShuffleAndRepeatDataset, self).__init__(input_dataset, + variant_tensor) + + +@deprecation.deprecated( + None, "Use `tf.data.Dataset.shuffle(buffer_size, seed)` followed by " + "`tf.data.Dataset.repeat(count)`. Static tf.data optimizations will take " + "care of using the fused implementation.") +@tf_export("data.experimental.shuffle_and_repeat") +def shuffle_and_repeat(buffer_size, count=None, seed=None): + """Shuffles and repeats a Dataset, reshuffling with each repetition. + + >>> d = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> d = d.apply(tf.data.experimental.shuffle_and_repeat(2, count=2)) + >>> [elem.numpy() for elem in d] # doctest: +SKIP + [2, 3, 1, 1, 3, 2] + + ```python + dataset.apply( + tf.data.experimental.shuffle_and_repeat(buffer_size, count, seed)) + ``` + + produces the same output as + + ```python + dataset.shuffle( + buffer_size, seed=seed, reshuffle_each_iteration=True).repeat(count) + ``` + + In each repetition, this dataset fills a buffer with `buffer_size` elements, + then randomly samples elements from this buffer, replacing the selected + elements with new elements. For perfect shuffling, set the buffer size equal + to the full size of the dataset. + + For instance, if your dataset contains 10,000 elements but `buffer_size` is + set to 1,000, then `shuffle` will initially select a random element from + only the first 1,000 elements in the buffer. Once an element is selected, + its space in the buffer is replaced by the next (i.e. 1,001-st) element, + maintaining the 1,000 element buffer. + + Args: + buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the maximum + number elements that will be buffered when prefetching. + count: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the number + of times the dataset should be repeated. The default behavior (if `count` + is `None` or `-1`) is for the dataset be repeated indefinitely. + seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random + seed that will be used to create the distribution. See + `tf.random.set_seed` for behavior. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): # pylint: disable=missing-docstring + return _ShuffleAndRepeatDataset(dataset, buffer_size, count, seed) + + return _apply_fn + + +def _process_file_infos(file_infos): + """Computes aggregate information about files to read. + + The method collects information about the files to read, the total number of + elements, and arrays that can be used to account for elements to be skipped, + which can be specified via the "skip" and "take" keys. + + To account for elements to skip, the range of each file can be divided into + three regions: + - S (elements to skip) + - T (elements to read) + - R (remainder of elements that will also be skipped) + + The `thresholds` and `offsets` arrays are initialized as follows: + `thresholds = [0, T_1, T_1 + T_2, ...]` and + `offsets = [S_1, S_1 + R_1 + S_2, S_1 + R_1 + S_2 + R_2 + S_3, ...]` + + This makes it possible to map an index from a contiguous range + `(0...num_elements_to_read)` to an index in the range of all elements, + skipping over elements as per the "skip" and "take" keys values. In + particular, for a given input index `X`, we find the greatest `thresholds` + value that is smaller or equal to `X`. Let `t(X)` denotes such index in the + `thresholds` array. The output index is computed as `X + offsets[t(X)]`. + + Args: + file_infos: See `file_infos` argument of `index_shuffle` for details. + + Returns: + A dictionary containing the following keys: + - `files`, the vector of pathnames of files to read + - `num_elements`, an integer identifying the total number of elements + - `offsets`, the vector of offsets to use for index adjustment (in case + any elements should be skipped) + - `thresholds`, the vector of thresholds to use for index adjustment (in + case any elements should be skipped) + """ + files = [] + num_elements = 0 + offsets = np.int64([]) + offset_sum = 0 + thresholds = np.int64([]) + threshold_sum = 0 + adjustment_needed = False + for file_info in file_infos: + files.append(file_info["path"]) + skip = 0 + if "skip" in file_info: + if file_info["skip"] < -1: + raise ValueError("`skip` should be greater than `-1` but got {}".format( + file_info["skip"])) + if file_info["skip"] == -1: + skip = file_info["num_elements"] + else: + skip = min(file_info["skip"], file_info["num_elements"]) + take = file_info["num_elements"] - skip + if "take" in file_info: + if file_info["take"] < -1: + raise ValueError("`take` should be greater than `-1` but got {}".format( + file_info["take"])) + # `file_info["take"] == -1` is a no-op + if file_info["take"] != -1: + take = min(file_info["take"], take) + remainder = file_info["num_elements"] - skip - take + if take != file_info["num_elements"]: + adjustment_needed = True + num_elements += take + offsets = np.append(offsets, offset_sum + skip) + offset_sum += skip + remainder + thresholds = np.append(thresholds, threshold_sum) + threshold_sum += take + result = {"files": files, "num_elements": num_elements} + if adjustment_needed: + result["offsets"] = offsets + result["thresholds"] = thresholds + return result + + +def _adjust_index(index, thresholds, offsets): + """Adjusts index to account for elements to be skipped.""" + t_index = array_ops.shape( + array_ops.boolean_mask( + thresholds, + math_ops.less_equal(thresholds, index)))[0] - 1 + return index + array_ops.gather(offsets, t_index) + + +# TODO(jsimsa): Expose this method in the public API. When we do, consider +# defining `FileInfo` as a public API to encapsulate the information provided +# through the `file_infos` argument. +def index_shuffle(file_infos, + reader_factory, + seed=None, + reshuffle_each_iteration=False, + num_parallel_calls=dataset_ops.AUTOTUNE): + """Creates a (globally) shuffled dataset from the given set of files. + + Unlike `tf.data.Dataset.shuffle()`, which uses an in-memory buffer to shuffle + elements of input dataset in a streaming fashion, + `tf.data.experimental.index_shuffle()` performs a global shuffle of element + indices and then reads the data in a shuffled order. The advantage of + `index_shuffle()` is that it can perform global shuffle of datasets that do + not fit into memory (as long as the array of their indices does) and that the + shuffling logic it provides is compatible with symbolic checkpointing. The + disadvantage of `index_shuffle()` is that reading data in a shuffled random + order will in general not be as efficient as reading data sequentially. + + Args: + file_infos: A list of dictionaries that describe each file of the input + dataset. Each dictionary is expected to contain the "path" key, which + identifies the path of the file and the "num_elements" key, which + identifies the number of elements in the file. In addition, the "skip" + and "take" keys can be used to identify the number of elements to skip + and take respectively. By default, no elements are skipped and all + elements are taken. + reader_factory: A function that maps a sequence of filenames to an instance + of `tf.data.Dataset` that reads data from the files. + seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random + seed that will be used to shuffle the order of elements. Default to + non-deterministic seed. + reshuffle_each_iteration: (Optional.) A `tf.bool` scalar `tf.Tensor`, that + determines whether to change the shuffle order each iteration. Defaults to + `False`. + num_parallel_calls: (Optional.) A `tf.int64` scalar `tf.Tensor`, that + determines the maximum number of random access operations to perform + in parallel. By default, the tf.data runtime uses autotuning to determine + the value dynamically. + + Returns: + A `tf.data.Dataset` object, representing a globally shuffled dataset of + the input data. + """ + + result = _process_file_infos(file_infos) + + def sequential_index_shuffle(seeds): + dataset = dataset_ops.Dataset.range(result["num_elements"]) + + def read_element(dataset, index): + # 1) Shuffle the index. + shuffled_index = stateless_random_ops.index_shuffle( + index, seeds, result["num_elements"] - 1) + # 2) If needed, adjust the index to the non-contiguous range. + if "thresholds" in result and "offsets" in result: + shuffled_index = _adjust_index(shuffled_index, result["thresholds"], + result["offsets"]) + # 3) Perform the read. + return random_access.at(dataset, shuffled_index) + + # We evaluate `reader_factory()` eagerly to prevent the dataset from being + # created on every lookup. + map_func = functools.partial(read_element, reader_factory(result["files"])) + return dataset.map(map_func, num_parallel_calls=num_parallel_calls) + + rng_ds = dataset_ops.Dataset.random( + seed=seed, + rerandomize_each_iteration=reshuffle_each_iteration) + rng_ds = rng_ds.take(2).batch(2, drop_remainder=True) + return rng_ds.flat_map(sequential_index_shuffle) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/snapshot.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..204e6b9c29010a41fc990f5b64bc47d475886448 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/snapshot.py @@ -0,0 +1,276 @@ +# 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. +# ============================================================================== +"""Dataset snapshot and related functionality.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +COMPRESSION_GZIP = "GZIP" +COMPRESSION_SNAPPY = "SNAPPY" +COMPRESSION_NONE = None + + +class _LegacySnapshotDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A Dataset that captures a snapshot or reads from a snapshot.""" + + def __init__(self, + input_dataset, + path, + compression=None, + reader_path_prefix=None, + writer_path_prefix=None, + shard_size_bytes=None, + pending_snapshot_expiry_seconds=None, + num_reader_threads=None, + reader_buffer_size=None, + num_writer_threads=None, + writer_buffer_size=None, + shuffle_on_read=None, + shuffle_seed=None, + mode=None, + snapshot_name=None): + + self._compression = compression if compression is not None else "" + self._reader_path_prefix = ( + reader_path_prefix if reader_path_prefix is not None else "") + self._writer_path_prefix = ( + writer_path_prefix if writer_path_prefix is not None else "") + self._shard_size_bytes = ( + shard_size_bytes if shard_size_bytes is not None else -1) + self._pending_snapshot_expiry_seconds = ( + pending_snapshot_expiry_seconds + if pending_snapshot_expiry_seconds is not None else -1) + self._num_reader_threads = ( + num_reader_threads if num_reader_threads is not None else -1) + self._reader_buffer_size = ( + reader_buffer_size if reader_buffer_size is not None else -1) + self._num_writer_threads = ( + num_writer_threads if num_writer_threads is not None else -1) + self._writer_buffer_size = ( + writer_buffer_size if writer_buffer_size is not None else -1) + self._shuffle_on_read = ( + shuffle_on_read if shuffle_on_read is not None else False) + self._mode = (mode if mode is not None else "auto") + self._snapshot_name = (snapshot_name if snapshot_name is not None else "") + + self._seed, self._seed2 = random_seed.get_seed(shuffle_seed) + + self._input_dataset = input_dataset + self._path = ops.convert_to_tensor(path, dtype=dtypes.string, name="path") + + variant_tensor = ged_ops.snapshot_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + path=self._path, + compression=self._compression, + reader_path_prefix=self._reader_path_prefix, + writer_path_prefix=self._writer_path_prefix, + shard_size_bytes=self._shard_size_bytes, + pending_snapshot_expiry_seconds=self._pending_snapshot_expiry_seconds, + num_reader_threads=self._num_reader_threads, + reader_buffer_size=self._reader_buffer_size, + num_writer_threads=self._num_writer_threads, + writer_buffer_size=self._writer_buffer_size, + shuffle_on_read=self._shuffle_on_read, + seed=self._seed, + seed2=self._seed2, + mode=self._mode, + snapshot_name=self._snapshot_name, + **self._flat_structure) + + super(_LegacySnapshotDataset, self).__init__(input_dataset, variant_tensor) + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.shapshot(...)` instead.") +def legacy_snapshot(path, + compression=None, + reader_path_prefix=None, + writer_path_prefix=None, + shard_size_bytes=None, + pending_snapshot_expiry_seconds=None, + num_reader_threads=None, + reader_buffer_size=None, + num_writer_threads=None, + writer_buffer_size=None, + shuffle_on_read=None, + shuffle_seed=None, + mode=None, + snapshot_name=None): + """Writes to/reads from a snapshot of a dataset. + + This function attempts to determine whether a valid snapshot exists at the + `path`, and reads from the snapshot if so. If not, it will run the + preprocessing pipeline as usual, and write out a snapshot of the data + processed for future use. + + Args: + path: A directory where we want to save our snapshots and/or read from a + previously saved snapshot. + compression: The type of compression to apply to the Dataset. Currently + supports "GZIP" or None. Defaults to None (no compression). + reader_path_prefix: A prefix to add to the path when reading from snapshots. + Defaults to None. + writer_path_prefix: A prefix to add to the path when writing to snapshots. + Defaults to None. + shard_size_bytes: The size of each shard to be written by the snapshot + dataset op. Defaults to 10 GiB. + pending_snapshot_expiry_seconds: How long to wait (in seconds) before the + snapshot op considers a previously unfinished snapshot to be stale. + num_reader_threads: Number of threads to parallelize reading from snapshot. + Especially useful if compression is turned on since the decompression + operation tends to be intensive. Defaults to 1. If > 1, then this might + introduce non-determinism i.e. the order in which the elements are read + from the snapshot are different from the order they're written. + reader_buffer_size: Maximum number of elements we can prefetch reading from + the snapshot. Defaults to 1. Increasing this might improve performance but + will increase memory consumption. + num_writer_threads: Number of threads to parallelize writing from snapshot. + We'll open up `num_writer_threads` files and write to them in parallel. + Especially useful if compression is turned on since the compression + operation tends to be intensive. Defaults to 1. If > 1, then this might + introduce non-determinism i.e. the order in which the elements are read + from the upstream iterator are different from the order they're written. + writer_buffer_size: Maximum number of pipeline elements to fill up the + buffer before writing them out using `num_writer_threads`. + shuffle_on_read: If this is True, then the order in which examples are + produced when reading from a snapshot will be random. Defaults to False. + shuffle_seed: Optional. If shuffle_seed is set, the random number generator + used for shuffling (when shuffle_on_read is turned on) is seeded by the + given seed. Otherwise, it is seeded by a random seed that differs for + every run. + mode: The mode at which snapshot should operate. Valid options are "auto", + "read", "write", and "passthrough". The default mode is "auto", where the + snapshot op will automatically determine what mode to operate in. + snapshot_name: If set, use the supplied string as a named snapshot name + instead of introspecting the data pipeline and automatically generating a + unique identifier for the snapshot. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return _LegacySnapshotDataset( + input_dataset=dataset, + path=path, + compression=compression, + reader_path_prefix=reader_path_prefix, + writer_path_prefix=writer_path_prefix, + shard_size_bytes=shard_size_bytes, + pending_snapshot_expiry_seconds=pending_snapshot_expiry_seconds, + num_reader_threads=num_reader_threads, + reader_buffer_size=reader_buffer_size, + num_writer_threads=num_writer_threads, + writer_buffer_size=writer_buffer_size, + shuffle_on_read=shuffle_on_read, + shuffle_seed=shuffle_seed, + mode=mode, + snapshot_name=snapshot_name) + + return _apply_fn + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.snapshot(...)`.") +@tf_export("data.experimental.snapshot") +def snapshot(path, compression="AUTO", reader_func=None, shard_func=None): + """API to persist the output of the input dataset. + + The snapshot API allows users to transparently persist the output of their + preprocessing pipeline to disk, and materialize the pre-processed data on a + different training run. + + This API enables repeated preprocessing steps to be consolidated, and allows + re-use of already processed data, trading off disk storage and network + bandwidth for freeing up more valuable CPU resources and accelerator compute + time. + + https://github.com/tensorflow/community/blob/master/rfcs/20200107-tf-data-snapshot.md + has detailed design documentation of this feature. + + Users can specify various options to control the behavior of snapshot, + including how snapshots are read from and written to by passing in + user-defined functions to the `reader_func` and `shard_func` parameters. + + `shard_func` is a user specified function that maps input elements to snapshot + shards. + + Users may want to specify this function to control how snapshot files should + be written to disk. Below is an example of how a potential shard_func could + be written. + + ```python + dataset = ... + dataset = dataset.enumerate() + dataset = dataset.apply(tf.data.Dataset.shapshot("/path/to/snapshot/dir", + shard_func=lambda x, y: x % NUM_SHARDS, ...)) + dataset = dataset.map(lambda x, y: y) + ``` + + `reader_func` is a user specified function that accepts a single argument: + (1) a Dataset of Datasets, each representing a "split" of elements of the + original dataset. The cardinality of the input dataset matches the + number of the shards specified in the `shard_func` (see above). The function + should return a Dataset of elements of the original dataset. + + Users may want specify this function to control how snapshot files should be + read from disk, including the amount of shuffling and parallelism. + + Here is an example of a standard reader function a user can define. This + function enables both dataset shuffling and parallel reading of datasets: + + ```python + def user_reader_func(datasets): + # shuffle the datasets splits + datasets = datasets.shuffle(NUM_CORES) + # read datasets in parallel and interleave their elements + return datasets.interleave(lambda x: x, num_parallel_calls=AUTOTUNE) + + dataset = dataset.apply(tf.data.Dataset.shapshot("/path/to/snapshot/dir", + reader_func=user_reader_func)) + ``` + + By default, snapshot parallelizes reads by the number of cores available on + the system, but will not attempt to shuffle the data. + + Args: + path: Required. A directory to use for storing / loading the snapshot to / + from. + compression: Optional. The type of compression to apply to the snapshot + written to disk. Supported options are `GZIP`, `SNAPPY`, `AUTO` or None. + Defaults to AUTO, which attempts to pick an appropriate compression + algorithm for the dataset. + reader_func: Optional. A function to control how to read data from snapshot + shards. + shard_func: Optional. A function to control how to shard data when writing a + snapshot. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + """Actual dataset transformation.""" + return dataset.snapshot( + path=path, + compression=compression, + reader_func=reader_func, + shard_func=shard_func) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/take_while_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/take_while_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..08324782dbfaae3ced6d11e44d2378fa71f4610d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/take_while_ops.py @@ -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. +# ============================================================================== +"""take-while dataset transformation.""" +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.take_while(...)") +@tf_export("data.experimental.take_while") +def take_while(predicate): + """A transformation that stops dataset iteration based on a `predicate`. + + Args: + predicate: A function that maps a nested structure of tensors (having shapes + and types defined by `self.output_shapes` and `self.output_types`) to a + scalar `tf.bool` tensor. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return dataset.take_while(predicate=predicate) + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/testing.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..e164bbac1cb7286967aad39157694387fd7edbd2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/testing.py @@ -0,0 +1,198 @@ +# 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. +# ============================================================================== +"""Experimental API for testing of tf.data.""" +from google.protobuf import text_format +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_experimental_dataset_ops + + +def assert_next(transformations): + """A transformation that asserts which transformations happen next. + + Transformations should be referred to by their base name, not including + version suffix. For example, use "Batch" instead of "BatchV2". "Batch" will + match any of "Batch", "BatchV1", "BatchV2", etc. + + Args: + transformations: A `tf.string` vector `tf.Tensor` identifying the + transformations that are expected to happen next. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + return _AssertNextDataset(dataset, transformations) + + return _apply_fn + + +def assert_prev(transformations): + r"""Asserts which transformations, with which attributes, happened previously. + + Each transformation is repesented as a tuple in the input. + + The first element is the base op name of the transformation, not including + version suffix. For example, use "BatchDataset" instead of + "BatchDatasetV2". "BatchDataset" will match any of "BatchDataset", + "BatchDatasetV1", "BatchDatasetV2", etc. + + The second element is a dict of attribute name-value pairs. Attributes + values must be of type bool, int, or string. + + Example usage: + + >>> dataset_ops.Dataset.from_tensors(0) \ + ... .map(lambda x: x) \ + ... .batch(1, deterministic=True, num_parallel_calls=8) \ + ... .assert_prev([("ParallelBatchDataset", {"deterministic": True}), \ + ... ("MapDataset", {})]) + + Args: + transformations: A list of tuples identifying the (required) transformation + name, with (optional) attribute name-value pairs, that are expected to + have happened previously. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + return _AssertPrevDataset(dataset, transformations) + + return _apply_fn + + +def non_serializable(): + """A non-serializable identity transformation. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + """Function from `Dataset` to `Dataset` that applies the transformation.""" + return _NonSerializableDataset(dataset) + + return _apply_fn + + +def sleep(sleep_microseconds): + """Sleeps for `sleep_microseconds` before producing each input element. + + Args: + sleep_microseconds: The number of microseconds to sleep before producing an + input element. + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return _SleepDataset(dataset, sleep_microseconds) + + return _apply_fn + + +class _AssertNextDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that asserts which transformations happen next.""" + + def __init__(self, input_dataset, transformations): + """See `assert_next()` for details.""" + self._input_dataset = input_dataset + if transformations is None: + raise ValueError( + "Invalid `transformations`. `transformations` should not be empty.") + + self._transformations = ops.convert_to_tensor( + transformations, dtype=dtypes.string, name="transformations") + variant_tensor = ( + gen_experimental_dataset_ops.experimental_assert_next_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._transformations, + **self._flat_structure)) + super(_AssertNextDataset, self).__init__(input_dataset, variant_tensor) + + +class _AssertPrevDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that asserts which transformations happened previously.""" + + def __init__(self, input_dataset, transformations): + """See `assert_prev()` for details.""" + self._input_dataset = input_dataset + if transformations is None: + raise ValueError("`transformations` cannot be empty") + + def serialize_transformation(op_name, attributes): + proto = attr_value_pb2.NameAttrList(name=op_name) + if attributes is None or isinstance(attributes, set): + attributes = dict() + for (name, value) in attributes.items(): + if isinstance(value, bool): + proto.attr[name].b = value + elif isinstance(value, int): + proto.attr[name].i = value + elif isinstance(value, str): + proto.attr[name].s = value.encode() + else: + raise ValueError( + f"attribute value type ({type(value)}) must be bool, int, or str") + return text_format.MessageToString(proto) + + self._transformations = ops.convert_to_tensor( + [serialize_transformation(*x) for x in transformations], + dtype=dtypes.string, + name="transformations") + variant_tensor = ( + gen_experimental_dataset_ops.assert_prev_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._transformations, + **self._flat_structure)) + super(_AssertPrevDataset, self).__init__(input_dataset, variant_tensor) + + +class _NonSerializableDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that performs non-serializable identity transformation.""" + + def __init__(self, input_dataset): + """See `non_serializable()` for details.""" + self._input_dataset = input_dataset + variant_tensor = ( + gen_experimental_dataset_ops.experimental_non_serializable_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + **self._flat_structure)) + super(_NonSerializableDataset, self).__init__(input_dataset, variant_tensor) + + +class _SleepDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that sleeps before producing each upstream element.""" + + def __init__(self, input_dataset, sleep_microseconds): + self._input_dataset = input_dataset + self._sleep_microseconds = sleep_microseconds + variant_tensor = gen_experimental_dataset_ops.sleep_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._sleep_microseconds, + **self._flat_structure) + super(_SleepDataset, self).__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/unique.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/unique.py new file mode 100644 index 0000000000000000000000000000000000000000..a028e8b87daae7990a0067e40ed37034eb192547 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/unique.py @@ -0,0 +1,43 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Unique element dataset transformations.""" +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@deprecation.deprecated(None, "Use `tf.data.Dataset.unique(...)") +@tf_export("data.experimental.unique") +def unique(): + """Creates a `Dataset` from another `Dataset`, discarding duplicates. + + Use this transformation to produce a dataset that contains one instance of + each unique element in the input. For example: + + ```python + dataset = tf.data.Dataset.from_tensor_slices([1, 37, 2, 37, 2, 1]) + + # Using `unique()` will drop the duplicate elements. + dataset = dataset.apply(tf.data.experimental.unique()) # ==> { 1, 37, 2 } + ``` + + Returns: + A `Dataset` transformation function, which can be passed to + `tf.data.Dataset.apply`. + """ + + def _apply_fn(dataset): + return dataset.unique() + + return _apply_fn diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/writers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/writers.py new file mode 100644 index 0000000000000000000000000000000000000000..7a77d7029130c4e12115d0b9110fdb90a5955cab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/ops/writers.py @@ -0,0 +1,126 @@ +# 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. +# ============================================================================== +"""Python wrappers for tf.data writers.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import convert +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.types import data as data_types +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.TFRecordWriter") +@deprecation.deprecated( + None, "To write TFRecords to disk, use `tf.io.TFRecordWriter`. To save " + "and load the contents of a dataset, use `tf.data.experimental.save` " + "and `tf.data.experimental.load`") +class TFRecordWriter: + """Writes a dataset to a TFRecord file. + + The elements of the dataset must be scalar strings. To serialize dataset + elements as strings, you can use the `tf.io.serialize_tensor` function. + + ```python + dataset = tf.data.Dataset.range(3) + dataset = dataset.map(tf.io.serialize_tensor) + writer = tf.data.experimental.TFRecordWriter("/path/to/file.tfrecord") + writer.write(dataset) + ``` + + To read back the elements, use `TFRecordDataset`. + + ```python + dataset = tf.data.TFRecordDataset("/path/to/file.tfrecord") + dataset = dataset.map(lambda x: tf.io.parse_tensor(x, tf.int64)) + ``` + + To shard a `dataset` across multiple TFRecord files: + + ```python + dataset = ... # dataset to be written + + def reduce_func(key, dataset): + filename = tf.strings.join([PATH_PREFIX, tf.strings.as_string(key)]) + writer = tf.data.experimental.TFRecordWriter(filename) + writer.write(dataset.map(lambda _, x: x)) + return tf.data.Dataset.from_tensors(filename) + + dataset = dataset.enumerate() + dataset = dataset.apply(tf.data.experimental.group_by_window( + lambda i, _: i % NUM_SHARDS, reduce_func, tf.int64.max + )) + + # Iterate through the dataset to trigger data writing. + for _ in dataset: + pass + ``` + """ + + def __init__(self, filename, compression_type=None): + """Initializes a `TFRecordWriter`. + + Args: + filename: a string path indicating where to write the TFRecord data. + compression_type: (Optional.) a string indicating what type of compression + to use when writing the file. See `tf.io.TFRecordCompressionType` for + what types of compression are available. Defaults to `None`. + """ + self._filename = ops.convert_to_tensor( + filename, dtypes.string, name="filename") + self._compression_type = convert.optional_param_to_tensor( + "compression_type", + compression_type, + argument_default="", + argument_dtype=dtypes.string) + + def write(self, dataset): + """Writes a dataset to a TFRecord file. + + An operation that writes the content of the specified dataset to the file + specified in the constructor. + + If the file exists, it will be overwritten. + + Args: + dataset: a `tf.data.Dataset` whose elements are to be written to a file + + Returns: + In graph mode, this returns an operation which when executed performs the + write. In eager mode, the write is performed by the method itself and + there is no return value. + + Raises + TypeError: if `dataset` is not a `tf.data.Dataset`. + TypeError: if the elements produced by the dataset are not scalar strings. + """ + if not isinstance(dataset, data_types.DatasetV2): + raise TypeError( + f"Invalid `dataset.` Expected a `tf.data.Dataset` object but got " + f"{type(dataset)}." + ) + if not dataset_ops.get_structure(dataset).is_compatible_with( + tensor_spec.TensorSpec([], dtypes.string)): + raise TypeError( + f"Invalid `dataset`. Expected a`dataset` that produces scalar " + f"`tf.string` elements, but got a dataset which produces elements " + f"with shapes {dataset_ops.get_legacy_output_shapes(dataset)} and " + f"types {dataset_ops.get_legacy_output_types(dataset)}.") + # pylint: disable=protected-access + dataset = dataset._apply_debug_options() + return gen_experimental_dataset_ops.dataset_to_tf_record( + dataset._variant_tensor, self._filename, self._compression_type) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4a3f3ce8e9d23fb0f4d839b0af55e31afec0ffcd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/__init__.py @@ -0,0 +1,426 @@ +# 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. +# ============================================================================== +"""API for using the tf.data service. + +This module contains: + +1. tf.data server implementations for running the tf.data service. +2. APIs for registering datasets with the tf.data service and reading from + the registered datasets. + +The tf.data service provides the following benefits: + +- Horizontal scaling of tf.data input pipeline processing to solve input + bottlenecks. +- Data coordination for distributed training. Coordinated reads + enable all replicas to train on similar-length examples across each global + training step, improving step times in synchronous training. +- Dynamic balancing of data across training replicas. + +>>> dispatcher = tf.data.experimental.service.DispatchServer() +>>> dispatcher_address = dispatcher.target.split("://")[1] +>>> worker = tf.data.experimental.service.WorkerServer( +... tf.data.experimental.service.WorkerConfig( +... dispatcher_address=dispatcher_address)) +>>> dataset = tf.data.Dataset.range(10) +>>> dataset = dataset.apply(tf.data.experimental.service.distribute( +... processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, +... service=dispatcher.target)) +>>> print(list(dataset.as_numpy_iterator())) +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +## Setup + +This section goes over how to set up the tf.data service. + +### Run tf.data servers + +The tf.data service consists of one dispatch server and `n` worker servers. +tf.data servers should be brought up alongside your training jobs, then brought +down when the jobs are finished. +Use `tf.data.experimental.service.DispatchServer` to start a dispatch server, +and `tf.data.experimental.service.WorkerServer` to start worker servers. Servers +can be run in the same process for testing purposes, or scaled up on separate +machines. + +See https://github.com/tensorflow/ecosystem/tree/master/data_service for an +example of using Google Kubernetes Engine (GKE) to manage the tf.data service. +Note that the server implementation in +[tf_std_data_server.py](https://github.com/tensorflow/ecosystem/blob/master/data_service/tf_std_data_server.py) +is not GKE-specific, and can be used to run the tf.data service in other +contexts. + +### Custom ops + +If your dataset uses custom ops, these ops need to be made available to tf.data +servers by calling +[load_op_library](https://www.tensorflow.org/api_docs/python/tf/load_op_library) +from the dispatcher and worker processes at startup. + +## Usage + +Users interact with tf.data service by programmatically registering their +datasets with tf.data service, then creating datasets that read from the +registered datasets. The +[register_dataset](https://www.tensorflow.org/api_docs/python/tf/data/experimental/service/register_dataset) +function registers a dataset, then the +[from_dataset_id](https://www.tensorflow.org/api_docs/python/tf/data/experimental/service/from_dataset_id) +function creates a new dataset which reads from the registered dataset. +The +[distribute](https://www.tensorflow.org/api_docs/python/tf/data/experimental/service/distribute) +function wraps `register_dataset` and `from_dataset_id` into a single convenient +transformation which registers its input dataset and then reads from it. +`distribute` enables tf.data service to be used with a one-line code change. +However, it assumes that the dataset is created and consumed by the same entity +and this assumption might not always be valid or desirable. In particular, in +certain scenarios, such as distributed training, it might be desirable to +decouple the creation and consumption of the dataset (via `register_dataset` +and `from_dataset_id` respectively) to avoid having to create the dataset on +each of the training workers. + +### Example + +#### `distribute` + +To use the `distribute` transformation, apply the transformation after the +prefix of your input pipeline that you would like to be executed using tf.data +service (typically at the end). + +``` +dataset = ... # Define your dataset here. +# Move dataset processing from the local machine to the tf.data service +dataset = dataset.apply( + tf.data.experimental.service.distribute( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + job_name="shared_job")) +# Any transformations added after `distribute` will be run on the local machine. +dataset = dataset.prefetch(1) +``` + +The above code will create a tf.data service "job", which iterates through the +dataset to generate data. To share the data from a job across multiple clients +(e.g. when using TPUStrategy or MultiWorkerMirroredStrategy), set a common +`job_name` across all clients. + +#### `register_dataset` and `from_dataset_id` + +`register_dataset` registers a dataset with the tf.data service, returning a +dataset id for the registered dataset. `from_dataset_id` creates a dataset that +reads from the registered dataset. These APIs can be used to reduce dataset +building time for distributed training. Instead of building the dataset on all +training workers, we can build the dataset just once and then register the +dataset using `register_dataset`. Then all workers can call `from_dataset_id` +without needing to build the dataset themselves. + +``` +dataset = ... # Define your dataset here. +dataset_id = tf.data.experimental.service.register_dataset( + service=FLAGS.tf_data_service_address, + dataset=dataset) +# Use `from_dataset_id` to create per-worker datasets. +per_worker_datasets = {} +for worker in workers: + per_worker_datasets[worker] = tf.data.experimental.service.from_dataset_id( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + dataset_id=dataset_id, + job_name="shared_job") +``` + +### Processing Modes + +`processing_mode` specifies how to shard a dataset among tf.data service +workers. tf.data service supports `OFF`, `DYNAMIC`, `FILE`, `DATA`, +`FILE_OR_DATA`, `HINT` sharding policies. + +OFF: No sharding will be performed. The entire input dataset will be processed +independently by each of the tf.data service workers. For this reason, it is +important to shuffle data (e.g. filenames) non-deterministically, so that each +worker will process the elements of the dataset in a different order. This mode +can be used to distribute datasets that aren't splittable. + +If a worker is added or restarted during ShardingPolicy.OFF processing, the +worker will instantiate a new copy of the dataset and begin producing data from +the beginning. + +#### Dynamic Sharding + +DYNAMIC: In this mode, tf.data service divides the dataset into two components: +a source component that generates "splits" such as filenames, and a processing +component that takes splits and outputs dataset elements. The source component +is executed in a centralized fashion by the tf.data service dispatcher, which +generates different splits of input data. The processing component is executed +in a parallel fashion by the tf.data service workers, each operating on a +different set of input data splits. + +For example, consider the following dataset: + +``` +dataset = tf.data.Dataset.from_tensor_slices(filenames) +dataset = dataset.interleave(TFRecordDataset) +dataset = dataset.map(preprocess_fn) +dataset = dataset.batch(batch_size) +dataset = dataset.apply( + tf.data.experimental.service.distribute( + processing_mode=tf.data.experimental.service.ShardingPolicy.DYNAMIC, + ...)) +``` + +The `from_tensor_slices` will be run on the dispatcher, while the `interleave`, +`map`, and `batch` will be run on tf.data service workers. The workers will pull +filenames from the dispatcher for processing. To process a dataset with +dynamic sharding, the dataset must have a splittable source, and all of +its transformations must be compatible with splitting. While most sources and +transformations support splitting, there are exceptions, such as custom datasets +which may not implement the splitting API. Please file a Github issue if you +would like to use distributed epoch processing for a currently unsupported +dataset source or transformation. + +If no workers are restarted during training, dynamic sharding mode will visit +every example exactly once. If workers are restarted during training, the splits +they were processing will not be fully visited. The dispatcher maintains a +cursor through the dataset's splits. Assuming fault tolerance is enabled (See +"Fault Tolerance" below), the dispatcher will store cursor state in write-ahead +logs so that the cursor can be restored in case the dispatcher is restarted +mid-training. This provides an at-most-once visitation guarantee in the presence +of server restarts. + +#### Static Sharding + +The following are static sharding policies. The semantics are similar to +`tf.data.experimental.AutoShardPolicy`. These policies require: + + * The tf.data service cluster is configured with a fixed list of workers + in DispatcherConfig. + * Each client only reads from the local tf.data service worker. + +If a worker is restarted while performing static sharding, the worker will +begin processing its shard again from the beginning. + +FILE: Shards by input files (i.e. each worker will get a fixed 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. + +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 partition the dataset elements, the dataset needs to +produce elements in a deterministic order. + +FILE_OR_DATA: Attempts FILE-based sharding, falling back to DATA-based +sharding on failure. + +HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated as a +placeholder to replace with `shard(num_workers, worker_index)`. + +For backwards compatibility, `processing_mode` may also be set to the strings +`"parallel_epochs"` or `"distributed_epoch"`, which are respectively equivalent +to `ShardingPolicy.OFF` and `ShardingPolicy.DYNAMIC`. + +### Coordinated Data Read + +By default, when multiple consumers read from the same job, they receive data on +a first-come first-served basis. In some use cases, it is advantageous to +coordinate the consumers. At each step, consumers read data from the same +worker. + +For example, the tf.data service can be used to coordinate example sizes across +a cluster during synchronous training, so that during each step all replicas +train on similar-sized elements. To achieve this, define a dataset which +generates rounds of `num_consumers` consecutive similar-sized batches, then +enable coordinated reads by setting `consumer_index` and `num_consumers`. + +NOTE: To keep consumers in sync, coordinated reads require that the dataset have +infinite cardinality. You can get this by adding `.repeat()` at the end of the +dataset definition. + +### Jobs + +A tf.data service "job" refers to the process of reading from a dataset managed +by the tf.data service, using one or more data consumers. Jobs are created when +iterating over datasets that read from tf.data service. The data produced by a +job is determined by (1) dataset associated with the job and (2) the job's +processing mode. For example, if a job is created for the dataset +`Dataset.range(5)`, and the processing mode is `ShardingPolicy.OFF`, each +tf.data worker will produce the elements `{0, 1, 2, 3, 4}` for the job, +resulting in the +job producing `5 * num_workers` elements. If the processing mode is +`ShardingPolicy.DYNAMIC`, the job will only produce `5` elements. + +One or more consumers can consume data from a job. By default, jobs are +"anonymous", meaning that only the consumer which created the job can read from +it. To share the output of a job across multiple consumers, you can set a common +`job_name`. + +### Fault Tolerance + +By default, the tf.data dispatch server stores its state in-memory, making it a +single point of failure during training. To avoid this, pass +`fault_tolerant_mode=True` when creating your `DispatchServer`. Dispatcher +fault tolerance requires `work_dir` to be configured and accessible from the +dispatcher both before and after restart (e.g. a GCS path). With fault tolerant +mode enabled, the dispatcher will journal its state to the work directory so +that no state is lost when the dispatcher is restarted. + +WorkerServers may be freely restarted, added, or removed during training. At +startup, workers will register with the dispatcher and begin processing all +outstanding jobs from the beginning. + +### Usage with tf.distribute + +tf.distribute is the TensorFlow API for distributed training. There are +several ways to use tf.data with tf.distribute: +`strategy.experimental_distribute_dataset`, +`strategy.distribute_datasets_from_function`, and (for PSStrategy) +`coordinator.create_per_worker_dataset`. The following sections give code +examples for each. + +In general we recommend using +`tf.data.experimental.service.{register_dataset,from_dataset_id}` over +`tf.data.experimental.service.distribute` for two reasons: + +- The dataset only needs to be constructed and optimized once, instead of once + per worker. This can significantly reduce startup time, because the current + `experimental_distribute_dataset` and `distribute_datasets_from_function` + implementations create and optimize worker datasets sequentially. +- If a dataset depends on lookup tables or variables that are only present on + one host, the dataset needs to be registered from that host. Typically this + only happens when resources are placed on the chief or worker 0. Registering + the dataset from the chief will avoid issues with depending on remote + resources. + +#### strategy.experimental_distribute_dataset + +Nothing special is required when using +`strategy.experimental_distribute_dataset`, just apply `register_dataset` and +`from_dataset_id` as above, making sure to specify a `job_name` so that all +workers consume from the same tf.data service job. + +``` +dataset = ... # Define your dataset here. +dataset_id = tf.data.experimental.service.register_dataset( + service=FLAGS.tf_data_service_address, + dataset=dataset) +dataset = tf.data.experimental.service.from_dataset_id( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + dataset_id=dataset_id, + job_name="shared_job") + +dataset = strategy.experimental_distribute_dataset(dataset) +``` + +#### strategy.distribute_datasets_from_function + +First, make sure the dataset produced by the `dataset_fn` does not depend on the +`input_context` for the training worker on which it is run. Instead of each +worker building its own (sharded) dataset, one worker should register an +unsharded dataset, and the remaining workers should consume data from that +dataset. + +``` +dataset = dataset_fn() +dataset_id = tf.data.experimental.service.register_dataset( + service=FLAGS.tf_data_service_address, + dataset=dataset) + +def new_dataset_fn(input_context): + del input_context + return tf.data.experimental.service.from_dataset_id( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + dataset_id=dataset_id, + job_name="shared_job") + +dataset = strategy.distribute_datasets_from_function(new_dataset_fn) +``` + +#### coordinator.create_per_worker_dataset + +`create_per_worker_dataset` works the same as +`distribute_datasets_from_function`. + +``` +dataset = dataset_fn() +dataset_id = tf.data.experimental.service.register_dataset( + service=FLAGS.tf_data_service_address, + dataset=dataset) + +def new_dataset_fn(input_context): + del input_context + return tf.data.experimental.service.from_dataset_id( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + dataset_id=dataset_id, + job_name="shared_job") + +dataset = coordinator.create_per_worker_dataset(new_dataset_fn) +``` + +### Sharing tf.data service with concurrent trainers + +If you run multiple trainers concurrently using the same training data, it could +save resources to cache the data in one tf.data service cluster and share the +cluster with the trainers. For example, if you use Vizier to tune +hyperparameters, the Vizier jobs can run concurrently and share one tf.data +service cluster. + +To enable this feature, each trainer needs to generate a unique trainer ID, and +you pass the trainer ID to `tf.data.experimental.service.distribute`. Once a job +has consumed data, the data remains in the cache and is re-used by jobs with +different `trainer_id`s. Requests with the same `trainer_id` do not re-use data. +For example: + +``` +dataset = expensive_computation() +dataset = dataset.apply(tf.data.experimental.service.distribute( + processing_mode=tf.data.experimental.service.ShardingPolicy.OFF, + service=FLAGS.tf_data_service_address, + job_name="job", + cross_trainer_cache=data_service_ops.CrossTrainerCache( + trainer_id=trainer_id()))) +``` + +tf.data service uses a sliding-window cache to store shared data. When one +trainer consumes data, the data remains in the cache. When other trainers need +data, they can get data from the cache instead of repeating the expensive +computation. The cache has a bounded size, so some workers may not read the full +dataset. To ensure all the trainers get sufficient training data, we require the +input dataset to be infinite. This can be achieved, for example, by repeating +the dataset and performing random augmentation on the training instances. + +## Limitations + +- Python-based data processing: Datasets which use Python-based data processing + (e.g. `tf.py_function`, `tf.numpy_function`, or + `tf.data.Dataset.from_generator`) are currently not supported. +- Non-Serializable Resources: Datasets may only depend on TF resources that + support serialization. Serialization is currently supported for lookup + tables and variables. If your dataset depends on a TF resource that cannot be + serialized, please file a Github issue. +- Remote Resources: If a dataset depends on a resource, the dataset must be + registered from the same process that created the resource (e.g. the "chief" + job of ParameterServerStrategy). +""" + +from tensorflow.python.data.experimental.ops.data_service_ops import distribute +from tensorflow.python.data.experimental.ops.data_service_ops import from_dataset_id +from tensorflow.python.data.experimental.ops.data_service_ops import register_dataset +from tensorflow.python.data.experimental.ops.data_service_ops import ShardingPolicy +from tensorflow.python.data.experimental.service.server_lib import DispatcherConfig +from tensorflow.python.data.experimental.service.server_lib import DispatchServer +from tensorflow.python.data.experimental.service.server_lib import WorkerConfig +from tensorflow.python.data.experimental.service.server_lib import WorkerServer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_server_lib.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_server_lib.pyi new file mode 100644 index 0000000000000000000000000000000000000000..d39c6ac8225da83eee388dcf303f75430c6526a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_server_lib.pyi @@ -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. +# ============================================================================== + +from typing import Any + +class DispatchGrpcDataServer: + def __init__(self, *args, **kwargs) -> None: ... + def bound_port(self) -> int: ... + def join(self) -> None: ... + def num_workers(self) -> int: ... + def snapshot_streams(self, *args, **kwargs) -> Any: ... + def start(self) -> Status: ... + def stop(self) -> None: ... + +class SnapshotStreamInfoWrapper: + def __init__(self) -> None: ... + @property + def index(self) -> int: ... + @property + def state(self) -> int: ... + +class SnapshotTaskProgressWrapper: + def __init__(self) -> None: ... + @property + def completed(self) -> bool: ... + @property + def snapshot_task_base_path(self) -> bytes: ... + @property + def snapshot_task_stream_index(self) -> int: ... + +class WorkerGrpcDataServer: + def __init__(self, *args, **kwargs) -> None: ... + def bound_port(self) -> int: ... + def join(self) -> None: ... + def num_tasks(self) -> int: ... + def snapshot_task_progresses(self, *args, **kwargs) -> Any: ... + def start(self) -> Status: ... + def stop(self) -> None: ... + +def TF_DATA_GetDataServiceMetadataByID(*args, **kwargs) -> Any: ... +def TF_DATA_NewDispatchServer(arg0: str) -> DispatchGrpcDataServer: ... +def TF_DATA_NewWorkerServer(arg0: str) -> WorkerGrpcDataServer: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_snapshot_utils.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_snapshot_utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c59b0f0b04b7544926e0a13e10bb9e0b5a77055f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_snapshot_utils.pyi @@ -0,0 +1,19 @@ +# 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. +# ============================================================================== + +def TF_DATA_CommittedChunksDirectory(arg0: str) -> str: ... +def TF_DATA_SnapshotDoneFilePath(arg0: str) -> str: ... +def TF_DATA_SnapshotErrorFilePath(arg0: str) -> str: ... +def TF_DATA_SnapshotMetadataFilePath(arg0: str) -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_utils.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..29126c1902939e48af637c64dfb529cf47902c51 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/_pywrap_utils.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def TF_DATA_DefaultProtocol() -> str: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/server_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/server_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..f00c1ad631427a7feb37e54813584084898f5f44 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/experimental/service/server_lib.py @@ -0,0 +1,478 @@ +# 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. +# ============================================================================== +"""A Python interface for creating dataset servers.""" + +import collections +from typing import Iterable + +# pylint: disable=invalid-import-order,g-bad-import-order, unused-import +from tensorflow.core.protobuf import service_config_pb2 +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.data.experimental.service import _pywrap_server_lib +from tensorflow.python.data.experimental.service import _pywrap_utils +from tensorflow.python.util.tf_export import tf_export + + +def _get_time_or_placeholder(value) -> int: + """Modifies time-based config values to account for special behaviors.""" + + # Servers interpret time values of 0 to mean "choose a reasonable + # default". However, the Python API uses `None` for this, and allows 0 as a + # normal value. To account for this, if a user explicitly configures the + # interval/timeout to 0, we interpret it to mean "a very small number", and + # replace it with 1. + if value == 0: + return 1 + # `None` indicates that the user wants to leave the behavior to the runtime. + if value is None: + return 0 + return value + + +@tf_export("data.experimental.service.DispatcherConfig") +class DispatcherConfig( + collections.namedtuple( + "DispatcherConfig", + [ + "port", + "protocol", + "work_dir", + "fault_tolerant_mode", + "worker_addresses", + "job_gc_check_interval_ms", + "job_gc_timeout_ms", + "worker_timeout_ms", + "worker_max_concurrent_snapshots", + ], + ) +): + """Configuration class for tf.data service dispatchers. + + Fields: + port: Specifies the port to bind to. A value of 0 indicates that the server + may bind to any available port. + protocol: The protocol to use for communicating with the tf.data service, + e.g. "grpc". + work_dir: A directory to store dispatcher state in. This + argument is required for the dispatcher to be able to recover from + restarts. + fault_tolerant_mode: Whether the dispatcher should write its state to a + journal so that it can recover from restarts. Dispatcher state, including + registered datasets and created jobs, is synchronously written to the + journal before responding to RPCs. If `True`, `work_dir` must also be + specified. + worker_addresses: If the job uses auto-sharding, it needs to specify a fixed + list of worker addresses that will register with the dispatcher. The + worker addresses should be in the format `"host"` or `"host:port"`, where + `"port"` is an integer, named port, or `%port%` to match any port. + job_gc_check_interval_ms: How often the dispatcher should scan through to + delete old and unused jobs, in milliseconds. If not set, the runtime will + select a reasonable default. A higher value will reduce load on the + dispatcher, while a lower value will reduce the time it takes for the + dispatcher to garbage collect expired jobs. + job_gc_timeout_ms: How long a job needs to be unused before it becomes a + candidate for garbage collection, in milliseconds. A value of -1 indicates + that jobs should never be garbage collected. If not set, the runtime will + select a reasonable default. A higher value will cause jobs to stay around + longer with no consumers. This is useful if there is a large gap in + time between when consumers read from the job. A lower value will reduce + the time it takes to reclaim the resources from expired jobs. + worker_timeout_ms: How long to wait for a worker to heartbeat before + considering it missing. If not set, the runtime will select a reasonable + default. + worker_max_concurrent_snapshots: The maximum number of snapshots a worker + can concurrently process. + """ + + def __new__( + cls, + port=0, + protocol=None, + work_dir=None, + fault_tolerant_mode=False, + worker_addresses=None, + job_gc_check_interval_ms=None, + job_gc_timeout_ms=None, + worker_timeout_ms=None, + worker_max_concurrent_snapshots=0, + ): + if protocol is None: + protocol = _pywrap_utils.TF_DATA_DefaultProtocol() + job_gc_check_interval_ms = _get_time_or_placeholder( + job_gc_check_interval_ms) + job_gc_timeout_ms = _get_time_or_placeholder(job_gc_timeout_ms) + return super().__new__( + cls, + port, + protocol, + work_dir, + fault_tolerant_mode, + worker_addresses, + job_gc_check_interval_ms, + job_gc_timeout_ms, + worker_timeout_ms, + worker_max_concurrent_snapshots, + ) + + +@tf_export("data.experimental.service.DispatchServer", v1=[]) +class DispatchServer: + """An in-process tf.data service dispatch server. + + A `tf.data.experimental.service.DispatchServer` coordinates a cluster of + `tf.data.experimental.service.WorkerServer`s. When the workers start, they + register themselves with the dispatcher. + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> worker = tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.apply(tf.data.experimental.service.distribute( + ... processing_mode="parallel_epochs", service=dispatcher.target)) + >>> print(list(dataset.as_numpy_iterator())) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + When starting a dedicated tf.data dispatch process, use join() to block + after starting up the server, until the server terminates. + + ``` + dispatcher = tf.data.experimental.service.DispatchServer( + tf.data.experimental.service.DispatcherConfig(port=5050)) + dispatcher.join() + ``` + + Call stop() to gracefully terminate the dispatcher. The server automatically + stops when all reference to it have been deleted. + + To start a `DispatchServer` in fault-tolerant mode, set `work_dir` and + `fault_tolerant_mode` like below: + + ``` + dispatcher = tf.data.experimental.service.DispatchServer( + tf.data.experimental.service.DispatcherConfig( + port=5050, + work_dir="gs://my-bucket/dispatcher/work_dir", + fault_tolerant_mode=True)) + ``` + """ + + def __init__(self, config=None, start=True): + """Creates a new dispatch server. + + Args: + config: (Optional.) A `tf.data.experimental.service.DispatcherConfig` + configration. If `None`, the dispatcher will use default + configuration values. + start: (Optional.) Boolean, indicating whether to start the server after + creating it. Defaults to True. + """ + config = config or DispatcherConfig() + if config.fault_tolerant_mode and not config.work_dir: + raise ValueError( + "Cannot enable fault tolerant mode without configuring a work dir. " + "Make sure to set `work_dir` in the `config` object passed to " + "`DispatcherServer`.") + self._config = config + if isinstance(config, service_config_pb2.DispatcherConfig): + config_proto = config + else: + config_proto = service_config_pb2.DispatcherConfig( + port=config.port, + protocol=config.protocol, + work_dir=config.work_dir, + fault_tolerant_mode=config.fault_tolerant_mode, + worker_addresses=config.worker_addresses, + job_gc_check_interval_ms=config.job_gc_check_interval_ms, + job_gc_timeout_ms=config.job_gc_timeout_ms, + worker_timeout_ms=config.worker_timeout_ms, + worker_max_concurrent_snapshots=config.worker_max_concurrent_snapshots + ) + self._server = _pywrap_server_lib.TF_DATA_NewDispatchServer( + config_proto.SerializeToString()) + if start: + self._server.start() + + def start(self): + """Starts this server. + + >>> dispatcher = tf.data.experimental.service.DispatchServer(start=False) + >>> dispatcher.start() + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + starting the server. + """ + self._server.start() + + def join(self) -> None: + """Blocks until the server has shut down. + + This is useful when starting a dedicated dispatch process. + + ``` + dispatcher = tf.data.experimental.service.DispatchServer( + tf.data.experimental.service.DispatcherConfig(port=5050)) + dispatcher.join() + ``` + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + joining the server. + """ + self._server.join() + + def stop(self) -> None: + """Stops the server. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + stopping the server. + """ + self._stop() + + @property + def target(self) -> str: + """Returns a target that can be used to connect to the server. + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.apply(tf.data.experimental.service.distribute( + ... processing_mode="parallel_epochs", service=dispatcher.target)) + + The returned string will be in the form protocol://address, e.g. + "grpc://localhost:5050". + """ + return "{0}://localhost:{1}".format(self._config.protocol, + self._server.bound_port()) + + def _stop(self) -> None: + """Stops the server. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + stopping the server. + """ + self._server.stop() + + def __del__(self) -> None: + self._stop() + + @property + def _address(self) -> str: + """Returns the address of the server. + + The returned string will be in the form address:port, e.g. "localhost:1000". + """ + return "localhost:{0}".format(self._server.bound_port()) + + def _num_workers(self) -> int: + """Returns the number of workers registered with the dispatcher.""" + return self._server.num_workers() + + def _snapshot_streams( + self, path) -> Iterable[_pywrap_server_lib.SnapshotStreamInfoWrapper]: + """Returns information about all the streams for a snapshot.""" + return self._server.snapshot_streams(path) + + +@tf_export("data.experimental.service.WorkerConfig") +class WorkerConfig( + collections.namedtuple("WorkerConfig", [ + "dispatcher_address", "worker_address", "port", "protocol", + "heartbeat_interval_ms", "dispatcher_timeout_ms", + "data_transfer_protocol", "data_transfer_address" + ])): + """Configuration class for tf.data service dispatchers. + + Fields: + dispatcher_address: Specifies the address of the dispatcher. + worker_address: Specifies the address of the worker server. This address is + passed to the dispatcher so that the dispatcher can tell clients how to + connect to this worker. + port: Specifies the port to bind to. A value of 0 indicates that the worker + can bind to any available port. + protocol: A string indicating the protocol to be used by the worker to + connect to the dispatcher. E.g. "grpc". + heartbeat_interval_ms: How often the worker should heartbeat to the + dispatcher, in milliseconds. If not set, the runtime will select a + reasonable default. A higher value will reduce the load on the dispatcher, + while a lower value will reduce the time it takes to reclaim resources + from finished jobs. + dispatcher_timeout_ms: How long, in milliseconds, to retry requests to the + dispatcher before giving up and reporting an error. Defaults to 1 hour. + data_transfer_protocol: A string indicating the protocol to be used by the + worker to transfer data to the client. E.g. "grpc". + data_transfer_address: A string indicating the data transfer address of the + worker server. + """ + + def __new__(cls, + dispatcher_address, + worker_address=None, + port=0, + protocol=None, + heartbeat_interval_ms=None, + dispatcher_timeout_ms=None, + data_transfer_protocol=None, + data_transfer_address=None): + if worker_address is None: + worker_address = "localhost:%port%" + if protocol is None: + protocol = _pywrap_utils.TF_DATA_DefaultProtocol() + if data_transfer_address is None: + data_transfer_address = "localhost:%port%" + heartbeat_interval_ms = _get_time_or_placeholder(heartbeat_interval_ms) + dispatcher_timeout_ms = _get_time_or_placeholder(dispatcher_timeout_ms) + + return super(WorkerConfig, + cls).__new__(cls, dispatcher_address, worker_address, port, + protocol, heartbeat_interval_ms, + dispatcher_timeout_ms, data_transfer_protocol, + data_transfer_address) + + +@tf_export("data.experimental.service.WorkerServer", v1=[]) +class WorkerServer: + """An in-process tf.data service worker server. + + A `tf.data.experimental.service.WorkerServer` performs `tf.data.Dataset` + processing for user-defined datasets, and provides the resulting elements over + RPC. A worker is associated with a single + `tf.data.experimental.service.DispatchServer`. + + >>> dispatcher = tf.data.experimental.service.DispatchServer() + >>> dispatcher_address = dispatcher.target.split("://")[1] + >>> worker = tf.data.experimental.service.WorkerServer( + ... tf.data.experimental.service.WorkerConfig( + ... dispatcher_address=dispatcher_address)) + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.apply(tf.data.experimental.service.distribute( + ... processing_mode="parallel_epochs", service=dispatcher.target)) + >>> print(list(dataset.as_numpy_iterator())) + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + When starting a dedicated tf.data worker process, use join() to block + after starting up the worker, until the worker terminates. + + ``` + worker = tf.data.experimental.service.WorkerServer( + port=5051, dispatcher_address="localhost:5050") + worker.join() + ``` + + Call stop() to gracefully terminate the worker. The worker automatically stops + when all reference to it have been deleted. + """ + + def __init__(self, config, start=True): + """Creates a new worker server. + + Args: + config: A `tf.data.experimental.service.WorkerConfig` configration. + start: (Optional.) Boolean, indicating whether to start the server after + creating it. Defaults to True. + """ + if config.dispatcher_address is None: + raise ValueError( + "Must specify a `dispatcher_address` in the `config` passed " + "to `WorkerServer`.") + if isinstance(config, service_config_pb2.WorkerConfig): + config_proto = config + else: + config_proto = service_config_pb2.WorkerConfig( + dispatcher_address=config.dispatcher_address, + worker_address=config.worker_address, + port=config.port, + protocol=config.protocol, + heartbeat_interval_ms=config.heartbeat_interval_ms, + dispatcher_timeout_ms=config.dispatcher_timeout_ms, + data_transfer_protocol=config.data_transfer_protocol, + data_transfer_address=config.data_transfer_address) + self._server = _pywrap_server_lib.TF_DATA_NewWorkerServer( + config_proto.SerializeToString()) + if start: + self._server.start() + + def start(self) -> None: + """Starts this server. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + starting the server. + """ + self._server.start() + + def join(self) -> None: + """Blocks until the server has shut down. + + This is useful when starting a dedicated worker process. + + ``` + worker_server = tf.data.experimental.service.WorkerServer( + port=5051, dispatcher_address="localhost:5050") + worker_server.join() + ``` + + This method currently blocks forever. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + joining the server. + """ + self._server.join() + + def stop(self) -> None: + """Stops the server. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + stopping the server. + """ + self._stop() + + def _stop(self) -> None: + """Stops the server. + + Raises: + tf.errors.OpError: Or one of its subclasses if an error occurs while + stopping the server. + """ + self._server.stop() + + def __del__(self) -> None: + self._stop() + + @property + def _address(self) -> str: + """Returns the address of the server. + + The returned string will be in the form address:port, e.g. "localhost:1000". + """ + return "localhost:{0}".format(self._server.bound_port()) + + def _num_tasks(self) -> int: + """Returns the number of tasks currently being executed on the worker.""" + return self._server.num_tasks() + + def _snapshot_task_progresses( + self) -> Iterable[_pywrap_server_lib.SnapshotTaskProgressWrapper]: + """Returns the progresses of the snapshot tasks currently being executed. + + Returns: + An `Iterable[common_pb2.SnapshotTaskProgress]`. + """ + return self._server.snapshot_task_progresses() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/checkpoint_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/checkpoint_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..21b9266c90b806d22b578c93d622de6f90c46370 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/checkpoint_test_base.py @@ -0,0 +1,619 @@ +# 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. +# ============================================================================== +"""Base test class for checkpointing datasets.""" + +import os + +import numpy as np +from tensorflow.python.checkpoint import checkpoint as tracking_util +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.checkpoint import checkpoint_options +from tensorflow.python.data.experimental.ops import iterator_ops as contrib_iterator_ops +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import combinations +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import variables +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.platform import gfile +from tensorflow.python.platform import test +from tensorflow.python.training import saver as saver_lib +from tensorflow.python.util import nest + + +def remove_variants(get_next_op): + # TODO(b/72408568): Remove this once session.run can get variant tensors. + """Remove variants from a nest structure, so sess.run will execute.""" + + def _remove_variant(x): + if isinstance(x, tensor.Tensor) and x.dtype == dtypes.variant: + return () + else: + return x + + return nest.map_structure(_remove_variant, get_next_op) + + +def default_test_combinations(): + """Returns the default test combinations for testing checkpointing.""" + + def disable_optimizations(ds_fn): + options = options_lib.Options() + options.experimental_optimization.apply_default_optimizations = False + + def ds_fn_no_opt(): + return ds_fn().with_options(options) + + return ds_fn_no_opt + + def verify_unused_iterator(obj, ds_fn, num_outputs, sparse_tensors=False): + obj.verify_unused_iterator( + ds_fn=disable_optimizations(ds_fn=ds_fn), + num_outputs=num_outputs, + sparse_tensors=sparse_tensors) + + verify_unused_iterator_combination = combinations.combine( + verify_fn=combinations.NamedObject("verify_unused_iterator", + verify_unused_iterator)) + + def verify_fully_used_iterator(obj, ds_fn, num_outputs, sparse_tensors=False): + obj.verify_fully_used_iterator( + ds_fn=disable_optimizations(ds_fn=ds_fn), + num_outputs=num_outputs, + sparse_tensors=sparse_tensors) + + verify_fully_used_iterator_combination = combinations.combine( + verify_fn=combinations.NamedObject("verify_fully_used_iterator", + verify_fully_used_iterator)) + + def verify_exhausted_iterator(obj, ds_fn, num_outputs, sparse_tensors=False): + obj.verify_exhausted_iterator( + ds_fn=disable_optimizations(ds_fn=ds_fn), + num_outputs=num_outputs, + sparse_tensors=sparse_tensors) + + verify_exhausted_iterator_combination = combinations.combine( + verify_fn=combinations.NamedObject("verify_exhausted_iterator", + verify_exhausted_iterator)) + + def verify_multiple_breaks(obj, ds_fn, num_outputs, sparse_tensors=False): + obj.verify_multiple_breaks( + ds_fn=disable_optimizations(ds_fn=ds_fn), + num_outputs=num_outputs, + sparse_tensors=sparse_tensors) + + verify_multiple_breaks_combination = combinations.combine( + verify_fn=combinations.NamedObject("verify_multiple_breaks", + verify_multiple_breaks)) + + def verify_reset_restored_iterator(obj, + ds_fn, + num_outputs, + sparse_tensors=False): + obj.verify_reset_restored_iterator( + ds_fn=disable_optimizations(ds_fn=ds_fn), + num_outputs=num_outputs, + sparse_tensors=sparse_tensors) + + verify_reset_restored_iterator_combination = combinations.combine( + verify_fn=combinations.NamedObject("verify_reset_restored_iterator", + verify_reset_restored_iterator)) + + return (verify_unused_iterator_combination + + verify_fully_used_iterator_combination + + verify_exhausted_iterator_combination + + verify_multiple_breaks_combination + + verify_reset_restored_iterator_combination) + + +# TODO(b/72657739): Remove sparse_tensor argument, which is to test the +# (deprecated) saveable `SparseTensorSliceDataset`, once the API +# `from_sparse_tensor_slices()` and related tests are deleted. +class CheckpointTestBase(test.TestCase): + """Base test class for checkpointing datasets.""" + + def tearDown(self): + self._delete_ckpt() + super(CheckpointTestBase, self).tearDown() + + def verify_unused_iterator(self, + ds_fn, + num_outputs, + sparse_tensors=False, + verify_exhausted=True): + """Verifies that saving and restoring an unused iterator works. + + Args: + ds_fn: 0-argument function that returns a Dataset. + num_outputs: Total number of outputs expected from this Dataset. + sparse_tensors: Whether dataset is built from SparseTensor(s). + verify_exhausted: Whether to verify that the iterator has been exhausted + after producing `num_outputs` elements. + + Raises: + AssertionError if any test fails. + """ + self.verify_run_with_breaks( + ds_fn, [0], + num_outputs, + sparse_tensors=sparse_tensors, + verify_exhausted=verify_exhausted) + + def verify_fully_used_iterator(self, + ds_fn, + num_outputs, + sparse_tensors=False): + """Verifies that saving and restoring a fully used iterator works. + + Note that this only checks saving and restoring an iterator from which + `num_outputs` items have been produced but does not check for an + exhausted iterator, i.e., one from which an OutOfRange error has been + returned. + + Args: + ds_fn: 0-argument function that returns a Dataset. + num_outputs: Total number of outputs expected from this Dataset. + sparse_tensors: Whether dataset is built from SparseTensor(s). + + Raises: + AssertionError if test fails. + """ + self.verify_run_with_breaks( + ds_fn, [num_outputs], num_outputs, sparse_tensors=sparse_tensors) + + def verify_exhausted_iterator(self, ds_fn, num_outputs, sparse_tensors=False): + """Verifies that saving and restoring an exhausted iterator works. + + An exhausted iterator is one which has returned an OutOfRange error. + + Args: + ds_fn: 0-argument function that returns a Dataset. + num_outputs: Total number of outputs expected from this Dataset. + sparse_tensors: Whether dataset is built from SparseTensor(s). + + Raises: + AssertionError if any test fails. + """ + self.gen_outputs( + ds_fn, [], + num_outputs, + verify_exhausted=True, + sparse_tensors=sparse_tensors) + actual = self.gen_outputs( + ds_fn, [], + 0, + ckpt_saved=True, + verify_exhausted=True, + sparse_tensors=sparse_tensors) + self.assertLen(actual, 0) + + def verify_multiple_breaks(self, + ds_fn, + num_outputs, + num_breaks=10, + sparse_tensors=False, + verify_exhausted=True): + """Attempts to save/restore at multiple break points. + + Args: + ds_fn: 0-argument function that returns a Dataset. + num_outputs: Total number of outputs expected from this Dataset. + num_breaks: The number of break points. These are uniformly spread in [0, + num_outputs] both inclusive. + sparse_tensors: Whether dataset is built from SparseTensor(s). + verify_exhausted: Whether to verify that the iterator has been exhausted + after producing `num_outputs` elements. + + Raises: + AssertionError if any test fails. + """ + self.verify_run_with_breaks( + ds_fn, + self.gen_break_points(num_outputs, num_breaks), + num_outputs, + sparse_tensors=sparse_tensors, + verify_exhausted=verify_exhausted) + + def verify_reset_restored_iterator(self, + ds_fn, + num_outputs, + break_point=None, + sparse_tensors=False, + verify_exhausted=True): + """Attempts to re-initialize a restored iterator. + + This is useful when restoring a training checkpoint during validation. + + Args: + ds_fn: 0-argument function that returns a Dataset. + num_outputs: Total number of outputs expected from this Dataset. + break_point: Break point. Optional. Defaults to num_outputs/2. + sparse_tensors: Whether dataset is built from SparseTensor(s). + verify_exhausted: Whether to verify that the iterator has been exhausted + after producing `num_outputs` elements. + + Raises: + AssertionError if any test fails. + """ + if context.executing_eagerly(): + self.skipTest("Eager mode iteration do not support re-initialization.") + + break_point = num_outputs // 2 if not break_point else break_point + + # Collect ground truth containing all outputs. + expected = self.gen_outputs( + ds_fn, [], + num_outputs, + sparse_tensors=sparse_tensors, + verify_exhausted=verify_exhausted) + + # Skip some items and save checkpoint. + self.gen_outputs( + ds_fn, [], + break_point, + sparse_tensors=sparse_tensors, + verify_exhausted=False) + + actual = [] + # Restore from checkpoint and then run init_op. + with ops.Graph().as_default() as g: + saver = self._import_meta_graph() + init_op, get_next_op = self._get_iterator_ops_from_collection( + ds_fn, sparse_tensors=sparse_tensors) + get_next_op = remove_variants(get_next_op) + with self.session(graph=g) as sess: + self._initialize(init_op, sess) + self._restore(saver, sess) + self._initialize(init_op, sess) + for _ in range(num_outputs): + actual.append(sess.run(get_next_op)) + if verify_exhausted: + with self.assertRaises(errors.OutOfRangeError): + sess.run(get_next_op) + self.match(expected, actual) + + def verify_error_on_save(self, + ds_fn, + num_outputs, + error, + break_point=None, + sparse_tensors=False): + """Attempts to save a non-saveable iterator. + + Args: + ds_fn: 0-argument function that returns a Dataset. + num_outputs: Total number of outputs expected from this Dataset. + error: Declared error when trying to save iterator. + break_point: Break point. Optional. Defaults to num_outputs/2. + sparse_tensors: Whether dataset is built from SparseTensor(s). + + Raises: + AssertionError if any test fails. + """ + break_point = num_outputs // 2 if not break_point else break_point + if context.executing_eagerly(): + iterator = iter(ds_fn()) + ckpt = tracking_util.Checkpoint(iterator=iterator) + for _ in range(break_point): + next(iterator) + with self.assertRaises(error): + ckpt.save(self._ckpt_path()) + else: + with ops.Graph().as_default() as g: + init_op, get_next_op, saver = self._build_graph( + ds_fn, sparse_tensors=sparse_tensors) + get_next_op = remove_variants(get_next_op) + with self.session(graph=g) as sess: + self._initialize(init_op, sess) + for _ in range(break_point): + sess.run(get_next_op) + with self.assertRaises(error): + self._save(sess, saver) + + def verify_run_with_breaks(self, + ds_fn, + break_points, + num_outputs, + sparse_tensors=False, + verify_exhausted=True): + """Verifies that ds_fn() produces the same outputs with and without breaks. + + 1. Builds a Dataset using `ds_fn` and produces `num_outputs` items from it + *without* stopping at break points. + 2. Builds a Dataset using `ds_fn` and produces `num_outputs` items from it + with stopping at break points. + + Deep matches outputs from 1 and 2. + + Args: + ds_fn: 0-argument function that returns a Dataset. + break_points: A list of integers. For each `break_point` in + `break_points`, we produce outputs till `break_point` number of items + have been produced and then checkpoint the state. The current graph and + session are destroyed and a new graph and session are used to produce + outputs till next checkpoint or till `num_outputs` elements have been + produced. `break_point` must be <= `num_outputs`. + num_outputs: Total number of outputs expected from this Dataset. + sparse_tensors: Whether dataset is built from SparseTensor(s). + verify_exhausted: Whether to verify that the iterator has been exhausted + after producing `num_outputs` elements. + + Raises: + AssertionError if any test fails. + """ + expected = self.gen_outputs( + ds_fn, [], + num_outputs, + sparse_tensors=sparse_tensors, + verify_exhausted=verify_exhausted) + + actual = self.gen_outputs( + ds_fn, + break_points, + num_outputs, + sparse_tensors=sparse_tensors, + verify_exhausted=verify_exhausted) + + self.match(expected, actual) + + def gen_outputs(self, + ds_fn, + break_points, + num_outputs, + ckpt_saved=False, + sparse_tensors=False, + verify_exhausted=True, + save_checkpoint_at_end=True): + """Generates elements from input dataset while stopping at break points. + + Produces `num_outputs` outputs and saves the state of the iterator in the + Saver checkpoint. + + Args: + ds_fn: 0-argument function that returns the dataset. + break_points: A list of integers. For each `break_point` in + `break_points`, we produce outputs till `break_point` number of items + have been produced and then checkpoint the state. The current graph and + session are destroyed and a new graph and session are used to produce + outputs till next checkpoint or till `num_outputs` elements have been + produced. `break_point` must be <= `num_outputs`. + num_outputs: The total number of outputs to produce from the iterator. + ckpt_saved: Whether a checkpoint already exists. + sparse_tensors: Whether dataset is built from SparseTensor(s). + verify_exhausted: Whether to verify that the iterator has been exhausted + after producing `num_outputs` elements. + save_checkpoint_at_end: Whether to save a checkpoint after producing all + outputs. If False, checkpoints are saved each break point but not at the + end. Note that checkpoints overwrite each other so there is always only + a single checkpoint available. Defaults to True. + + Returns: + A list of `num_outputs` items. + """ + outputs = [] + + if context.executing_eagerly(): + for i in range(len(break_points) + 1): + iterator = iter(ds_fn()) + ckpt = tracking_util.Checkpoint(iterator=iterator) + if ckpt_saved: + ckpt_path = self._latest_ckpt() + ckpt.restore(ckpt_path) + start = break_points[i - 1] if i > 0 else 0 + end = break_points[i] if i < len(break_points) else num_outputs + num_iters = end - start + for _ in range(num_iters): + outputs.append(self.evaluate(next(iterator))) + if i == len(break_points) and verify_exhausted: + with self.assertRaises(StopIteration): + next(iterator) + if save_checkpoint_at_end or i < len(break_points): + # TODO(b/275117275): Verify if TF2 async checkpoint works. + ckpt_options = checkpoint_options.CheckpointOptions() + ckpt_options.experimental_enable_async_checkpoint = False + ckpt_options.enable_async = False + ckpt_path = ckpt.save(self._ckpt_path(), options=ckpt_options) + ckpt_saved = True + else: + def get_ops(): + if ckpt_saved: + saver = self._import_meta_graph() + init_op, get_next_op = self._get_iterator_ops_from_collection( + ds_fn, sparse_tensors=sparse_tensors) + else: + init_op, get_next_op, saver = self._build_graph( + ds_fn, sparse_tensors=sparse_tensors) + return init_op, get_next_op, saver + + for i in range(len(break_points) + 1): + with ops.Graph().as_default() as g: + init_op, get_next_op, saver = get_ops() + get_next_op = remove_variants(get_next_op) + with self.session(graph=g) as sess: + if ckpt_saved: + self._initialize(init_op, sess) + self._restore(saver, sess) + else: + self._initialize(init_op, sess) + start = break_points[i - 1] if i > 0 else 0 + end = break_points[i] if i < len(break_points) else num_outputs + num_iters = end - start + for _ in range(num_iters): + outputs.append(sess.run(get_next_op)) + if i == len(break_points) and verify_exhausted: + with self.assertRaises(errors.OutOfRangeError): + sess.run(get_next_op) + if save_checkpoint_at_end or i < len(break_points): + self._save(sess, saver) + ckpt_saved = True + + return outputs + + def match(self, expected, actual): + """Matches nested structures. + + Recursively matches shape and values of `expected` and `actual`. + Handles scalars, numpy arrays and other python sequence containers + e.g. list, dict, as well as SparseTensorValue and RaggedTensorValue. + + Args: + expected: Nested structure 1. + actual: Nested structure 2. + + Raises: + AssertionError if matching fails. + """ + if isinstance(expected, np.ndarray): + expected = expected.tolist() + if isinstance(actual, np.ndarray): + actual = actual.tolist() + self.assertEqual(type(expected), type(actual)) + + if nest.is_nested(expected): + self.assertEqual(len(expected), len(actual)) + if isinstance(expected, dict): + for key1, key2 in zip(sorted(expected), sorted(actual)): + self.assertEqual(key1, key2) + self.match(expected[key1], actual[key2]) + else: + for item1, item2 in zip(expected, actual): + self.match(item1, item2) + elif isinstance(expected, sparse_tensor.SparseTensorValue): + self.match((expected.indices, expected.values, expected.dense_shape), + (actual.indices, actual.values, actual.dense_shape)) + elif isinstance(expected, ragged_tensor_value.RaggedTensorValue): + self.match((expected.values, expected.row_splits), + (actual.values, actual.row_splits)) + else: + self.assertEqual(expected, actual) + + def does_not_match(self, expected, actual): + with self.assertRaises(AssertionError): + self.match(expected, actual) + + def gen_break_points(self, num_outputs, num_samples=10): + """Generates `num_samples` unique break points in [0, num_outputs].""" + return np.unique(np.linspace(0, num_outputs, num_samples, dtype=int)) + + def _build_graph(self, ds_fn, sparse_tensors=False): + dataset = ds_fn() + iterator = dataset_ops.make_initializable_iterator(dataset) + external_state_policy = dataset.options().experimental_external_state_policy + saveable = contrib_iterator_ops.make_saveable_from_iterator( + iterator, external_state_policy=external_state_policy) + ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable) + init_op = iterator.initializer + if sparse_tensors: + get_next = sparse_tensor.SparseTensor(*iterator.get_next()) + else: + get_next = iterator.get_next() + self._add_iterator_ops_to_collection(init_op, get_next, ds_fn, + sparse_tensors) + saver = saver_lib.Saver(allow_empty=True) + return init_op, get_next, saver + + def _add_iterator_ops_to_collection(self, + init_op, + get_next, + ds_fn, + sparse_tensors=False): + ops.add_to_collection("iterator_ops", init_op) + # `get_next` may be a tuple e.g. in TensorSliceDataset. Since Collections + # do not support tuples we flatten the tensors and restore the shape in + # `_get_iterator_ops_from_collection`. + if sparse_tensors: # specific for deprecated `from_sparse_tensor_slices`. + ops.add_to_collection("iterator_ops", get_next.indices) + ops.add_to_collection("iterator_ops", get_next.values) + ops.add_to_collection("iterator_ops", get_next.dense_shape) + return + + get_next_list = nest.flatten(get_next) + for i, output_class in enumerate( + nest.flatten(self._get_output_classes(ds_fn))): + if output_class is sparse_tensor.SparseTensor: + ops.add_to_collection("iterator_ops", get_next_list[i].indices) + ops.add_to_collection("iterator_ops", get_next_list[i].values) + ops.add_to_collection("iterator_ops", get_next_list[i].dense_shape) + else: + ops.add_to_collection("iterator_ops", get_next_list[i]) + + def _get_iterator_ops_from_collection(self, ds_fn, sparse_tensors=False): + all_ops = ops.get_collection("iterator_ops") + if sparse_tensors: # specific for deprecated `from_sparse_tensor_slices`. + init_op, indices, values, dense_shape = all_ops + return init_op, sparse_tensor.SparseTensor(indices, values, dense_shape) + get_next_list = [] + i = 1 + for output_class in nest.flatten(self._get_output_classes(ds_fn)): + if output_class is sparse_tensor.SparseTensor: + indices, values, dense_shape = all_ops[i:i + 3] + i += 3 + get_next_list.append( + sparse_tensor.SparseTensor(indices, values, dense_shape)) + else: + get_next_list.append(all_ops[i]) + i += 1 + return all_ops[0], nest.pack_sequence_as( + self._get_output_types(ds_fn), get_next_list) + + def _get_output_types(self, ds_fn): + assert not context.executing_eagerly() + with ops.Graph().as_default(): + return dataset_ops.get_legacy_output_types(ds_fn()) + + def _get_output_shapes(self, ds_fn): + assert not context.executing_eagerly() + with ops.Graph().as_default(): + return dataset_ops.get_legacy_output_shapes(ds_fn()) + + def _get_output_classes(self, ds_fn): + assert not context.executing_eagerly() + with ops.Graph().as_default(): + return dataset_ops.get_legacy_output_classes(ds_fn()) + + def _ckpt_path(self): + return os.path.join(self.get_temp_dir(), "iterator") + + def _latest_ckpt(self): + return checkpoint_management.latest_checkpoint(self.get_temp_dir()) + + def _save(self, sess, saver): + saver.save(sess, self._ckpt_path()) + + def _restore(self, saver, sess): + sess.run(lookup_ops.tables_initializer()) + saver.restore(sess, self._latest_ckpt()) + + def _initialize(self, init_op, sess): + sess.run(variables.global_variables_initializer()) + sess.run(lookup_ops.tables_initializer()) + sess.run(init_op) + + def _import_meta_graph(self): + meta_file_path = self._ckpt_path() + ".meta" + return saver_lib.import_meta_graph(meta_file_path) + + def _delete_ckpt(self): + # Remove all checkpoint files. + prefix = self._ckpt_path() + pattern = prefix + "*" + files = gfile.Glob(pattern) + map(gfile.Remove, files) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..cb46d47c77009e1e2db7d06450883413b79d2a3b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/test_base.py @@ -0,0 +1,448 @@ +# 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. +# ============================================================================== +"""Test utilities for tf.data functionality.""" +import os +import random +import re + +from tensorflow.python.data.experimental.ops import lookup_ops as data_lookup_ops +from tensorflow.python.data.experimental.ops import random_access +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import test_mode +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.eager import context +from tensorflow.python.framework import combinations +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import test + + +def default_test_combinations(): + """Returns the default test combinations for tf.data tests.""" + return combinations.combine(tf_api_version=[1, 2], mode=["eager", "graph"]) + + +def eager_only_combinations(): + """Returns the default test combinations for eager mode only tf.data tests.""" + return combinations.combine(tf_api_version=[1, 2], mode="eager") + + +def graph_only_combinations(): + """Returns the default test combinations for graph mode only tf.data tests.""" + return combinations.combine(tf_api_version=[1, 2], mode="graph") + + +def v1_only_combinations(): + """Returns the default test combinations for v1 only tf.data tests.""" + return combinations.combine(tf_api_version=1, mode=["eager", "graph"]) + + +def v2_only_combinations(): + """Returns the default test combinations for v2 only tf.data tests.""" + return combinations.combine(tf_api_version=2, mode=["eager", "graph"]) + + +def v2_eager_only_combinations(): + """Returns the default test combinations for v2 eager only tf.data tests.""" + return combinations.combine(tf_api_version=2, mode="eager") + + +class DatasetTestBase(test.TestCase): + """Base class for dataset tests.""" + + def setUp(self): + super().setUp() + test_mode.toggle_test_mode(True) + + def assert_op_cancelled(self, op): + with self.assertRaises(errors.CancelledError): + self.evaluate(op) + + def assertValuesEqual(self, expected, actual): + """Asserts that two values are equal.""" + if isinstance(expected, dict): + self.assertItemsEqual(list(expected.keys()), list(actual.keys())) + for k in expected.keys(): + self.assertValuesEqual(expected[k], actual[k]) + elif sparse_tensor.is_sparse(expected): + self.assertAllEqual(expected.indices, actual.indices) + self.assertAllEqual(expected.values, actual.values) + self.assertAllEqual(expected.dense_shape, actual.dense_shape) + else: + self.assertAllEqual(expected, actual) + + def getNext(self, dataset, requires_initialization=False, shared_name=None): + """Returns a callable that returns the next element of the dataset. + + Example use: + ```python + # In both graph and eager modes + dataset = ... + get_next = self.getNext(dataset) + result = self.evaluate(get_next()) + ``` + + Args: + dataset: A dataset whose elements will be returned. + requires_initialization: Indicates that when the test is executed in graph + mode, it should use an initializable iterator to iterate through the + dataset (e.g. when it contains stateful nodes). Defaults to False. + shared_name: (Optional.) If non-empty, the returned iterator will be + shared under the given name across multiple sessions that share the same + devices (e.g. when using a remote server). + Returns: + A callable that returns the next element of `dataset`. Any `TensorArray` + objects `dataset` outputs are stacked. + """ + def ta_wrapper(gn): + def _wrapper(): + r = gn() + if isinstance(r, tensor_array_ops.TensorArray): + return r.stack() + else: + return r + return _wrapper + + # Create an anonymous iterator if we are in eager-mode or are graph inside + # of a tf.function. + if context.executing_eagerly() or ops.inside_function(): + iterator = iter(dataset) + return ta_wrapper(iterator._next_internal) # pylint: disable=protected-access + else: + if requires_initialization: + iterator = dataset_ops.make_initializable_iterator(dataset, shared_name) + self.evaluate(iterator.initializer) + else: + iterator = dataset_ops.make_one_shot_iterator(dataset) + get_next = iterator.get_next() + return ta_wrapper(lambda: get_next) + + def _compareOutputToExpected(self, result_values, expected_values, + assert_items_equal): + if assert_items_equal: + # TODO(shivaniagrawal): add support for nested elements containing sparse + # tensors when needed. + self.assertItemsEqual(result_values, expected_values) + return + for i in range(len(result_values)): + nest.assert_same_structure(result_values[i], expected_values[i]) + for result_value, expected_value in zip( + nest.flatten(result_values[i]), nest.flatten(expected_values[i])): + self.assertValuesEqual(expected_value, result_value) + + def getDatasetOutput(self, dataset, requires_initialization=False): + get_next = self.getNext( + dataset, requires_initialization=requires_initialization) + return self.getIteratorOutput(get_next) + + def getIteratorOutput(self, get_next): + """Evaluates `get_next` until end of input, returning the results.""" + results = [] + while True: + try: + results.append(self.evaluate(get_next())) + except errors.OutOfRangeError: + break + return results + + def assertDatasetProduces(self, + dataset, + expected_output=None, + expected_shapes=None, + expected_error=None, + requires_initialization=False, + num_test_iterations=1, + assert_items_equal=False, + expected_error_iter=1): + """Asserts that a dataset produces the expected output / error. + + Args: + dataset: A dataset to check for the expected output / error. + expected_output: A list of elements that the dataset is expected to + produce. + expected_shapes: A list of TensorShapes which is expected to match + output_shapes of dataset. + expected_error: A tuple `(type, predicate)` identifying the expected error + `dataset` should raise. The `type` should match the expected exception + type, while `predicate` should either be 1) a unary function that inputs + the raised exception and returns a boolean indicator of success or 2) a + regular expression that is expected to match the error message + partially. + requires_initialization: Indicates that when the test is executed in graph + mode, it should use an initializable iterator to iterate through the + dataset (e.g. when it contains stateful nodes). Defaults to False. + num_test_iterations: Number of times `dataset` will be iterated. Defaults + to 1. + assert_items_equal: Tests expected_output has (only) the same elements + regardless of order. + expected_error_iter: How many times to iterate before expecting an error, + if an error is expected. + """ + self.assertTrue( + expected_error is not None or expected_output is not None, + "Exactly one of expected_output or expected error should be provided.") + if expected_error: + self.assertTrue( + expected_output is None, + "Exactly one of expected_output or expected error should be provided." + ) + with self.assertRaisesWithPredicateMatch(expected_error[0], + expected_error[1]): + get_next = self.getNext( + dataset, requires_initialization=requires_initialization) + for _ in range(expected_error_iter): + self.evaluate(get_next()) + return + if expected_shapes: + self.assertEqual(expected_shapes, + dataset_ops.get_legacy_output_shapes(dataset)) + self.assertGreater(num_test_iterations, 0) + for _ in range(num_test_iterations): + get_next = self.getNext( + dataset, requires_initialization=requires_initialization) + result = [] + for _ in range(len(expected_output)): + try: + result.append(self.evaluate(get_next())) + except errors.OutOfRangeError: + raise AssertionError( + "Dataset ended early, producing %d elements out of %d. " + "Dataset output: %s" % + (len(result), len(expected_output), str(result))) + self._compareOutputToExpected(result, expected_output, assert_items_equal) + with self.assertRaises(errors.OutOfRangeError): + self.evaluate(get_next()) + with self.assertRaises(errors.OutOfRangeError): + self.evaluate(get_next()) + + def assertDatasetsEqual(self, dataset1, dataset2): + """Checks that datasets are equal. Supports both graph and eager mode.""" + self.assertTrue( + structure.are_compatible( + dataset_ops.get_structure(dataset1), + dataset_ops.get_structure(dataset2))) + + flattened_types = nest.flatten( + dataset_ops.get_legacy_output_types(dataset1)) + + next1 = self.getNext(dataset1) + next2 = self.getNext(dataset2) + + while True: + try: + op1 = self.evaluate(next1()) + except errors.OutOfRangeError: + with self.assertRaises(errors.OutOfRangeError): + self.evaluate(next2()) + break + op2 = self.evaluate(next2()) + + op1 = nest.flatten(op1) + op2 = nest.flatten(op2) + assert len(op1) == len(op2) + for i in range(len(op1)): + if sparse_tensor.is_sparse(op1[i]) or ragged_tensor.is_ragged(op1[i]): + self.assertValuesEqual(op1[i], op2[i]) + elif flattened_types[i] == dtypes.string: + self.assertAllEqual(op1[i], op2[i]) + else: + self.assertAllClose(op1[i], op2[i]) + + def assertDatasetsRaiseSameError(self, + dataset1, + dataset2, + exception_class, + replacements=None): + """Checks that datasets raise the same error on the first get_next call.""" + if replacements is None: + replacements = [] + next1 = self.getNext(dataset1) + next2 = self.getNext(dataset2) + try: + self.evaluate(next1()) + raise ValueError( + "Expected dataset to raise an error of type %s, but it did not." % + repr(exception_class)) + except exception_class as e: + expected_message = e.message + for old, new, count in replacements: + expected_message = expected_message.replace(old, new, count) + # Check that the first segment of the error messages are the same. + with self.assertRaisesRegexp(exception_class, + re.escape(expected_message)): + self.evaluate(next2()) + + def structuredDataset(self, dataset_structure, shape=None, + dtype=dtypes.int64): + """Returns a singleton dataset with the given structure.""" + if shape is None: + shape = [] + if dataset_structure is None: + return dataset_ops.Dataset.from_tensors( + array_ops.zeros(shape, dtype=dtype)) + else: + return dataset_ops.Dataset.zip( + tuple([ + self.structuredDataset(substructure, shape, dtype) + for substructure in dataset_structure + ])) + + def verifyRandomAccess(self, dataset, expected): + self.verifyRandomAccessInfiniteCardinality(dataset, expected) + with self.assertRaises(errors.OutOfRangeError): + self.evaluate(random_access.at(dataset, index=len(expected))) + + def verifyRandomAccessInfiniteCardinality(self, dataset, expected): + """Tests randomly accessing elements of a dataset.""" + # Tests accessing the elements in a shuffled order with repeats. + len_expected = len(expected) + indices = list(range(len_expected)) * 2 + random.shuffle(indices) + for i in indices: + self.assertAllEqual(expected[i], + self.evaluate(random_access.at(dataset, i))) + + # Tests accessing the elements in order. + indices = set(sorted(indices)) + for i in indices: + self.assertAllEqual(expected[i], + self.evaluate(random_access.at(dataset, i))) + + def textFileInitializer(self, vals): + file = os.path.join(self.get_temp_dir(), "text_file_initializer") + with open(file, "w") as f: + f.write("\n".join(str(v) for v in vals) + "\n") + return lookup_ops.TextFileInitializer(file, dtypes.int64, + lookup_ops.TextFileIndex.LINE_NUMBER, + dtypes.int64, + lookup_ops.TextFileIndex.WHOLE_LINE) + + def keyValueTensorInitializer(self, vals): + keys_tensor = constant_op.constant( + list(range(len(vals))), dtype=dtypes.int64) + vals_tensor = constant_op.constant(vals) + return lookup_ops.KeyValueTensorInitializer(keys_tensor, vals_tensor) + + def datasetInitializer(self, vals): + keys = dataset_ops.Dataset.range(len(vals)) + values = dataset_ops.Dataset.from_tensor_slices(vals) + ds = dataset_ops.Dataset.zip((keys, values)) + return data_lookup_ops.DatasetInitializer(ds) + + def lookupTableInitializer(self, init_source, vals): + """Returns a lookup table initializer for the given source and values. + + Args: + init_source: One of ["textfile", "keyvalue", "dataset"], indicating what + type of initializer to use. + vals: The initializer values. The keys will be `range(len(vals))`. + """ + if init_source == "textfile": + return self.textFileInitializer(vals) + elif init_source == "keyvaluetensor": + return self.keyValueTensorInitializer(vals) + elif init_source == "dataset": + return self.datasetInitializer(vals) + else: + raise ValueError("Unrecognized init_source: " + init_source) + + def graphRoundTrip(self, dataset, allow_stateful=False): + """Converts a dataset to a graph and back.""" + graph = gen_dataset_ops.dataset_to_graph( + dataset._variant_tensor, allow_stateful=allow_stateful) # pylint: disable=protected-access + return dataset_ops.from_variant( + gen_experimental_dataset_ops.dataset_from_graph(graph), + dataset.element_spec) + + def structuredElement(self, element_structure, shape=None, + dtype=dtypes.int64): + """Returns an element with the given structure.""" + if shape is None: + shape = [] + if element_structure is None: + return array_ops.zeros(shape, dtype=dtype) + else: + return tuple([ + self.structuredElement(substructure, shape, dtype) + for substructure in element_structure + ]) + + def checkDeterminism(self, dataset_fn, expect_determinism, expected_elements): + """Tests whether a dataset produces its elements deterministically. + + `dataset_fn` takes a delay_ms argument, which tells it how long to delay + production of the first dataset element. This gives us a way to trigger + out-of-order production of dataset elements. + + Args: + dataset_fn: A function taking a delay_ms argument. + expect_determinism: Whether to expect deterministic ordering. + expected_elements: The elements expected to be produced by the dataset, + assuming the dataset produces elements in deterministic order. + """ + if expect_determinism: + dataset = dataset_fn(100) + actual = self.getDatasetOutput(dataset) + self.assertAllEqual(expected_elements, actual) + return + + # We consider the test a success if it succeeds under any delay_ms. The + # delay_ms needed to observe non-deterministic ordering varies across + # test machines. Usually 10 or 100 milliseconds is enough, but on slow + # machines it could take longer. + for delay_ms in [10, 100, 1000, 20000, 100000]: + dataset = dataset_fn(delay_ms) + actual = self.getDatasetOutput(dataset) + self.assertCountEqual(expected_elements, actual) + for i in range(len(actual)): + if actual[i] != expected_elements[i]: + return + self.fail("Failed to observe nondeterministic ordering") + + def configureDevicesForMultiDeviceTest(self, num_devices): + """Configures number of logical devices for multi-device tests. + + It returns a list of device names. If invoked in GPU-enabled runtime, the + last device name will be for a GPU device. Otherwise, all device names will + be for a CPU device. + + Args: + num_devices: The number of devices to configure. + + Returns: + A list of device names to use for a multi-device test. + """ + cpus = config.list_physical_devices("CPU") + gpus = config.list_physical_devices("GPU") + config.set_logical_device_configuration(cpus[0], [ + context.LogicalDeviceConfiguration() for _ in range(num_devices) + ]) + devices = ["/device:CPU:" + str(i) for i in range(num_devices - 1)] + if gpus: + devices.append("/device:GPU:0") + else: + devices.append("/device:CPU:" + str(num_devices - 1)) + return devices diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/tf_record_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/tf_record_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd4d4afccc9039f0b166d342cb788e642ec637e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/kernel_tests/tf_record_test_base.py @@ -0,0 +1,338 @@ +# 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. +# ============================================================================== +"""Base class for testing reader datasets.""" + +import os + +from tensorflow.core.example import example_pb2 +from tensorflow.core.example import feature_pb2 +from tensorflow.python.data.experimental.ops import readers +from tensorflow.python.data.kernel_tests import test_base +from tensorflow.python.data.ops import readers as core_readers +from tensorflow.python.framework import dtypes +from tensorflow.python.lib.io import python_io +from tensorflow.python.ops import parsing_ops +from tensorflow.python.util import compat + + +class FeaturesTestBase(test_base.DatasetTestBase): + """Base class for testing TFRecord-based features.""" + + def setUp(self): + super(FeaturesTestBase, self).setUp() + self._num_files = 2 + self._num_records = 7 + self._filenames = self._createFiles() + + def make_batch_feature(self, + filenames, + num_epochs, + batch_size, + label_key=None, + reader_num_threads=1, + parser_num_threads=1, + shuffle=False, + shuffle_seed=None, + drop_final_batch=False): + self.filenames = filenames + self.num_epochs = num_epochs + self.batch_size = batch_size + + return readers.make_batched_features_dataset( + file_pattern=self.filenames, + batch_size=self.batch_size, + features={ + "file": parsing_ops.FixedLenFeature([], dtypes.int64), + "record": parsing_ops.FixedLenFeature([], dtypes.int64), + "keywords": parsing_ops.VarLenFeature(dtypes.string), + "label": parsing_ops.FixedLenFeature([], dtypes.string), + }, + label_key=label_key, + reader=core_readers.TFRecordDataset, + num_epochs=self.num_epochs, + shuffle=shuffle, + shuffle_seed=shuffle_seed, + reader_num_threads=reader_num_threads, + parser_num_threads=parser_num_threads, + drop_final_batch=drop_final_batch) + + def _record(self, f, r, l): + example = example_pb2.Example( + features=feature_pb2.Features( + feature={ + "file": + feature_pb2.Feature( + int64_list=feature_pb2.Int64List(value=[f])), + "record": + feature_pb2.Feature( + int64_list=feature_pb2.Int64List(value=[r])), + "keywords": + feature_pb2.Feature( + bytes_list=feature_pb2.BytesList( + value=self._get_keywords(f, r))), + "label": + feature_pb2.Feature( + bytes_list=feature_pb2.BytesList( + value=[compat.as_bytes(l)])) + })) + return example.SerializeToString() + + def _get_keywords(self, f, r): + num_keywords = 1 + (f + r) % 2 + keywords = [] + for index in range(num_keywords): + keywords.append(compat.as_bytes("keyword%d" % index)) + return keywords + + def _sum_keywords(self, num_files): + sum_keywords = 0 + for i in range(num_files): + for j in range(self._num_records): + sum_keywords += 1 + (i + j) % 2 + return sum_keywords + + def _createFiles(self): + filenames = [] + for i in range(self._num_files): + fn = os.path.join(self.get_temp_dir(), "tf_record.%d.txt" % i) + filenames.append(fn) + writer = python_io.TFRecordWriter(fn) + for j in range(self._num_records): + writer.write(self._record(i, j, "fake-label")) + writer.close() + return filenames + + def _run_actual_batch(self, outputs, label_key_provided=False): + if label_key_provided: + # outputs would be a tuple of (feature dict, label) + features, label = self.evaluate(outputs()) + else: + features = self.evaluate(outputs()) + label = features["label"] + file_out = features["file"] + keywords_indices = features["keywords"].indices + keywords_values = features["keywords"].values + keywords_dense_shape = features["keywords"].dense_shape + record = features["record"] + return ([ + file_out, keywords_indices, keywords_values, keywords_dense_shape, + record, label + ]) + + def _next_actual_batch(self, label_key_provided=False): + return self._run_actual_batch(self.outputs, label_key_provided) + + def _interleave(self, iterators, cycle_length): + pending_iterators = iterators + open_iterators = [] + num_open = 0 + for i in range(cycle_length): + if pending_iterators: + open_iterators.append(pending_iterators.pop(0)) + num_open += 1 + + while num_open: + for i in range(min(cycle_length, len(open_iterators))): + if open_iterators[i] is None: + continue + try: + yield next(open_iterators[i]) + except StopIteration: + if pending_iterators: + open_iterators[i] = pending_iterators.pop(0) + else: + open_iterators[i] = None + num_open -= 1 + + def _next_expected_batch(self, + file_indices, + batch_size, + num_epochs, + cycle_length=1): + + def _next_record(file_indices): + for j in file_indices: + for i in range(self._num_records): + yield j, i, compat.as_bytes("fake-label") + + def _next_record_interleaved(file_indices, cycle_length): + return self._interleave([_next_record([i]) for i in file_indices], + cycle_length) + + file_batch = [] + keywords_batch_indices = [] + keywords_batch_values = [] + keywords_batch_max_len = 0 + record_batch = [] + batch_index = 0 + label_batch = [] + for _ in range(num_epochs): + if cycle_length == 1: + next_records = _next_record(file_indices) + else: + next_records = _next_record_interleaved(file_indices, cycle_length) + for record in next_records: + f = record[0] + r = record[1] + label_batch.append(record[2]) + file_batch.append(f) + record_batch.append(r) + keywords = self._get_keywords(f, r) + keywords_batch_values.extend(keywords) + keywords_batch_indices.extend( + [[batch_index, i] for i in range(len(keywords))]) + batch_index += 1 + keywords_batch_max_len = max(keywords_batch_max_len, len(keywords)) + if len(file_batch) == batch_size: + yield [ + file_batch, keywords_batch_indices, keywords_batch_values, + [batch_size, keywords_batch_max_len], record_batch, label_batch + ] + file_batch = [] + keywords_batch_indices = [] + keywords_batch_values = [] + keywords_batch_max_len = 0 + record_batch = [] + batch_index = 0 + label_batch = [] + if file_batch: + yield [ + file_batch, keywords_batch_indices, keywords_batch_values, + [len(file_batch), keywords_batch_max_len], record_batch, label_batch + ] + + def _verify_records(self, + batch_size, + file_index=None, + num_epochs=1, + label_key_provided=False, + interleave_cycle_length=1): + if file_index is not None: + file_indices = [file_index] + else: + file_indices = range(self._num_files) + + for expected_batch in self._next_expected_batch( + file_indices, + batch_size, + num_epochs, + cycle_length=interleave_cycle_length): + actual_batch = self._next_actual_batch( + label_key_provided=label_key_provided) + for i in range(len(expected_batch)): + self.assertAllEqual(expected_batch[i], actual_batch[i]) + + +class TFRecordTestBase(test_base.DatasetTestBase): + """Base class for TFRecord-based tests.""" + + def setUp(self): + super(TFRecordTestBase, self).setUp() + self._num_files = 2 + self._num_records = 7 + self._filenames = self._createFiles() + + def _interleave(self, iterators, cycle_length): + pending_iterators = iterators + open_iterators = [] + num_open = 0 + for i in range(cycle_length): + if pending_iterators: + open_iterators.append(pending_iterators.pop(0)) + num_open += 1 + + while num_open: + for i in range(min(cycle_length, len(open_iterators))): + if open_iterators[i] is None: + continue + try: + yield next(open_iterators[i]) + except StopIteration: + if pending_iterators: + open_iterators[i] = pending_iterators.pop(0) + else: + open_iterators[i] = None + num_open -= 1 + + def _next_expected_batch(self, file_indices, batch_size, num_epochs, + cycle_length, drop_final_batch, use_parser_fn): + + def _next_record(file_indices): + for j in file_indices: + for i in range(self._num_records): + yield j, i + + def _next_record_interleaved(file_indices, cycle_length): + return self._interleave([_next_record([i]) for i in file_indices], + cycle_length) + + record_batch = [] + batch_index = 0 + for _ in range(num_epochs): + if cycle_length == 1: + next_records = _next_record(file_indices) + else: + next_records = _next_record_interleaved(file_indices, cycle_length) + for f, r in next_records: + record = self._record(f, r) + if use_parser_fn: + record = record[1:] + record_batch.append(record) + batch_index += 1 + if len(record_batch) == batch_size: + yield record_batch + record_batch = [] + batch_index = 0 + if record_batch and not drop_final_batch: + yield record_batch + + def _verify_records(self, outputs, batch_size, file_index, num_epochs, + interleave_cycle_length, drop_final_batch, use_parser_fn): + if file_index is not None: + if isinstance(file_index, list): + file_indices = file_index + else: + file_indices = [file_index] + else: + file_indices = range(self._num_files) + + for expected_batch in self._next_expected_batch( + file_indices, batch_size, num_epochs, interleave_cycle_length, + drop_final_batch, use_parser_fn): + actual_batch = self.evaluate(outputs()) + self.assertAllEqual(expected_batch, actual_batch) + + def _record(self, f, r): + return compat.as_bytes("Record %d of file %d" % (r, f)) + + def _createFiles(self): + filenames = [] + for i in range(self._num_files): + fn = os.path.join(self.get_temp_dir(), "tf_record.%d.txt" % i) + filenames.append(fn) + writer = python_io.TFRecordWriter(fn) + for j in range(self._num_records): + writer.write(self._record(i, j)) + writer.close() + return filenames + + def _writeFile(self, name, data): + filename = os.path.join(self.get_temp_dir(), name) + writer = python_io.TFRecordWriter(filename) + for d in data: + writer.write(compat.as_bytes(str(d))) + writer.close() + return filename + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/batch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/batch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..1816013a87db152900d5300c01f01820c82599ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/batch_op.py @@ -0,0 +1,142 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.batch`.""" + +import warnings + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import debug_mode +from tensorflow.python.data.util import nest +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_dataset_ops + + +def _batch(input_dataset, + batch_size, + drop_remainder=False, + num_parallel_calls=None, + deterministic=None, + name=None): + """See `Dataset.batch` for details.""" + if num_parallel_calls is None or debug_mode.DEBUG_MODE: + if deterministic is not None and not debug_mode.DEBUG_MODE: + warnings.warn("The `deterministic` argument has no effect unless the " + "`num_parallel_calls` argument is specified.") + return _BatchDataset(input_dataset, batch_size, drop_remainder, name=name) + else: + return _ParallelBatchDataset( + input_dataset, + batch_size, + drop_remainder, + num_parallel_calls, + deterministic, + name=name) + + +class _BatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that batches contiguous elements from its input.""" + + def __init__(self, input_dataset, batch_size, drop_remainder, name=None): + """See `Dataset.batch()` for details.""" + self._input_dataset = input_dataset + self._batch_size = ops.convert_to_tensor( + batch_size, dtype=dtypes.int64, name="batch_size") + self._drop_remainder = ops.convert_to_tensor( + drop_remainder, dtype=dtypes.bool, name="drop_remainder") + + constant_drop_remainder = tensor_util.constant_value(self._drop_remainder) + # pylint: disable=protected-access + if constant_drop_remainder: + # NOTE(mrry): `constant_drop_remainder` may be `None` (unknown statically) + # or `False` (explicitly retaining the remainder). + # pylint: disable=g-long-lambda + constant_batch_size = tensor_util.constant_value(self._batch_size) + self._structure = nest.map_structure( + lambda component_spec: component_spec._batch(constant_batch_size), + input_dataset.element_spec) + else: + self._structure = nest.map_structure( + lambda component_spec: component_spec._batch(None), + input_dataset.element_spec) + + self._name = name + variant_tensor = gen_dataset_ops.batch_dataset_v2( + input_dataset._variant_tensor, + batch_size=self._batch_size, + drop_remainder=self._drop_remainder, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._structure + + +class _ParallelBatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that batches contiguous elements from its input in parallel.""" + + def __init__(self, + input_dataset, + batch_size, + drop_remainder, + num_parallel_calls, + deterministic, + name=None): + """See `Dataset.batch()` for details.""" + self._input_dataset = input_dataset + self._batch_size = ops.convert_to_tensor( + batch_size, dtype=dtypes.int64, name="batch_size") + self._drop_remainder = ops.convert_to_tensor( + drop_remainder, dtype=dtypes.bool, name="drop_remainder") + self._num_parallel_calls = ops.convert_to_tensor( + num_parallel_calls, dtype=dtypes.int64, name="num_parallel_calls") + if deterministic is None: + self._deterministic = "default" + elif deterministic: + self._deterministic = "true" + else: + self._deterministic = "false" + + constant_drop_remainder = tensor_util.constant_value(self._drop_remainder) + # pylint: disable=protected-access + if constant_drop_remainder: + # NOTE(mrry): `constant_drop_remainder` may be `None` (unknown statically) + # or `False` (explicitly retaining the remainder). + # pylint: disable=g-long-lambda + constant_batch_size = tensor_util.constant_value(self._batch_size) + self._structure = nest.map_structure( + lambda component_spec: component_spec._batch(constant_batch_size), + input_dataset.element_spec) + else: + self._structure = nest.map_structure( + lambda component_spec: component_spec._batch(None), + input_dataset.element_spec) + + self._name = name + variant_tensor = gen_dataset_ops.parallel_batch_dataset( + input_dataset._variant_tensor, + batch_size=self._batch_size, + num_parallel_calls=self._num_parallel_calls, + drop_remainder=self._drop_remainder, + deterministic=self._deterministic, + **self._common_args) + + super().__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/cache_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/cache_op.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1029661a6d3fa3a13bcf0f6d03266b6dce04ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/cache_op.py @@ -0,0 +1,49 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.cache`.""" + +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _cache(input_dataset, filename, name): # pylint: disable=unused-private-name + return CacheDataset(input_dataset, filename, name) + + +class CacheDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that caches elements of its input.""" + + def __init__(self, input_dataset, filename, name=None): + """See `Dataset.cache()` for details.""" + self._input_dataset = input_dataset + self._filename = ops.convert_to_tensor( + filename, dtype=dtypes.string, name="filename") + self._name = name + if tf2.enabled() and (context.executing_eagerly() or ops.inside_function()): + variant_tensor = gen_dataset_ops.cache_dataset_v2( + input_dataset._variant_tensor, # pylint: disable=protected-access + filename=self._filename, + cache=gen_dataset_ops.dummy_memory_cache(), + **self._common_args) + else: + variant_tensor = gen_dataset_ops.cache_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + filename=self._filename, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/choose_from_datasets_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/choose_from_datasets_op.py new file mode 100644 index 0000000000000000000000000000000000000000..d349dd5b2bb8a454d12c330f830d6049b4c4c6ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/choose_from_datasets_op.py @@ -0,0 +1,54 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.choose_from_datasets`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import directed_interleave_op +from tensorflow.python.data.util import structure +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.types import data as data_types + + +def _choose_from_datasets( # pylint: disable=unused-private-name + datasets, choice_dataset, stop_on_empty_dataset=True +): + """See `Dataset.choose_from_datasets()` for details.""" + + if not datasets: + raise ValueError("Invalid `datasets`. `datasets` should not be empty.") + if not isinstance(choice_dataset, data_types.DatasetV2): + raise TypeError( + "Invalid `choice_dataset`. `choice_dataset` should be a " + f"`tf.data.Dataset` but is {type(choice_dataset)}." + ) + if not structure.are_compatible( + choice_dataset.element_spec, tensor_spec.TensorSpec([], dtypes.int64) + ): + raise TypeError( + "Invalid `choice_dataset`. Elements of `choice_dataset` " + "must be scalar `tf.int64` tensors but are " + f"{choice_dataset.element_spec}." + ) + # Replicates the `choice_dataset` component so that each split makes choices + # independently. This avoids the need for prohibitively expensive + # cross-split coordination. + # pylint: disable=protected-access + choice_dataset = dataset_ops._apply_rewrite( + choice_dataset, "replicate_on_split" + ) + return directed_interleave_op._directed_interleave( # pylint: disable=protected-access + choice_dataset, datasets, stop_on_empty_dataset + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/concatenate_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/concatenate_op.py new file mode 100644 index 0000000000000000000000000000000000000000..9cef9eae16b247026b5ba217c94226991b0e49ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/concatenate_op.py @@ -0,0 +1,63 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.concatenate`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.util import nest as tf_nest + + +def _concatenate(input_dataset, dataset_to_concatenate, name): # pylint: disable=unused-private-name + return _ConcatenateDataset(input_dataset, dataset_to_concatenate, name) + + +class _ConcatenateDataset(dataset_ops.DatasetV2): + """A `Dataset` that concatenates its input with given dataset.""" + + def __init__(self, input_dataset, dataset_to_concatenate, name=None): + """See `Dataset.concatenate()` for details.""" + self._input_dataset = input_dataset + self._dataset_to_concatenate = dataset_to_concatenate + + def common_supertype(a, b): + result = a.most_specific_common_supertype([b]) + if result is None: + raise TypeError(f"No common supertype of {a} and {b}.") + return result + + try: + self._structure = tf_nest.map_structure( + common_supertype, input_dataset.element_spec, + dataset_to_concatenate.element_spec) + except (TypeError, ValueError) as e: + raise TypeError(f"Incompatible dataset elements:\n" + f" {input_dataset.element_spec} vs. " + f" {dataset_to_concatenate.element_spec}") from e + + self._input_datasets = [input_dataset, dataset_to_concatenate] + self._name = name + # pylint: disable=protected-access + variant_tensor = gen_dataset_ops.concatenate_dataset( + input_dataset._variant_tensor, dataset_to_concatenate._variant_tensor, + **self._common_args) + # pylint: enable=protected-access + super().__init__(variant_tensor) + + def _inputs(self): + return self._input_datasets + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/counter_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/counter_op.py new file mode 100644 index 0000000000000000000000000000000000000000..b34478f2d9027c4b55653b0e38f9b534b78fd7b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/counter_op.py @@ -0,0 +1,26 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.counter`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import ops + + +def _counter(start, step, dtype, name=None): + with ops.name_scope("counter"): + start = ops.convert_to_tensor(start, dtype=dtype, name="start") + step = ops.convert_to_tensor(step, dtype=dtype, name="step") + return (dataset_ops.Dataset.from_tensors(0, name=name).repeat(None).scan( + start, lambda state, _: (state + step, state))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/dataset_autograph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/dataset_autograph.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a1acb7d421f39a2e4d0bc468e03ca19a68c33b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/dataset_autograph.py @@ -0,0 +1,224 @@ +# 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. +# ============================================================================== +"""Autograph specifc overrides for dataset_ops.""" +from tensorflow.python.autograph.operators import control_flow +from tensorflow.python.autograph.operators import py_builtins +from tensorflow.python.data.experimental.ops import take_while_ops +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import gen_string_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import nest + + +def _general_purpose_scan(ds, init_state, body): + """Variant of Dataset.scan with semantics of general-purpose computation.""" + # Datasets are typically intended for data preprocessing. However, in + # autograph loops they usually appear as general-purpose computations (for + # example, a custom training loop). These two use cases require significantly + # different optimization policies, the most important of which is the device + # placement. The flag override for use_default_device below instructs the + # runtime to treat the computation as general-purpose, rather than data + # preprocessing. + + # Loaded lazily due to a circular dependency (dataset_ops -> + # scan_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import scan_op + return scan_op._ScanDataset(ds, init_state, body, use_default_device=False) + # pylint: enable=g-import-not-at-top,protected-access + + +def _tf_ag_dataset_for_stmt( + ds, extra_test, body, get_state, set_state, symbol_names, opts +): + """Overload of _dataset_for_stmt with early stopping. See for_stmt.""" + # Note: This is easier to follow with the insight that the computations in + # a dataset pipeline are transposed (aka fused). + # For example, given a pipeline input -> scan -> take_while -> reduce, + # and a dataset with input [1, 2, 3], the computations occur in the following + # order: + # reduce(take_while(scan(1))) + # reduce(take_while(scan(2))) + # reduce(take_while(scan(3))) + + init_vars = get_state() + control_flow.verify_loop_init_vars(init_vars, symbol_names) + + # Workaround for Dataset.reduce not allowing empty state tensors - create + # a dummy state variable that remains unused. + # TODO(mdan): reduce should allow and match empty structures. + if not init_vars: + init_vars = (constant_op.constant(0),) + symbol_names = ("",) + + def dummy_set_state(unused_dummy): + pass + + def dummy_get_state(): + return (constant_op.constant(0),) + + get_state, set_state = dummy_get_state, dummy_set_state + + def scan_body(scan_state, scan_inputs): + """Main body of the Dataset.scan.""" + loop_vars, iterate = scan_state, scan_inputs + set_state(loop_vars) + + def main_path(): + body(iterate) + new_loop_vars = get_state() + control_flow.verify_tf_loop_vars( + init_vars, + loop_vars, + new_loop_vars, + symbol_names, + opts, + check_shapes=False) + return new_loop_vars + + if extra_test is not None: + extra_cond = extra_test() + new_loop_vars = cond.cond(extra_cond, main_path, + lambda: loop_vars) + else: + # TODO(mdan): the optimizer should be able to remove an invariant cond? + extra_cond = (constant_op.constant(True),) # dummy value, unused + new_loop_vars = main_path() + + scan_outputs = new_loop_vars, extra_cond + new_scan_state = new_loop_vars + return new_scan_state, scan_outputs + + def take_while_predicate(unused_loop_vars, extra_cond): + return extra_cond + + def reduce_body(unused_reduce_state, scan_outputs): + output_loop_vars, unused_extra_cond = scan_outputs + new_reduce_state = output_loop_vars + return new_reduce_state + + ds = _general_purpose_scan(ds, init_vars, scan_body) + if extra_test is not None: + ds = ds.apply(take_while_ops.take_while(take_while_predicate)) + final_loop_vars = ds.reduce(init_vars, reduce_body) + set_state(final_loop_vars) + + +def _tf_ag_dataset_abs(ds): + specs = nest.flatten(ds.element_spec) + if len(specs) == 1: + return ds.map(math_ops.abs, num_parallel_calls=dataset_ops.AUTOTUNE) + return ds.map( + lambda *e: nest.map_structure(math_ops.abs, e), + num_parallel_calls=dataset_ops.AUTOTUNE) + + +def _tf_ag_dataset_len(s): + """Autograph override of the builtin len for dataset_ops.DataSetV2.""" + l = s.cardinality() + msg = gen_string_ops.string_join([ + "len requires dataset with definitive cardinality, got ", + gen_string_ops.as_string(l), + ]) + # TODO(yongtang): UNKNOWN is treated as an error. + # In case there are more UNKNOWN cases for dataset, we could + # use dataset.reduce() to find out the length (in an expensive way). + with ops.control_dependencies([ + control_flow_assert.Assert( + math_ops.logical_and( + math_ops.not_equal(l, dataset_ops.INFINITE), + math_ops.not_equal(l, dataset_ops.UNKNOWN)), [msg]) + ]): + l = array_ops.identity(l) + + return l + + +def _tf_ag_dataset_enumerate(ds, start=0): + return ds.enumerate(start) + + +def _tf_ag_dataset_zip(*iterables, strict=False): + if strict: + raise ValueError("strict zip not supported by Dataset") + return dataset_ops.DatasetV2.zip(iterables) + + +def _tf_ag_dataset_map(fn, *iterables): + return dataset_ops.DatasetV2.zip(iterables).map(fn) + + +def _tf_ag_dataset_filter(fn, iterable): + return iterable.filter(fn) + + +# any() operation is essentially a "if first True element exist". +# For that it could be translated to `filter(True)` to filter out +# only `True` element, and then `take(1)`. This works in tf.data +# as tf.data's filter+take is done in pipeline so it will stop +# as soon as `take(1)` returns. +def _tf_ag_dataset_any(iterable): + # check and make sure iterable.element_spec only consists of one + # element of tf.bool. + specs = nest.flatten(iterable.element_spec) + if len(specs) != 1 or specs[0].dtype != dtypes.bool: + raise ValueError('in graph mode, the "any" builtin only supports datasets ' + 'that return bool scalars; got: {}'.format( + iterable.element_spec)) + ds = iterable.filter(lambda x: x) + ds = ds.take(1) + ds = ds.reduce(constant_op.constant(False, dtype=dtypes.bool), lambda _, y: y) + return ds + + +# all() operation is similar to any() and could be translated +# to `filter(False)` then `take(1)`, and check if `False` exists. +def _tf_ag_dataset_all(iterable): + # check and make sure iterable.element_spec only consists of one + # element of tf.bool. + specs = nest.flatten(iterable.element_spec) + if len(specs) != 1 or specs[0].dtype != dtypes.bool: + raise ValueError('in graph mode, the "all" builtin only supports datasets ' + 'that return bool scalars; got: {}'.format( + iterable.element_spec)) + ds = iterable.filter(math_ops.logical_not) + ds = ds.take(1) + ds = ds.reduce(constant_op.constant(True, dtype=dtypes.bool), lambda _, y: y) + return ds + + +def register_overrides(): + """Registers the autograph specific overrides for dataset_ops.""" + control_flow.for_loop_registry.register( + dataset_ops.DatasetV2, _tf_ag_dataset_for_stmt + ) + py_builtins.abs_registry.register(dataset_ops.DatasetV2, _tf_ag_dataset_abs) + py_builtins.len_registry.register(dataset_ops.DatasetV2, _tf_ag_dataset_len) + py_builtins.enumerate_registry.register( + dataset_ops.DatasetV2, _tf_ag_dataset_enumerate + ) + py_builtins.zip_registry.register(dataset_ops.DatasetV2, _tf_ag_dataset_zip) + py_builtins.map_registry.register(dataset_ops.DatasetV2, _tf_ag_dataset_map) + py_builtins.filter_registry.register( + dataset_ops.DatasetV2, _tf_ag_dataset_filter + ) + py_builtins.any_registry.register(dataset_ops.DatasetV2, _tf_ag_dataset_any) + py_builtins.all_registry.register(dataset_ops.DatasetV2, _tf_ag_dataset_all) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/dataset_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/dataset_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..08ea8693d1cbbcba1c5e2c20e31973418e50efb4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/dataset_ops.py @@ -0,0 +1,5217 @@ +# 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. +# ============================================================================== +"""Python wrappers for Datasets.""" + +import abc +import functools +import queue +import threading +from typing import Union +import warnings + +import numpy as np + +from tensorflow.core.framework import dataset_metadata_pb2 +from tensorflow.core.framework import dataset_options_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_autograph +from tensorflow.python.data.ops import debug_mode +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.data.util import traverse +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import wrap_function +from tensorflow.python.framework import auto_control_deps +from tensorflow.python.framework import auto_control_deps_utils as acd_utils +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import none_tensor +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed as core_random_seed +from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_assert +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_io_ops +from tensorflow.python.ops import gen_parsing_ops +from tensorflow.python.ops import logging_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.trackable import asset +from tensorflow.python.trackable import base as tracking_base +from tensorflow.python.trackable import resource as resource_lib +from tensorflow.python.types import data as data_types +from tensorflow.python.types import trace +from tensorflow.python.util import deprecation +from tensorflow.python.util import lazy_loader +from tensorflow.python.util import nest as tf_nest +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +# Symbols forwarded for legacy access through dataset_ops.py. These forwarded +# symbols can be removed once all internal uses are updated. +StructuredFunctionWrapper = structured_function.StructuredFunctionWrapper + +# TODO(b/240947712): Clean up the circular dependencies. +# Loaded lazily due to a circular dependency (dataset_ops -> +# prefetch_op -> dataset_ops). +prefetch_op = lazy_loader.LazyLoader( + "prefetch_op", globals(), + "tensorflow.python.data.ops.prefetch_op") +# Loaded lazily due to a circular dependency (dataset_ops -> +# shuffle_op -> dataset_ops). +shuffle_op = lazy_loader.LazyLoader( + "shuffle_op", globals(), + "tensorflow.python.data.ops.shuffle_op") + + +ops.NotDifferentiable("ReduceDataset") + +# A constant that can be used to enable auto-tuning. +AUTOTUNE = -1 +tf_export("data.AUTOTUNE").export_constant(__name__, "AUTOTUNE") +# TODO(b/168128531): Deprecate and remove this symbol. +tf_export("data.experimental.AUTOTUNE").export_constant(__name__, "AUTOTUNE") + +# Constants representing infinite and unknown cardinalities. +INFINITE = -1 +UNKNOWN = -2 +COMPRESSION_GZIP = "GZIP" +COMPRESSION_SNAPPY = "NONE" +DATASET_SPEC_FILENAME = "dataset_spec.pb" +tf_export("data.INFINITE_CARDINALITY").export_constant(__name__, "INFINITE") +tf_export("data.UNKNOWN_CARDINALITY").export_constant(__name__, "UNKNOWN") + + +def _validate_and_encode(name): + if not name.isidentifier(): + raise ValueError("Invalid `name`. The argument `name` needs to be a valid " + "identifier. Value is considered a valid identifier if it " + "only contains alphanumeric characters (a-z), (A-Z), and " + "(0-9), or underscores (_). A valid identifier cannot " + "start with a number, or contain any spaces.") + return name.encode("utf-8") + + +def get_type(value): + """Returns the type of `value` if it is a TypeSpec.""" + + if isinstance(value, type_spec.TypeSpec): + return value.value_type() + else: + return type(value) + + +@tf_export("data.Dataset", v1=[]) +class DatasetV2( + collections_abc.Iterable, + tracking_base.Trackable, + composite_tensor.CompositeTensor, + data_types.DatasetV2, + metaclass=abc.ABCMeta): + """Represents a potentially large set of elements. + + The `tf.data.Dataset` API supports writing descriptive and efficient input + pipelines. `Dataset` usage follows a common pattern: + + 1. Create a source dataset from your input data. + 2. Apply dataset transformations to preprocess the data. + 3. Iterate over the dataset and process the elements. + + Iteration happens in a streaming fashion, so the full dataset does not need to + fit into memory. + + Source Datasets: + + The simplest way to create a dataset is to create it from a python `list`: + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> for element in dataset: + ... print(element) + tf.Tensor(1, shape=(), dtype=int32) + tf.Tensor(2, shape=(), dtype=int32) + tf.Tensor(3, shape=(), dtype=int32) + + To process lines from files, use `tf.data.TextLineDataset`: + + >>> dataset = tf.data.TextLineDataset(["file1.txt", "file2.txt"]) + + To process records written in the `TFRecord` format, use `TFRecordDataset`: + + >>> dataset = tf.data.TFRecordDataset(["file1.tfrecords", "file2.tfrecords"]) + + To create a dataset of all files matching a pattern, use + `tf.data.Dataset.list_files`: + + ```python + dataset = tf.data.Dataset.list_files("/path/*.txt") + ``` + + See `tf.data.FixedLengthRecordDataset` and `tf.data.Dataset.from_generator` + for more ways to create datasets. + + Transformations: + + Once you have a dataset, you can apply transformations to prepare the data for + your model: + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> dataset = dataset.map(lambda x: x*2) + >>> list(dataset.as_numpy_iterator()) + [2, 4, 6] + + Common Terms: + + **Element**: A single output from calling `next()` on a dataset iterator. + Elements may be nested structures containing multiple components. For + example, the element `(1, (3, "apple"))` has one tuple nested in another + tuple. The components are `1`, `3`, and `"apple"`. + + **Component**: The leaf in the nested structure of an element. + + Supported types: + + Elements can be nested structures of tuples, named tuples, and dictionaries. + Note that Python lists are *not* treated as nested structures of components. + Instead, lists are converted to tensors and treated as components. For + example, the element `(1, [1, 2, 3])` has only two components; the tensor `1` + and the tensor `[1, 2, 3]`. Element components can be of any type + representable by `tf.TypeSpec`, including `tf.Tensor`, `tf.data.Dataset`, + `tf.sparse.SparseTensor`, `tf.RaggedTensor`, and `tf.TensorArray`. + + ```python + a = 1 # Integer element + b = 2.0 # Float element + c = (1, 2) # Tuple element with 2 components + d = {"a": (2, 2), "b": 3} # Dict element with 3 components + Point = collections.namedtuple("Point", ["x", "y"]) + e = Point(1, 2) # Named tuple + f = tf.data.Dataset.range(10) # Dataset element + ``` + + For more information, + read [this guide](https://www.tensorflow.org/guide/data). + """ + + def __init__(self, variant_tensor): + """Creates a DatasetV2 object. + + This is a difference between DatasetV1 and DatasetV2. DatasetV1 does not + take anything in its constructor whereas in the DatasetV2, we expect + subclasses to create a variant_tensor and pass it in to the super() call. + + Args: + variant_tensor: A DT_VARIANT tensor that represents the dataset. + """ + self._variant_tensor_attr = variant_tensor + self._graph_attr = ops.get_default_graph() + + # Initialize the options for this dataset and its inputs. + self._options_attr = options_lib.Options() + for input_dataset in self._inputs(): + input_options = None + if isinstance(input_dataset, data_types.DatasetV1): + # If the V1 dataset does not have the `_dataset` attribute, we assume it + # is a dataset source and hence does not have options. Otherwise, we + # grab the options of `_dataset` object + if hasattr(input_dataset, "_dataset"): + if not isinstance(input_dataset._dataset, data_types.DatasetV2): + raise TypeError( + f"Each input of dataset {type(self)} should be a subclass of " + f"`tf.data.Dataset` but encountered " + f"{type(input_dataset._dataset)}.") + input_options = input_dataset._dataset._options_attr + elif isinstance(input_dataset, data_types.DatasetV2): + input_options = input_dataset._options_attr + else: + raise TypeError( + f"Each input of dataset {type(self)} should be a subclass of " + f"`tf.data.Dataset` but encountered {type(input_dataset)}.") + if input_options is not None: + self._options_attr = self._options_attr.merge(input_options) + self._options_attr._set_mutable(False) # pylint: disable=protected-access + + @property + def _variant_tensor(self): + return self._variant_tensor_attr + + @_variant_tensor.setter + def _variant_tensor(self, _): + raise ValueError("The `_variant_tensor` property cannot be modified.") + + @deprecation.deprecated_args(None, "Use external_state_policy instead", + "allow_stateful") + def _as_serialized_graph( + self, + allow_stateful=None, + strip_device_assignment=None, + external_state_policy=options_lib.ExternalStatePolicy.WARN): + """Produces serialized graph representation of the dataset. + + Args: + allow_stateful: If true, we allow stateful ops to be present in the graph + def. In that case, the state in these ops would be thrown away. + strip_device_assignment: If true, non-local (i.e. job and task) device + assignment is stripped from ops in the serialized graph. + external_state_policy: The ExternalStatePolicy enum that determines how we + handle input pipelines that depend on external state. By default, its + set to WARN. + + Returns: + A scalar `tf.Tensor` of `tf.string` type, representing this dataset as a + serialized graph. + """ + if external_state_policy: + policy = external_state_policy.value + return gen_dataset_ops.dataset_to_graph_v2( + self._variant_tensor, + external_state_policy=policy, + strip_device_assignment=strip_device_assignment) + if strip_device_assignment: + return gen_dataset_ops.dataset_to_graph( + self._variant_tensor, + allow_stateful=allow_stateful, + strip_device_assignment=strip_device_assignment) + return gen_dataset_ops.dataset_to_graph( + self._variant_tensor, allow_stateful=allow_stateful) + + def _maybe_track_assets(self, graph_def): + """Finds and tracks nodes in `graph_def` that refer to asset files. + + Args: + graph_def: Serialized graph representation of this dataset. + + Returns: + A dictionary mapping the node name of an asset constant to a tracked + `asset.Asset` object. + """ + asset_tracker = {} + for node in graph_def.node: + if node.name.startswith("FileIdentity"): + asset_tracker[node.input[0]] = None + + if not asset_tracker: + return {} + + for node in graph_def.node: + if node.name in asset_tracker: + tensor_proto = node.attr["value"].tensor + with context.eager_mode(), ops.device("CPU"): + node_value = gen_parsing_ops.parse_tensor( + tensor_proto.SerializeToString(), dtypes.string).numpy() + asset_tracker[node.name] = ([ + self._track_trackable(asset.Asset(n), + name=node.name + "_" + str(i), overwrite=True) + for i, n in enumerate(node_value) + ]) + return asset_tracker + + def _trackable_children(self, + save_type=tracking_base.SaveType.CHECKPOINT, + **kwargs): + if save_type != tracking_base.SaveType.SAVEDMODEL: + return {} + + # _trace_variant_creation only works when executing eagerly, so we don't + # want to run it in the object initialization. + @def_function.function(input_signature=[], autograph=False) + def _creator(): + resource = self._trace_variant_creation()() # pylint: disable=protected-access + return resource + _creator.get_concrete_function() # Trigger asset tracking + + children = super(DatasetV2, self)._trackable_children(save_type, **kwargs) + children["_variant_tracker"] = _VariantTracker(self._variant_tensor, + _creator) + return children + + def _trace_variant_creation(self): + """Traces a function which outputs a variant `tf.Tensor` for this dataset. + + Note that creating this function involves evaluating an op, and is currently + only supported when executing eagerly. + + Returns: + A zero-argument `ConcreteFunction` which outputs a variant `tf.Tensor`. + """ + variant = self._variant_tensor + if not isinstance(variant, ops.EagerTensor): + raise NotImplementedError( + "Constructing a tf.function that reproduces a given dataset is only " + "supported for datasets created eagerly. Please file a feature " + "request if this is important to you.") + with context.eager_mode(), ops.device("CPU"): + # pylint: disable=protected-access + graph_def = graph_pb2.GraphDef().FromString( + self._as_serialized_graph(external_state_policy=options_lib + .ExternalStatePolicy.FAIL).numpy()) + output_node_names = [] + for node in graph_def.node: + if node.op == "_Retval": + output_node_names = node.input + + if len(output_node_names) != 1: + raise AssertionError( + f"Dataset graph is expected to only have one return value but found " + f"{len(output_node_names)} return values: {output_node_names}.") + + output_node_name = output_node_names[0] + + file_path_nodes = {} + # When building a tf.function, track files as `saved_model.Asset`s. + if ops.get_default_graph().building_function: + asset_tracker = self._maybe_track_assets(graph_def) + for key in asset_tracker: + assets_list = [ + array_ops.expand_dims(asset.asset_path, axis=0) + for asset in asset_tracker[key] + ] + file_path_nodes[key] = array_ops.concat(assets_list, axis=0) + + # Add functions used in this Dataset to the function's graph, since they + # need to follow it around (and for example be added to a SavedModel which + # references the dataset). + variant_function = wrap_function.function_from_graph_def( + graph_def, + inputs=[], + outputs=output_node_name + ":0", + captures=file_path_nodes) + for used_function in self._functions(): + used_function.function.add_to_graph(variant_function.graph) + return variant_function + + @abc.abstractmethod + def _inputs(self): + """Returns a list of the input datasets of the dataset.""" + + raise NotImplementedError(f"{type(self)}._inputs()") + + @property + def _graph(self): + return self._graph_attr + + @_graph.setter + def _graph(self, _): + raise ValueError("The `_graph` property cannot be modified.") + + # TODO(jsimsa): Change this to be the transitive closure of functions used + # by this dataset and its inputs. + def _functions(self) -> list[StructuredFunctionWrapper]: + """Returns a list of functions associated with this dataset. + + Returns: + A list of `StructuredFunctionWrapper` objects. + """ + return [] + + def _options(self): + """Returns the options tensor for this dataset.""" + # pylint: disable=protected-access + return gen_dataset_ops.get_options(self._variant_tensor) + + @classmethod + def _options_tensor_to_options(cls, serialized_options): + """Converts options tensor to tf.data.Options object.""" + options = options_lib.Options() + if tensor_util.constant_value(serialized_options) is not None: + pb = dataset_options_pb2.Options.FromString(tensor_util.constant_value( + serialized_options)) + options._from_proto(pb) # pylint: disable=protected-access + return options + + def options(self): + """Returns the options for this dataset and its inputs. + + Returns: + A `tf.data.Options` object representing the dataset options. + """ + if context.executing_eagerly(): + options = self._options_tensor_to_options(self._options()) + options._set_mutable(False) # pylint: disable=protected-access + return options + warnings.warn("To make it possible to preserve tf.data options across " + "serialization boundaries, their implementation has moved to " + "be part of the TensorFlow graph. As a consequence, the " + "options value is in general no longer known at graph " + "construction time. Invoking this method in graph mode " + "retains the legacy behavior of the original implementation, " + "but note that the returned value might not reflect the " + "actual value of the options.") + return self._options_attr + + def _apply_debug_options(self): + if debug_mode.DEBUG_MODE: + # Disable autotuning and static optimizations that could introduce + # parallelism or asynchrony. + options = options_lib.Options() + options.autotune.enabled = False + options.experimental_optimization.filter_parallelization = False + options.experimental_optimization.map_and_batch_fusion = False + options.experimental_optimization.map_parallelization = False + dataset = _OptionsDataset(self, options) + else: + dataset = self + + return dataset + + def __iter__(self) -> iterator_ops.OwnedIterator: + """Creates an iterator for elements of this dataset. + + The returned iterator implements the Python Iterator protocol. + + Returns: + An `tf.data.Iterator` for the elements of this dataset. + + Raises: + RuntimeError: If not inside of tf.function and not executing eagerly. + """ + if context.executing_eagerly() or ops.inside_function(): + with ops.colocate_with(self._variant_tensor): + return iterator_ops.OwnedIterator(self) + else: + raise RuntimeError("`tf.data.Dataset` only supports Python-style " + "iteration in eager mode or within tf.function.") + + def __bool__(self): + return True # Required as __len__ is defined + + __nonzero__ = __bool__ # Python 2 backward compatibility + + def __len__(self): + """Returns the length of the dataset if it is known and finite. + + This method requires that you are running in eager mode, and that the + length of the dataset is known and non-infinite. When the length may be + unknown or infinite, or if you are running in graph mode, use + `tf.data.Dataset.cardinality` instead. + + Returns: + An integer representing the length of the dataset. + + Raises: + RuntimeError: If the dataset length is unknown or infinite, or if eager + execution is not enabled. + """ + if not context.executing_eagerly(): + raise TypeError("`tf.data.Dataset` only supports `len` in eager mode. " + "Use `tf.data.Dataset.cardinality()` instead.") + length = self.cardinality() + if length.numpy() == INFINITE: + raise TypeError("The dataset is infinite.") + if length.numpy() == UNKNOWN: + raise TypeError("The dataset length is unknown.") + return length + + @abc.abstractproperty + def element_spec(self): + """The type specification of an element of this dataset. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> dataset.element_spec + TensorSpec(shape=(), dtype=tf.int32, name=None) + + For more information, + read [this guide](https://www.tensorflow.org/guide/data#dataset_structure). + + Returns: + A (nested) structure of `tf.TypeSpec` objects matching the structure of an + element of this dataset and specifying the type of individual components. + """ + raise NotImplementedError(f"{type(self)}.element_spec()") + + def __repr__(self): + type_ = type(self._dataset if isinstance(self, DatasetV1Adapter) else self) + return f"<{type_.__name__} element_spec={self.element_spec}>" + + def __debug_string__(self): + """Returns a string showing the type of the dataset and its inputs. + + This string is intended only for debugging purposes, and may change without + warning. + """ + lines = [] + to_process = [(self, 0)] # Stack of (dataset, depth) pairs. + while to_process: + dataset, depth = to_process.pop() + lines.append("-"*2*depth + repr(dataset)) + to_process.extend([(ds, depth+1) for ds in dataset._inputs()]) # pylint: disable=protected-access + return "\n".join(lines) + + def as_numpy_iterator(self): + """Returns an iterator which converts all elements of the dataset to numpy. + + Use `as_numpy_iterator` to inspect the content of your dataset. To see + element shapes and types, print dataset elements directly instead of using + `as_numpy_iterator`. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> for element in dataset: + ... print(element) + tf.Tensor(1, shape=(), dtype=int32) + tf.Tensor(2, shape=(), dtype=int32) + tf.Tensor(3, shape=(), dtype=int32) + + This method requires that you are running in eager mode and the dataset's + element_spec contains only `TensorSpec` components. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> for element in dataset.as_numpy_iterator(): + ... print(element) + 1 + 2 + 3 + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> print(list(dataset.as_numpy_iterator())) + [1, 2, 3] + + `as_numpy_iterator()` will preserve the nested structure of dataset + elements. + + >>> dataset = tf.data.Dataset.from_tensor_slices({'a': ([1, 2], [3, 4]), + ... 'b': [5, 6]}) + >>> list(dataset.as_numpy_iterator()) == [{'a': (1, 3), 'b': 5}, + ... {'a': (2, 4), 'b': 6}] + True + + Returns: + An iterable over the elements of the dataset, with their tensors converted + to numpy arrays. + + Raises: + TypeError: if an element contains a non-`Tensor` value. + RuntimeError: if eager execution is not enabled. + """ + if not context.executing_eagerly(): + raise RuntimeError("`tf.data.Dataset.as_numpy_iterator()` is only " + "supported in eager mode.") + for component_spec in nest.flatten(self.element_spec): + if not isinstance( + component_spec, + (tensor_spec.TensorSpec, ragged_tensor.RaggedTensorSpec, + sparse_tensor_lib.SparseTensorSpec, none_tensor.NoneTensorSpec)): + raise TypeError( + f"`tf.data.Dataset.as_numpy_iterator()` is not supported for " + f"datasets that produce values of type {component_spec.value_type}") + + return NumpyIterator(self) + + @property + def _flat_shapes(self): + """Returns a list `tf.TensorShapes`s for the element tensor representation. + + Returns: + A list `tf.TensorShapes`s for the element tensor representation. + """ + return structure.get_flat_tensor_shapes(self.element_spec) + + @property + def _flat_types(self): + """Returns a list `tf.DType`s for the element tensor representation. + + Returns: + A list `tf.DType`s for the element tensor representation. + """ + return structure.get_flat_tensor_types(self.element_spec) + + @property + def _flat_structure(self): + """Helper for setting `output_shapes` and `output_types` attrs of an op. + + Most dataset op constructors expect `output_shapes` and `output_types` + arguments that represent the flattened structure of an element. This helper + function generates these attrs as a keyword argument dictionary, allowing + `Dataset._variant_tensor` implementations to pass `**self._flat_structure` + to the op constructor. + + Returns: + A dictionary of keyword arguments that can be passed to a dataset op + constructor. + """ + return { + "output_shapes": self._flat_shapes, + "output_types": self._flat_types, + } + + @property + def _metadata(self): + """Helper for generating dataset metadata.""" + metadata = dataset_metadata_pb2.Metadata() + if self._name: + metadata.name = _validate_and_encode(self._name) + return metadata + + @property + def _common_args(self): + """Helper for generating arguments that are common across most dataset ops. + + Most dataset op constructors expect `output_shapes` and `output_types` + arguments that represent the flattened structure of an element, as well as a + `metadata` argument for additional metadata such as user-defined dataset + name. This helper function generates common attributes as a keyword argument + dictionary, allowing `Dataset._variant_tensor` implementations to pass + `**self._common_args` to the op constructor. + + Returns: + A dictionary of keyword arguments that can be passed to a dataset op + constructor. + """ + return { + "metadata": self._metadata.SerializeToString(), + "output_shapes": self._flat_shapes, + "output_types": self._flat_types, + } + + @property + def _type_spec(self): + return DatasetSpec(self.element_spec) + + @staticmethod + def from_tensors(tensors, name=None) -> "DatasetV2": + """Creates a `Dataset` with a single element, comprising the given tensors. + + `from_tensors` produces a dataset containing only a single element. To slice + the input tensor into multiple elements, use `from_tensor_slices` instead. + + >>> dataset = tf.data.Dataset.from_tensors([1, 2, 3]) + >>> list(dataset.as_numpy_iterator()) + [array([1, 2, 3], dtype=int32)] + >>> dataset = tf.data.Dataset.from_tensors(([1, 2, 3], 'A')) + >>> list(dataset.as_numpy_iterator()) + [(array([1, 2, 3], dtype=int32), b'A')] + + >>> # You can use `from_tensors` to produce a dataset which repeats + >>> # the same example many times. + >>> example = tf.constant([1,2,3]) + >>> dataset = tf.data.Dataset.from_tensors(example).repeat(2) + >>> list(dataset.as_numpy_iterator()) + [array([1, 2, 3], dtype=int32), array([1, 2, 3], dtype=int32)] + + Note that if `tensors` contains a NumPy array, and eager execution is not + enabled, the values will be embedded in the graph as one or more + `tf.constant` operations. For large datasets (> 1 GB), this can waste + memory and run into byte limits of graph serialization. If `tensors` + contains one or more large NumPy arrays, consider the alternative described + in [this + guide](https://tensorflow.org/guide/data#consuming_numpy_arrays). + + Args: + tensors: A dataset "element". Supported values are documented + [here](https://www.tensorflow.org/guide/data#dataset_structure). + name: (Optional.) A name for the tf.data operation. + + Returns: + Dataset: A `Dataset`. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # from_tensors_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import from_tensors_op + return from_tensors_op._from_tensors(tensors, name) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + def from_tensor_slices(tensors, name=None) -> "DatasetV2": + """Creates a `Dataset` whose elements are slices of the given tensors. + + The given tensors are sliced along their first dimension. This operation + preserves the structure of the input tensors, removing the first dimension + of each tensor and using it as the dataset dimension. All input tensors + must have the same size in their first dimensions. + + >>> # Slicing a 1D tensor produces scalar tensor elements. + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> list(dataset.as_numpy_iterator()) + [1, 2, 3] + + >>> # Slicing a 2D tensor produces 1D tensor elements. + >>> dataset = tf.data.Dataset.from_tensor_slices([[1, 2], [3, 4]]) + >>> list(dataset.as_numpy_iterator()) + [array([1, 2], dtype=int32), array([3, 4], dtype=int32)] + + >>> # Slicing a tuple of 1D tensors produces tuple elements containing + >>> # scalar tensors. + >>> dataset = tf.data.Dataset.from_tensor_slices(([1, 2], [3, 4], [5, 6])) + >>> list(dataset.as_numpy_iterator()) + [(1, 3, 5), (2, 4, 6)] + + >>> # Dictionary structure is also preserved. + >>> dataset = tf.data.Dataset.from_tensor_slices({"a": [1, 2], "b": [3, 4]}) + >>> list(dataset.as_numpy_iterator()) == [{'a': 1, 'b': 3}, + ... {'a': 2, 'b': 4}] + True + + >>> # Two tensors can be combined into one Dataset object. + >>> features = tf.constant([[1, 3], [2, 1], [3, 3]]) # ==> 3x2 tensor + >>> labels = tf.constant(['A', 'B', 'A']) # ==> 3x1 tensor + >>> dataset = Dataset.from_tensor_slices((features, labels)) + >>> # Both the features and the labels tensors can be converted + >>> # to a Dataset object separately and combined after. + >>> features_dataset = Dataset.from_tensor_slices(features) + >>> labels_dataset = Dataset.from_tensor_slices(labels) + >>> dataset = Dataset.zip((features_dataset, labels_dataset)) + >>> # A batched feature and label set can be converted to a Dataset + >>> # in similar fashion. + >>> batched_features = tf.constant([[[1, 3], [2, 3]], + ... [[2, 1], [1, 2]], + ... [[3, 3], [3, 2]]], shape=(3, 2, 2)) + >>> batched_labels = tf.constant([['A', 'A'], + ... ['B', 'B'], + ... ['A', 'B']], shape=(3, 2, 1)) + >>> dataset = Dataset.from_tensor_slices((batched_features, batched_labels)) + >>> for element in dataset.as_numpy_iterator(): + ... print(element) + (array([[1, 3], + [2, 3]], dtype=int32), array([[b'A'], + [b'A']], dtype=object)) + (array([[2, 1], + [1, 2]], dtype=int32), array([[b'B'], + [b'B']], dtype=object)) + (array([[3, 3], + [3, 2]], dtype=int32), array([[b'A'], + [b'B']], dtype=object)) + + Note that if `tensors` contains a NumPy array, and eager execution is not + enabled, the values will be embedded in the graph as one or more + `tf.constant` operations. For large datasets (> 1 GB), this can waste + memory and run into byte limits of graph serialization. If `tensors` + contains one or more large NumPy arrays, consider the alternative described + in [this guide]( + https://tensorflow.org/guide/data#consuming_numpy_arrays). + + Args: + tensors: A dataset element, whose components have the same first + dimension. Supported values are documented + [here](https://www.tensorflow.org/guide/data#dataset_structure). + name: (Optional.) A name for the tf.data operation. + + Returns: + Dataset: A `Dataset`. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # from_tensor_slices_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import from_tensor_slices_op + return from_tensor_slices_op._from_tensor_slices(tensors, name) + # pylint: enable=g-import-not-at-top,protected-access + + class _GeneratorState: + """Stores outstanding iterators created from a Python generator. + + This class keeps track of potentially multiple iterators that may have + been created from a generator, e.g. in the case that the dataset is + repeated, or nested within a parallel computation. + """ + + def __init__(self, generator): + self._generator = generator + self._lock = threading.Lock() + self._next_id = 0 # GUARDED_BY(self._lock) + self._args = {} + self._iterators = {} + + def _normalize_id(self, iterator_id): + # In debug mode, iterator ids may be eagerly-generated np.arrays instead + # of Tensors. We convert them to scalars to make them hashable. + if isinstance(iterator_id, np.ndarray): + return iterator_id.item() + return iterator_id + + def get_next_id(self, *args): + with self._lock: + ret = self._next_id + self._next_id += 1 + self._args[ret] = args + # NOTE(mrry): Explicitly create an array of `np.int64` because implicit + # casting in `py_func()` will create an array of `np.int32` on Windows, + # leading to a runtime error. + return np.array(ret, dtype=np.int64) + + def get_iterator(self, iterator_id): + iterator_id = self._normalize_id(iterator_id) + try: + return self._iterators[iterator_id] + except KeyError: + iterator = iter(self._generator(*self._args.pop(iterator_id))) + self._iterators[iterator_id] = iterator + return iterator + + def iterator_completed(self, iterator_id): + del self._iterators[self._normalize_id(iterator_id)] + + @staticmethod + @deprecation.deprecated_args(None, "Use output_signature instead", + "output_types", "output_shapes") + def from_generator( + generator, + output_types=None, + output_shapes=None, + args=None, + output_signature=None, + name=None, + ) -> "DatasetV2": + """Creates a `Dataset` whose elements are generated by `generator`. + + Note: The current implementation of `Dataset.from_generator()` uses + `tf.numpy_function` and inherits the same constraints. In particular, it + requires the dataset and iterator related operations to be placed + on a device in the same process as the Python program that called + `Dataset.from_generator()`. In particular, using `from_generator` will + preclude the use of tf.data service for scaling out dataset processing. + The body of `generator` will not be serialized in a `GraphDef`, and you + should not use this method if you need to serialize your model and restore + it in a different environment. + + The `generator` argument must be a callable object that returns + an object that supports the `iter()` protocol (e.g. a generator function). + + The elements generated by `generator` must be compatible with either the + given `output_signature` argument or with the given `output_types` and + (optionally) `output_shapes` arguments, whichever was specified. + + The recommended way to call `from_generator` is to use the + `output_signature` argument. In this case the output will be assumed to + consist of objects with the classes, shapes and types defined by + `tf.TypeSpec` objects from `output_signature` argument: + + >>> def gen(): + ... ragged_tensor = tf.ragged.constant([[1, 2], [3]]) + ... yield 42, ragged_tensor + >>> + >>> dataset = tf.data.Dataset.from_generator( + ... gen, + ... output_signature=( + ... tf.TensorSpec(shape=(), dtype=tf.int32), + ... tf.RaggedTensorSpec(shape=(2, None), dtype=tf.int32))) + >>> + >>> list(dataset.take(1)) + [(, + )] + + There is also a deprecated way to call `from_generator` by either with + `output_types` argument alone or together with `output_shapes` argument. + In this case the output of the function will be assumed to consist of + `tf.Tensor` objects with the types defined by `output_types` and with the + shapes which are either unknown or defined by `output_shapes`. + + Note: If `generator` depends on mutable global variables or other external + state, be aware that the runtime may invoke `generator` multiple times + (in order to support repeating the `Dataset`) and at any time + between the call to `Dataset.from_generator()` and the production of the + first element from the generator. Mutating global variables or external + state can cause undefined behavior, and we recommend that you explicitly + cache any external state in `generator` before calling + `Dataset.from_generator()`. + + Note: While the `output_signature` parameter makes it possible to yield + `Dataset` elements, the scope of `Dataset.from_generator()` should be + limited to logic that cannot be expressed through tf.data operations. Using + tf.data operations within the generator function is an anti-pattern and may + result in incremental memory growth. + + Args: + generator: A callable object that returns an object that supports the + `iter()` protocol. If `args` is not specified, `generator` must take no + arguments; otherwise it must take as many arguments as there are values + in `args`. + output_types: (Optional.) A (nested) structure of `tf.DType` objects + corresponding to each component of an element yielded by `generator`. + output_shapes: (Optional.) A (nested) structure of `tf.TensorShape` + objects corresponding to each component of an element yielded by + `generator`. + args: (Optional.) A tuple of `tf.Tensor` objects that will be evaluated + and passed to `generator` as NumPy-array arguments. + output_signature: (Optional.) A (nested) structure of `tf.TypeSpec` + objects corresponding to each component of an element yielded by + `generator`. + name: (Optional.) A name for the tf.data operations used by + `from_generator`. + + Returns: + Dataset: A `Dataset`. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # from_generator_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import from_generator_op + return from_generator_op._from_generator(generator, output_types, + output_shapes, args, + output_signature, name) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + def range(*args, **kwargs) -> "DatasetV2": + """Creates a `Dataset` of a step-separated range of values. + + >>> list(Dataset.range(5).as_numpy_iterator()) + [0, 1, 2, 3, 4] + >>> list(Dataset.range(2, 5).as_numpy_iterator()) + [2, 3, 4] + >>> list(Dataset.range(1, 5, 2).as_numpy_iterator()) + [1, 3] + >>> list(Dataset.range(1, 5, -2).as_numpy_iterator()) + [] + >>> list(Dataset.range(5, 1).as_numpy_iterator()) + [] + >>> list(Dataset.range(5, 1, -2).as_numpy_iterator()) + [5, 3] + >>> list(Dataset.range(2, 5, output_type=tf.int32).as_numpy_iterator()) + [2, 3, 4] + >>> list(Dataset.range(1, 5, 2, output_type=tf.float32).as_numpy_iterator()) + [1.0, 3.0] + + Args: + *args: follows the same semantics as python's range. + len(args) == 1 -> start = 0, stop = args[0], step = 1. + len(args) == 2 -> start = args[0], stop = args[1], step = 1. + len(args) == 3 -> start = args[0], stop = args[1], step = args[2]. + **kwargs: + - output_type: Its expected dtype. (Optional, default: `tf.int64`). + - name: (Optional.) A name for the tf.data operation. + + Returns: + Dataset: A `RangeDataset`. + + Raises: + ValueError: if len(args) == 0. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> range_op -> + # -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import range_op + return range_op._range(*args, **kwargs) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + def zip(*args, datasets=None, name=None) -> "DatasetV2": + """Creates a `Dataset` by zipping together the given datasets. + + This method has similar semantics to the built-in `zip()` function + in Python, with the main difference being that the `datasets` + argument can be a (nested) structure of `Dataset` objects. The supported + nesting mechanisms are documented + [here] (https://www.tensorflow.org/guide/data#dataset_structure). + + >>> # The datasets or nested structure of datasets `*args` argument + >>> # determines the structure of elements in the resulting dataset. + >>> a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ] + >>> b = tf.data.Dataset.range(4, 7) # ==> [ 4, 5, 6 ] + >>> ds = tf.data.Dataset.zip(a, b) + >>> list(ds.as_numpy_iterator()) + [(1, 4), (2, 5), (3, 6)] + >>> ds = tf.data.Dataset.zip(b, a) + >>> list(ds.as_numpy_iterator()) + [(4, 1), (5, 2), (6, 3)] + >>> + >>> # The `datasets` argument may contain an arbitrary number of datasets. + >>> c = tf.data.Dataset.range(7, 13).batch(2) # ==> [ [7, 8], + ... # [9, 10], + ... # [11, 12] ] + >>> ds = tf.data.Dataset.zip(a, b, c) + >>> for element in ds.as_numpy_iterator(): + ... print(element) + (1, 4, array([7, 8])) + (2, 5, array([ 9, 10])) + (3, 6, array([11, 12])) + >>> + >>> # The number of elements in the resulting dataset is the same as + >>> # the size of the smallest dataset in `datasets`. + >>> d = tf.data.Dataset.range(13, 15) # ==> [ 13, 14 ] + >>> ds = tf.data.Dataset.zip(a, d) + >>> list(ds.as_numpy_iterator()) + [(1, 13), (2, 14)] + + Args: + *args: Datasets or nested structures of datasets to zip together. This + can't be set if `datasets` is set. + datasets: A (nested) structure of datasets. This can't be set if `*args` + is set. Note that this exists only for backwards compatibility and it is + preferred to use *args. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> zip_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import zip_op + + if not args and datasets is None: + raise TypeError("Must pass at least one dataset to `zip`.") + if args and datasets is not None: + raise TypeError("Both `*args` and `datasets` cannot be set.") + if len(args) == 1: + datasets = args[0] + elif len(args) > 1: + datasets = args + return zip_op._zip(datasets, name) + # pylint: enable=g-import-not-at-top,protected-access + + def concatenate(self, dataset, name=None) -> "DatasetV2": + """Creates a `Dataset` by concatenating the given dataset with this dataset. + + >>> a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ] + >>> b = tf.data.Dataset.range(4, 8) # ==> [ 4, 5, 6, 7 ] + >>> ds = a.concatenate(b) + >>> list(ds.as_numpy_iterator()) + [1, 2, 3, 4, 5, 6, 7] + >>> # The input dataset and dataset to be concatenated should have + >>> # compatible element specs. + >>> c = tf.data.Dataset.zip((a, b)) + >>> a.concatenate(c) + Traceback (most recent call last): + TypeError: Two datasets to concatenate have different types + and (tf.int64, tf.int64) + >>> d = tf.data.Dataset.from_tensor_slices(["a", "b", "c"]) + >>> a.concatenate(d) + Traceback (most recent call last): + TypeError: Two datasets to concatenate have different types + and + + Args: + dataset: `Dataset` to be concatenated. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # concatenate_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import concatenate_op + return concatenate_op._concatenate(self, dataset, name) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + def counter(start=0, step=1, dtype=dtypes.int64, name=None) -> "DatasetV2": + """Creates a `Dataset` that counts from `start` in steps of size `step`. + + Unlike `tf.data.Dataset.range`, which stops at some ending number, + `tf.data.Dataset.counter` produces elements indefinitely. + + >>> dataset = tf.data.experimental.Counter().take(5) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 2, 3, 4] + >>> dataset.element_spec + TensorSpec(shape=(), dtype=tf.int64, name=None) + >>> dataset = tf.data.experimental.Counter(dtype=tf.int32) + >>> dataset.element_spec + TensorSpec(shape=(), dtype=tf.int32, name=None) + >>> dataset = tf.data.experimental.Counter(start=2).take(5) + >>> list(dataset.as_numpy_iterator()) + [2, 3, 4, 5, 6] + >>> dataset = tf.data.experimental.Counter(start=2, step=5).take(5) + >>> list(dataset.as_numpy_iterator()) + [2, 7, 12, 17, 22] + >>> dataset = tf.data.experimental.Counter(start=10, step=-1).take(5) + >>> list(dataset.as_numpy_iterator()) + [10, 9, 8, 7, 6] + + Args: + start: (Optional.) The starting value for the counter. Defaults to 0. + step: (Optional.) The step size for the counter. Defaults to 1. + dtype: (Optional.) The data type for counter elements. Defaults to + `tf.int64`. + name: (Optional.) A name for the tf.data operation. + + Returns: + A `Dataset` of scalar `dtype` elements. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> counter_op + # -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import counter_op + return counter_op._counter(start, step, dtype, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def rebatch(self, batch_size, drop_remainder=False, name=None) -> "DatasetV2": + """Creates a `Dataset` that rebatches the elements from this dataset. + + `rebatch(N)` is functionally equivalent to `unbatch().batch(N)`, but is + more efficient, performing one copy instead of two. + + >>> ds = tf.data.Dataset.range(6) + >>> ds = ds.batch(2) + >>> ds = ds.rebatch(3) + >>> list(ds.as_numpy_iterator()) + [array([0, 1, 2]), array([3, 4, 5])] + + >>> ds = tf.data.Dataset.range(7) + >>> ds = ds.batch(4) + >>> ds = ds.rebatch(3) + >>> list(ds.as_numpy_iterator()) + [array([0, 1, 2]), array([3, 4, 5]), array([6])] + + >>> ds = tf.data.Dataset.range(7) + >>> ds = ds.batch(2) + >>> ds = ds.rebatch(3, drop_remainder=True) + >>> list(ds.as_numpy_iterator()) + [array([0, 1, 2]), array([3, 4, 5])] + + If the `batch_size` argument is a list, `rebatch` cycles through the list + to determine the size of each batch. + + >>> ds = tf.data.Dataset.range(8) + >>> ds = ds.batch(4) + >>> ds = ds.rebatch([2, 1, 1]) + >>> list(ds.as_numpy_iterator()) + [array([0, 1]), array([2]), array([3]), array([4, 5]), array([6]), + array([7])] + + Args: + batch_size: A `tf.int64` scalar or vector, representing the size of + batches to produce. If this argument is a vector, these values are + cycled through in round robin fashion. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size[cycle_index]` elements; the default behavior is not to drop + the smaller batch. + name: (Optional.) A name for the tf.data operation. + + Returns: + A `Dataset` of scalar `dtype` elements. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> rebatch_op -> + # rebatch_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import rebatch_op + return rebatch_op._rebatch(self, batch_size, drop_remainder, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def prefetch(self, buffer_size, name=None) -> "DatasetV2": + """Creates a `Dataset` that prefetches elements from this dataset. + + Most dataset input pipelines should end with a call to `prefetch`. This + allows later elements to be prepared while the current element is being + processed. This often improves latency and throughput, at the cost of + using additional memory to store prefetched elements. + + Note: Like other `Dataset` methods, prefetch operates on the + elements of the input dataset. It has no concept of examples vs. batches. + `examples.prefetch(2)` will prefetch two elements (2 examples), + while `examples.batch(20).prefetch(2)` will prefetch 2 elements + (2 batches, of 20 examples each). + + >>> dataset = tf.data.Dataset.range(3) + >>> dataset = dataset.prefetch(2) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 2] + + Args: + buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the maximum + number of elements that will be buffered when prefetching. If the value + `tf.data.AUTOTUNE` is used, then the buffer size is dynamically tuned. + name: Optional. A name for the tf.data transformation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + return prefetch_op._prefetch( # pylint: disable=protected-access + self, buffer_size, name=name) + + @staticmethod + def list_files( + file_pattern, shuffle=None, seed=None, name=None + ) -> "DatasetV2": + """A dataset of all files matching one or more glob patterns. + + The `file_pattern` argument should be a small number of glob patterns. + If your filenames have already been globbed, use + `Dataset.from_tensor_slices(filenames)` instead, as re-globbing every + filename with `list_files` may result in poor performance with remote + storage systems. + + Note: The default behavior of this method is to return filenames in + a non-deterministic random shuffled order. Pass a `seed` or `shuffle=False` + to get results in a deterministic order. + + Example: + If we had the following files on our filesystem: + + - /path/to/dir/a.txt + - /path/to/dir/b.py + - /path/to/dir/c.py + + If we pass "/path/to/dir/*.py" as the directory, the dataset + would produce: + + - /path/to/dir/b.py + - /path/to/dir/c.py + + Args: + file_pattern: A string, a list of strings, or a `tf.Tensor` of string type + (scalar or vector), representing the filename glob (i.e. shell wildcard) + pattern(s) that will be matched. + shuffle: (Optional.) If `True`, the file names will be shuffled randomly. + Defaults to `True`. + seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random + seed that will be used to create the distribution. See + `tf.random.set_seed` for behavior. + name: Optional. A name for the tf.data operations used by `list_files`. + + Returns: + Dataset: A `Dataset` of strings corresponding to file names. + """ + with ops.name_scope("list_files"): + if shuffle is None: + shuffle = True + file_pattern = ops.convert_to_tensor( + file_pattern, dtype=dtypes.string, name="file_pattern") + matching_files = gen_io_ops.matching_files(file_pattern) + + # Raise an exception if `file_pattern` does not match any files. + condition = math_ops.greater(array_ops.shape(matching_files)[0], 0, + name="match_not_empty") + + message = math_ops.add( + "No files matched pattern: ", + string_ops.reduce_join(file_pattern, separator=", "), name="message") + + assert_not_empty = control_flow_assert.Assert( + condition, [message], summarize=1, name="assert_not_empty") + with ops.control_dependencies([assert_not_empty]): + matching_files = array_ops.identity(matching_files) + + # TODO(b/240947712): Remove lazy import after this method is factored out. + # Loaded lazily due to a circular dependency (dataset_ops -> + # from_tensor_slices_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import from_tensor_slices_op + dataset = from_tensor_slices_op._TensorSliceDataset( + matching_files, is_files=True, name=name) + # pylint: enable=g-import-not-at-top,protected-access + if issubclass(Dataset, DatasetV1): + dataset = DatasetV1Adapter(dataset) + if shuffle: + # NOTE(mrry): The shuffle buffer size must be greater than zero, but the + # list of files might be empty. + buffer_size = math_ops.maximum( + array_ops.shape(matching_files, out_type=dtypes.int64)[0], 1) + dataset = dataset.shuffle(buffer_size, seed=seed, name=name) + return dataset + + def repeat(self, count=None, name=None) -> "DatasetV2": + """Repeats this dataset so each original value is seen `count` times. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> dataset = dataset.repeat(3) + >>> list(dataset.as_numpy_iterator()) + [1, 2, 3, 1, 2, 3, 1, 2, 3] + + Note: If the input dataset depends on global state (e.g. a random number + generator) or its output is non-deterministic (e.g. because of upstream + `shuffle`), then different repetitions may produce different elements. + + Args: + count: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the + number of times the dataset should be repeated. The default behavior (if + `count` is `None` or `-1`) is for the dataset be repeated indefinitely. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> repeat_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access,redefined-outer-name + from tensorflow.python.data.ops import repeat_op + return repeat_op._repeat(self, count, name) + # pylint: enable=g-import-not-at-top,protected-access,redefined-outer-name + + def enumerate(self, start=0, name=None) -> "DatasetV2": + """Enumerates the elements of this dataset. + + It is similar to python's `enumerate`. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> dataset = dataset.enumerate(start=5) + >>> for element in dataset.as_numpy_iterator(): + ... print(element) + (5, 1) + (6, 2) + (7, 3) + + >>> # The (nested) structure of the input dataset determines the + >>> # structure of elements in the resulting dataset. + >>> dataset = tf.data.Dataset.from_tensor_slices([(7, 8), (9, 10)]) + >>> dataset = dataset.enumerate() + >>> for element in dataset.as_numpy_iterator(): + ... print(element) + (0, array([7, 8], dtype=int32)) + (1, array([ 9, 10], dtype=int32)) + + Args: + start: A `tf.int64` scalar `tf.Tensor`, representing the start value for + enumeration. + name: Optional. A name for the tf.data operations used by `enumerate`. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + + max_value = np.iinfo(dtypes.int64.as_numpy_dtype).max + range_dataset = Dataset.range(start, max_value, name=name) + # Replicate the range component so that each split is enumerated + # independently. This avoids the need for prohibitively expensive + # cross-split coordination. + range_dataset = _apply_rewrite(range_dataset, "replicate_on_split") + return Dataset.zip((range_dataset, self), name=name) + + def shuffle( + self, buffer_size, seed=None, reshuffle_each_iteration=None, name=None + ) -> "DatasetV2": + """Randomly shuffles the elements of this dataset. + + This dataset fills a buffer with `buffer_size` elements, then randomly + samples elements from this buffer, replacing the selected elements with new + elements. For perfect shuffling, a buffer size greater than or equal to the + full size of the dataset is required. + + For instance, if your dataset contains 10,000 elements but `buffer_size` is + set to 1,000, then `shuffle` will initially select a random element from + only the first 1,000 elements in the buffer. Once an element is selected, + its space in the buffer is replaced by the next (i.e. 1,001-st) element, + maintaining the 1,000 element buffer. + + `reshuffle_each_iteration` controls whether the shuffle order should be + different for each epoch. In TF 1.X, the idiomatic way to create epochs + was through the `repeat` transformation: + + ```python + dataset = tf.data.Dataset.range(3) + dataset = dataset.shuffle(3, reshuffle_each_iteration=True) + dataset = dataset.repeat(2) + # [1, 0, 2, 1, 2, 0] + + dataset = tf.data.Dataset.range(3) + dataset = dataset.shuffle(3, reshuffle_each_iteration=False) + dataset = dataset.repeat(2) + # [1, 0, 2, 1, 0, 2] + ``` + + In TF 2.0, `tf.data.Dataset` objects are Python iterables which makes it + possible to also create epochs through Python iteration: + + ```python + dataset = tf.data.Dataset.range(3) + dataset = dataset.shuffle(3, reshuffle_each_iteration=True) + list(dataset.as_numpy_iterator()) + # [1, 0, 2] + list(dataset.as_numpy_iterator()) + # [1, 2, 0] + ``` + + ```python + dataset = tf.data.Dataset.range(3) + dataset = dataset.shuffle(3, reshuffle_each_iteration=False) + list(dataset.as_numpy_iterator()) + # [1, 0, 2] + list(dataset.as_numpy_iterator()) + # [1, 0, 2] + ``` + + #### Fully shuffling all the data + + To shuffle an entire dataset, set `buffer_size=dataset.cardinality(). This + is equivalent to setting the `buffer_size` equal to the number of elements + in the dataset, resulting in uniform shuffle. + + Note: `shuffle(dataset.cardinality())` loads the full dataset into memory so + that it can be shuffled. This will cause a memory overflow (OOM) error if + the dataset is too large, so full-shuffle should only be used for datasets + that are known to fit in the memory, such as datasets of filenames or other + small datasets. + + ```python + dataset = tf.data.Dataset.range(20) + dataset = dataset.shuffle(dataset.cardinality()) + # [18, 4, 9, 2, 17, 8, 5, 10, 0, 6, 16, 3, 19, 7, 14, 11, 15, 13, 12, 1] + ``` + + Args: + buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + elements from this dataset from which the new dataset will sample. To + uniformly shuffle the entire dataset, use + `buffer_size=dataset.cardinality()`. + seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random + seed that will be used to create the distribution. See + `tf.random.set_seed` for behavior. + reshuffle_each_iteration: (Optional.) A boolean, which if true indicates + that the dataset should be pseudorandomly reshuffled each time it is + iterated over. (Defaults to `True`.) + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + return shuffle_op._shuffle( # pylint: disable=protected-access + self, buffer_size, seed, reshuffle_each_iteration, name=name) + + def cache(self, filename="", name=None) -> "DatasetV2": + """Caches the elements in this dataset. + + The first time the dataset is iterated over, its elements will be cached + either in the specified file or in memory. Subsequent iterations will + use the cached data. + + Note: To guarantee that the cache gets finalized, the input dataset must be + iterated through in its entirety, until it raises StopIteration. Otherwise, + subsequent iterations may not use cached data. + + >>> dataset = tf.data.Dataset.range(5) + >>> dataset = dataset.map(lambda x: x**2) + >>> dataset = dataset.cache() + >>> # The first time reading through the data will generate the data using + >>> # `range` and `map`. + >>> list(dataset.as_numpy_iterator()) + [0, 1, 4, 9, 16] + >>> # Subsequent iterations read from the cache. + >>> list(dataset.as_numpy_iterator()) + [0, 1, 4, 9, 16] + + When caching to a file, the cached data will persist across runs. Even the + first iteration through the data will read from the cache file. Changing + the input pipeline before the call to `.cache()` will have no effect until + the cache file is removed or the filename is changed. + + ```python + dataset = tf.data.Dataset.range(5) + dataset = dataset.cache("/path/to/file") + list(dataset.as_numpy_iterator()) + # [0, 1, 2, 3, 4] + dataset = tf.data.Dataset.range(10) + dataset = dataset.cache("/path/to/file") # Same file! + list(dataset.as_numpy_iterator()) + # [0, 1, 2, 3, 4] + ``` + + Note: `cache` will produce exactly the same elements during each iteration + through the dataset. If you wish to randomize the iteration order, make sure + to call `shuffle` *after* calling `cache`. + + Args: + filename: A `tf.string` scalar `tf.Tensor`, representing the name of a + directory on the filesystem to use for caching elements in this Dataset. + If a filename is not provided, the dataset will be cached in memory. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> cache_op -> + # -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import cache_op + return cache_op._cache(self, filename, name) + # pylint: enable=g-import-not-at-top,protected-access + + def take(self, count, name=None) -> "DatasetV2": + """Creates a `Dataset` with at most `count` elements from this dataset. + + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.take(3) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 2] + + Args: + count: A `tf.int64` scalar `tf.Tensor`, representing the number of + elements of this dataset that should be taken to form the new dataset. + If `count` is -1, or if `count` is greater than the size of this + dataset, the new dataset will contain all elements of this dataset. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # take_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import take_op + return take_op._take(self, count, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def skip(self, count, name=None) -> "DatasetV2": + """Creates a `Dataset` that skips `count` elements from this dataset. + + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.skip(7) + >>> list(dataset.as_numpy_iterator()) + [7, 8, 9] + + Args: + count: A `tf.int64` scalar `tf.Tensor`, representing the number of + elements of this dataset that should be skipped to form the new dataset. + If `count` is greater than the size of this dataset, the new dataset + will contain no elements. If `count` is -1, skips the entire dataset. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # skip_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import skip_op + return skip_op._skip(self, count, name) + # pylint: enable=g-import-not-at-top,protected-access + + def shard(self, num_shards, index, name=None) -> "DatasetV2": + """Creates a `Dataset` that includes only 1/`num_shards` of this dataset. + + `shard` is deterministic. The Dataset produced by `A.shard(n, i)` will + contain all elements of A whose index mod n = i. + + >>> A = tf.data.Dataset.range(10) + >>> B = A.shard(num_shards=3, index=0) + >>> list(B.as_numpy_iterator()) + [0, 3, 6, 9] + >>> C = A.shard(num_shards=3, index=1) + >>> list(C.as_numpy_iterator()) + [1, 4, 7] + >>> D = A.shard(num_shards=3, index=2) + >>> list(D.as_numpy_iterator()) + [2, 5, 8] + + This dataset operator is very useful when running distributed training, as + it allows each worker to read a unique subset. + + When reading a single input file, you can shard elements as follows: + + ```python + d = tf.data.TFRecordDataset(input_file) + d = d.shard(num_workers, worker_index) + d = d.repeat(num_epochs) + d = d.shuffle(shuffle_buffer_size) + d = d.map(parser_fn, num_parallel_calls=num_map_threads) + ``` + + Important caveats: + + - Be sure to shard before you use any randomizing operator (such as + shuffle). + - Generally it is best if the shard operator is used early in the dataset + pipeline. For example, when reading from a set of TFRecord files, shard + before converting the dataset to input samples. This avoids reading every + file on every worker. The following is an example of an efficient + sharding strategy within a complete pipeline: + + ```python + d = Dataset.list_files(pattern, shuffle=False) + d = d.shard(num_workers, worker_index) + d = d.repeat(num_epochs) + d = d.shuffle(shuffle_buffer_size) + d = d.interleave(tf.data.TFRecordDataset, + cycle_length=num_readers, block_length=1) + d = d.map(parser_fn, num_parallel_calls=num_map_threads) + ``` + + Args: + num_shards: A `tf.int64` scalar `tf.Tensor`, representing the number of + shards operating in parallel. + index: A `tf.int64` scalar `tf.Tensor`, representing the worker index. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + + Raises: + InvalidArgumentError: if `num_shards` or `index` are illegal values. + + Note: error checking is done on a best-effort basis, and errors aren't + guaranteed to be caught upon dataset creation. (e.g. providing in a + placeholder tensor bypasses the early checking, and will instead result + in an error during a session.run call.) + """ + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import shard_op + return shard_op._shard(self, num_shards, index, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def save(self, + path, + compression=None, + shard_func=None, + checkpoint_args=None): + """Saves the content of the given dataset. + + Example usage: + + >>> import tempfile + >>> path = os.path.join(tempfile.gettempdir(), "saved_data") + >>> # Save a dataset + >>> dataset = tf.data.Dataset.range(2) + >>> dataset.save(path) + >>> new_dataset = tf.data.Dataset.load(path) + >>> for elem in new_dataset: + ... print(elem) + tf.Tensor(0, shape=(), dtype=int64) + tf.Tensor(1, shape=(), dtype=int64) + + The saved dataset is saved in multiple file "shards". By default, the + dataset output is divided to shards in a round-robin fashion but custom + sharding can be specified via the `shard_func` function. For example, you + can save the dataset to using a single shard as follows: + + ```python + dataset = make_dataset() + def custom_shard_func(element): + return np.int64(0) + dataset.save( + path="/path/to/data", ..., shard_func=custom_shard_func) + ``` + + To enable checkpointing, pass in `checkpoint_args` to the `save` method + as follows: + + ```python + dataset = tf.data.Dataset.range(100) + save_dir = "..." + checkpoint_prefix = "..." + step_counter = tf.Variable(0, trainable=False) + checkpoint_args = { + "checkpoint_interval": 50, + "step_counter": step_counter, + "directory": checkpoint_prefix, + "max_to_keep": 20, + } + dataset.save(dataset, save_dir, checkpoint_args=checkpoint_args) + ``` + + NOTE: The directory layout and file format used for saving the dataset is + considered an implementation detail and may change. For this reason, + datasets saved through `tf.data.Dataset.save` should only be consumed + through `tf.data.Dataset.load`, which is guaranteed to be + backwards compatible. + + Args: + path: Required. A directory to use for saving the dataset. + compression: Optional. The algorithm to use to compress data when writing + it. Supported options are `GZIP` and `NONE`. Defaults to `NONE`. + shard_func: Optional. A function to control the mapping of dataset + elements to file shards. The function is expected to map elements of + the input dataset to int64 shard IDs. If present, the function will be + traced and executed as graph computation. + checkpoint_args: Optional args for checkpointing which will be passed into + the `tf.train.CheckpointManager`. If `checkpoint_args` are not + specified, then checkpointing will not be performed. The `save()` + implementation creates a `tf.train.Checkpoint` object internally, so + users should not set the `checkpoint` argument in `checkpoint_args`. + + Returns: + An operation which when executed performs the save. When writing + checkpoints, returns None. The return value is useful in unit tests. + + Raises: + ValueError if `checkpoint` is passed into `checkpoint_args`. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> save_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import save_op + return save_op._save(self, path, compression, shard_func, checkpoint_args) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + def load( + path, element_spec=None, compression=None, reader_func=None + ) -> "DatasetV2": + """Loads a previously saved dataset. + + Example usage: + + >>> import tempfile + >>> path = os.path.join(tempfile.gettempdir(), "saved_data") + >>> # Save a dataset + >>> dataset = tf.data.Dataset.range(2) + >>> tf.data.Dataset.save(dataset, path) + >>> new_dataset = tf.data.Dataset.load(path) + >>> for elem in new_dataset: + ... print(elem) + tf.Tensor(0, shape=(), dtype=int64) + tf.Tensor(1, shape=(), dtype=int64) + + + If the default option of sharding the saved dataset was used, the element + order of the saved dataset will be preserved when loading it. + + The `reader_func` argument can be used to specify a custom order in which + elements should be loaded from the individual shards. The `reader_func` is + expected to take a single argument -- a dataset of datasets, each containing + elements of one of the shards -- and return a dataset of elements. For + example, the order of shards can be shuffled when loading them as follows: + + ```python + def custom_reader_func(datasets): + datasets = datasets.shuffle(NUM_SHARDS) + return datasets.interleave(lambda x: x, num_parallel_calls=AUTOTUNE) + + dataset = tf.data.Dataset.load( + path="/path/to/data", ..., reader_func=custom_reader_func) + ``` + + Args: + path: Required. A path pointing to a previously saved dataset. + element_spec: Optional. A nested structure of `tf.TypeSpec` objects + matching the structure of an element of the saved dataset and specifying + the type of individual element components. If not provided, the nested + structure of `tf.TypeSpec` saved with the saved dataset is used. Note + that this argument is required in graph mode. + compression: Optional. The algorithm to use to decompress the data when + reading it. Supported options are `GZIP` and `NONE`. Defaults to `NONE`. + reader_func: Optional. A function to control how to read data from shards. + If present, the function will be traced and executed as graph + computation. + + Returns: + A `tf.data.Dataset` instance. + + Raises: + FileNotFoundError: If `element_spec` is not specified and the saved nested + structure of `tf.TypeSpec` can not be located with the saved dataset. + ValueError: If `element_spec` is not specified and the method is executed + in graph mode. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> load_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import load_op + return load_op._load( + path=path, + element_spec=element_spec, + compression=compression, + reader_func=reader_func) + # pylint: enable=g-import-not-at-top,protected-access + + def batch( + self, + batch_size, + drop_remainder=False, + num_parallel_calls=None, + deterministic=None, + name=None, + ) -> "DatasetV2": + """Combines consecutive elements of this dataset into batches. + + >>> dataset = tf.data.Dataset.range(8) + >>> dataset = dataset.batch(3) + >>> list(dataset.as_numpy_iterator()) + [array([0, 1, 2]), array([3, 4, 5]), array([6, 7])] + + >>> dataset = tf.data.Dataset.range(8) + >>> dataset = dataset.batch(3, drop_remainder=True) + >>> list(dataset.as_numpy_iterator()) + [array([0, 1, 2]), array([3, 4, 5])] + + The components of the resulting element will have an additional outer + dimension, which will be `batch_size` (or `N % batch_size` for the last + element if `batch_size` does not divide the number of input elements `N` + evenly and `drop_remainder` is `False`). If your program depends on the + batches having the same outer dimension, you should set the `drop_remainder` + argument to `True` to prevent the smaller batch from being produced. + + Note: If your program requires data to have a statically known shape (e.g., + when using XLA), you should use `drop_remainder=True`. Without + `drop_remainder=True` the shape of the output dataset will have an unknown + leading dimension due to the possibility of a smaller final batch. + + Args: + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size` elements; the default behavior is not to drop the smaller + batch. + num_parallel_calls: (Optional.) A `tf.int64` scalar `tf.Tensor`, + representing the number of batches to compute asynchronously in + parallel. + If not specified, batches will be computed sequentially. If the value + `tf.data.AUTOTUNE` is used, then the number of parallel + calls is set dynamically based on available resources. + deterministic: (Optional.) When `num_parallel_calls` is specified, if this + boolean is specified (`True` or `False`), it controls the order in which + the transformation produces elements. If set to `False`, the + transformation is allowed to yield elements out of order to trade + determinism for performance. If not specified, the + `tf.data.Options.deterministic` option (`True` by default) controls the + behavior. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> batch_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access,redefined-outer-name + from tensorflow.python.data.ops import batch_op + return batch_op._batch(self, batch_size, drop_remainder, num_parallel_calls, + deterministic, name) + # pylint: enable=g-import-not-at-top,protected-access,redefined-outer-name + + def padded_batch( + self, + batch_size, + padded_shapes=None, + padding_values=None, + drop_remainder=False, + name=None, + ) -> "DatasetV2": + """Combines consecutive elements of this dataset into padded batches. + + This transformation combines multiple consecutive elements of the input + dataset into a single element. + + Like `tf.data.Dataset.batch`, the components of the resulting element will + have an additional outer dimension, which will be `batch_size` (or + `N % batch_size` for the last element if `batch_size` does not divide the + number of input elements `N` evenly and `drop_remainder` is `False`). If + your program depends on the batches having the same outer dimension, you + should set the `drop_remainder` argument to `True` to prevent the smaller + batch from being produced. + + Unlike `tf.data.Dataset.batch`, the input elements to be batched may have + different shapes, and this transformation will pad each component to the + respective shape in `padded_shapes`. The `padded_shapes` argument + determines the resulting shape for each dimension of each component in an + output element: + + * If the dimension is a constant, the component will be padded out to that + length in that dimension. + * If the dimension is unknown, the component will be padded out to the + maximum length of all elements in that dimension. + + >>> A = (tf.data.Dataset + ... .range(1, 5, output_type=tf.int32) + ... .map(lambda x: tf.fill([x], x))) + >>> # Pad to the smallest per-batch size that fits all elements. + >>> B = A.padded_batch(2) + >>> for element in B.as_numpy_iterator(): + ... print(element) + [[1 0] + [2 2]] + [[3 3 3 0] + [4 4 4 4]] + >>> # Pad to a fixed size. + >>> C = A.padded_batch(2, padded_shapes=5) + >>> for element in C.as_numpy_iterator(): + ... print(element) + [[1 0 0 0 0] + [2 2 0 0 0]] + [[3 3 3 0 0] + [4 4 4 4 0]] + >>> # Pad with a custom value. + >>> D = A.padded_batch(2, padded_shapes=5, padding_values=-1) + >>> for element in D.as_numpy_iterator(): + ... print(element) + [[ 1 -1 -1 -1 -1] + [ 2 2 -1 -1 -1]] + [[ 3 3 3 -1 -1] + [ 4 4 4 4 -1]] + >>> # Components of nested elements can be padded independently. + >>> elements = [([1, 2, 3], [10]), + ... ([4, 5], [11, 12])] + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: iter(elements), (tf.int32, tf.int32)) + >>> # Pad the first component of the tuple to length 4, and the second + >>> # component to the smallest size that fits. + >>> dataset = dataset.padded_batch(2, + ... padded_shapes=([4], [None]), + ... padding_values=(-1, 100)) + >>> list(dataset.as_numpy_iterator()) + [(array([[ 1, 2, 3, -1], [ 4, 5, -1, -1]], dtype=int32), + array([[ 10, 100], [ 11, 12]], dtype=int32))] + >>> # Pad with a single value and multiple components. + >>> E = tf.data.Dataset.zip((A, A)).padded_batch(2, padding_values=-1) + >>> for element in E.as_numpy_iterator(): + ... print(element) + (array([[ 1, -1], + [ 2, 2]], dtype=int32), array([[ 1, -1], + [ 2, 2]], dtype=int32)) + (array([[ 3, 3, 3, -1], + [ 4, 4, 4, 4]], dtype=int32), array([[ 3, 3, 3, -1], + [ 4, 4, 4, 4]], dtype=int32)) + + See also `tf.data.experimental.dense_to_sparse_batch`, which combines + elements that may have different shapes into a `tf.sparse.SparseTensor`. + + Args: + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + padded_shapes: (Optional.) A (nested) structure of `tf.TensorShape` or + `tf.int64` vector tensor-like objects representing the shape to which + the respective component of each input element should be padded prior + to batching. Any unknown dimensions will be padded to the maximum size + of that dimension in each batch. If unset, all dimensions of all + components are padded to the maximum size in the batch. `padded_shapes` + must be set if any component has an unknown rank. + padding_values: (Optional.) A (nested) structure of scalar-shaped + `tf.Tensor`, representing the padding values to use for the respective + components. None represents that the (nested) structure should be padded + with default values. Defaults are `0` for numeric types and the empty + string for string types. The `padding_values` should have the same + (nested) structure as the input dataset. If `padding_values` is a single + element and the input dataset has multiple components, then the same + `padding_values` will be used to pad every component of the dataset. + If `padding_values` is a scalar, then its value will be broadcasted + to match the shape of each component. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size` elements; the default behavior is not to drop the smaller + batch. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + + Raises: + ValueError: If a component has an unknown rank, and the `padded_shapes` + argument is not set. + TypeError: If a component is of an unsupported type. The list of supported + types is documented in + https://www.tensorflow.org/guide/data#dataset_structure. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # padded_batch_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import padded_batch_op + return padded_batch_op._padded_batch(self, batch_size, padded_shapes, + padding_values, drop_remainder, name) + # pylint: enable=g-import-not-at-top,protected-access + + def ragged_batch( + self, + batch_size, + drop_remainder=False, + row_splits_dtype=dtypes.int64, + name=None, + ) -> "DatasetV2": + """Combines consecutive elements of this dataset into `tf.RaggedTensor`s. + + Like `tf.data.Dataset.batch`, the components of the resulting element will + have an additional outer dimension, which will be `batch_size` (or + `N % batch_size` for the last element if `batch_size` does not divide the + number of input elements `N` evenly and `drop_remainder` is `False`). If + your program depends on the batches having the same outer dimension, you + should set the `drop_remainder` argument to `True` to prevent the smaller + batch from being produced. + + Unlike `tf.data.Dataset.batch`, the input elements to be batched may have + different shapes: + + * If an input element is a `tf.Tensor` whose static `tf.TensorShape` is + fully defined, then it is batched as normal. + * If an input element is a `tf.Tensor` whose static `tf.TensorShape` + contains one or more axes with unknown size (i.e., `shape[i]=None`), then + the output will contain a `tf.RaggedTensor` that is ragged up to any of such + dimensions. + * If an input element is a `tf.RaggedTensor` or any other type, then it is + batched as normal. + + Example: + + >>> dataset = tf.data.Dataset.range(6) + >>> dataset = dataset.map(lambda x: tf.range(x)) + >>> dataset.element_spec.shape + TensorShape([None]) + >>> dataset = dataset.ragged_batch(2) + >>> for batch in dataset: + ... print(batch) + + + + + Args: + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size` elements; the default behavior is not to drop the smaller + batch. + row_splits_dtype: The dtype that should be used for the `row_splits` of + any new ragged tensors. Existing `tf.RaggedTensor` elements do not have + their row_splits dtype changed. + name: (Optional.) A string indicating a name for the `tf.data` operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # ragged_batch_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import ragged_batch_op + return ragged_batch_op._ragged_batch(self, batch_size, drop_remainder, + row_splits_dtype, name) + # pylint: enable=g-import-not-at-top,protected-access + + def sparse_batch(self, batch_size, row_shape, name=None) -> "DatasetV2": + """Combines consecutive elements into `tf.sparse.SparseTensor`s. + + Like `Dataset.padded_batch()`, this transformation combines multiple + consecutive elements of the dataset, which might have different + shapes, into a single element. The resulting element has three + components (`indices`, `values`, and `dense_shape`), which + comprise a `tf.sparse.SparseTensor` that represents the same data. The + `row_shape` represents the dense shape of each row in the + resulting `tf.sparse.SparseTensor`, to which the effective batch size is + prepended. For example: + + ```python + # NOTE: The following examples use `{ ... }` to represent the + # contents of a dataset. + a = { ['a', 'b', 'c'], ['a', 'b'], ['a', 'b', 'c', 'd'] } + + a.apply(tf.data.experimental.dense_to_sparse_batch( + batch_size=2, row_shape=[6])) == + { + ([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1]], # indices + ['a', 'b', 'c', 'a', 'b'], # values + [2, 6]), # dense_shape + ([[0, 0], [0, 1], [0, 2], [0, 3]], + ['a', 'b', 'c', 'd'], + [1, 6]) + } + ``` + + Args: + batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements of this dataset to combine in a single batch. + row_shape: A `tf.TensorShape` or `tf.int64` vector tensor-like object + representing the equivalent dense shape of a row in the resulting + `tf.sparse.SparseTensor`. Each element of this dataset must have the + same rank as `row_shape`, and must have size less than or equal to + `row_shape` in each dimension. + name: (Optional.) A string indicating a name for the `tf.data` operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # sparse_batch_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import sparse_batch_op + return sparse_batch_op._sparse_batch(self, batch_size, row_shape, name) + # pylint: disable=g-import-not-at-top,protected-access + + def map( + self, map_func, num_parallel_calls=None, deterministic=None, name=None + ) -> "DatasetV2": + """Maps `map_func` across the elements of this dataset. + + This transformation applies `map_func` to each element of this dataset, and + returns a new dataset containing the transformed elements, in the same + order as they appeared in the input. `map_func` can be used to change both + the values and the structure of a dataset's elements. Supported structure + constructs are documented + [here](https://www.tensorflow.org/guide/data#dataset_structure). + + For example, `map` can be used for adding 1 to each element, or projecting a + subset of element components. + + >>> dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ] + >>> dataset = dataset.map(lambda x: x + 1) + >>> list(dataset.as_numpy_iterator()) + [2, 3, 4, 5, 6] + + The input signature of `map_func` is determined by the structure of each + element in this dataset. + + >>> dataset = Dataset.range(5) + >>> # `map_func` takes a single argument of type `tf.Tensor` with the same + >>> # shape and dtype. + >>> result = dataset.map(lambda x: x + 1) + + >>> # Each element is a tuple containing two `tf.Tensor` objects. + >>> elements = [(1, "foo"), (2, "bar"), (3, "baz")] + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: elements, (tf.int32, tf.string)) + >>> # `map_func` takes two arguments of type `tf.Tensor`. This function + >>> # projects out just the first component. + >>> result = dataset.map(lambda x_int, y_str: x_int) + >>> list(result.as_numpy_iterator()) + [1, 2, 3] + + >>> # Each element is a dictionary mapping strings to `tf.Tensor` objects. + >>> elements = ([{"a": 1, "b": "foo"}, + ... {"a": 2, "b": "bar"}, + ... {"a": 3, "b": "baz"}]) + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: elements, {"a": tf.int32, "b": tf.string}) + >>> # `map_func` takes a single argument of type `dict` with the same keys + >>> # as the elements. + >>> result = dataset.map(lambda d: str(d["a"]) + d["b"]) + + The value or values returned by `map_func` determine the structure of each + element in the returned dataset. + + >>> dataset = tf.data.Dataset.range(3) + >>> # `map_func` returns two `tf.Tensor` objects. + >>> def g(x): + ... return tf.constant(37.0), tf.constant(["Foo", "Bar", "Baz"]) + >>> result = dataset.map(g) + >>> result.element_spec + (TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(3,), \ +dtype=tf.string, name=None)) + >>> # Python primitives, lists, and NumPy arrays are implicitly converted to + >>> # `tf.Tensor`. + >>> def h(x): + ... return 37.0, ["Foo", "Bar"], np.array([1.0, 2.0], dtype=np.float64) + >>> result = dataset.map(h) + >>> result.element_spec + (TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(2,), \ +dtype=tf.string, name=None), TensorSpec(shape=(2,), dtype=tf.float64, \ +name=None)) + >>> # `map_func` can return nested structures. + >>> def i(x): + ... return (37.0, [42, 16]), "foo" + >>> result = dataset.map(i) + >>> result.element_spec + ((TensorSpec(shape=(), dtype=tf.float32, name=None), + TensorSpec(shape=(2,), dtype=tf.int32, name=None)), + TensorSpec(shape=(), dtype=tf.string, name=None)) + + `map_func` can accept as arguments and return any type of dataset element. + + Note that irrespective of the context in which `map_func` is defined (eager + vs. graph), tf.data traces the function and executes it as a graph. To use + Python code inside of the function you have a few options: + + 1) Rely on AutoGraph to convert Python code into an equivalent graph + computation. The downside of this approach is that AutoGraph can convert + some but not all Python code. + + 2) Use `tf.py_function`, which allows you to write arbitrary Python code but + will generally result in worse performance than 1). For example: + + >>> d = tf.data.Dataset.from_tensor_slices(['hello', 'world']) + >>> # transform a string tensor to upper case string using a Python function + >>> def upper_case_fn(t: tf.Tensor): + ... return t.numpy().decode('utf-8').upper() + >>> d = d.map(lambda x: tf.py_function(func=upper_case_fn, + ... inp=[x], Tout=tf.string)) + >>> list(d.as_numpy_iterator()) + [b'HELLO', b'WORLD'] + + 3) Use `tf.numpy_function`, which also allows you to write arbitrary + Python code. Note that `tf.py_function` accepts `tf.Tensor` whereas + `tf.numpy_function` accepts numpy arrays and returns only numpy arrays. + For example: + + >>> d = tf.data.Dataset.from_tensor_slices(['hello', 'world']) + >>> def upper_case_fn(t: np.ndarray): + ... return t.decode('utf-8').upper() + >>> d = d.map(lambda x: tf.numpy_function(func=upper_case_fn, + ... inp=[x], Tout=tf.string)) + >>> list(d.as_numpy_iterator()) + [b'HELLO', b'WORLD'] + + Note that the use of `tf.numpy_function` and `tf.py_function` + in general precludes the possibility of executing user-defined + transformations in parallel (because of Python GIL). + + Performance can often be improved by setting `num_parallel_calls` so that + `map` will use multiple threads to process elements. If deterministic order + isn't required, it can also improve performance to set + `deterministic=False`. + + >>> dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ] + >>> dataset = dataset.map(lambda x: x + 1, + ... num_parallel_calls=tf.data.AUTOTUNE, + ... deterministic=False) + + The order of elements yielded by this transformation is deterministic if + `deterministic=True`. If `map_func` contains stateful operations and + `num_parallel_calls > 1`, the order in which that state is accessed is + undefined, so the values of output elements may not be deterministic + regardless of the `deterministic` flag value. + + Args: + map_func: A function mapping a dataset element to another dataset element. + num_parallel_calls: (Optional.) A `tf.int64` scalar `tf.Tensor`, + representing the number elements to process asynchronously in parallel. + If not specified, elements will be processed sequentially. If the value + `tf.data.AUTOTUNE` is used, then the number of parallel + calls is set dynamically based on available CPU. + deterministic: (Optional.) When `num_parallel_calls` is specified, if this + boolean is specified (`True` or `False`), it controls the order in which + the transformation produces elements. If set to `False`, the + transformation is allowed to yield elements out of order to trade + determinism for performance. If not specified, the + `tf.data.Options.deterministic` option (`True` by default) controls the + behavior. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> map_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import map_op + return map_op._map_v2( + self, + map_func, + num_parallel_calls=num_parallel_calls, + deterministic=deterministic, + name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def flat_map(self, map_func, name=None) -> "DatasetV2": + """Maps `map_func` across this dataset and flattens the result. + + The type signature is: + + ``` + def flat_map( + self: Dataset[T], + map_func: Callable[[T], Dataset[S]] + ) -> Dataset[S] + ``` + + Use `flat_map` if you want to make sure that the order of your dataset + stays the same. For example, to flatten a dataset of batches into a + dataset of their elements: + + >>> dataset = tf.data.Dataset.from_tensor_slices( + ... [[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> dataset = dataset.flat_map(tf.data.Dataset.from_tensor_slices) + >>> list(dataset.as_numpy_iterator()) + [1, 2, 3, 4, 5, 6, 7, 8, 9] + + `tf.data.Dataset.interleave()` is a generalization of `flat_map`, since + `flat_map` produces the same output as + `tf.data.Dataset.interleave(cycle_length=1)` + + Args: + map_func: A function mapping a dataset element to a dataset. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> flat_map_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import flat_map_op + return flat_map_op._flat_map(self, map_func, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def ignore_errors(self, log_warning=False, name=None) -> "DatasetV2": + """Drops elements that cause errors. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1., 2., 0., 4.]) + >>> dataset = dataset.map(lambda x: tf.debugging.check_numerics(1. / x, "")) + >>> list(dataset.as_numpy_iterator()) + Traceback (most recent call last): + ... + InvalidArgumentError: ... Tensor had Inf values + >>> dataset = dataset.ignore_errors() + >>> list(dataset.as_numpy_iterator()) + [1.0, 0.5, 0.25] + + Args: + log_warning: (Optional.) A bool indicating whether or not ignored errors + should be logged to stderr. Defaults to `False`. + name: (Optional.) A string indicating a name for the `tf.data` operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # ignore_errors_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import ignore_errors_op + return ignore_errors_op._ignore_errors(self, log_warning, name) + # pylint: enable=g-import-not-at-top,protected-access + + def interleave( + self, + map_func, + cycle_length=None, + block_length=None, + num_parallel_calls=None, + deterministic=None, + name=None, + ) -> "DatasetV2": + """Maps `map_func` across this dataset, and interleaves the results. + + The type signature is: + + ``` + def interleave( + self: Dataset[T], + map_func: Callable[[T], Dataset[S]] + ) -> Dataset[S] + ``` + + For example, you can use `Dataset.interleave()` to process many input files + concurrently: + + >>> # Preprocess 4 files concurrently, and interleave blocks of 16 records + >>> # from each file. + >>> filenames = ["/var/data/file1.txt", "/var/data/file2.txt", + ... "/var/data/file3.txt", "/var/data/file4.txt"] + >>> dataset = tf.data.Dataset.from_tensor_slices(filenames) + >>> def parse_fn(filename): + ... return tf.data.Dataset.range(10) + >>> dataset = dataset.interleave(lambda x: + ... tf.data.TextLineDataset(x).map(parse_fn, num_parallel_calls=1), + ... cycle_length=4, block_length=16) + + The `cycle_length` and `block_length` arguments control the order in which + elements are produced. `cycle_length` controls the number of input elements + that are processed concurrently. If you set `cycle_length` to 1, this + transformation will handle one input element at a time, and will produce + identical results to `tf.data.Dataset.flat_map`. In general, + this transformation will apply `map_func` to `cycle_length` input elements, + open iterators on the returned `Dataset` objects, and cycle through them + producing `block_length` consecutive elements from each iterator, and + consuming the next input element each time it reaches the end of an + iterator. + + For example: + + >>> dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ] + >>> # NOTE: New lines indicate "block" boundaries. + >>> dataset = dataset.interleave( + ... lambda x: Dataset.from_tensors(x).repeat(6), + ... cycle_length=2, block_length=4) + >>> list(dataset.as_numpy_iterator()) + [1, 1, 1, 1, + 2, 2, 2, 2, + 1, 1, + 2, 2, + 3, 3, 3, 3, + 4, 4, 4, 4, + 3, 3, + 4, 4, + 5, 5, 5, 5, + 5, 5] + + Note: The order of elements yielded by this transformation is + deterministic, as long as `map_func` is a pure function and + `deterministic=True`. If `map_func` contains any stateful operations, the + order in which that state is accessed is undefined. + + Performance can often be improved by setting `num_parallel_calls` so that + `interleave` will use multiple threads to fetch elements. If determinism + isn't required, it can also improve performance to set + `deterministic=False`. + + >>> filenames = ["/var/data/file1.txt", "/var/data/file2.txt", + ... "/var/data/file3.txt", "/var/data/file4.txt"] + >>> dataset = tf.data.Dataset.from_tensor_slices(filenames) + >>> dataset = dataset.interleave(lambda x: tf.data.TFRecordDataset(x), + ... cycle_length=4, num_parallel_calls=tf.data.AUTOTUNE, + ... deterministic=False) + + Args: + map_func: A function that takes a dataset element and returns a + `tf.data.Dataset`. + cycle_length: (Optional.) The number of input elements that will be + processed concurrently. If not set, the tf.data runtime decides what it + should be based on available CPU. If `num_parallel_calls` is set to + `tf.data.AUTOTUNE`, the `cycle_length` argument identifies + the maximum degree of parallelism. + block_length: (Optional.) The number of consecutive elements to produce + from each input element before cycling to another input element. If not + set, defaults to 1. + num_parallel_calls: (Optional.) If specified, the implementation creates a + threadpool, which is used to fetch inputs from cycle elements + asynchronously and in parallel. The default behavior is to fetch inputs + from cycle elements synchronously with no parallelism. If the value + `tf.data.AUTOTUNE` is used, then the number of parallel + calls is set dynamically based on available CPU. + deterministic: (Optional.) When `num_parallel_calls` is specified, if this + boolean is specified (`True` or `False`), it controls the order in which + the transformation produces elements. If set to `False`, the + transformation is allowed to yield elements out of order to trade + determinism for performance. If not specified, the + `tf.data.Options.deterministic` option (`True` by default) controls the + behavior. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency ( + # dataset_ops -> interleave_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import interleave_op + return interleave_op._interleave(self, map_func, cycle_length, block_length, + num_parallel_calls, deterministic, name) + # pylint: enable=g-import-not-at-top,protected-access + + def filter(self, predicate, name=None) -> "DatasetV2": + """Filters this dataset according to `predicate`. + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> dataset = dataset.filter(lambda x: x < 3) + >>> list(dataset.as_numpy_iterator()) + [1, 2] + >>> # `tf.math.equal(x, y)` is required for equality comparison + >>> def filter_fn(x): + ... return tf.math.equal(x, 1) + >>> dataset = dataset.filter(filter_fn) + >>> list(dataset.as_numpy_iterator()) + [1] + + Args: + predicate: A function mapping a dataset element to a boolean. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> filter_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import filter_op + return filter_op._filter(self, predicate, name) + # pylint: enable=g-import-not-at-top,protected-access + + def apply(self, transformation_func) -> "DatasetV2": + """Applies a transformation function to this dataset. + + `apply` enables chaining of custom `Dataset` transformations, which are + represented as functions that take one `Dataset` argument and return a + transformed `Dataset`. + + >>> dataset = tf.data.Dataset.range(100) + >>> def dataset_fn(ds): + ... return ds.filter(lambda x: x < 5) + >>> dataset = dataset.apply(dataset_fn) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 2, 3, 4] + + Args: + transformation_func: A function that takes one `Dataset` argument and + returns a `Dataset`. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + dataset = transformation_func(self) + if not isinstance(dataset, data_types.DatasetV2): + raise TypeError( + f"`transformation_func` must return a `tf.data.Dataset` object. " + f"Got {type(dataset)}.") + dataset._input_datasets = [self] # pylint: disable=protected-access + return dataset + + def window( + self, size, shift=None, stride=1, drop_remainder=False, name=None + ) -> "DatasetV2": + """Returns a dataset of "windows". + + Each "window" is a dataset that contains a subset of elements of the + input dataset. These are finite datasets of size `size` (or possibly fewer + if there are not enough input elements to fill the window and + `drop_remainder` evaluates to `False`). + + For example: + + >>> dataset = tf.data.Dataset.range(7).window(3) + >>> for window in dataset: + ... print(window) + <...Dataset element_spec=TensorSpec(shape=(), dtype=tf.int64, name=None)> + <...Dataset element_spec=TensorSpec(shape=(), dtype=tf.int64, name=None)> + <...Dataset element_spec=TensorSpec(shape=(), dtype=tf.int64, name=None)> + + Since windows are datasets, they can be iterated over: + + >>> for window in dataset: + ... print(list(window.as_numpy_iterator())) + [0, 1, 2] + [3, 4, 5] + [6] + + #### Shift + + The `shift` argument determines the number of input elements to shift + between the start of each window. If windows and elements are both numbered + starting at 0, the first element in window `k` will be element `k * shift` + of the input dataset. In particular, the first element of the first window + will always be the first element of the input dataset. + + >>> dataset = tf.data.Dataset.range(7).window(3, shift=1, + ... drop_remainder=True) + >>> for window in dataset: + ... print(list(window.as_numpy_iterator())) + [0, 1, 2] + [1, 2, 3] + [2, 3, 4] + [3, 4, 5] + [4, 5, 6] + + #### Stride + + The `stride` argument determines the stride between input elements within a + window. + + >>> dataset = tf.data.Dataset.range(7).window(3, shift=1, stride=2, + ... drop_remainder=True) + >>> for window in dataset: + ... print(list(window.as_numpy_iterator())) + [0, 2, 4] + [1, 3, 5] + [2, 4, 6] + + #### Nested elements + + When the `window` transformation is applied to a dataset whos elements are + nested structures, it produces a dataset where the elements have the same + nested structure but each leaf is replaced by a window. In other words, + the nesting is applied outside of the windows as opposed inside of them. + + The type signature is: + + ``` + def window( + self: Dataset[Nest[T]], ... + ) -> Dataset[Nest[Dataset[T]]] + ``` + + Applying `window` to a `Dataset` of tuples gives a tuple of windows: + + >>> dataset = tf.data.Dataset.from_tensor_slices(([1, 2, 3, 4, 5], + ... [6, 7, 8, 9, 10])) + >>> dataset = dataset.window(2) + >>> windows = next(iter(dataset)) + >>> windows + (<...Dataset element_spec=TensorSpec(shape=(), dtype=tf.int32, name=None)>, + <...Dataset element_spec=TensorSpec(shape=(), dtype=tf.int32, name=None)>) + + >>> def to_numpy(ds): + ... return list(ds.as_numpy_iterator()) + >>> + >>> for windows in dataset: + ... print(to_numpy(windows[0]), to_numpy(windows[1])) + [1, 2] [6, 7] + [3, 4] [8, 9] + [5] [10] + + Applying `window` to a `Dataset` of dictionaries gives a dictionary of + `Datasets`: + + >>> dataset = tf.data.Dataset.from_tensor_slices({'a': [1, 2, 3], + ... 'b': [4, 5, 6], + ... 'c': [7, 8, 9]}) + >>> dataset = dataset.window(2) + >>> def to_numpy(ds): + ... return list(ds.as_numpy_iterator()) + >>> + >>> for windows in dataset: + ... print(tf.nest.map_structure(to_numpy, windows)) + {'a': [1, 2], 'b': [4, 5], 'c': [7, 8]} + {'a': [3], 'b': [6], 'c': [9]} + + #### Flatten a dataset of windows + + The `Dataset.flat_map` and `Dataset.interleave` methods can be used to + flatten a dataset of windows into a single dataset. + + The argument to `flat_map` is a function that takes an element from the + dataset and returns a `Dataset`. `flat_map` chains together the resulting + datasets sequentially. + + For example, to turn each window into a dense tensor: + + >>> dataset = tf.data.Dataset.range(7).window(3, shift=1, + ... drop_remainder=True) + >>> batched = dataset.flat_map(lambda x:x.batch(3)) + >>> for batch in batched: + ... print(batch.numpy()) + [0 1 2] + [1 2 3] + [2 3 4] + [3 4 5] + [4 5 6] + + Args: + size: A `tf.int64` scalar `tf.Tensor`, representing the number of elements + of the input dataset to combine into a window. Must be positive. + shift: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the + number of input elements by which the window moves in each iteration. + Defaults to `size`. Must be positive. + stride: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the + stride of the input elements in the sliding window. Must be positive. + The default value of 1 means "retain every input element". + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last windows should be dropped if their size is smaller than + `size`. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> window_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import window_op + return window_op._window(self, size, shift, stride, drop_remainder, name) + # pylint: enable=g-import-not-at-top,protected-access + + def reduce(self, initial_state, reduce_func, name=None): + """Reduces the input dataset to a single element. + + The transformation calls `reduce_func` successively on every element of + the input dataset until the dataset is exhausted, aggregating information in + its internal state. The `initial_state` argument is used for the initial + state and the final state is returned as the result. + + >>> tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, _: x + 1).numpy() + 5 + >>> tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, y: x + y).numpy() + 10 + + Args: + initial_state: An element representing the initial state of the + transformation. + reduce_func: A function that maps `(old_state, input_element)` to + `new_state`. It must take two arguments and return a new element + The structure of `new_state` must match the structure of + `initial_state`. + name: (Optional.) A name for the tf.data operation. + + Returns: + A dataset element corresponding to the final state of the transformation. + + """ + + with ops.name_scope("initial_state"): + initial_state = structure.normalize_element(initial_state) + state_structure = structure.type_spec_from_value(initial_state) + + # Iteratively rerun the reduce function until reaching a fixed point on + # `state_structure`. + need_to_rerun = True + while need_to_rerun: + + wrapped_func = structured_function.StructuredFunctionWrapper( + reduce_func, + "reduce()", + input_structure=(state_structure, self.element_spec), + add_to_graph=False) + + # Extract and validate class information from the returned values. + output_classes = wrapped_func.output_classes + state_classes = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + state_structure) + for new_state_class, state_class in zip( + nest.flatten(output_classes), nest.flatten(state_classes)): + if not issubclass(new_state_class, state_class): + raise TypeError( + f"The element classes for the new state must match the initial " + f"state. Expected {state_classes} but got " + f"{wrapped_func.output_classes}.") + + # Extract and validate type information from the returned values. + output_types = wrapped_func.output_types + state_types = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + state_structure) + for new_state_type, state_type in zip( + nest.flatten(output_types), nest.flatten(state_types)): + if new_state_type != state_type: + raise TypeError( + f"The element types for the new state must match the initial " + f"state. Expected {state_types} but got " + f"{wrapped_func.output_types}.") + + # Extract shape information from the returned values. + output_shapes = wrapped_func.output_shapes + state_shapes = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + state_structure) + flat_state_shapes = nest.flatten(state_shapes) + flat_new_state_shapes = nest.flatten(output_shapes) + weakened_state_shapes = [ + original.most_specific_compatible_shape(new) + for original, new in zip(flat_state_shapes, flat_new_state_shapes) + ] + + need_to_rerun = False + for original_shape, weakened_shape in zip(flat_state_shapes, + weakened_state_shapes): + if original_shape.ndims is not None and ( + weakened_shape.ndims is None or + original_shape.as_list() != weakened_shape.as_list()): + need_to_rerun = True + break + + if need_to_rerun: + # TODO(b/110122868): Support a "most specific compatible structure" + # method for combining structures, to avoid using legacy structures + # here. + state_structure = structure.convert_legacy_structure( + state_types, + nest.pack_sequence_as(state_shapes, weakened_state_shapes), + state_classes) + + reduce_func = wrapped_func.function + reduce_func.add_to_graph(ops.get_default_graph()) + + dataset = self._apply_debug_options() + + # pylint: disable=protected-access + metadata = dataset_metadata_pb2.Metadata() + if name: + metadata.name = _validate_and_encode(name) + return structure.from_compatible_tensor_list( + state_structure, + gen_dataset_ops.reduce_dataset( + dataset._variant_tensor, + structure.to_tensor_list(state_structure, initial_state), + reduce_func.captured_inputs, + f=reduce_func, + output_shapes=structure.get_flat_tensor_shapes(state_structure), + output_types=structure.get_flat_tensor_types(state_structure), + metadata=metadata.SerializeToString())) + + def get_single_element(self, name=None): + """Returns the single element of the `dataset`. + + The function enables you to use a `tf.data.Dataset` in a stateless + "tensor-in tensor-out" expression, without creating an iterator. + This facilitates the ease of data transformation on tensors using the + optimized `tf.data.Dataset` abstraction on top of them. + + For example, lets consider a `preprocessing_fn` which would take as an + input the raw features and returns the processed feature along with + it's label. + + ```python + def preprocessing_fn(raw_feature): + # ... the raw_feature is preprocessed as per the use-case + return feature + + raw_features = ... # input batch of BATCH_SIZE elements. + dataset = (tf.data.Dataset.from_tensor_slices(raw_features) + .map(preprocessing_fn, num_parallel_calls=BATCH_SIZE) + .batch(BATCH_SIZE)) + + processed_features = dataset.get_single_element() + ``` + + In the above example, the `raw_features` tensor of length=BATCH_SIZE + was converted to a `tf.data.Dataset`. Next, each of the `raw_feature` was + mapped using the `preprocessing_fn` and the processed features were + grouped into a single batch. The final `dataset` contains only one element + which is a batch of all the processed features. + + NOTE: The `dataset` should contain only one element. + + Now, instead of creating an iterator for the `dataset` and retrieving the + batch of features, the `tf.data.get_single_element()` function is used + to skip the iterator creation process and directly output the batch of + features. + + This can be particularly useful when your tensor transformations are + expressed as `tf.data.Dataset` operations, and you want to use those + transformations while serving your model. + + #### Keras + + ```python + + model = ... # A pre-built or custom model + + class PreprocessingModel(tf.keras.Model): + def __init__(self, model): + super().__init__(self) + self.model = model + + @tf.function(input_signature=[...]) + def serving_fn(self, data): + ds = tf.data.Dataset.from_tensor_slices(data) + ds = ds.map(preprocessing_fn, num_parallel_calls=BATCH_SIZE) + ds = ds.batch(batch_size=BATCH_SIZE) + return tf.argmax(self.model(ds.get_single_element()), axis=-1) + + preprocessing_model = PreprocessingModel(model) + your_exported_model_dir = ... # save the model to this path. + tf.saved_model.save(preprocessing_model, your_exported_model_dir, + signatures={'serving_default': preprocessing_model.serving_fn} + ) + ``` + + #### Estimator + + In the case of estimators, you need to generally define a `serving_input_fn` + which would require the features to be processed by the model while + inferencing. + + ```python + def serving_input_fn(): + + raw_feature_spec = ... # Spec for the raw_features + input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn( + raw_feature_spec, default_batch_size=None) + ) + serving_input_receiver = input_fn() + raw_features = serving_input_receiver.features + + def preprocessing_fn(raw_feature): + # ... the raw_feature is preprocessed as per the use-case + return feature + + dataset = (tf.data.Dataset.from_tensor_slices(raw_features) + .map(preprocessing_fn, num_parallel_calls=BATCH_SIZE) + .batch(BATCH_SIZE)) + + processed_features = dataset.get_single_element() + + # Please note that the value of `BATCH_SIZE` should be equal to + # the size of the leading dimension of `raw_features`. This ensures + # that `dataset` has only element, which is a pre-requisite for + # using `dataset.get_single_element()`. + + return tf.estimator.export.ServingInputReceiver( + processed_features, serving_input_receiver.receiver_tensors) + + estimator = ... # A pre-built or custom estimator + estimator.export_saved_model(your_exported_model_dir, serving_input_fn) + ``` + + Args: + name: (Optional.) A name for the tf.data operation. + + Returns: + A nested structure of `tf.Tensor` objects, corresponding to the single + element of `dataset`. + + Raises: + InvalidArgumentError: (at runtime) if `dataset` does not contain exactly + one element. + """ + + metadata = dataset_metadata_pb2.Metadata() + if name: + metadata.name = _validate_and_encode(name) + return structure.from_compatible_tensor_list( + self.element_spec, + gen_dataset_ops.dataset_to_single_element( + self._variant_tensor, + metadata=metadata.SerializeToString(), + **self._flat_structure)) # pylint: disable=protected-access + + def unbatch(self, name=None) -> "DatasetV2": + """Splits elements of a dataset into multiple elements. + + For example, if elements of the dataset are shaped `[B, a0, a1, ...]`, + where `B` may vary for each input element, then for each element in the + dataset, the unbatched dataset will contain `B` consecutive elements + of shape `[a0, a1, ...]`. + + >>> elements = [ [1, 2, 3], [1, 2], [1, 2, 3, 4] ] + >>> dataset = tf.data.Dataset.from_generator(lambda: elements, tf.int64) + >>> dataset = dataset.unbatch() + >>> list(dataset.as_numpy_iterator()) + [1, 2, 3, 1, 2, 1, 2, 3, 4] + + Note: `unbatch` requires a data copy to slice up the batched tensor into + smaller, unbatched tensors. When optimizing performance, try to avoid + unnecessary usage of `unbatch`. + + Args: + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency ( + # dataset_ops -> unbatch_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import unbatch_op + return unbatch_op._unbatch(self, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def with_options(self, options, name=None) -> "DatasetV2": + """Returns a new `tf.data.Dataset` with the given options set. + + The options are "global" in the sense they apply to the entire dataset. + If options are set multiple times, they are merged as long as different + options do not use different non-default values. + + >>> ds = tf.data.Dataset.range(5) + >>> ds = ds.interleave(lambda x: tf.data.Dataset.range(5), + ... cycle_length=3, + ... num_parallel_calls=3) + >>> options = tf.data.Options() + >>> # This will make the interleave order non-deterministic. + >>> options.deterministic = False + >>> ds = ds.with_options(options) + + Args: + options: A `tf.data.Options` that identifies the options the use. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + + Raises: + ValueError: when an option is set more than once to a non-default value + """ + return _OptionsDataset(self, options, name=name) + + def cardinality(self): + """Returns the cardinality of the dataset, if known. + + `cardinality` may return `tf.data.INFINITE_CARDINALITY` if the dataset + contains an infinite number of elements or `tf.data.UNKNOWN_CARDINALITY` if + the analysis fails to determine the number of elements in the dataset + (e.g. when the dataset source is a file). + + >>> dataset = tf.data.Dataset.range(42) + >>> print(dataset.cardinality().numpy()) + 42 + >>> dataset = dataset.repeat() + >>> cardinality = dataset.cardinality() + >>> print((cardinality == tf.data.INFINITE_CARDINALITY).numpy()) + True + >>> dataset = dataset.filter(lambda x: True) + >>> cardinality = dataset.cardinality() + >>> print((cardinality == tf.data.UNKNOWN_CARDINALITY).numpy()) + True + + Returns: + A scalar `tf.int64` `Tensor` representing the cardinality of the dataset. + If the cardinality is infinite or unknown, `cardinality` returns the + named constants `tf.data.INFINITE_CARDINALITY` and + `tf.data.UNKNOWN_CARDINALITY` respectively. + """ + return gen_dataset_ops.dataset_cardinality(self._variant_tensor) + + def group_by_window( + self, + key_func, + reduce_func, + window_size=None, + window_size_func=None, + name=None, + ) -> "DatasetV2": + """Groups windows of elements by key and reduces them. + + This transformation maps each consecutive element in a dataset to a key + using `key_func` and groups the elements by key. It then applies + `reduce_func` to at most `window_size_func(key)` elements matching the same + key. All except the final window for each key will contain + `window_size_func(key)` elements; the final window may be smaller. + + You may provide either a constant `window_size` or a window size determined + by the key through `window_size_func`. + + >>> dataset = tf.data.Dataset.range(10) + >>> window_size = 5 + >>> key_func = lambda x: x%2 + >>> reduce_func = lambda key, dataset: dataset.batch(window_size) + >>> dataset = dataset.group_by_window( + ... key_func=key_func, + ... reduce_func=reduce_func, + ... window_size=window_size) + >>> for elem in dataset.as_numpy_iterator(): + ... print(elem) + [0 2 4 6 8] + [1 3 5 7 9] + + Args: + key_func: A function mapping a nested structure of tensors (having shapes + and types defined by `self.output_shapes` and `self.output_types`) to a + scalar `tf.int64` tensor. + reduce_func: A function mapping a key and a dataset of up to `window_size` + consecutive elements matching that key to another dataset. + window_size: A `tf.int64` scalar `tf.Tensor`, representing the number of + consecutive elements matching the same key to combine in a single batch, + which will be passed to `reduce_func`. Mutually exclusive with + `window_size_func`. + window_size_func: A function mapping a key to a `tf.int64` scalar + `tf.Tensor`, representing the number of consecutive elements matching + the same key to combine in a single batch, which will be passed to + `reduce_func`. Mutually exclusive with `window_size`. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + + Raises: + ValueError: if neither or both of {`window_size`, `window_size_func`} are + passed. + """ + # Loaded lazily due to a circular dependency ( + # dataset_ops -> group_by_window_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import group_by_window_op + return group_by_window_op._group_by_window( + self, key_func, reduce_func, window_size, window_size_func, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def bucket_by_sequence_length( + self, + element_length_func, + bucket_boundaries, + bucket_batch_sizes, + padded_shapes=None, + padding_values=None, + pad_to_bucket_boundary=False, + no_padding=False, + drop_remainder=False, + name=None, + ) -> "DatasetV2": + """A transformation that buckets elements in a `Dataset` by length. + + Elements of the `Dataset` are grouped together by length and then are padded + and batched. + + This is useful for sequence tasks in which the elements have variable + length. Grouping together elements that have similar lengths reduces the + total fraction of padding in a batch which increases training step + efficiency. + + Below is an example to bucketize the input data to the 3 buckets + "[0, 3), [3, 5), [5, inf)" based on sequence length, with batch size 2. + + >>> elements = [ + ... [0], [1, 2, 3, 4], [5, 6, 7], + ... [7, 8, 9, 10, 11], [13, 14, 15, 16, 19, 20], [21, 22]] + >>> dataset = tf.data.Dataset.from_generator( + ... lambda: elements, tf.int64, output_shapes=[None]) + >>> dataset = dataset.bucket_by_sequence_length( + ... element_length_func=lambda elem: tf.shape(elem)[0], + ... bucket_boundaries=[3, 5], + ... bucket_batch_sizes=[2, 2, 2]) + >>> for elem in dataset.as_numpy_iterator(): + ... print(elem) + [[1 2 3 4] + [5 6 7 0]] + [[ 7 8 9 10 11 0] + [13 14 15 16 19 20]] + [[ 0 0] + [21 22]] + + Args: + element_length_func: function from element in `Dataset` to `tf.int32`, + determines the length of the element, which will determine the bucket it + goes into. + bucket_boundaries: `list`, upper length boundaries of the buckets. + bucket_batch_sizes: `list`, batch size per bucket. Length should be + `len(bucket_boundaries) + 1`. + padded_shapes: Nested structure of `tf.TensorShape` to pass to + `tf.data.Dataset.padded_batch`. If not provided, will use + `dataset.output_shapes`, which will result in variable length dimensions + being padded out to the maximum length in each batch. + padding_values: Values to pad with, passed to + `tf.data.Dataset.padded_batch`. Defaults to padding with 0. + pad_to_bucket_boundary: bool, if `False`, will pad dimensions with unknown + size to maximum length in batch. If `True`, will pad dimensions with + unknown size to bucket boundary minus 1 (i.e., the maximum length in + each bucket), and caller must ensure that the source `Dataset` does not + contain any elements with length longer than `max(bucket_boundaries)`. + no_padding: `bool`, indicates whether to pad the batch features (features + need to be either of type `tf.sparse.SparseTensor` or of same shape). + drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing + whether the last batch should be dropped in the case it has fewer than + `batch_size` elements; the default behavior is not to drop the smaller + batch. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + + Raises: + ValueError: if `len(bucket_batch_sizes) != len(bucket_boundaries) + 1`. + """ + if len(bucket_batch_sizes) != (len(bucket_boundaries) + 1): + raise ValueError( + f"`len(bucket_batch_sizes)` must equal `len(bucket_boundaries) + 1` " + f"but `len(bucket_batch_sizes)={len(bucket_batch_sizes)}` and " + f"`len(bucket_boundaries)={len(bucket_boundaries)}`.") + + batch_sizes = constant_op.constant(bucket_batch_sizes, dtype=dtypes.int64) + + def element_to_bucket_id(*args): + """Return int64 id of the length bucket for this element.""" + seq_length = element_length_func(*args) + + boundaries = list(bucket_boundaries) + buckets_min = [np.iinfo(np.int32).min] + boundaries + buckets_max = boundaries + [np.iinfo(np.int32).max] + conditions_c = math_ops.logical_and( + math_ops.less_equal(buckets_min, seq_length), + math_ops.less(seq_length, buckets_max)) + bucket_id = math_ops.reduce_min(array_ops.where(conditions_c)) + + return bucket_id + + def window_size_fn(bucket_id): + # The window size is set to the batch size for this bucket + window_size = batch_sizes[bucket_id] + return window_size + + def make_padded_shapes(shapes, none_filler=None): + padded = [] + for shape in nest.flatten(shapes): + shape = tensor_shape.TensorShape(shape) + shape = [ + none_filler if tensor_shape.dimension_value(d) is None else d + for d in shape + ] + padded.append(shape) + return nest.pack_sequence_as(shapes, padded) + + def batching_fn(bucket_id, grouped_dataset): + """Batch elements in dataset.""" + batch_size = window_size_fn(bucket_id) + if no_padding: + return grouped_dataset.batch( + batch_size, drop_remainder=drop_remainder, name=name) + none_filler = None + if pad_to_bucket_boundary: + err_msg = ("When pad_to_bucket_boundary=True, elements must have " + "length < max(bucket_boundaries).") + check = check_ops.assert_less( + bucket_id, + constant_op.constant( + len(bucket_batch_sizes) - 1, dtype=dtypes.int64), + message=err_msg) + with ops.control_dependencies([check]): + boundaries = constant_op.constant( + bucket_boundaries, dtype=dtypes.int64) + bucket_boundary = boundaries[bucket_id] + none_filler = bucket_boundary - 1 + input_shapes = get_legacy_output_shapes(grouped_dataset) + shapes = make_padded_shapes( + padded_shapes or input_shapes, none_filler=none_filler) + return grouped_dataset.padded_batch( + batch_size, + shapes, + padding_values, + drop_remainder=drop_remainder, + name=name) + + return self.group_by_window( + key_func=element_to_bucket_id, + reduce_func=batching_fn, + window_size_func=window_size_fn, + name=name) + + @staticmethod + def random( + seed=None, rerandomize_each_iteration=None, name=None + ) -> "DatasetV2": + """Creates a `Dataset` of pseudorandom values. + + The dataset generates a sequence of uniformly distributed integer values. + + `rerandomize_each_iteration` controls whether the sequence of random number + generated should be re-randomized for each epoch. The default value is False + where the dataset generates the same sequence of random numbers for each + epoch. + + >>> ds1 = tf.data.Dataset.random(seed=4).take(10) + >>> ds2 = tf.data.Dataset.random(seed=4).take(10) + >>> print(list(ds1.as_numpy_iterator())==list(ds2.as_numpy_iterator())) + True + + >>> ds3 = tf.data.Dataset.random(seed=4).take(10) + >>> ds3_first_epoch = list(ds3.as_numpy_iterator()) + >>> ds3_second_epoch = list(ds3.as_numpy_iterator()) + >>> print(ds3_first_epoch == ds3_second_epoch) + True + + >>> ds4 = tf.data.Dataset.random( + ... seed=4, rerandomize_each_iteration=True).take(10) + >>> ds4_first_epoch = list(ds4.as_numpy_iterator()) + >>> ds4_second_epoch = list(ds4.as_numpy_iterator()) + >>> print(ds4_first_epoch == ds4_second_epoch) + False + + Args: + seed: (Optional) If specified, the dataset produces a deterministic + sequence of values. + rerandomize_each_iteration: (Optional) If set to False, the dataset + generates the same sequence of random numbers for each epoch. If set to + True, it generates a different deterministic sequence of random numbers + for each epoch. It is defaulted to False if left unspecified. + name: (Optional.) A name for the tf.data operation. + + Returns: + Dataset: A `Dataset`. + """ + # Loaded lazily due to a circular dependency ( + # dataset_ops -> random_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import random_op + return random_op._random( + seed=seed, + rerandomize_each_iteration=rerandomize_each_iteration, + name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def snapshot( + self, + path, + compression="AUTO", + reader_func=None, + shard_func=None, + name=None, + ) -> "DatasetV2": + """API to persist the output of the input dataset. + + The snapshot API allows users to transparently persist the output of their + preprocessing pipeline to disk, and materialize the pre-processed data on a + different training run. + + This API enables repeated preprocessing steps to be consolidated, and allows + re-use of already processed data, trading off disk storage and network + bandwidth for freeing up more valuable CPU resources and accelerator compute + time. + + https://github.com/tensorflow/community/blob/master/rfcs/20200107-tf-data-snapshot.md + has detailed design documentation of this feature. + + Users can specify various options to control the behavior of snapshot, + including how snapshots are read from and written to by passing in + user-defined functions to the `reader_func` and `shard_func` parameters. + + `shard_func` is a user specified function that maps input elements to + snapshot shards. + + Users may want to specify this function to control how snapshot files should + be written to disk. Below is an example of how a potential `shard_func` + could be written. + + ```python + dataset = ... + dataset = dataset.enumerate() + dataset = dataset.snapshot("/path/to/snapshot/dir", + shard_func=lambda x, y: x % NUM_SHARDS, ...) + dataset = dataset.map(lambda x, y: y) + ``` + + `reader_func` is a user specified function that accepts a single argument: + (1) a Dataset of Datasets, each representing a "split" of elements of the + original dataset. The cardinality of the input dataset matches the + number of the shards specified in the `shard_func` (see above). The function + should return a Dataset of elements of the original dataset. + + Users may want specify this function to control how snapshot files should be + read from disk, including the amount of shuffling and parallelism. + + Here is an example of a standard reader function a user can define. This + function enables both dataset shuffling and parallel reading of datasets: + + ```python + def user_reader_func(datasets): + # shuffle the datasets splits + datasets = datasets.shuffle(NUM_CORES) + # read datasets in parallel and interleave their elements + return datasets.interleave(lambda x: x, num_parallel_calls=AUTOTUNE) + + dataset = dataset.snapshot("/path/to/snapshot/dir", + reader_func=user_reader_func) + ``` + + By default, snapshot parallelizes reads by the number of cores available on + the system, but will not attempt to shuffle the data. + + Args: + path: Required. A directory to use for storing / loading the snapshot to / + from. + compression: Optional. The type of compression to apply to the snapshot + written to disk. Supported options are `GZIP`, `SNAPPY`, `AUTO` or None. + Defaults to `AUTO`, which attempts to pick an appropriate compression + algorithm for the dataset. + reader_func: Optional. A function to control how to read data from + snapshot shards. + shard_func: Optional. A function to control how to shard data when writing + a snapshot. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency ( + # dataset_ops -> snapshot_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import snapshot_op + return snapshot_op._snapshot( + self, path, compression, reader_func, shard_func, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def scan(self, initial_state, scan_func, name=None) -> "DatasetV2": + """A transformation that scans a function across an input dataset. + + This transformation is a stateful relative of `tf.data.Dataset.map`. + In addition to mapping `scan_func` across the elements of the input dataset, + `scan()` accumulates one or more state tensors, whose initial values are + `initial_state`. + + >>> dataset = tf.data.Dataset.range(10) + >>> initial_state = tf.constant(0, dtype=tf.int64) + >>> scan_func = lambda state, i: (state + i, state + i) + >>> dataset = dataset.scan(initial_state=initial_state, scan_func=scan_func) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] + + Args: + initial_state: A nested structure of tensors, representing the initial + state of the accumulator. + scan_func: A function that maps `(old_state, input_element)` to + `(new_state, output_element)`. It must take two arguments and return a + pair of nested structures of tensors. The `new_state` must match the + structure of `initial_state`. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + + # Loaded lazily due to a circular dependency (dataset_ops -> + # scan_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import scan_op + return scan_op._scan(self, initial_state, scan_func, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def take_while(self, predicate, name=None) -> "DatasetV2": + """A transformation that stops dataset iteration based on a `predicate`. + + >>> dataset = tf.data.Dataset.range(10) + >>> dataset = dataset.take_while(lambda x: x < 5) + >>> list(dataset.as_numpy_iterator()) + [0, 1, 2, 3, 4] + + Args: + predicate: A function that maps a nested structure of tensors (having + shapes and types defined by `self.output_shapes` and + `self.output_types`) to a scalar `tf.bool` tensor. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency ( + # dataset_ops -> take_while_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import take_while_op + return take_while_op._take_while(self, predicate, name=name) + # pylint: enable=g-import-not-at-top,protected-access + + def unique(self, name=None) -> "DatasetV2": + """A transformation that discards duplicate elements of a `Dataset`. + + Use this transformation to produce a dataset that contains one instance of + each unique element in the input. For example: + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 37, 2, 37, 2, 1]) + >>> dataset = dataset.unique() + >>> sorted(list(dataset.as_numpy_iterator())) + [1, 2, 37] + + Note: This transformation only supports datasets which fit into memory + and have elements of either `tf.int32`, `tf.int64` or `tf.string` type. + + Args: + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> unique_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import unique_op + return unique_op._unique(self, name) + # pylint: enable=g-import-not-at-top,protected-access + + def rejection_resample( + self, class_func, target_dist, initial_dist=None, seed=None, name=None + ) -> "DatasetV2": + """Resamples elements to reach a target distribution. + + Note: This implementation can reject **or repeat** elements in order to + reach the `target_dist`. So, in some cases, the output `Dataset` may be + larger than the input `Dataset`. + + >>> initial_dist = [0.6, 0.4] + >>> n = 1000 + >>> elems = np.random.choice(len(initial_dist), size=n, p=initial_dist) + >>> dataset = tf.data.Dataset.from_tensor_slices(elems) + >>> zero, one = np.bincount(list(dataset.as_numpy_iterator())) / n + + Following from `initial_dist`, `zero` is ~0.6 and `one` is ~0.4. + + >>> target_dist = [0.5, 0.5] + >>> dataset = dataset.rejection_resample( + ... class_func=lambda x: x, + ... target_dist=target_dist, + ... initial_dist=initial_dist) + >>> dataset = dataset.map(lambda class_func_result, data: data) + >>> zero, one = np.bincount(list(dataset.as_numpy_iterator())) / n + + Following from `target_dist`, `zero` is ~0.5 and `one` is ~0.5. + + Args: + class_func: A function mapping an element of the input dataset to a scalar + `tf.int32` tensor. Values should be in `[0, num_classes)`. + target_dist: A floating point type tensor, shaped `[num_classes]`. + initial_dist: (Optional.) A floating point type tensor, shaped + `[num_classes]`. If not provided, the true class distribution is + estimated live in a streaming fashion. + seed: (Optional.) Python integer seed for the resampler. + name: (Optional.) A name for the tf.data operation. + + Returns: + A new `Dataset` with the transformation applied as described above. + """ + + # TODO(b/245793127): Consider switching back to the 'v1' implementation. + + target_dist_t = ops.convert_to_tensor(target_dist, name="target_dist") + target_dist_t = math_ops.cast(target_dist_t, dtypes.float32) + + # Get initial distribution. + if initial_dist is not None: + initial_dist_t = ops.convert_to_tensor(initial_dist, name="initial_dist") + initial_dist_t = math_ops.cast(initial_dist_t, dtypes.float32) + acceptance_dist, prob_of_original = ( + _calculate_acceptance_probs_with_mixing(initial_dist_t, + target_dist_t)) + initial_dist_ds = DatasetV2.from_tensors( + initial_dist_t, name=name).repeat(name=name) + acceptance_dist_ds = DatasetV2.from_tensors( + acceptance_dist, name=name).repeat(name=name) + prob_of_original_ds = DatasetV2.from_tensors( + prob_of_original, name=name).repeat(name=name) + else: + initial_dist_ds = _estimate_initial_dist_ds( + target_dist_t, self.map(class_func, name=name), name=name) + acceptance_and_original_prob_ds = initial_dist_ds.map( + lambda initial: _calculate_acceptance_probs_with_mixing( # pylint: disable=g-long-lambda + initial, target_dist_t), + name=name) + acceptance_dist_ds = acceptance_and_original_prob_ds.map( + lambda accept_prob, _: accept_prob, name=name) + prob_of_original_ds = acceptance_and_original_prob_ds.map( + lambda _, prob_original: prob_original, name=name) + filtered_ds = _filter_ds(self, acceptance_dist_ds, initial_dist_ds, + class_func, seed) + # Prefetch filtered dataset for speed. + filtered_ds = filtered_ds.prefetch(3, name=name) + + prob_original_static = _get_prob_original_static( + initial_dist_t, target_dist_t) if initial_dist is not None else None + + def add_class_value(*x): + if len(x) == 1: + return class_func(*x), x[0] + else: + return class_func(*x), x + + if prob_original_static == 1: + return self.map(add_class_value, name=name) + elif prob_original_static == 0: + return filtered_ds + else: + return Dataset.sample_from_datasets( + [self.map(add_class_value), filtered_ds], + weights=prob_of_original_ds.map(lambda prob: [(prob, 1.0 - prob)]), + seed=seed, + stop_on_empty_dataset=True) + + @staticmethod + def sample_from_datasets( + datasets, + weights=None, + seed=None, + stop_on_empty_dataset=False, + rerandomize_each_iteration=None, + ) -> "DatasetV2": + """Samples elements at random from the datasets in `datasets`. + + Creates a dataset by interleaving elements of `datasets` with `weight[i]` + probability of picking an element from dataset `i`. Sampling is done without + replacement. For example, suppose we have 2 datasets: + + ```python + dataset1 = tf.data.Dataset.range(0, 3) + dataset2 = tf.data.Dataset.range(100, 103) + ``` + + Suppose that we sample from these 2 datasets with the following weights: + + ```python + sample_dataset = tf.data.Dataset.sample_from_datasets( + [dataset1, dataset2], weights=[0.5, 0.5]) + ``` + + One possible outcome of elements in sample_dataset is: + + ``` + print(list(sample_dataset.as_numpy_iterator())) + # [100, 0, 1, 101, 2, 102] + ``` + + Args: + datasets: A non-empty list of `tf.data.Dataset` objects with compatible + structure. + weights: (Optional.) A list or Tensor of `len(datasets)` floating-point + values where `weights[i]` represents the probability to sample from + `datasets[i]`, or a `tf.data.Dataset` object where each element is such + a list. Defaults to a uniform distribution across `datasets`. + seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random + seed that will be used to create the distribution. See + `tf.random.set_seed` for behavior. + stop_on_empty_dataset: If `True`, sampling stops if it encounters an empty + dataset. If `False`, it continues sampling and skips any empty datasets. + It is recommended to set it to `True`. Otherwise, the distribution of + samples starts off as the user intends, but may change as input datasets + become empty. This can be difficult to detect since the dataset starts + off looking correct. Default to `False` for backward compatibility. + rerandomize_each_iteration: An optional `bool`. The boolean argument + controls whether the sequence of random numbers used to determine which + dataset to sample from will be rerandomized each epoch. That is, it + determinies whether datasets will be sampled in the same order across + different epochs (the default behavior) or not. + + Returns: + A dataset that interleaves elements from `datasets` at random, according + to `weights` if provided, otherwise with uniform probability. + + Raises: + TypeError: If the `datasets` or `weights` arguments have the wrong type. + ValueError: + - If `datasets` is empty, or + - If `weights` is specified and does not match the length of `datasets`. + """ + # Loaded lazily due to a circular dependency + # (dataset_ops -> sample_from_datasets_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import sample_from_datasets_op + return sample_from_datasets_op._sample_from_datasets( # pylint: disable=protected-access + datasets, + weights, + seed, + stop_on_empty_dataset, + rerandomize_each_iteration, + ) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + def choose_from_datasets( + datasets, choice_dataset, stop_on_empty_dataset=True + ) -> "DatasetV2": + """Creates a dataset that deterministically chooses elements from `datasets`. + + For example, given the following datasets: + + ```python + datasets = [tf.data.Dataset.from_tensors("foo").repeat(), + tf.data.Dataset.from_tensors("bar").repeat(), + tf.data.Dataset.from_tensors("baz").repeat()] + + # Define a dataset containing `[0, 1, 2, 0, 1, 2, 0, 1, 2]`. + choice_dataset = tf.data.Dataset.range(3).repeat(3) + + result = tf.data.Dataset.choose_from_datasets(datasets, choice_dataset) + ``` + + The elements of `result` will be: + + ``` + "foo", "bar", "baz", "foo", "bar", "baz", "foo", "bar", "baz" + ``` + + Args: + datasets: A non-empty list of `tf.data.Dataset` objects with compatible + structure. + choice_dataset: A `tf.data.Dataset` of scalar `tf.int64` tensors between + `0` and `len(datasets) - 1`. + stop_on_empty_dataset: If `True`, selection stops if it encounters an + empty dataset. If `False`, it skips empty datasets. It is recommended to + set it to `True`. Otherwise, the selected elements start off as the user + intends, but may change as input datasets become empty. This can be + difficult to detect since the dataset starts off looking correct. + Defaults to `True`. + + Returns: + A new `Dataset` with the transformation applied as described above. + + Raises: + TypeError: If `datasets` or `choice_dataset` has the wrong type. + ValueError: If `datasets` is empty. + """ + # Loaded lazily due to a circular dependency + # (dataset_ops -> choose_from_datasets_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import choose_from_datasets_op + return choose_from_datasets_op._choose_from_datasets( + datasets, choice_dataset, stop_on_empty_dataset) + # pylint: enable=g-import-not-at-top,protected-access + + +@tf_export(v1=["data.Dataset"]) +class DatasetV1(DatasetV2, data_types.DatasetV1): + """Represents a potentially large set of elements. + + A `Dataset` can be used to represent an input pipeline as a + collection of elements and a "logical plan" of transformations that act on + those elements. + """ + + def __init__(self): + try: + variant_tensor = self._as_variant_tensor() + except AttributeError as e: + if "_as_variant_tensor" in str(e): + raise AttributeError("Please use `_variant_tensor` instead of " + "`_as_variant_tensor()` to obtain the variant " + "associated with a dataset.") + raise AttributeError("{}: A likely cause of this error is that the super " + "call for this dataset is not the last line of the " + "`__init__` method. The base class invokes the " + "`_as_variant_tensor()` method in its constructor " + "and if that method uses attributes defined in the " + "`__init__` method, those attributes need to be " + "defined before the super call.".format(e)) + super(DatasetV1, self).__init__(variant_tensor) + + @abc.abstractmethod + def _as_variant_tensor(self): + """Creates a scalar `tf.Tensor` of `tf.variant` representing this dataset. + + Returns: + A scalar `tf.Tensor` of `tf.variant` type, which represents this dataset. + """ + raise NotImplementedError(f"{type(self)}.as_variant_tensor()") + + @deprecation.deprecated( + None, "This is a deprecated API that should only be used in TF 1 graph " + "mode and legacy TF 2 graph mode available through `tf.compat.v1`. In " + "all other situations -- namely, eager mode and inside `tf.function` -- " + "you can consume dataset elements using `for elem in dataset: ...` or " + "by explicitly creating iterator via `iterator = iter(dataset)` and " + "fetching its elements via `values = next(iterator)`. Furthermore, " + "this API is not available in TF 2. During the transition from TF 1 " + "to TF 2 you can use `tf.compat.v1.data.make_one_shot_iterator(dataset)` " + "to create a TF 1 graph mode style iterator for a dataset created " + "through TF 2 APIs. Note that this should be a transient state of your " + "code base as there are in general no guarantees about the " + "interoperability of TF 1 and TF 2 code.") + def make_one_shot_iterator( + self, + ) -> Union[iterator_ops.Iterator, iterator_ops.OwnedIterator]: + """Creates an iterator for elements of this dataset. + + Note: The returned iterator will be initialized automatically. + A "one-shot" iterator does not currently support re-initialization. For + that see `make_initializable_iterator`. + + Example: + + ```python + # Building graph ... + dataset = ... + next_value = dataset.make_one_shot_iterator().get_next() + + # ... from within a session ... + try: + while True: + value = sess.run(next_value) + ... + except tf.errors.OutOfRangeError: + pass + ``` + + Returns: + An `tf.data.Iterator` for elements of this dataset. + """ + return self._make_one_shot_iterator() + + def _make_one_shot_iterator( + self, + ) -> Union[iterator_ops.Iterator, iterator_ops.OwnedIterator]: # pylint: disable=missing-docstring + if context.executing_eagerly(): + with ops.colocate_with(self._variant_tensor): + return iterator_ops.OwnedIterator(self) + + _ensure_same_dataset_graph(self) + # Some ops (e.g. dataset ops) are marked as stateful but are stil safe to + # to capture by value. We must allowlist these ops so that the capturing + # logic captures the ops instead of raising an exception. + allowlisted_stateful_ops = traverse.obtain_capture_by_value_ops(self) + graph_level_seed, op_level_seed = core_random_seed.get_seed(None) + + # NOTE(mrry): We capture by value here to ensure that `_make_dataset()` is + # a 0-argument function. + @function.Defun( + capture_by_value=True, + allowlisted_stateful_ops=allowlisted_stateful_ops) + def _make_dataset(): + """Factory function for a dataset.""" + # NOTE(mrry): `Defun` does not capture the graph-level seed from the + # enclosing graph, so if a graph-level seed is present we set the local + # graph seed based on a combination of the graph- and op-level seeds. + if graph_level_seed is not None: + assert op_level_seed is not None + core_random_seed.set_random_seed( + (graph_level_seed + 87654321 * op_level_seed) % (2 ** 63 - 1)) + + dataset = self._apply_debug_options() + return dataset._variant_tensor # pylint: disable=protected-access + + try: + _make_dataset.add_to_graph(ops.get_default_graph()) + except ValueError as err: + if "Cannot capture a stateful node" in str(err): + raise ValueError( + "{}: A likely cause of this error is that the dataset for which " + "you are calling `make_one_shot_iterator()` captures a stateful " + "object, such as a `tf.Variable` or `tf.lookup.StaticHashTable`, " + "which is not supported. Use `make_initializable_iterator()` " + "instead.".format(err)) from None + else: + raise + + with ops.colocate_with(self._variant_tensor): + # pylint: disable=protected-access + return iterator_ops.Iterator( + gen_dataset_ops.one_shot_iterator( + dataset_factory=_make_dataset, **self._flat_structure), None, + get_legacy_output_types(self), get_legacy_output_shapes(self), + get_legacy_output_classes(self)) + + @deprecation.deprecated( + None, "This is a deprecated API that should only be used in TF 1 graph " + "mode and legacy TF 2 graph mode available through `tf.compat.v1`. " + "In all other situations -- namely, eager mode and inside `tf.function` " + "-- you can consume dataset elements using `for elem in dataset: ...` " + "or by explicitly creating iterator via `iterator = iter(dataset)` " + "and fetching its elements via `values = next(iterator)`. " + "Furthermore, this API is not available in TF 2. During the transition " + "from TF 1 to TF 2 you can use " + "`tf.compat.v1.data.make_initializable_iterator(dataset)` to create a TF " + "1 graph mode style iterator for a dataset created through TF 2 APIs. " + "Note that this should be a transient state of your code base as there " + "are in general no guarantees about the interoperability of TF 1 and TF " + "2 code.") + def make_initializable_iterator( + self, shared_name=None + ) -> iterator_ops.Iterator: + """Creates an iterator for elements of this dataset. + + Note: The returned iterator will be in an uninitialized state, + and you must run the `iterator.initializer` operation before using it: + + ```python + # Building graph ... + dataset = ... + iterator = dataset.make_initializable_iterator() + next_value = iterator.get_next() # This is a Tensor. + + # ... from within a session ... + sess.run(iterator.initializer) + try: + while True: + value = sess.run(next_value) + ... + except tf.errors.OutOfRangeError: + pass + ``` + + Args: + shared_name: (Optional.) If non-empty, the returned iterator will be + shared under the given name across multiple sessions that share the same + devices (e.g. when using a remote server). + + Returns: + A `tf.data.Iterator` for elements of this dataset. + + Raises: + RuntimeError: If eager execution is enabled. + """ + return self._make_initializable_iterator(shared_name) + + def _make_initializable_iterator( + self, shared_name=None + ) -> iterator_ops.Iterator: # pylint: disable=missing-docstring + if context.executing_eagerly(): + raise RuntimeError("`make_initializable_iterator()` is not supported in " + "eager mode. Use Python-style iteration instead.") + _ensure_same_dataset_graph(self) + dataset = self._apply_debug_options() + if shared_name is None: + shared_name = "" + + with ops.colocate_with(self._variant_tensor): + iterator_resource = gen_dataset_ops.iterator_v2( + container="", shared_name=shared_name, **self._flat_structure) + + initializer = gen_dataset_ops.make_iterator( + dataset._variant_tensor, # pylint: disable=protected-access + iterator_resource) + + # pylint: disable=protected-access + return iterator_ops.Iterator(iterator_resource, initializer, + get_legacy_output_types(dataset), + get_legacy_output_shapes(dataset), + get_legacy_output_classes(dataset)) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_classes(dataset)`.") + def output_classes(self): + """Returns the class of each component of an element of this dataset. + + Returns: + A (nested) structure of Python `type` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + self.element_spec) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_shapes(dataset)`.") + def output_shapes(self): + """Returns the shape of each component of an element of this dataset. + + Returns: + A (nested) structure of `tf.TensorShape` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + self.element_spec) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_types(dataset)`.") + def output_types(self): + """Returns the type of each component of an element of this dataset. + + Returns: + A (nested) structure of `tf.DType` objects corresponding to each component + of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + self.element_spec) + + @property + def element_spec(self): + # TODO(b/110122868): Remove this override once all `Dataset` instances + # implement `element_structure`. + return structure.convert_legacy_structure( + self.output_types, self.output_shapes, self.output_classes) + + @staticmethod + @functools.wraps(DatasetV2.from_tensors) + def from_tensors(tensors, name=None): + return DatasetV1Adapter(DatasetV2.from_tensors(tensors, name=name)) + + @staticmethod + @functools.wraps(DatasetV2.from_tensor_slices) + def from_tensor_slices(tensors, name=None): + return DatasetV1Adapter(DatasetV2.from_tensor_slices(tensors, name=name)) + + @staticmethod + @deprecation.deprecated(None, "Use `tf.data.Dataset.from_tensor_slices()`.") + def from_sparse_tensor_slices(sparse_tensor): + """Splits each rank-N `tf.sparse.SparseTensor` in this dataset row-wise. + + Args: + sparse_tensor: A `tf.sparse.SparseTensor`. + + Returns: + Dataset: A `Dataset` of rank-(N-1) sparse tensors. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> + # from_sparse_tensor_slices_op -> dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import from_sparse_tensor_slices_op + return from_sparse_tensor_slices_op._from_sparse_tensor_slices( + sparse_tensor) + # pylint: enable=g-import-not-at-top,protected-access + + @staticmethod + @functools.wraps(DatasetV2.from_generator) + @deprecation.deprecated_args(None, "Use output_signature instead", + "output_types", "output_shapes") + def from_generator(generator, + output_types=None, + output_shapes=None, + args=None, + output_signature=None, + name=None): + # Calling DatasetV2.from_generator with output_shapes or output_types is + # deprecated, but this is already checked by the decorator on this function. + with deprecation.silence(): + return DatasetV1Adapter( + DatasetV2.from_generator( + generator, + output_types, + output_shapes, + args, + output_signature, + name=name)) + + @staticmethod + @functools.wraps(DatasetV2.range) + def range(*args, **kwargs): + return DatasetV1Adapter(DatasetV2.range(*args, **kwargs)) + + @staticmethod + @functools.wraps(DatasetV2.zip) + def zip(*args, datasets=None, name=None): + return DatasetV1Adapter(DatasetV2.zip(*args, datasets=datasets, name=name)) + + @functools.wraps(DatasetV2.concatenate) + def concatenate(self, dataset, name=None): + return DatasetV1Adapter( + super(DatasetV1, self).concatenate(dataset, name=name)) + + @functools.wraps(DatasetV2.prefetch) + def prefetch(self, buffer_size, name=None): + return DatasetV1Adapter( + super(DatasetV1, self).prefetch(buffer_size, name=name)) + + @staticmethod + @functools.wraps(DatasetV2.list_files) + def list_files(file_pattern, shuffle=None, seed=None, name=None): + return DatasetV1Adapter( + DatasetV2.list_files(file_pattern, shuffle, seed, name=name)) + + @functools.wraps(DatasetV2.repeat) + def repeat(self, count=None, name=None): + return DatasetV1Adapter(super(DatasetV1, self).repeat(count, name=name)) + + @functools.wraps(DatasetV2.shuffle) + def shuffle(self, + buffer_size, + seed=None, + reshuffle_each_iteration=None, + name=None): + return DatasetV1Adapter( + super(DatasetV1, self).shuffle( + buffer_size, seed, reshuffle_each_iteration, name=name)) + + @functools.wraps(DatasetV2.cache) + def cache(self, filename="", name=None): + return DatasetV1Adapter(super(DatasetV1, self).cache(filename, name=name)) + + @functools.wraps(DatasetV2.take) + def take(self, count, name=None): + return DatasetV1Adapter(super(DatasetV1, self).take(count, name=name)) + + @functools.wraps(DatasetV2.skip) + def skip(self, count, name=None): + return DatasetV1Adapter(super(DatasetV1, self).skip(count, name=name)) + + @functools.wraps(DatasetV2.shard) + def shard(self, num_shards, index, name=None): + return DatasetV1Adapter( + super(DatasetV1, self).shard(num_shards, index, name=name)) + + @functools.wraps(DatasetV2.batch) + def batch(self, + batch_size, + drop_remainder=False, + num_parallel_calls=None, + deterministic=None, + name=None): + return DatasetV1Adapter( + super(DatasetV1, self).batch( + batch_size, + drop_remainder, + num_parallel_calls, + deterministic, + name=name)) + + @functools.wraps(DatasetV2.padded_batch) + def padded_batch(self, + batch_size, + padded_shapes=None, + padding_values=None, + drop_remainder=False, + name=None): + return DatasetV1Adapter( + super(DatasetV1, self).padded_batch( + batch_size, + padded_shapes, + padding_values, + drop_remainder, + name=name)) + + @functools.wraps(DatasetV2.map) + def map(self, + map_func, + num_parallel_calls=None, + deterministic=None, + name=None): + # Loaded lazily due to a circular dependency (dataset_ops -> map_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import map_op + return map_op._map_v1( + self, + map_func, + num_parallel_calls=num_parallel_calls, + deterministic=deterministic) + # pylint: enable=g-import-not-at-top,protected-access + + @deprecation.deprecated(None, "Use `tf.data.Dataset.map()") + def map_with_legacy_function( + self, map_func, num_parallel_calls=None, deterministic=None + ) -> "DatasetV1Adapter": + """Maps `map_func` across the elements of this dataset. + + Note: This is an escape hatch for existing uses of `map` that do not work + with V2 functions. New uses are strongly discouraged and existing uses + should migrate to `map` as this method will be removed in V2. + + Args: + map_func: A function mapping a (nested) structure of tensors (having + shapes and types defined by `self.output_shapes` and + `self.output_types`) to another (nested) structure of tensors. + num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`, + representing the number elements to process asynchronously in parallel. + If not specified, elements will be processed sequentially. If the value + `tf.data.AUTOTUNE` is used, then the number of parallel calls is set + dynamically based on available CPU. + deterministic: (Optional.) When `num_parallel_calls` is specified, this + boolean controls the order in which the transformation produces + elements. If set to `False`, the transformation is allowed to yield + elements out of order to trade determinism for performance. If not + specified, the `tf.data.Options.deterministic` option (`True` by + default) controls the behavior. + + Returns: + Dataset: A `Dataset`. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> map_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import map_op + return map_op._map_v1_with_legacy_function( + self, + map_func, + num_parallel_calls=num_parallel_calls, + deterministic=deterministic) + # pylint: enable=g-import-not-at-top,protected-access + + @functools.wraps(DatasetV2.flat_map) + def flat_map(self, map_func, name=None) -> "DatasetV1Adapter": + return DatasetV1Adapter( + super(DatasetV1, self).flat_map(map_func, name=name)) + + @functools.wraps(DatasetV2.interleave) + def interleave( + self, + map_func, + cycle_length=None, + block_length=None, + num_parallel_calls=None, + deterministic=None, + name=None, + ) -> "DatasetV1Adapter": + return DatasetV1Adapter( + super(DatasetV1, self).interleave( + map_func, + cycle_length, + block_length, + num_parallel_calls, + deterministic, + name=name)) + + @functools.wraps(DatasetV2.filter) + def filter(self, predicate, name=None) -> "DatasetV1Adapter": + return DatasetV1Adapter(super(DatasetV1, self).filter(predicate, name=name)) + + @deprecation.deprecated(None, "Use `tf.data.Dataset.filter()") + def filter_with_legacy_function(self, predicate) -> "DatasetV2": + """Filters this dataset according to `predicate`. + + Note: This is an escape hatch for existing uses of `filter` that do not work + with V2 functions. New uses are strongly discouraged and existing uses + should migrate to `filter` as this method will be removed in V2. + + Args: + predicate: A function mapping a (nested) structure of tensors (having + shapes and types defined by `self.output_shapes` and + `self.output_types`) to a scalar `tf.bool` tensor. + + Returns: + Dataset: The `Dataset` containing the elements of this dataset for which + `predicate` is `True`. + """ + # Loaded lazily due to a circular dependency (dataset_ops -> filter_op -> + # dataset_ops). + # pylint: disable=g-import-not-at-top,protected-access + from tensorflow.python.data.ops import filter_op + return filter_op._FilterDataset(self, predicate, use_legacy_function=True) + # pylint: enable=g-import-not-at-top,protected-access + + @functools.wraps(DatasetV2.apply) + def apply(self, transformation_func) -> "DatasetV1Adapter": + return DatasetV1Adapter(super(DatasetV1, self).apply(transformation_func)) + + @functools.wraps(DatasetV2.window) + def window( + self, size, shift=None, stride=1, drop_remainder=False, name=None + ) -> "DatasetV1Adapter": + return DatasetV1Adapter( + super(DatasetV1, + self).window(size, shift, stride, drop_remainder, name=name)) + + @functools.wraps(DatasetV2.unbatch) + def unbatch(self, name=None) -> "DatasetV1Adapter": + return DatasetV1Adapter(super(DatasetV1, self).unbatch(name=name)) + + @functools.wraps(DatasetV2.with_options) + def with_options(self, options, name=None) -> "DatasetV1Adapter": + return DatasetV1Adapter( + super(DatasetV1, self).with_options(options, name=name)) + + +if tf2.enabled(): + Dataset = DatasetV2 +else: + Dataset = DatasetV1 + + +class DatasetV1Adapter(DatasetV1): + """Wraps a V2 `Dataset` object in the `tf.compat.v1.data.Dataset` API.""" + + def __init__(self, dataset: DatasetV2): + self._dataset = dataset + super(DatasetV1Adapter, self).__init__() + + def _as_variant_tensor(self): + return self._dataset._variant_tensor # pylint: disable=protected-access + + def _inputs(self): + return self._dataset._inputs() # pylint: disable=protected-access + + def _functions(self) -> list[StructuredFunctionWrapper]: + return self._dataset._functions() # pylint: disable=protected-access + + def options(self): + return self._dataset.options() + + @property + def element_spec(self): + return self._dataset.element_spec # pylint: disable=protected-access + + def __iter__(self): + return iter(self._dataset) + + +def _ensure_same_dataset_graph(dataset): + """Walks the dataset graph to ensure all datasets come from the same graph.""" + # pylint: disable=protected-access + current_graph = ops.get_default_graph() + bfs_q = queue.Queue() + bfs_q.put(dataset) + visited = [] + while not bfs_q.empty(): + ds = bfs_q.get() + visited.append(ds) + ds_graph = ds._graph + if current_graph != ds_graph: + raise ValueError( + f"The graph {current_graph} of the iterator is different from the " + f"graph {ds_graph} the dataset: {ds._variant_tensor} was created in. " + f"If you are using the Estimator API, make sure that no part of the " + f"dataset returned by the `input_fn` function is defined outside the " + f"`input_fn` function. Otherwise, make sure that the dataset is " + f"created in the same graph as the iterator.") + for input_ds in ds._inputs(): + if input_ds not in visited: + bfs_q.put(input_ds) + + +@tf_export(v1=["data.make_one_shot_iterator"]) +def make_one_shot_iterator( + dataset: DatasetV1, +) -> Union[iterator_ops.Iterator, iterator_ops.OwnedIterator]: + """Creates an iterator for elements of `dataset`. + + Note: The returned iterator will be initialized automatically. + A "one-shot" iterator does not support re-initialization. + + Args: + dataset: A `tf.data.Dataset`. + + Returns: + A `tf.data.Iterator` for elements of `dataset`. + + @compatibility(TF2) + This is a legacy API for consuming dataset elements and should only be used + during transition from TF 1 to TF 2. Note that using this API should be + a transient state of your code base as there are in general no guarantees + about the interoperability of TF 1 and TF 2 code. + + In TF 2 datasets are Python iterables which means you can consume their + elements using `for elem in dataset: ...` or by explicitly creating iterator + via `iterator = iter(dataset)` and fetching its elements via + `values = next(iterator)`. + @end_compatibility + """ + try: + # Call the defined `_make_one_shot_iterator()` if there is one, because some + # datasets (e.g. for prefetching) override its behavior. + return dataset._make_one_shot_iterator() # pylint: disable=protected-access + except AttributeError: + return DatasetV1Adapter(dataset)._make_one_shot_iterator() # pylint: disable=protected-access + + +@tf_export(v1=["data.make_initializable_iterator"]) +def make_initializable_iterator( + dataset: DatasetV1, shared_name=None +) -> iterator_ops.Iterator: + """Creates an iterator for elements of `dataset`. + + Note: The returned iterator will be in an uninitialized state, + and you must run the `iterator.initializer` operation before using it: + + ```python + dataset = ... + iterator = tf.compat.v1.data.make_initializable_iterator(dataset) + # ... + sess.run(iterator.initializer) + ``` + + Args: + dataset: A `tf.data.Dataset`. + shared_name: (Optional.) If non-empty, the returned iterator will be shared + under the given name across multiple sessions that share the same devices + (e.g. when using a remote server). + + Returns: + A `tf.data.Iterator` for elements of `dataset`. + + Raises: + RuntimeError: If eager execution is enabled. + + @compatibility(TF2) + This is a legacy API for consuming dataset elements and should only be used + during transition from TF 1 to TF 2. Note that using this API should be + a transient state of your code base as there are in general no guarantees + about the interoperability of TF 1 and TF 2 code. + + In TF 2 datasets are Python iterables which means you can consume their + elements using `for elem in dataset: ...` or by explicitly creating iterator + via `iterator = iter(dataset)` and fetching its elements via + `values = next(iterator)`. + @end_compatibility + """ + try: + # Call the defined `_make_initializable_iterator()` if there is one, because + # some datasets (e.g. for prefetching) override its behavior. + return dataset._make_initializable_iterator(shared_name) # pylint: disable=protected-access + except AttributeError: + return DatasetV1Adapter(dataset)._make_initializable_iterator(shared_name) # pylint: disable=protected-access + + +@tf_export("data.experimental.get_structure") +def get_structure(dataset_or_iterator): + """Returns the type signature for elements of the input dataset / iterator. + + For example, to get the structure of a `tf.data.Dataset`: + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> tf.data.experimental.get_structure(dataset) + TensorSpec(shape=(), dtype=tf.int32, name=None) + + >>> dataset = tf.data.experimental.from_list([(1, 'a'), (2, 'b'), (3, 'c')]) + >>> tf.data.experimental.get_structure(dataset) + (TensorSpec(shape=(), dtype=tf.int32, name=None), + TensorSpec(shape=(), dtype=tf.string, name=None)) + + To get the structure of an `tf.data.Iterator`: + + >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + >>> tf.data.experimental.get_structure(iter(dataset)) + TensorSpec(shape=(), dtype=tf.int32, name=None) + + Args: + dataset_or_iterator: A `tf.data.Dataset` or an `tf.data.Iterator`. + + Returns: + A (nested) structure of `tf.TypeSpec` objects matching the structure of an + element of `dataset_or_iterator` and specifying the type of individual + components. + + Raises: + TypeError: If input is not a `tf.data.Dataset` or an `tf.data.Iterator` + object. + """ + try: + return dataset_or_iterator.element_spec # pylint: disable=protected-access + except AttributeError: + raise TypeError(f"Invalid `dataset_or_iterator`. `dataset_or_iterator` " + f"must be a `tf.data.Dataset` or tf.data.Iterator object, " + f"but got {type(dataset_or_iterator)}.") + + +@tf_export(v1=["data.get_output_classes"]) +def get_legacy_output_classes(dataset_or_iterator): + """Returns the output classes for elements of the input dataset / iterator. + + Args: + dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`. + + Returns: + A (nested) structure of Python `type` objects matching the structure of the + dataset / iterator elements and specifying the class of the individual + components. + + @compatibility(TF2) + This is a legacy API for inspecting the type signature of dataset elements. In + TF 2, you should use the `tf.data.Dataset.element_spec` attribute instead. + @end_compatibility + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + get_structure(dataset_or_iterator)) + + +@tf_export(v1=["data.get_output_shapes"]) +def get_legacy_output_shapes(dataset_or_iterator): + """Returns the output shapes for elements of the input dataset / iterator. + + Args: + dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`. + + Returns: + A (nested) structure of `tf.TensorShape` objects matching the structure of + the dataset / iterator elements and specifying the shape of the individual + components. + + @compatibility(TF2) + This is a legacy API for inspecting the type signature of dataset elements. In + TF 2, you should use the `tf.data.Dataset.element_spec` attribute instead. + @end_compatibility + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + get_structure(dataset_or_iterator)) + + +@tf_export(v1=["data.get_output_types"]) +def get_legacy_output_types(dataset_or_iterator): + """Returns the output shapes for elements of the input dataset / iterator. + + Args: + dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`. + + Returns: + A (nested) structure of `tf.DType` objects matching the structure of + dataset / iterator elements and specifying the shape of the individual + components. + + @compatibility(TF2) + This is a legacy API for inspecting the type signature of dataset elements. In + TF 2, you should use the `tf.data.Dataset.element_spec` attribute instead. + @end_compatibility + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + get_structure(dataset_or_iterator)) + + +class DatasetSource(DatasetV2): + """Abstract class representing a dataset with no inputs.""" + + def _inputs(self): + return [] + + +class UnaryDataset(DatasetV2): + """Abstract class representing a dataset with one input.""" + + def __init__(self, input_dataset: DatasetV2, variant_tensor): + self._input_dataset = input_dataset + super(UnaryDataset, self).__init__(variant_tensor) + + def _inputs(self): + return [self._input_dataset] + + +class UnaryUnchangedStructureDataset(UnaryDataset): + """Represents a unary dataset with the same input and output structure.""" + + def __init__(self, input_dataset: DatasetV2, variant_tensor): + self._input_dataset = input_dataset + super(UnaryUnchangedStructureDataset, self).__init__( + input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._input_dataset.element_spec + + +class _VariantDataset(DatasetV2): + """A Dataset wrapper around a `tf.variant`-typed function argument.""" + + def __init__(self, dataset_variant, element_spec): + self._element_spec = element_spec + super(_VariantDataset, self).__init__(dataset_variant) + + def _inputs(self): + return [] + + @property + def element_spec(self): + return self._element_spec + + +class _NestedVariant(composite_tensor.CompositeTensor): + + def __init__(self, variant_tensor, element_spec, dataset_shape): + self._variant_tensor = variant_tensor + self._element_spec = element_spec + self._dataset_shape = dataset_shape + + @property + def _type_spec(self): + return DatasetSpec(self._element_spec, self._dataset_shape) + + +@tf_export("data.experimental.from_variant") +def from_variant(variant, structure): + """Constructs a dataset from the given variant and (nested) structure. + + Args: + variant: A scalar `tf.variant` tensor representing a dataset. + structure: A (nested) structure of `tf.TypeSpec` objects representing the + structure of each element in the dataset. + + Returns: + A `tf.data.Dataset` instance. + """ + return _VariantDataset(variant, structure) # pylint: disable=protected-access + + +@tf_export("data.experimental.to_variant") +def to_variant(dataset: DatasetV2): + """Returns a variant representing the given dataset. + + Args: + dataset: A `tf.data.Dataset`. + + Returns: + A scalar `tf.variant` tensor representing the given dataset. + """ + return dataset._variant_tensor # pylint: disable=protected-access + + +@tf_export( + "data.DatasetSpec", + v1=["data.DatasetSpec", "data.experimental.DatasetStructure"]) +class DatasetSpec(type_spec.BatchableTypeSpec): + """Type specification for `tf.data.Dataset`. + + See `tf.TypeSpec` for more information about TensorFlow type specifications. + + >>> dataset = tf.data.Dataset.range(3) + >>> tf.data.DatasetSpec.from_value(dataset) + DatasetSpec(TensorSpec(shape=(), dtype=tf.int64, name=None), TensorShape([])) + """ + + __slots__ = ["_element_spec", "_dataset_shape"] + + def __init__(self, element_spec, dataset_shape=()): + self._element_spec = element_spec + self._dataset_shape = tensor_shape.as_shape(dataset_shape) + + @property + def value_type(self): + return Dataset + + @property + def element_spec(self): + """The inner element spec.""" + return self._element_spec + + def is_subtype_of(self, other): + """See base class.""" + if type(self) is not type(other): + return False + + # TODO(b/220385675): _element_spec should always be a TypeSpec. + try: + tf_nest.assert_same_structure(self.element_spec, other.element_spec) + except (TypeError, ValueError): + return False + + self_elements = tf_nest.flatten(self.element_spec) + other_elements = tf_nest.flatten(other.element_spec) + + def is_subtype_or_equal(a, b): + if isinstance(a, trace.TraceType): + return a.is_subtype_of(b) + else: + return a == b + + for self_element, other_element in zip(self_elements, other_elements): + if not is_subtype_or_equal(self_element, other_element): + return False + + return self._dataset_shape.is_subtype_of(other._dataset_shape) # pylint: disable=protected-access + + def most_specific_common_supertype(self, others): + """See base class.""" + if not all(type(self) is type(other) for other in others): + return None + + try: + for other in others: + tf_nest.assert_same_structure(self.element_spec, other.element_spec) + except (TypeError, ValueError): + return None + + self_components = tf_nest.flatten(self.element_spec) + others_components = [ + tf_nest.flatten(other.element_spec) for other in others + ] + common_components = [None] * len(self_components) + + def common_supertype_or_equal(a, bs): + if isinstance(a, trace.TraceType): + return a.most_specific_common_supertype(bs) + else: + return a if all(a == b for b in bs) else None + + for i, self_component in enumerate(self_components): + common_components[i] = common_supertype_or_equal( + self_component, + [other_components[i] for other_components in others_components]) + if self_component is not None and common_components[i] is None: + return None + common_element_spec = tf_nest.pack_sequence_as(self._element_spec, + common_components) + + common_dataset_shape = self._dataset_shape.most_specific_common_supertype( + [other._dataset_shape for other in others]) # pylint: disable=protected-access + if common_dataset_shape is None: + return None + + return DatasetSpec(common_element_spec, common_dataset_shape) + + # TODO(b/220385675): Once _element_spec is guaranteed to be TypeSpec, the + # following functions do not need to be overloaded: is_subtype_of, + # most_specific_common_supertype, __hash__ and __eq__ + def _serialize(self): + return (self._element_spec, self._dataset_shape) + + @property + def _component_specs(self): + return tensor_spec.TensorSpec(self._dataset_shape, dtypes.variant) + + def _to_components(self, value): + return value._variant_tensor # pylint: disable=protected-access + + def _from_components(self, components): + # pylint: disable=protected-access + if self._dataset_shape.ndims == 0: + return _VariantDataset(components, self._element_spec) + else: + return _NestedVariant(components, self._element_spec, self._dataset_shape) + + def _to_tensor_list(self, value): + return [ + ops.convert_to_tensor( + tf_nest.map_structure(lambda x: x._variant_tensor, value)) # pylint: disable=protected-access + ] + + @staticmethod + def from_value(value): + """Creates a `DatasetSpec` for the given `tf.data.Dataset` value.""" + return DatasetSpec(value.element_spec) # pylint: disable=protected-access + + def _batch(self, batch_size): + return DatasetSpec( + self._element_spec, + tensor_shape.TensorShape([batch_size]).concatenate(self._dataset_shape)) + + def _unbatch(self): + if self._dataset_shape.ndims == 0: + raise ValueError("Slicing dataset elements is not supported for rank 0.") + return DatasetSpec(self._element_spec, self._dataset_shape[1:]) + + def _to_batched_tensor_list(self, value): + if self._dataset_shape.ndims == 0: + raise ValueError("Slicing dataset elements is not supported for rank 0.") + return self._to_tensor_list(value) + + def _to_legacy_output_types(self): + return self + + def _to_legacy_output_shapes(self): + return self + + def _to_legacy_output_classes(self): + return self + + def __hash__(self): + # TODO(b/220385675): attributes can be dicts and hence unhashable. + return hash(DatasetSpec) + + def __eq__(self, other): + return (isinstance(other, DatasetSpec) and + self._element_spec == other._element_spec and + self._dataset_shape == other._dataset_shape) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + DatasetSpec, struct_pb2.TypeSpecProto.DATA_DATASET_SPEC + ) +) + + +@tf_export("data.NumpyIterator") +class NumpyIterator(tracking_base.Trackable): + """Iterator over a dataset with elements converted to numpy.""" + + __slots__ = ["_iterator"] + + def __init__(self, dataset): + self._iterator = iter(dataset) + self._dataset = dataset + + def __iter__(self): + return self + + def __next__(self): + + def to_numpy(x): + if hasattr(x, "_numpy"): + numpy = x._numpy() # pylint: disable=protected-access + else: + numpy = x.numpy() + if isinstance(numpy, np.ndarray): + # `numpy` shares the same underlying buffer as the `x` Tensor. + # Tensors are expected to be immutable, so we disable writes. + numpy.setflags(write=False) + return numpy + + return nest.map_structure(to_numpy, next(self._iterator)) + + def next(self): + return self.__next__() + + # override + def _serialize_to_tensors(self): + # pylint: disable=protected-access + return self._iterator._serialize_to_tensors() + + # override + def _restore_from_tensors(self, restored_tensors): + # pylint: disable=protected-access + return self._iterator._restore_from_tensors(restored_tensors) + + # override + def _copy_trackable_to_cpu(self, object_map): + if self not in object_map: + # If self is not populated in object_map yet, instantiate the copy + object_map[self] = NumpyIterator(self._dataset) + + # Copy values from `self` to copy of `self` + serialized = self._serialize_to_tensors() + object_map[self]._restore_from_tensors(serialized) # pylint: disable=protected-access + + # TODO(b/284309865): Remove once `_save` is no longer used anywhere. + def _save(self): + # pylint: disable=protected-access + return self.save() + + def save(self): + # pylint: disable=protected-access + return self._iterator._save() + + # TODO(b/284309865): Remove once `_restore` is no longer used anywhere. + def _restore(self, state): + return self.restore(state) + + def restore(self, state): + # pylint: disable=protected-access + return self._iterator._restore(state) + + +# TODO(b/284309865): Remove once `_NumpyIterator` is no longer used anywhere. +_NumpyIterator = NumpyIterator + + +class _VariantTracker(resource_lib.CapturableResource): + """Allows export of functions capturing a Dataset in SavedModels. + + When saving a SavedModel, `tf.saved_model.save` traverses the object + graph. Since Datasets reference _VariantTracker objects, that traversal will + find a _VariantTracker for each Dataset and so know how to save and restore + functions which reference the Dataset's variant Tensor. + """ + + def __init__(self, variant_tensor, resource_creator): + """Record that `variant_tensor` is associated with `resource_creator`. + + Args: + variant_tensor: The variant-dtype Tensor associated with the Dataset. This + Tensor will be a captured input to functions which use the Dataset, and + is used by saving code to identify the corresponding _VariantTracker. + resource_creator: A zero-argument function which creates a new + variant-dtype Tensor. This function will be included in SavedModels and + run to re-create the Dataset's variant Tensor on restore. + """ + super(_VariantTracker, self).__init__(device="CPU") + self._resource_handle = variant_tensor + if not isinstance(resource_creator, def_function.Function): + # Internal validation -- _VariantTracker assumes that resource creator is + # already a tf.function. + raise TypeError("Resource creator should already be a tf.function.") + self._create_resource = resource_creator + + def _trackable_children(self, + save_type=tracking_base.SaveType.CHECKPOINT, + **kwargs): + if save_type != tracking_base.SaveType.SAVEDMODEL: + return {} + + children = super(_VariantTracker, + self)._trackable_children(save_type, **kwargs) + # Overwrite the _create_resource function, since `self._create_resource` + # is already a tf.function. + children["_create_resource"] = self._create_resource + return children + + +# TODO(b/254291122): Remove. +# Loaded lazily due to a circular dependency (dataset_ops -> +# batch_op -> dataset_ops). +batch_op = lazy_loader.LazyLoader( + "batch_op", globals(), + "tensorflow.python.data.ops.batch_op") +BatchDataset = batch_op._BatchDataset # pylint: disable=protected-access +PrefetchDataset = prefetch_op._PrefetchDataset # pylint: disable=protected-access +ShuffleDataset = shuffle_op._ShuffleDataset # pylint: disable=protected-access + + +# TODO(b/254291122): Remove. +# Loaded lazily due to a circular dependency (dataset_ops -> +# repeat_op -> dataset_ops). +repeat_op = lazy_loader.LazyLoader( + "repeat_op", globals(), + "tensorflow.python.data.ops.repeat_op") +RepeatDataset = repeat_op._RepeatDataset # pylint: disable=protected-access + + +class _OptionsDataset(UnaryUnchangedStructureDataset): + """An identity `Dataset` that stores options.""" + + def __init__(self, input_dataset, options, name=None): + # pylint: disable=protected-access + self._input_dataset = input_dataset + options_pb = dataset_options_pb2.Options() + options_pb.CopyFrom(options._to_proto()) + self._name = name + with ops.colocate_with(input_dataset._variant_tensor): + variant_tensor = gen_dataset_ops.options_dataset( + input_dataset._variant_tensor, options_pb.SerializeToString(), + **self._common_args) + super(_OptionsDataset, self).__init__(input_dataset, variant_tensor) + + if self._options_attr: + self._options_attr._set_mutable(True) + self._options_attr = self._options_attr.merge(options) + else: + self._options_attr = options + self._options_attr._set_mutable(False) + + +def normalize_to_dense(dataset: Dataset): + """Normalizes non-tensor components in a dataset to dense representations. + + This is necessary for dataset transformations that slice along the batch + dimension and are oblivious to non-tensors, e.g. `unbatch`, `rebatch`. + + Args: + dataset: Dataset to normalize. + + Returns: + A dataset whose sparse and ragged tensors have been normalized to their + dense representations. + """ + + # NOTE(mrry): This leads to a somewhat inefficient re-encoding step for all + # non-tensor components. + # + # TODO(mrry): Consider optimizing this if it turns out to be a bottleneck. + if structured_function._should_unpack(dataset.element_spec): # pylint: disable=protected-access + + def normalize(*args): + return structure.to_batched_tensor_list(dataset.element_spec, tuple(args)) + else: + def normalize(arg): + return structure.to_batched_tensor_list(dataset.element_spec, arg) + + normalized_dataset = dataset.map(normalize) + + # NOTE(mrry): Our `map()` has lost information about the structure of + # non-tensor components, so re-apply the structure of the original dataset. + return _RestructuredDataset(normalized_dataset, dataset.element_spec) + + +class _RestructuredDataset(UnaryDataset): + """An internal helper for changing the element spec of a dataset.""" + + def __init__(self, dataset, element_spec): + self._input_dataset = dataset + self._element_spec = element_spec + + variant_tensor = self._input_dataset._variant_tensor # pylint: disable=protected-access + super(_RestructuredDataset, self).__init__(dataset, variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +def _get_prob_original_static(initial_dist_t, target_dist_t): + """Returns the static probability of sampling from the original. + + `tensor_util.constant_value(prob_of_original)` returns `None` if it encounters + an Op that it isn't defined for. We have some custom logic to avoid this. + + Args: + initial_dist_t: A tensor of the initial distribution. + target_dist_t: A tensor of the target distribution. + + Returns: + The probability of sampling from the original distribution as a constant, + if it is a constant, or `None`. + """ + init_static = tensor_util.constant_value(initial_dist_t) + target_static = tensor_util.constant_value(target_dist_t) + + if init_static is None or target_static is None: + return None + else: + return np.min(target_static / init_static) + + +def _filter_ds(dataset, + acceptance_dist_ds, + initial_dist_ds, + class_func, + seed, + name=None) -> DatasetV2: + """Filters a dataset based on per-class acceptance probabilities. + + Args: + dataset: The dataset to be filtered. + acceptance_dist_ds: A dataset of acceptance probabilities. + initial_dist_ds: A dataset of the initial probability distribution, given or + estimated. + class_func: A function mapping an element of the input dataset to a scalar + `tf.int32` tensor. Values should be in `[0, num_classes)`. + seed: (Optional.) Python integer seed for the resampler. + name: (Optional.) A name for the tf.data operation. + + Returns: + A dataset of (class value, data) after filtering. + """ + + def maybe_warn_on_large_rejection(accept_dist, initial_dist): + proportion_rejected = math_ops.reduce_sum((1 - accept_dist) * initial_dist) + return cond.cond( + math_ops.less(proportion_rejected, .5), + lambda: accept_dist, + lambda: logging_ops.Print( # pylint: disable=g-long-lambda + accept_dist, [proportion_rejected, initial_dist, accept_dist], + message="Proportion of examples rejected by sampler is high: ", + summarize=100, + first_n=10)) + + acceptance_dist_ds = ( + DatasetV2.zip((acceptance_dist_ds, initial_dist_ds), + name=name).map(maybe_warn_on_large_rejection, name=name)) + + def _gather_and_copy(acceptance_prob, data): + if isinstance(data, tuple): + class_val = class_func(*data) + else: + class_val = class_func(data) + return class_val, array_ops.gather(acceptance_prob, class_val), data + + current_probabilities_and_class_and_data_ds = DatasetV2.zip( + (acceptance_dist_ds, dataset), name=name).map( + _gather_and_copy, name=name) + + def _reject(unused_class_val, p, unused_data): + return random_ops.random_uniform([], seed=seed, dtype=p.dtype) < p + + filtered_ds = current_probabilities_and_class_and_data_ds.filter( + _reject, name=name) + return filtered_ds.map( + lambda class_value, _, data: (class_value, data), name=name) + + +# pylint: disable=missing-function-docstring +def _estimate_initial_dist_ds(target_dist_t, + class_values_ds, + dist_estimation_batch_size=32, + smoothing_constant=10, + name=None): + num_classes = (target_dist_t.shape[0] or array_ops.shape(target_dist_t)[0]) + initial_examples_per_class_seen = array_ops.fill([num_classes], + np.int64(smoothing_constant)) + + def update_estimate_and_tile(num_examples_per_class_seen, c): + updated_examples_per_class_seen, dist = _estimate_data_distribution( + c, num_examples_per_class_seen) + tiled_dist = array_ops.tile( + array_ops.expand_dims(dist, 0), [dist_estimation_batch_size, 1]) + return updated_examples_per_class_seen, tiled_dist + + initial_dist_ds = ( + class_values_ds.batch(dist_estimation_batch_size, name=name).scan( + initial_examples_per_class_seen, update_estimate_and_tile, + name=name).unbatch(name=name)) + + return initial_dist_ds + + +def _get_target_to_initial_ratio(initial_probs, target_probs): + # Add tiny to initial_probs to avoid divide by zero. + denom = (initial_probs + np.finfo(initial_probs.dtype.as_numpy_dtype).tiny) + return target_probs / denom + + +def _estimate_data_distribution(c, num_examples_per_class_seen): + """Estimate data distribution as labels are seen. + + Args: + c: The class labels. Type `int32`, shape `[batch_size]`. + num_examples_per_class_seen: Type `int64`, shape `[num_classes]`, containing + counts. + + Returns: + num_examples_per_lass_seen: Updated counts. Type `int64`, shape + `[num_classes]`. + dist: The updated distribution. Type `float32`, shape `[num_classes]`. + """ + num_classes = num_examples_per_class_seen.get_shape()[0] + # Update the class-count based on what labels are seen in batch. + num_examples_per_class_seen = math_ops.add( + num_examples_per_class_seen, + math_ops.reduce_sum( + array_ops.one_hot(c, num_classes, dtype=dtypes.int64), 0)) + init_prob_estimate = math_ops.truediv( + num_examples_per_class_seen, + math_ops.reduce_sum(num_examples_per_class_seen)) + dist = math_ops.cast(init_prob_estimate, dtypes.float32) + return num_examples_per_class_seen, dist + + +def _calculate_acceptance_probs_with_mixing(initial_probs, target_probs): + """Calculates the acceptance probabilities and mixing ratio. + + In this case, we assume that we can *either* sample from the original data + distribution with probability `m`, or sample from a reshaped distribution + that comes from rejection sampling on the original distribution. This + rejection sampling is done on a per-class basis, with `a_i` representing the + probability of accepting data from class `i`. + + This method is based on solving the following analysis for the reshaped + distribution: + + Let F be the probability of a rejection (on any example). + Let p_i be the proportion of examples in the data in class i (init_probs) + Let a_i is the rate the rejection sampler should *accept* class i + Let t_i is the target proportion in the minibatches for class i (target_probs) + + ``` + F = sum_i(p_i * (1-a_i)) + = 1 - sum_i(p_i * a_i) using sum_i(p_i) = 1 + ``` + + An example with class `i` will be accepted if `k` rejections occur, then an + example with class `i` is seen by the rejector, and it is accepted. This can + be written as follows: + + ``` + t_i = sum_k=0^inf(F^k * p_i * a_i) + = p_i * a_j / (1 - F) using geometric series identity, since 0 <= F < 1 + = p_i * a_i / sum_j(p_j * a_j) using F from above + ``` + + Note that the following constraints hold: + ``` + 0 <= p_i <= 1, sum_i(p_i) = 1 + 0 <= a_i <= 1 + 0 <= t_i <= 1, sum_i(t_i) = 1 + ``` + + A solution for a_i in terms of the other variables is the following: + ```a_i = (t_i / p_i) / max_i[t_i / p_i]``` + + If we try to minimize the amount of data rejected, we get the following: + + M_max = max_i [ t_i / p_i ] + M_min = min_i [ t_i / p_i ] + + The desired probability of accepting data if it comes from class `i`: + + a_i = (t_i/p_i - m) / (M_max - m) + + The desired probability of pulling a data element from the original dataset, + rather than the filtered one: + + m = M_min + + Args: + initial_probs: A Tensor of the initial probability distribution, given or + estimated. + target_probs: A Tensor of the corresponding classes. + + Returns: + (A 1D Tensor with the per-class acceptance probabilities, the desired + probability of pull from the original distribution.) + """ + ratio_l = _get_target_to_initial_ratio(initial_probs, target_probs) + max_ratio = math_ops.reduce_max(ratio_l) + min_ratio = math_ops.reduce_min(ratio_l) + + # Target prob to sample from original distribution. + m = min_ratio + + # TODO(joelshor): Simplify fraction, if possible. + a_i = (ratio_l - m) / (max_ratio - m) + return a_i, m + + +def _apply_rewrite(dataset, rewrite): + # pylint: disable=protected-access + return _VariantDataset( + gen_dataset_ops.rewrite_dataset(dataset._variant_tensor, rewrite, + **dataset._flat_structure), + dataset.element_spec) + + +def _collect_resource_inputs(op): + """Collects resource inputs for the given ops (and its variant inputs).""" + + def _process(op_queue, seen_ops): + """Processes the next element of the op queue. + + Args: + op_queue: Queue of Dataset operations to process. + seen_ops: Already processed set of Operations. + + Returns: + A 2-tuple containing sets of resource handles. The first tuple entry + contains read-only handles and the second entry contains read-write + handles. + """ + + reads = [] + writes = [] + op = op_queue.pop() + if op in seen_ops: + return reads, writes + seen_ops.add(op) + # TODO(b/150139257): All resource inputs are in writes right now since we + # have not updated the functional ops to set the special attribute that ACD + # uses to figure out which of the op's inputs are read-only. + reads, writes = acd_utils.get_read_write_resource_inputs(op) + # Conservatively assume that any variant inputs are datasets. + op_queue.extend(t.op for t in op.inputs if t.dtype == dtypes.variant) + return reads, writes + + op_queue = [op] + seen_ops = set() + all_reads = [] + all_writes = [] + while op_queue: + reads, writes = _process(op_queue, seen_ops) + all_reads.extend(reads) + all_writes.extend(writes) + + return all_reads, all_writes + + +@auto_control_deps.register_acd_resource_resolver +def _resource_resolver(op, resource_reads, resource_writes): + """Updates resource inputs for tf.data ops with indirect dependencies.""" + + updated = False + if op.type in [ + "DatasetToSingleElement", "DatasetToTFRecord", "ReduceDataset" + ]: + reads, writes = _collect_resource_inputs(op) + for inp in reads: + if inp not in resource_reads: + updated = True + resource_reads.add(inp) + for inp in writes: + if inp not in resource_writes: + updated = True + resource_writes.add(inp) + + if op.type in [ + "IteratorGetNext", "IteratorGetNextSync", "IteratorGetNextAsOptional" + ]: + iterator_resource = op.inputs[0] + make_iterator_ops = [ + op for op in iterator_resource.consumers() if op.type == "MakeIterator" + ] + + if len(make_iterator_ops) == 1: + reads, writes = _collect_resource_inputs(make_iterator_ops[0]) + for inp in reads: + if inp not in resource_reads: + updated = True + resource_reads.add(inp) + for inp in writes: + if inp not in resource_writes: + updated = True + resource_writes.add(inp) + + return updated + + +dataset_autograph.register_overrides() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/debug_mode.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/debug_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..d6ac28e356221097ff88a5bd39f9aa8bac7cbfd5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/debug_mode.py @@ -0,0 +1,77 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Python debug mode enabler.""" + +from tensorflow.python.eager import context +from tensorflow.python.util.tf_export import tf_export + + +DEBUG_MODE = False + + +@tf_export("data.experimental.enable_debug_mode") +def enable_debug_mode(): + """Enables debug mode for tf.data. + + Example usage with pdb module: + ``` + import tensorflow as tf + import pdb + + tf.data.experimental.enable_debug_mode() + + def func(x): + # Python 3.7 and older requires `pdb.Pdb(nosigint=True).set_trace()` + pdb.set_trace() + x = x + 1 + return x + + dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3]) + dataset = dataset.map(func) + + for item in dataset: + print(item) + ``` + + The effect of debug mode is two-fold: + + 1) Any transformations that would introduce asynchrony, parallelism, or + non-determinism to the input pipeline execution will be forced to execute + synchronously, sequentially, and deterministically. + + 2) Any user-defined functions passed into tf.data transformations such as + `map` will be wrapped in `tf.py_function` so that their body is executed + "eagerly" as a Python function as opposed to a traced TensorFlow graph, which + is the default behavior. Note that even when debug mode is enabled, the + user-defined function is still traced to infer the shape and type of its + outputs; as a consequence, any `print` statements or breakpoints will be + triggered once during the tracing before the actual execution of the input + pipeline. + + NOTE: As the debug mode setting affects the construction of the tf.data input + pipeline, it should be enabled before any tf.data definitions. + + Raises: + ValueError: When invoked from graph mode. + """ + if context.executing_eagerly(): + toggle_debug_mode(True) + else: + raise ValueError("`enable_debug_mode() is only supported in eager mode.") + + +def toggle_debug_mode(debug_mode): + global DEBUG_MODE + DEBUG_MODE = debug_mode diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/directed_interleave_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/directed_interleave_op.py new file mode 100644 index 0000000000000000000000000000000000000000..b8ce72db6269ec8de3e6c8711c18ae9254ed56a8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/directed_interleave_op.py @@ -0,0 +1,72 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.shuffle`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _directed_interleave( # pylint: disable=unused-private-name + selector_input, data_inputs, stop_on_empty_dataset=False +): + return _DirectedInterleaveDataset( + selector_input, data_inputs, stop_on_empty_dataset=stop_on_empty_dataset + ) + + +class _DirectedInterleaveDataset(dataset_ops.DatasetV2): + """A substitute for `Dataset.interleave()` on a fixed list of datasets.""" + + def __init__(self, selector_input, data_inputs, stop_on_empty_dataset=False): + self._selector_input = selector_input + self._data_inputs = list(data_inputs) + self._stop_on_empty_dataset = stop_on_empty_dataset + + spec = self._data_inputs[0].element_spec + for i, data_input in enumerate(self._data_inputs[1:]): + def common_supertype(a, b): + result = a.most_specific_common_supertype([b]) + if result is None: + raise TypeError(f"No common supertype of {a} and {b}.") + return result + + try: + spec = nest.map_structure(common_supertype, spec, + data_input.element_spec) + except (TypeError, ValueError) as e: + raise TypeError(f"Invalid `datasets`. `datasets` must have compatible " + f"element specs.\n Dataset 0 " + f"element_spec={data_inputs[0].element_spec}.\n" + f"Dataset {i+1} " + f"element_spec={data_input.element_spec}.") from e + self._element_spec = spec + + # pylint: disable=protected-access + variant_tensor = ( + ged_ops.directed_interleave_dataset( + self._selector_input._variant_tensor, + [data_input._variant_tensor for data_input in self._data_inputs], + stop_on_empty_dataset=self._stop_on_empty_dataset, + **self._flat_structure)) + + super().__init__(variant_tensor) + + def _inputs(self): + return [self._selector_input] + self._data_inputs + + @property + def element_spec(self): + return self._element_spec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/filter_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/filter_op.py new file mode 100644 index 0000000000000000000000000000000000000000..fb36a8c5d4f59197aedcb3e2ee2aaac1a5eb8522 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/filter_op.py @@ -0,0 +1,61 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.filter`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_dataset_ops + + +def _filter(input_dataset, predicate, name=None): # pylint: disable=redefined-builtin + return _FilterDataset(input_dataset, predicate, name=name) + + +class _FilterDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that filters its input according to a predicate function.""" + + def __init__(self, + input_dataset, + predicate, + use_legacy_function=False, + name=None): + """See `Dataset.filter` for details.""" + self._input_dataset = input_dataset + wrapped_func = structured_function.StructuredFunctionWrapper( + predicate, + self._transformation_name(), + dataset=input_dataset, + use_legacy_function=use_legacy_function) + if not wrapped_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.bool)): + raise ValueError(f"Invalid `predicate`. `predicate` must return a " + f"`tf.bool` scalar tensor, but its return type is " + f"{wrapped_func.output_structure}.") + self._predicate = wrapped_func + self._name = name + variant_tensor = gen_dataset_ops.filter_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + other_arguments=self._predicate.function.captured_inputs, + predicate=self._predicate.function, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._predicate] + + def _transformation_name(self): + return "Dataset.filter()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/flat_map_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/flat_map_op.py new file mode 100644 index 0000000000000000000000000000000000000000..baf0e02da4b9e51dd5251b43439871fb04b6b713 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/flat_map_op.py @@ -0,0 +1,57 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.flat_map`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.ops import gen_dataset_ops + + +def _flat_map(input_dataset, map_func, name=None): # pylint: disable=unused-private-name + """See `Dataset.flat_map()` for details.""" + return _FlatMapDataset(input_dataset, map_func, name) + + +class _FlatMapDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over its input and flattens the result.""" + + def __init__(self, input_dataset, map_func, name=None): + + self._input_dataset = input_dataset + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, self._transformation_name(), dataset=input_dataset) + if not isinstance(self._map_func.output_structure, dataset_ops.DatasetSpec): + raise TypeError( + "The `map_func` argument must return a `Dataset` object. Got " + f"{dataset_ops.get_type(self._map_func.output_structure)!r}.") + # pylint: disable=protected-access + self._structure = self._map_func.output_structure._element_spec + self._name = name + variant_tensor = gen_dataset_ops.flat_map_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, + f=self._map_func.function, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._structure + + def _transformation_name(self): + return "Dataset.flat_map()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_generator_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_generator_op.py new file mode 100644 index 0000000000000000000000000000000000000000..248fc4f284404f19117210e3d89a39fc944f7e11 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_generator_op.py @@ -0,0 +1,400 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.from_generator`.""" + +import numpy as np + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import script_ops + + +def _from_generator(generator, output_types, output_shapes, args, + output_signature, name): + """Creates a `Dataset` whose elements are generated by `generator`. + + Note: The current implementation of `Dataset.from_generator()` uses + `tf.numpy_function` and inherits the same constraints. In particular, it + requires the dataset and iterator related operations to be placed + on a device in the same process as the Python program that called + `Dataset.from_generator()`. In particular, using `from_generator` will + preclude the use of tf.data service for scaling out dataset processing. + The body of `generator` will not be serialized in a `GraphDef`, and you + should not use this method if you need to serialize your model and restore + it in a different environment. + + The `generator` argument must be a callable object that returns + an object that supports the `iter()` protocol (e.g. a generator function). + + The elements generated by `generator` must be compatible with either the + given `output_signature` argument or with the given `output_types` and + (optionally) `output_shapes` arguments, whichever was specified. + + The recommended way to call `from_generator` is to use the + `output_signature` argument. In this case the output will be assumed to + consist of objects with the classes, shapes and types defined by + `tf.TypeSpec` objects from `output_signature` argument: + + >>> def gen(): + ... ragged_tensor = tf.ragged.constant([[1, 2], [3]]) + ... yield 42, ragged_tensor + >>> + >>> dataset = tf.data.Dataset.from_generator( + ... gen, + ... output_signature=( + ... tf.TensorSpec(shape=(), dtype=tf.int32), + ... tf.RaggedTensorSpec(shape=(2, None), dtype=tf.int32))) + >>> + >>> list(dataset.take(1)) + [(, + )] + + There is also a deprecated way to call `from_generator` by either with + `output_types` argument alone or together with `output_shapes` argument. + In this case the output of the function will be assumed to consist of + `tf.Tensor` objects with the types defined by `output_types` and with the + shapes which are either unknown or defined by `output_shapes`. + + Note: If `generator` depends on mutable global variables or other external + state, be aware that the runtime may invoke `generator` multiple times + (in order to support repeating the `Dataset`) and at any time + between the call to `Dataset.from_generator()` and the production of the + first element from the generator. Mutating global variables or external + state can cause undefined behavior, and we recommend that you explicitly + cache any external state in `generator` before calling + `Dataset.from_generator()`. + + Note: While the `output_signature` parameter makes it possible to yield + `Dataset` elements, the scope of `Dataset.from_generator()` should be + limited to logic that cannot be expressed through tf.data operations. Using + tf.data operations within the generator function is an anti-pattern and may + result in incremental memory growth. + + Args: + generator: A callable object that returns an object that supports the + `iter()` protocol. If `args` is not specified, `generator` must take no + arguments; otherwise it must take as many arguments as there are values in + `args`. + output_types: (Optional.) A (nested) structure of `tf.DType` objects + corresponding to each component of an element yielded by `generator`. + output_shapes: (Optional.) A (nested) structure of `tf.TensorShape` objects + corresponding to each component of an element yielded by `generator`. + args: (Optional.) A tuple of `tf.Tensor` objects that will be evaluated and + passed to `generator` as NumPy-array arguments. + output_signature: (Optional.) A (nested) structure of `tf.TypeSpec` objects + corresponding to each component of an element yielded by `generator`. + name: (Optional.) A name for the tf.data operations used by + `from_generator`. + + Returns: + Dataset: A `Dataset`. + """ + if not callable(generator): + raise TypeError("`generator` must be a Python callable.") + + if output_signature is not None: + if output_types is not None: + raise TypeError("The `output_types` argument can not be used together " + "with the `output_signature` argument.") + if output_shapes is not None: + raise TypeError("The `output_shapes` argument can not be used together " + "with the `output_signature` argument.") + for spec in nest.flatten(output_signature): + if not isinstance(spec, type_spec.TypeSpec): + raise TypeError(f"`output_signature` must contain objects that are " + f"subclass of `tf.TypeSpec` but found {type(spec)} " + f"which is not.") + else: + if output_types is None: + raise TypeError("To specify the output signature you need to provide " + "either the `output_signature` argument or the " + "`output_types` argument.") + + if output_signature is None: + if output_shapes is None: + output_shapes = nest.map_structure( + lambda _: tensor_shape.TensorShape(None), output_types) + else: + output_shapes = nest.map_structure_up_to(output_types, + tensor_shape.as_shape, + output_shapes) + output_signature = nest.map_structure_up_to(output_types, + tensor_spec.TensorSpec, + output_shapes, output_types) + if all( + isinstance(x, tensor_spec.TensorSpec) + for x in nest.flatten(output_signature)): + output_types = nest.pack_sequence_as( + output_signature, [x.dtype for x in nest.flatten(output_signature)]) + output_shapes = nest.pack_sequence_as( + output_signature, [x.shape for x in nest.flatten(output_signature)]) + + if args is None: + args = () + else: + args = tuple(ops.convert_n_to_tensor(args, name="args")) + + generator_state = dataset_ops.DatasetV2._GeneratorState(generator) # pylint: disable=protected-access + + def get_iterator_id_fn(unused_dummy): + """Creates a unique `iterator_id` for each pass over the dataset. + + The returned `iterator_id` disambiguates between multiple concurrently + existing iterators. + + Args: + unused_dummy: Ignored value. + + Returns: + A `tf.int64` tensor whose value uniquely identifies an iterator in + `generator_state`. + """ + return script_ops.numpy_function(generator_state.get_next_id, args, + dtypes.int64) + + def generator_next_fn(iterator_id_t): + """Generates the next element from iterator with ID `iterator_id_t`. + + We map this function across an infinite repetition of the + `iterator_id_t`, and raise `StopIteration` to terminate the iteration. + + Args: + iterator_id_t: A `tf.int64` tensor whose value uniquely identifies the + iterator in `generator_state` from which to generate an element. + + Returns: + The next element to generate from the iterator. + """ + if output_types and output_shapes: + flattened_types = [ + dtypes.as_dtype(dt) for dt in nest.flatten(output_types) + ] + flattened_shapes = nest.flatten(output_shapes) + + def generator_py_func(iterator_id): + """A `py_func` that will be called to invoke the iterator.""" + # `next()` raises `StopIteration` when there are no more + # elements remaining to be generated. + values = next(generator_state.get_iterator(iterator_id)) + + # Use the same _convert function from the py_func() implementation to + # convert the returned values to arrays early, so that we can inspect + # their values. + try: + flattened_values = nest.flatten_up_to(output_types, values) + except (TypeError, ValueError) as e: + raise TypeError( + f"`generator` yielded an element that did not match the " + f"expected structure. The expected structure was " + f"{output_types}, but the yielded element was {values}.") from e + ret_arrays = [] + for ret, dtype in zip(flattened_values, flattened_types): + try: + ret_arrays.append( + script_ops.FuncRegistry._convert( # pylint: disable=protected-access + ret, + dtype=dtype.as_numpy_dtype)) + except (TypeError, ValueError) as e: + raise TypeError( + f"`generator` yielded an element that could not be " + f"converted to the expected type. The expected type was " + f"{dtype.name}, but the yielded element was {ret}.") from e + + # Additional type and shape checking to ensure that the components of + # the generated element match the `output_types` and `output_shapes` + # arguments. + for (ret_array, expected_dtype, + expected_shape) in zip(ret_arrays, flattened_types, + flattened_shapes): + if ret_array.dtype != expected_dtype.as_numpy_dtype: + raise TypeError( + f"`generator` yielded an element of type {ret_array.dtype} " + f"where an element of type {expected_dtype.as_numpy_dtype} " + f"was expected.") + if not expected_shape.is_compatible_with(ret_array.shape): + raise TypeError( + f"`generator` yielded an element of shape {ret_array.shape} " + f"where an element of shape {expected_shape} was expected.") + + return ret_arrays + + flat_values = script_ops.numpy_function(generator_py_func, + [iterator_id_t], flattened_types) + + # In debug mode the numpy_function will return a scalar if + # generator_py_func produces only a single value. + if not isinstance(flat_values, (list, tuple)): + flat_values = [flat_values] + + # The `py_func()` op drops the inferred shapes, so we add them back in + # here. + if output_shapes is not None: + for ret_t, shape in zip(flat_values, flattened_shapes): + ret_t.set_shape(shape) + + return nest.pack_sequence_as(output_types, flat_values) + else: + flat_output_types = structure.get_flat_tensor_types(output_signature) + + def generator_py_func(iterator_id): + """A `py_func` that will be called to invoke the iterator.""" + # `next()` raises `StopIteration` when there are no more + # elements remaining to be generated. + values = next(generator_state.get_iterator(iterator_id.numpy())) + + try: + values = structure.normalize_element(values, output_signature) + except (TypeError, ValueError) as e: + raise TypeError( + f"`generator` yielded an element that did not match the " + f"expected structure. The expected structure was " + f"{output_signature}, but the yielded element was " + f"{values}.") from e + + values_spec = structure.type_spec_from_value(values) + + if not structure.are_compatible(values_spec, output_signature): + raise TypeError( + f"`generator` yielded an element of {values_spec} where an " + f"element of {output_signature} was expected.") + + return structure.to_tensor_list(output_signature, values) + + return script_ops.eager_py_func( + generator_py_func, inp=[iterator_id_t], Tout=flat_output_types) + + def finalize_fn(iterator_id_t): + """Releases host-side state for the iterator with ID `iterator_id_t`.""" + + def finalize_py_func(iterator_id): + generator_state.iterator_completed(iterator_id) + # We return a dummy value so that the `finalize_fn` has a valid + # signature. + # NOTE(mrry): Explicitly create an array of `np.int64` because implicit + # casting in `py_func()` will create an array of `np.int32` on Windows, + # leading to a runtime error. + return np.array(0, dtype=np.int64) + + return script_ops.numpy_function(finalize_py_func, [iterator_id_t], + dtypes.int64) + + # This function associates each traversal of `generator` with a unique + # iterator ID. + def flat_map_fn(dummy_arg): + # The `get_iterator_id_fn` gets a unique ID for the current instance of + # of the generator. + # The `generator_next_fn` gets the next element from the iterator with the + # given ID, and raises StopIteration when that iterator contains no + # more elements. + return _GeneratorDataset( + dummy_arg, + get_iterator_id_fn, + generator_next_fn, + finalize_fn, + output_signature, + name=name) + + # A single-element dataset that, each time it is evaluated, contains a + # freshly-generated and unique (for the returned dataset) int64 + # ID that will be used to identify the appropriate Python state, which + # is encapsulated in `generator_state`, and captured in + # `get_iterator_id_map_fn`. + dummy = 0 + id_dataset = dataset_ops.Dataset.from_tensors(dummy, name=name) + + # A dataset that contains all of the elements generated by a + # single iterator created from `generator`, identified by the + # iterator ID contained in `id_dataset`. Lifting the iteration + # into a flat_map here enables multiple repetitions and/or nested + # versions of the returned dataset to be created, because it forces + # the generation of a new ID for each version. + return id_dataset.flat_map(flat_map_fn, name=name) + + +class _GeneratorDataset(dataset_ops.DatasetSource): + """A `Dataset` that generates elements by invoking a function.""" + + def __init__(self, + init_args, + init_func, + next_func, + finalize_func, + output_signature, + name=None): + """Constructs a `_GeneratorDataset`. + + Args: + init_args: A (nested) structure representing the arguments to `init_func`. + init_func: A TensorFlow function that will be called on `init_args` each + time a C++ iterator over this dataset is constructed. Returns a (nested) + structure representing the "state" of the dataset. + next_func: A TensorFlow function that will be called on the result of + `init_func` to produce each element, and that raises `OutOfRangeError` + to terminate iteration. + finalize_func: A TensorFlow function that will be called on the result of + `init_func` immediately before a C++ iterator over this dataset is + destroyed. The return value is ignored. + output_signature: A (nested) structure of `tf.TypeSpec` objects describing + the output of `next_func`. + name: Optional. A name for the tf.data transformation. + """ + self._init_args = init_args + + self._init_structure = structure.type_spec_from_value(init_args) + + self._init_func = structured_function.StructuredFunctionWrapper( + init_func, + self._transformation_name(), + input_structure=self._init_structure) + + self._next_func = structured_function.StructuredFunctionWrapper( + next_func, + self._transformation_name(), + input_structure=self._init_func.output_structure) + + self._finalize_func = structured_function.StructuredFunctionWrapper( + finalize_func, + self._transformation_name(), + input_structure=self._init_func.output_structure) + + self._output_signature = output_signature + + self._name = name + + variant_tensor = gen_dataset_ops.generator_dataset( + structure.to_tensor_list(self._init_structure, self._init_args) + + self._init_func.function.captured_inputs, + self._next_func.function.captured_inputs, + self._finalize_func.function.captured_inputs, + init_func=self._init_func.function, + next_func=self._next_func.function, + finalize_func=self._finalize_func.function, + **self._common_args) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return self._output_signature + + def _transformation_name(self): + return "Dataset.from_generator()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_sparse_tensor_slices_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_sparse_tensor_slices_op.py new file mode 100644 index 0000000000000000000000000000000000000000..9f70b4e72dbae7fa47e737e8cd8261dd635bebdd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_sparse_tensor_slices_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.from_sparse_tensor_slices`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_dataset_ops + + +def _from_sparse_tensor_slices(sparse_tensor): # pylint: disable=unused-private-name + return dataset_ops.DatasetV1Adapter(_SparseTensorSliceDataset(sparse_tensor)) + + +class _SparseTensorSliceDataset(dataset_ops.DatasetSource): + """A `Dataset` that splits a rank-N `tf.sparse.SparseTensor` into its rows.""" + + def __init__(self, sparse_tensor): + """See `Dataset.from_sparse_tensor_slices()` for details.""" + if not isinstance(sparse_tensor, sparse_tensor_lib.SparseTensor): + raise TypeError(f"Invalid `sparse_tensor`. `sparse_tensor` must be a " + f"`tf.sparse.SparseTensor`. Got {type(sparse_tensor)}.") + self._sparse_tensor = sparse_tensor + + indices_shape = self._sparse_tensor.indices.get_shape() + shape_shape = self._sparse_tensor.dense_shape.get_shape() + rank = (indices_shape.dims[1] - 1).merge_with(shape_shape.dims[0] - 1) + self._structure = (tensor_spec.TensorSpec([None, rank], dtypes.int64), + tensor_spec.TensorSpec([None], + self._sparse_tensor.dtype), + tensor_spec.TensorSpec([rank], dtypes.int64)) + + variant_tensor = gen_dataset_ops.sparse_tensor_slice_dataset( + self._sparse_tensor.indices, self._sparse_tensor.values, + self._sparse_tensor.dense_shape) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_tensor_slices_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_tensor_slices_op.py new file mode 100644 index 0000000000000000000000000000000000000000..e3951a0aedfe0bc43ca043fe500ae6765ded0e0c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_tensor_slices_op.py @@ -0,0 +1,58 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.from_tensor_slices`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import gen_dataset_ops + + +def _from_tensor_slices(tensors, name=None): + return _TensorSliceDataset(tensors, name=name) + + +class _TensorSliceDataset(dataset_ops.DatasetSource): + """A `Dataset` of slices from a dataset element.""" + + def __init__(self, element, is_files=False, name=None): + """See `Dataset.from_tensor_slices` for details.""" + element = structure.normalize_element(element) + batched_spec = structure.type_spec_from_value(element) + self._tensors = structure.to_batched_tensor_list(batched_spec, element) + if not self._tensors: + raise ValueError("Invalid `element`. `element` should not be empty.") + self._structure = nest.map_structure( + lambda component_spec: component_spec._unbatch(), batched_spec) # pylint: disable=protected-access + self._name = name + + batch_dim = tensor_shape.Dimension( + tensor_shape.dimension_value(self._tensors[0].get_shape()[0])) + for t in self._tensors[1:]: + batch_dim.assert_is_compatible_with( + tensor_shape.Dimension( + tensor_shape.dimension_value(t.get_shape()[0]))) + + variant_tensor = gen_dataset_ops.tensor_slice_dataset( + self._tensors, + output_shapes=structure.get_flat_tensor_shapes(self._structure), + is_files=is_files, + metadata=self._metadata.SerializeToString()) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_tensors_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_tensors_op.py new file mode 100644 index 0000000000000000000000000000000000000000..1588784ee55c29edb6dd9a1f56382d91b93d1f69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/from_tensors_op.py @@ -0,0 +1,43 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.from_tensors`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import structure +from tensorflow.python.ops import gen_dataset_ops + + +def _from_tensors(tensors, name): # pylint: disable=unused-private-name + return _TensorDataset(tensors, name) + + +class _TensorDataset(dataset_ops.DatasetSource): + """A `Dataset` with a single element.""" + + def __init__(self, element, name=None): + """See `tf.data.Dataset.from_tensors` for details.""" + element = structure.normalize_element(element) + self._structure = structure.type_spec_from_value(element) + self._tensors = structure.to_tensor_list(self._structure, element) + self._name = name + variant_tensor = gen_dataset_ops.tensor_dataset( + self._tensors, + output_shapes=structure.get_flat_tensor_shapes(self._structure), + metadata=self._metadata.SerializeToString()) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/group_by_window_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/group_by_window_op.py new file mode 100644 index 0000000000000000000000000000000000000000..967264a25f7090c539ad3b42566bc42be5f82144 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/group_by_window_op.py @@ -0,0 +1,132 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.group_by_window`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _group_by_window(input_dataset, # pylint: disable=unused-private-name + key_func, + reduce_func, + window_size=None, + window_size_func=None, + name=None): + """See `Dataset.group_by_window()` for details.""" + + if (window_size is not None and window_size_func or + not (window_size is not None or window_size_func)): + raise ValueError("Either the `window_size` argument or the " + "`window_size_func` argument must be specified.") + + if window_size is not None: + + def constant_window_func(unused_key): + return ops.convert_to_tensor(window_size, dtype=dtypes.int64) + + window_size_func = constant_window_func + + assert window_size_func is not None + + return _GroupByWindowDataset( + input_dataset, key_func, reduce_func, window_size_func, name=name) + + +class _GroupByWindowDataset(dataset_ops.UnaryDataset): + """A `Dataset` that groups its input and performs a windowed reduction.""" + + def __init__(self, + input_dataset, + key_func, + reduce_func, + window_size_func, + name=None): + """See `group_by_window()` for details.""" + self._input_dataset = input_dataset + self._make_key_func(key_func, input_dataset) + self._make_reduce_func(reduce_func, input_dataset) + self._make_window_size_func(window_size_func) + self._name = name + variant_tensor = ged_ops.group_by_window_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._key_func.function.captured_inputs, + self._reduce_func.function.captured_inputs, + self._window_size_func.function.captured_inputs, + key_func=self._key_func.function, + reduce_func=self._reduce_func.function, + window_size_func=self._window_size_func.function, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _make_window_size_func(self, window_size_func): + """Make wrapping defun for window_size_func.""" + + def window_size_func_wrapper(key): + return ops.convert_to_tensor(window_size_func(key), dtype=dtypes.int64) + + self._window_size_func = structured_function.StructuredFunctionWrapper( + window_size_func_wrapper, + self._transformation_name(), + input_structure=tensor_spec.TensorSpec([], dtypes.int64)) + if not self._window_size_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.int64)): + raise ValueError(f"Invalid `window_size_func`. `window_size_func` must " + f"return a single `tf.int64` scalar tensor but its " + f"return type is " + f"{self._window_size_func.output_structure}.") + + def _make_key_func(self, key_func, input_dataset): + """Make wrapping defun for key_func.""" + + def key_func_wrapper(*args): + return ops.convert_to_tensor(key_func(*args), dtype=dtypes.int64) + + self._key_func = structured_function.StructuredFunctionWrapper( + key_func_wrapper, self._transformation_name(), dataset=input_dataset) + if not self._key_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.int64)): + raise ValueError(f"Invalid `key_func`. `key_func` must return a single " + f"`tf.int64` scalar tensor but its return type is " + f"{self._key_func.output_structure}.") + + def _make_reduce_func(self, reduce_func, input_dataset): + """Make wrapping defun for reduce_func.""" + nested_dataset = dataset_ops.DatasetSpec(input_dataset.element_spec) + input_structure = (tensor_spec.TensorSpec([], dtypes.int64), nested_dataset) + self._reduce_func = structured_function.StructuredFunctionWrapper( + reduce_func, + self._transformation_name(), + input_structure=input_structure) + if not isinstance(self._reduce_func.output_structure, + dataset_ops.DatasetSpec): + raise TypeError(f"Invalid `reduce_func`. `reduce_func` must return a " + f"single `tf.data.Dataset` object but its return type " + f"is {self._reduce_func.output_structure}.") + # pylint: disable=protected-access + self._element_spec = (self._reduce_func.output_structure._element_spec) + + @property + def element_spec(self): + return self._element_spec + + def _functions(self): + return [self._key_func, self._reduce_func, self._window_size_func] + + def _transformation_name(self): + return "Dataset.group_by_window()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/ignore_errors_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/ignore_errors_op.py new file mode 100644 index 0000000000000000000000000000000000000000..4f2f58fe1c6ee552332ec06ef36016f67c4f7f17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/ignore_errors_op.py @@ -0,0 +1,37 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.ignore_errors`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops + + +def _ignore_errors(input_dataset, log_warning=False, name=None): + return _IgnoreErrorsDataset(input_dataset, log_warning, name) + + +class _IgnoreErrorsDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that drops erroneous elements from its input.""" + + def __init__(self, input_dataset, log_warning, name=None): + """See `Dataset.ignore_errors` for details.""" + self._input_dataset = input_dataset + self._name = name + variant_tensor = ( + gen_experimental_dataset_ops.ignore_errors_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + log_warning=log_warning, + **self._flat_structure)) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/interleave_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/interleave_op.py new file mode 100644 index 0000000000000000000000000000000000000000..75372e7d3449afa9aa4867b03ce61b1d9db6c2a6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/interleave_op.py @@ -0,0 +1,170 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.interleave`.""" + +import warnings + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import debug_mode +from tensorflow.python.data.ops import structured_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _interleave( # pylint: disable=unused-private-name + input_dataset, + map_func, + cycle_length=None, + block_length=None, + num_parallel_calls=None, + deterministic=None, + name=None): + """See `Dataset.interleave()` for details.""" + if block_length is None: + block_length = 1 + + if cycle_length is None: + cycle_length = dataset_ops.AUTOTUNE + + if num_parallel_calls is None or debug_mode.DEBUG_MODE: + if deterministic is not None and not debug_mode.DEBUG_MODE: + warnings.warn("The `deterministic` argument has no effect unless the " + "`num_parallel_calls` argument is specified.") + return _InterleaveDataset( + input_dataset, map_func, cycle_length, block_length, name=name) + else: + return _ParallelInterleaveDataset( + input_dataset, + map_func, + cycle_length, + block_length, + num_parallel_calls, + deterministic=deterministic, + name=name) + + +class _InterleaveDataset(dataset_ops.UnaryDataset): + """A `Dataset` that interleaves the result of transformed inputs.""" + + def __init__(self, + input_dataset, + map_func, + cycle_length, + block_length, + name=None): + """See `Dataset.interleave()` for details.""" + + self._input_dataset = input_dataset + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, self._transformation_name(), dataset=input_dataset) + if not isinstance(self._map_func.output_structure, dataset_ops.DatasetSpec): + raise TypeError( + "The `map_func` argument must return a `Dataset` object. Got " + f"{dataset_ops.get_type(self._map_func.output_structure)!r}.") + self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access + self._cycle_length = ops.convert_to_tensor( + cycle_length, dtype=dtypes.int64, name="cycle_length") + self._block_length = ops.convert_to_tensor( + block_length, dtype=dtypes.int64, name="block_length") + self._name = name + variant_tensor = gen_dataset_ops.interleave_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, # pylint: disable=protected-access + self._cycle_length, + self._block_length, + f=self._map_func.function, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._structure + + def _transformation_name(self): + return "Dataset.interleave()" + + +class _ParallelInterleaveDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over its input and interleaves the result. + """ + + def __init__(self, + input_dataset, + map_func, + cycle_length, + block_length, + num_parallel_calls, + buffer_output_elements=dataset_ops.AUTOTUNE, + prefetch_input_elements=dataset_ops.AUTOTUNE, + deterministic=None, + name=None): + """See `Dataset.interleave()` for details.""" + self._input_dataset = input_dataset + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, self._transformation_name(), dataset=input_dataset) + if not isinstance(self._map_func.output_structure, dataset_ops.DatasetSpec): + raise TypeError( + "The `map_func` argument must return a `Dataset` object. Got " + f"{dataset_ops.get_type(self._map_func.output_structure)!r}.") + self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access + self._cycle_length = ops.convert_to_tensor( + cycle_length, dtype=dtypes.int64, name="cycle_length") + self._block_length = ops.convert_to_tensor( + block_length, dtype=dtypes.int64, name="block_length") + self._buffer_output_elements = ops.convert_to_tensor( + buffer_output_elements, + dtype=dtypes.int64, + name="buffer_output_elements") + self._prefetch_input_elements = ops.convert_to_tensor( + prefetch_input_elements, + dtype=dtypes.int64, + name="prefetch_input_elements") + + self._num_parallel_calls = ops.convert_to_tensor( + num_parallel_calls, dtype=dtypes.int64, name="num_parallel_calls") + if deterministic is None: + deterministic_string = "default" + elif deterministic: + deterministic_string = "true" + else: + deterministic_string = "false" + + self._name = name + variant_tensor = gen_dataset_ops.parallel_interleave_dataset_v4( + input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, # pylint: disable=protected-access + self._cycle_length, + self._block_length, + self._buffer_output_elements, + self._prefetch_input_elements, + self._num_parallel_calls, + f=self._map_func.function, + deterministic=deterministic_string, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._structure + + def _transformation_name(self): + return "Dataset.interleave()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_autograph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_autograph.py new file mode 100644 index 0000000000000000000000000000000000000000..f566a4ecd9e1d8069b214f9869aa79567f5eebc9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_autograph.py @@ -0,0 +1,119 @@ +# 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. +# ============================================================================== +"""Autograph specifc overrides for tf.data.ops.""" +import functools + +import numpy as np + +from tensorflow.python.autograph.operators import control_flow +from tensorflow.python.autograph.operators import py_builtins +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import cond +from tensorflow.python.util import nest + + +# TODO(mdan): These checks should be easier. Fix the nest API. +def _verify_spec_compatible(input_name, spec_name, input_, spec): + """Verifies that a symbol has a type compatible vith a given spec. + + Here, compatibility is viewed in the general TensorFlow sense: that the dtypes + are the same after implicit conversion, if both are tensors. + + This verifier ensures consistent treatment of types across AutoGraph. + + Args: + input_name: A name to use for `input_` in error messages. + spec_name: A name to use for `spec` in error messages. + input_: Any, value to verify. + spec: TypeSpec that `input_` must be compatible with. + + Raises: + ValueError if the two types have been determined not to be compatible. + """ + assert isinstance(spec, tensor_spec.TensorSpec) + if input is None: + # TODO(mdan): raise from None when switching to Py3. + raise ValueError("{} cannot be None".format(input_name)) + + # TODO(mdan): Use TensorCompatible when ready. + if isinstance(input_, (bool, int, float, str, np.ndarray)): + input_ = tensor_conversion.convert_to_tensor_v2(input_) + + input_dtype = getattr(input_, "dtype", None) + + if input_dtype != spec.dtype: + input_dtype_str = "no dtype" if input_dtype is None else str(input_dtype) + + raise TypeError( + "{} must have the same dtype as {}. Expected {}, got {}".format( + input_name, spec_name, spec.dtype, input_dtype_str + ) + ) + + +def _verify_structure_compatible(input_name, spec_name, input_, spec): + """Verifies that possibly-structured symbol has types compatible vith another. + + See _verify_spec_compatible for a more concrete meaning of "compatible". + Unspec _verify_spec_compatible, which handles singular Tensor-spec objects, + verify_structures_compatible can process structures recognized by tf.nest. + + Args: + input_name: A name to use for `input_` in error messages. + spec_name: A name to use for `spec` in error messages. + input_: Any, value to verify. May, but doesn't need to, be a structure. + spec: Any, value that `input_` must be compatible with. May, but doesn't + need to, be a structure. + + Raises: + ValueError if the two types have been determined not to be compatible. + """ + try: + nest.assert_same_structure(input_, spec, expand_composites=True) + except (ValueError, TypeError) as e: + raise TypeError( + "{} must have the same element structure as {}.\n\n{}".format( + input_name, spec_name, str(e) + ) + ) from e + + nest.map_structure( + functools.partial(_verify_spec_compatible, input_name, spec_name), input_, + spec) + + +def _next_tf_iterator(iterator, default=py_builtins.UNSPECIFIED): + if default is py_builtins.UNSPECIFIED: + # Without a default, fall back to the "normal" behavior which raises + # a runtime exception. + return next(iterator) + opt_iterate = iterator.get_next_as_optional() + _verify_structure_compatible( + "the default argument", "the iterate", default, iterator.element_spec + ) + return cond.cond( + opt_iterate.has_value(), opt_iterate.get_value, lambda: default + ) + + +def register_overrides(): + py_builtins.next_registry.register( + iterator_ops.OwnedIterator, _next_tf_iterator + ) + control_flow.for_loop_registry.register( + iterator_ops.OwnedIterator, control_flow._tf_iterator_for_stmt # pylint: disable=protected-access + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8c09060ab859762b70f8e9fc860aa35da47c33b1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_ops.py @@ -0,0 +1,1017 @@ +# 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. +# ============================================================================== +"""Python wrappers for Iterators.""" +import abc +import threading +import warnings + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.checkpoint import saveable_compat +from tensorflow.python.data.ops import iterator_autograph +from tensorflow.python.data.ops import optional_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_utils +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training.saver import BaseSaverBuilder +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import deprecation +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +# NOTE(mrry): It is legitimate to call `Iterator.get_next()` multiple +# times, e.g. when you are distributing different elements to multiple +# devices in a single step. However, a common pitfall arises when +# users call `Iterator.get_next()` in each iteration of their training +# loop. `Iterator.get_next()` adds ops to the graph, and executing +# each op allocates resources (including threads); as a consequence, +# invoking it in every iteration of a training loop causes slowdown +# and eventual resource exhaustion. To guard against this outcome, we +# log a warning when the number of uses crosses a threshold of suspicion. +GET_NEXT_CALL_WARNING_THRESHOLD = 32 + +GET_NEXT_CALL_WARNING_MESSAGE = ( + "An unusually high number of `Iterator.get_next()` calls was detected. " + "This often indicates that `Iterator.get_next()` is being called inside " + "a training loop, which will cause gradual slowdown and eventual resource " + "exhaustion. If this is the case, restructure your code to call " + "`next_element = iterator.get_next()` once outside the loop, and use " + "`next_element` as the input to some computation that is invoked inside " + "the loop.") + +# NOTE(jsimsa): Threshold used as a heuristic to check for infinite loop during +# tf.function tracing. +GET_NEXT_CALL_ERROR_THRESHOLD = 32 + +GET_NEXT_CALL_ERROR_MESSAGE = ( + "An unusually high number of `tf.data.Iterator.get_next()` calls was " + "detected. This suggests that the `for elem in dataset: ...` idiom is used " + "within tf.function with AutoGraph disabled. This idiom is only supported " + "when AutoGraph is enabled.") + +# Collection of all IteratorResources in the `Graph`. +GLOBAL_ITERATORS = "iterators" + + +def _device_stack_is_empty(): + if context.executing_eagerly(): + return context.context().device_name is None + # pylint: disable=protected-access + device_stack = ops.get_default_graph()._device_functions_outer_to_inner + # pylint: enable=protected-access + return not bool(device_stack) + + +@saveable_compat.legacy_saveable_name("ITERATOR") +@tf_export(v1=["data.Iterator"]) +class Iterator(trackable.Trackable): + """Represents the state of iterating through a `Dataset`.""" + + def __init__(self, iterator_resource, initializer, output_types, + output_shapes, output_classes): + """Creates a new iterator from the given iterator resource. + + Note: Most users will not call this initializer directly, and will + instead use `Dataset.make_initializable_iterator()` or + `Dataset.make_one_shot_iterator()`. + + Args: + iterator_resource: A `tf.resource` scalar `tf.Tensor` representing the + iterator. + initializer: A `tf.Operation` that should be run to initialize this + iterator. + output_types: A (nested) structure of `tf.DType` objects corresponding to + each component of an element of this iterator. + output_shapes: A (nested) structure of `tf.TensorShape` objects + corresponding to each component of an element of this iterator. + output_classes: A (nested) structure of Python `type` objects + corresponding to each component of an element of this iterator. + + Raises: + TypeError: If `output_types`, `output_shapes`, or `output_classes` is not + specified. + """ + self._iterator_resource = iterator_resource + self._initializer = initializer + + if (output_types is None or output_shapes is None + or output_classes is None): + raise ValueError( + "All of `output_types`, `output_shapes`, and `output_classes` " + "must be specified to create an iterator. Got " + f"`output_types` = {output_types!r}, " + f"`output_shapes` = {output_shapes!r}, " + f"`output_classes` = {output_classes!r}.") + self._element_spec = structure.convert_legacy_structure( + output_types, output_shapes, output_classes) + self._flat_tensor_shapes = structure.get_flat_tensor_shapes( + self._element_spec) + self._flat_tensor_types = structure.get_flat_tensor_types( + self._element_spec) + + self._string_handle = gen_dataset_ops.iterator_to_string_handle( + self._iterator_resource) + self._get_next_call_count = 0 + ops.add_to_collection(GLOBAL_ITERATORS, self._iterator_resource) + + @staticmethod + def from_structure(output_types, + output_shapes=None, + shared_name=None, + output_classes=None): + """Creates a new, uninitialized `Iterator` with the given structure. + + This iterator-constructing method can be used to create an iterator that + is reusable with many different datasets. + + The returned iterator is not bound to a particular dataset, and it has + no `initializer`. To initialize the iterator, run the operation returned by + `Iterator.make_initializer(dataset)`. + + The following is an example + + ```python + iterator = Iterator.from_structure(tf.int64, tf.TensorShape([])) + + dataset_range = Dataset.range(10) + range_initializer = iterator.make_initializer(dataset_range) + + dataset_evens = dataset_range.filter(lambda x: x % 2 == 0) + evens_initializer = iterator.make_initializer(dataset_evens) + + # Define a model based on the iterator; in this example, the model_fn + # is expected to take scalar tf.int64 Tensors as input (see + # the definition of 'iterator' above). + prediction, loss = model_fn(iterator.get_next()) + + # Train for `num_epochs`, where for each epoch, we first iterate over + # dataset_range, and then iterate over dataset_evens. + for _ in range(num_epochs): + # Initialize the iterator to `dataset_range` + sess.run(range_initializer) + while True: + try: + pred, loss_val = sess.run([prediction, loss]) + except tf.errors.OutOfRangeError: + break + + # Initialize the iterator to `dataset_evens` + sess.run(evens_initializer) + while True: + try: + pred, loss_val = sess.run([prediction, loss]) + except tf.errors.OutOfRangeError: + break + ``` + + Args: + output_types: A (nested) structure of `tf.DType` objects corresponding to + each component of an element of this dataset. + output_shapes: (Optional.) A (nested) structure of `tf.TensorShape` + objects corresponding to each component of an element of this dataset. + If omitted, each component will have an unconstrainted shape. + shared_name: (Optional.) If non-empty, this iterator will be shared under + the given name across multiple sessions that share the same devices + (e.g. when using a remote server). + output_classes: (Optional.) A (nested) structure of Python `type` objects + corresponding to each component of an element of this iterator. If + omitted, each component is assumed to be of type `tf.Tensor`. + + Returns: + An `Iterator`. + + Raises: + TypeError: If the structures of `output_shapes` and `output_types` are + not the same. + """ + output_types = nest.map_structure(dtypes.as_dtype, output_types) + if output_shapes is None: + output_shapes = nest.map_structure( + lambda _: tensor_shape.TensorShape(None), output_types) + else: + output_shapes = nest.map_structure_up_to(output_types, + tensor_shape.as_shape, + output_shapes) + if output_classes is None: + output_classes = nest.map_structure(lambda _: tensor.Tensor, output_types) + nest.assert_same_structure(output_types, output_shapes) + output_structure = structure.convert_legacy_structure( + output_types, output_shapes, output_classes) + if shared_name is None: + shared_name = "" + iterator_resource = gen_dataset_ops.iterator_v2( + container="", + shared_name=shared_name, + output_types=structure.get_flat_tensor_types(output_structure), + output_shapes=structure.get_flat_tensor_shapes( + output_structure)) + return Iterator(iterator_resource, None, output_types, output_shapes, + output_classes) + + @staticmethod + def from_string_handle(string_handle, + output_types, + output_shapes=None, + output_classes=None): + """Creates a new, uninitialized `Iterator` based on the given handle. + + This method allows you to define a "feedable" iterator where you can choose + between concrete iterators by feeding a value in a `tf.Session.run` call. + In that case, `string_handle` would be a `tf.compat.v1.placeholder`, and you + would + feed it with the value of `tf.data.Iterator.string_handle` in each step. + + For example, if you had two iterators that marked the current position in + a training dataset and a test dataset, you could choose which to use in + each step as follows: + + ```python + train_iterator = tf.data.Dataset(...).make_one_shot_iterator() + train_iterator_handle = sess.run(train_iterator.string_handle()) + + test_iterator = tf.data.Dataset(...).make_one_shot_iterator() + test_iterator_handle = sess.run(test_iterator.string_handle()) + + handle = tf.compat.v1.placeholder(tf.string, shape=[]) + iterator = tf.data.Iterator.from_string_handle( + handle, train_iterator.output_types) + + next_element = iterator.get_next() + loss = f(next_element) + + train_loss = sess.run(loss, feed_dict={handle: train_iterator_handle}) + test_loss = sess.run(loss, feed_dict={handle: test_iterator_handle}) + ``` + + Args: + string_handle: A scalar `tf.Tensor` of type `tf.string` that evaluates to + a handle produced by the `Iterator.string_handle()` method. + output_types: A (nested) structure of `tf.DType` objects corresponding to + each component of an element of this dataset. + output_shapes: (Optional.) A (nested) structure of `tf.TensorShape` + objects corresponding to each component of an element of this dataset. + If omitted, each component will have an unconstrainted shape. + output_classes: (Optional.) A (nested) structure of Python `type` objects + corresponding to each component of an element of this iterator. If + omitted, each component is assumed to be of type `tf.Tensor`. + + Returns: + An `Iterator`. + """ + output_types = nest.map_structure(dtypes.as_dtype, output_types) + if output_shapes is None: + output_shapes = nest.map_structure( + lambda _: tensor_shape.TensorShape(None), output_types) + else: + output_shapes = nest.map_structure_up_to(output_types, + tensor_shape.as_shape, + output_shapes) + if output_classes is None: + output_classes = nest.map_structure(lambda _: tensor.Tensor, output_types) + nest.assert_same_structure(output_types, output_shapes) + output_structure = structure.convert_legacy_structure( + output_types, output_shapes, output_classes) + string_handle = ops.convert_to_tensor(string_handle, dtype=dtypes.string) + iterator_resource = gen_dataset_ops.iterator_from_string_handle_v2( + string_handle, + output_types=structure.get_flat_tensor_types(output_structure), + output_shapes=structure.get_flat_tensor_shapes(output_structure)) + return Iterator(iterator_resource, None, output_types, output_shapes, + output_classes) + + @property + def initializer(self): + """A `tf.Operation` that should be run to initialize this iterator. + + Returns: + A `tf.Operation` that should be run to initialize this iterator + + Raises: + ValueError: If this iterator initializes itself automatically. + """ + if self._initializer is not None: + return self._initializer + else: + # TODO(mrry): Consider whether one-shot iterators should have + # initializers that simply reset their state to the beginning. + raise ValueError( + "The iterator does not have an initializer. This means it was likely " + "created using `tf.data.Dataset.make_one_shot_iterator()`. For an " + "initializable iterator, use " + "`tf.data.Dataset.make_initializable_iterator()` instead.") + + def make_initializer(self, dataset, name=None): + """Returns a `tf.Operation` that initializes this iterator on `dataset`. + + Args: + dataset: A `Dataset` whose `element_spec` if compatible with this + iterator. + name: (Optional.) A name for the created operation. + + Returns: + A `tf.Operation` that can be run to initialize this iterator on the given + `dataset`. + + Raises: + TypeError: If `dataset` and this iterator do not have a compatible + `element_spec`. + """ + with ops.name_scope(name, "make_initializer") as name: + # NOTE(mrry): Cannot depend on `dataset_ops.get_legacy_output*()` due + # to that creating a circular dependency. + # pylint: disable=protected-access + dataset_output_types = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), + dataset.element_spec) + dataset_output_shapes = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), + dataset.element_spec) + dataset_output_classes = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), + dataset.element_spec) + # pylint: enable=protected-access + + nest.assert_same_structure(self.output_types, dataset_output_types) + nest.assert_same_structure(self.output_shapes, dataset_output_shapes) + for iterator_class, dataset_class in zip( + nest.flatten(self.output_classes), + nest.flatten(dataset_output_classes)): + if iterator_class is not dataset_class: + raise TypeError( + f"Expected output classes {self.output_classes!r} but got " + f"dataset with output classes {dataset_output_classes!r}.") + for iterator_dtype, dataset_dtype in zip( + nest.flatten(self.output_types), nest.flatten(dataset_output_types)): + if iterator_dtype != dataset_dtype: + raise TypeError( + f"Expected output types {self.output_types!r} but got dataset " + f"with output types {dataset_output_types!r}.") + for iterator_shape, dataset_shape in zip( + nest.flatten(self.output_shapes), nest.flatten( + dataset_output_shapes)): + if not iterator_shape.is_compatible_with(dataset_shape): + raise TypeError( + f"Expected output shapes compatible with {self.output_shapes!r} " + f"but got dataset with output shapes {dataset_output_shapes!r}.") + + # TODO(b/169442955): Investigate the need for this colocation constraint. + with ops.colocate_with(self._iterator_resource): + # pylint: disable=protected-access + return gen_dataset_ops.make_iterator( + dataset._variant_tensor, self._iterator_resource, name=name) + + def get_next(self, name=None): + """Returns the next element. + + In graph mode, you should typically call this method *once* and use its + result as the input to another computation. A typical loop will then call + `tf.Session.run` on the result of that computation. The loop will terminate + when the `Iterator.get_next()` operation raises + `tf.errors.OutOfRangeError`. The following skeleton shows how to use + this method when building a training loop: + + ```python + dataset = ... # A `tf.data.Dataset` object. + iterator = dataset.make_initializable_iterator() + next_element = iterator.get_next() + + # Build a TensorFlow graph that does something with each element. + loss = model_function(next_element) + optimizer = ... # A `tf.compat.v1.train.Optimizer` object. + train_op = optimizer.minimize(loss) + + with tf.compat.v1.Session() as sess: + try: + while True: + sess.run(train_op) + except tf.errors.OutOfRangeError: + pass + ``` + + NOTE: It is legitimate to call `Iterator.get_next()` multiple times, e.g. + when you are distributing different elements to multiple devices in a single + step. However, a common pitfall arises when users call `Iterator.get_next()` + in each iteration of their training loop. `Iterator.get_next()` adds ops to + the graph, and executing each op allocates resources (including threads); as + a consequence, invoking it in every iteration of a training loop causes + slowdown and eventual resource exhaustion. To guard against this outcome, we + log a warning when the number of uses crosses a fixed threshold of + suspiciousness. + + Args: + name: (Optional.) A name for the created operation. + + Returns: + A (nested) structure of values matching `tf.data.Iterator.element_spec`. + """ + self._get_next_call_count += 1 + if self._get_next_call_count > GET_NEXT_CALL_WARNING_THRESHOLD: + warnings.warn(GET_NEXT_CALL_WARNING_MESSAGE) + + # TODO(b/169442955): Investigate the need for this colocation constraint. + with ops.colocate_with(self._iterator_resource): + # pylint: disable=protected-access + flat_ret = gen_dataset_ops.iterator_get_next( + self._iterator_resource, + output_types=self._flat_tensor_types, + output_shapes=self._flat_tensor_shapes, + name=name) + return structure.from_tensor_list(self._element_spec, flat_ret) + + def get_next_as_optional(self): + # TODO(b/169442955): Investigate the need for this colocation constraint. + with ops.colocate_with(self._iterator_resource): + # pylint: disable=protected-access + return optional_ops._OptionalImpl( + gen_dataset_ops.iterator_get_next_as_optional( + self._iterator_resource, + output_types=structure.get_flat_tensor_types(self.element_spec), + output_shapes=structure.get_flat_tensor_shapes( + self.element_spec)), self.element_spec) + + def string_handle(self, name=None): + """Returns a string-valued `tf.Tensor` that represents this iterator. + + Args: + name: (Optional.) A name for the created operation. + + Returns: + A scalar `tf.Tensor` of type `tf.string`. + """ + if name is None: + return self._string_handle + else: + return gen_dataset_ops.iterator_to_string_handle( + self._iterator_resource, name=name) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_classes(iterator)`.") + def output_classes(self): + """Returns the class of each component of an element of this iterator. + + The expected values are `tf.Tensor` and `tf.sparse.SparseTensor`. + + Returns: + A (nested) structure of Python `type` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + self._element_spec) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_shapes(iterator)`.") + def output_shapes(self): + """Returns the shape of each component of an element of this iterator. + + Returns: + A (nested) structure of `tf.TensorShape` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + self._element_spec) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_types(iterator)`.") + def output_types(self): + """Returns the type of each component of an element of this iterator. + + Returns: + A (nested) structure of `tf.DType` objects corresponding to each component + of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + self._element_spec) + + @property + def element_spec(self): + """The type specification of an element of this iterator. + + For more information, + read [this guide](https://www.tensorflow.org/guide/data#dataset_structure). + + Returns: + A (nested) structure of `tf.TypeSpec` objects matching the structure of an + element of this iterator and specifying the type of individual components. + """ + + return self._element_spec + + # override + def _serialize_to_tensors(self): + serialized_iterator = gen_dataset_ops.serialize_iterator( + self._iterator_resource, + options_lib.ExternalStatePolicy.FAIL.value) + return {"_STATE": serialized_iterator} + + # override + def _restore_from_tensors(self, restored_tensors): + with ops.colocate_with(self._iterator_resource): + return [gen_dataset_ops.deserialize_iterator( + self._iterator_resource, restored_tensors["_STATE"])] + + +_uid_counter = 0 +_uid_lock = threading.Lock() + + +def _generate_shared_name(prefix): + with _uid_lock: + global _uid_counter + uid = _uid_counter + _uid_counter += 1 + return "{}{}".format(prefix, uid) + + +@tf_export("data.Iterator", v1=[]) +class IteratorBase( + collections_abc.Iterator, + trackable.Trackable, + composite_tensor.CompositeTensor, + metaclass=abc.ABCMeta): + """Represents an iterator of a `tf.data.Dataset`. + + `tf.data.Iterator` is the primary mechanism for enumerating elements of a + `tf.data.Dataset`. It supports the Python Iterator protocol, which means + it can be iterated over using a for-loop: + + >>> dataset = tf.data.Dataset.range(2) + >>> for element in dataset: + ... print(element) + tf.Tensor(0, shape=(), dtype=int64) + tf.Tensor(1, shape=(), dtype=int64) + + or by fetching individual elements explicitly via `get_next()`: + + >>> dataset = tf.data.Dataset.range(2) + >>> iterator = iter(dataset) + >>> print(iterator.get_next()) + tf.Tensor(0, shape=(), dtype=int64) + >>> print(iterator.get_next()) + tf.Tensor(1, shape=(), dtype=int64) + + In addition, non-raising iteration is supported via `get_next_as_optional()`, + which returns the next element (if available) wrapped in a + `tf.experimental.Optional`. + + >>> dataset = tf.data.Dataset.from_tensors(42) + >>> iterator = iter(dataset) + >>> optional = iterator.get_next_as_optional() + >>> print(optional.has_value()) + tf.Tensor(True, shape=(), dtype=bool) + >>> optional = iterator.get_next_as_optional() + >>> print(optional.has_value()) + tf.Tensor(False, shape=(), dtype=bool) + """ + + @abc.abstractproperty + def element_spec(self): + """The type specification of an element of this iterator. + + >>> dataset = tf.data.Dataset.from_tensors(42) + >>> iterator = iter(dataset) + >>> iterator.element_spec + tf.TensorSpec(shape=(), dtype=tf.int32, name=None) + + For more information, + read [this guide](https://www.tensorflow.org/guide/data#dataset_structure). + + Returns: + A (nested) structure of `tf.TypeSpec` objects matching the structure of an + element of this iterator, specifying the type of individual components. + """ + raise NotImplementedError("Iterator.element_spec") + + @abc.abstractmethod + def get_next(self): + """Returns the next element. + + >>> dataset = tf.data.Dataset.from_tensors(42) + >>> iterator = iter(dataset) + >>> print(iterator.get_next()) + tf.Tensor(42, shape=(), dtype=int32) + + Returns: + A (nested) structure of values matching `tf.data.Iterator.element_spec`. + + Raises: + `tf.errors.OutOfRangeError`: If the end of the iterator has been reached. + """ + raise NotImplementedError("Iterator.get_next()") + + @abc.abstractmethod + def get_next_as_optional(self): + """Returns the next element wrapped in `tf.experimental.Optional`. + + If the iterator has reached the end of the sequence, the returned + `tf.experimental.Optional` will have no value. + + >>> dataset = tf.data.Dataset.from_tensors(42) + >>> iterator = iter(dataset) + >>> optional = iterator.get_next_as_optional() + >>> print(optional.has_value()) + tf.Tensor(True, shape=(), dtype=bool) + >>> print(optional.get_value()) + tf.Tensor(42, shape=(), dtype=int32) + >>> optional = iterator.get_next_as_optional() + >>> print(optional.has_value()) + tf.Tensor(False, shape=(), dtype=bool) + + Returns: + A `tf.experimental.Optional` object representing the next element. + """ + raise NotImplementedError("Iterator.get_next_as_optional()") + + +@saveable_compat.legacy_saveable_name("ITERATOR") +class OwnedIterator(IteratorBase): + """An iterator producing tf.Tensor objects from a tf.data.Dataset. + + The iterator resource created through `OwnedIterator` is owned by the Python + object and the life time of the underlying resource is tied to the life time + of the `OwnedIterator` object. This makes `OwnedIterator` appropriate for use + in eager mode and inside of tf.functions. + """ + + def __init__(self, dataset=None, components=None, element_spec=None): + """Creates a new iterator from the given dataset. + + If `dataset` is not specified, the iterator will be created from the given + tensor components and element structure. In particular, the alternative for + constructing the iterator is used when the iterator is reconstructed from + it `CompositeTensor` representation. + + Args: + dataset: A `tf.data.Dataset` object. + components: Tensor components to construct the iterator from. + element_spec: A (nested) structure of `TypeSpec` objects that + represents the type specification of elements of the iterator. + + Raises: + ValueError: If `dataset` is not provided and either `components` or + `element_spec` is not provided. Or `dataset` is provided and either + `components` and `element_spec` is provided. + """ + super(OwnedIterator, self).__init__() + + if dataset is None: + if (components is None or element_spec is None): + raise ValueError( + "When `dataset` is not provided, both `components` and " + "`element_spec` must be specified.") + # pylint: disable=protected-access + self._element_spec = element_spec + self._flat_output_types = structure.get_flat_tensor_types( + self._element_spec) + self._flat_output_shapes = structure.get_flat_tensor_shapes( + self._element_spec) + self._components = components + self._iterator_resource, = components + else: + if (components is not None or element_spec is not None): + raise ValueError( + "When `dataset` is provided, `element_spec` and `components` must " + "not be specified.") + self._create_iterator(dataset) + + self._get_next_call_count = 0 + + def _create_iterator(self, dataset): + # pylint: disable=protected-access + dataset = dataset._apply_debug_options() + + # Store dataset reference to ensure that dataset is alive when this iterator + # is being used. For example, `tf.data.Dataset.from_generator` registers + # a few py_funcs that are needed in `self._next_internal`. If the dataset + # is deleted, this iterator crashes on `self.__next__(...)` call. + self._dataset = dataset + + ds_variant = dataset._variant_tensor + self._element_spec = dataset.element_spec + self._flat_output_types = structure.get_flat_tensor_types( + self._element_spec) + self._flat_output_shapes = structure.get_flat_tensor_shapes( + self._element_spec) + with ops.colocate_with(ds_variant): + self._iterator_resource = ( + gen_dataset_ops.anonymous_iterator_v3( + output_types=self._flat_output_types, + output_shapes=self._flat_output_shapes)) + if not context.executing_eagerly(): + # Add full type information to the graph so host memory types inside + # variants stay on CPU, e.g, ragged string tensors. + # TODO(b/224776031) Remove this when AnonymousIterateV3 can use + # (reverse) type inference and all other ops that are needed to + # provide type information to the AnonymousIterateV3 also support + # type inference (esp. cross-function type inference) instead of + # setting the full type information manually. + fulltype = type_utils.iterator_full_type_from_spec( + self._element_spec) + # fulltype is PRODUCT[ITERATOR[PRODUCT[...]]] + assert len(fulltype.args[0].args[0].args) == len( + self._flat_output_types) + self._iterator_resource.op.experimental_set_type(fulltype) + gen_dataset_ops.make_iterator(ds_variant, self._iterator_resource) + + def __iter__(self): + return self + + def next(self): # For Python 2 compatibility + return self.__next__() + + def _next_internal(self): + autograph_status = autograph_ctx.control_status_ctx().status + autograph_disabled = autograph_status == autograph_ctx.Status.DISABLED + if not context.executing_eagerly() and autograph_disabled: + self._get_next_call_count += 1 + if self._get_next_call_count > GET_NEXT_CALL_ERROR_THRESHOLD: + raise ValueError(GET_NEXT_CALL_ERROR_MESSAGE) + + if not context.executing_eagerly(): + # TODO(b/169442955): Investigate the need for this colocation constraint. + with ops.colocate_with(self._iterator_resource): + ret = gen_dataset_ops.iterator_get_next( + self._iterator_resource, + output_types=self._flat_output_types, + output_shapes=self._flat_output_shapes) + return structure.from_compatible_tensor_list(self._element_spec, ret) + + # TODO(b/77291417): This runs in sync mode as iterators use an error status + # to communicate that there is no more data to iterate over. + with context.execution_mode(context.SYNC): + ret = gen_dataset_ops.iterator_get_next( + self._iterator_resource, + output_types=self._flat_output_types, + output_shapes=self._flat_output_shapes) + + try: + # Fast path for the case `self._structure` is not a nested structure. + return self._element_spec._from_compatible_tensor_list(ret) # pylint: disable=protected-access + except AttributeError: + return structure.from_compatible_tensor_list(self._element_spec, ret) + + def _save(self): + external_state_policy = None + if ( + self._dataset + and self._dataset.options().experimental_external_state_policy + ): + external_state_policy = ( + self._dataset.options().experimental_external_state_policy.value + ) + state_variant = gen_dataset_ops.serialize_iterator( + self._iterator_resource, external_state_policy + ) + return parsing_ops.serialize_tensor(state_variant) + + def _restore(self, state): + state_variant = parsing_ops.parse_tensor(state, dtypes.variant) + return gen_dataset_ops.deserialize_iterator( + self._iterator_resource, state_variant + ) + + @property + def _type_spec(self): + return IteratorSpec(self.element_spec) + + def __next__(self): + try: + return self._next_internal() + except errors.OutOfRangeError: + raise StopIteration + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_classes(iterator)`.") + def output_classes(self): + """Returns the class of each component of an element of this iterator. + + The expected values are `tf.Tensor` and `tf.sparse.SparseTensor`. + + Returns: + A (nested) structure of Python `type` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + self._element_spec) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_shapes(iterator)`.") + def output_shapes(self): + """Returns the shape of each component of an element of this iterator. + + Returns: + A (nested) structure of `tf.TensorShape` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + self._element_spec) + + @property + @deprecation.deprecated( + None, "Use `tf.compat.v1.data.get_output_types(iterator)`.") + def output_types(self): + """Returns the type of each component of an element of this iterator. + + Returns: + A (nested) structure of `tf.DType` objects corresponding to each component + of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + self._element_spec) + + @property + def element_spec(self): + return self._element_spec + + def get_next(self): + return self._next_internal() + + def get_next_as_optional(self): + # TODO(b/169442955): Investigate the need for this colocation constraint. + with ops.colocate_with(self._iterator_resource): + # pylint: disable=protected-access + return optional_ops._OptionalImpl( + gen_dataset_ops.iterator_get_next_as_optional( + self._iterator_resource, + output_types=structure.get_flat_tensor_types(self.element_spec), + output_shapes=structure.get_flat_tensor_shapes( + self.element_spec)), self.element_spec) + + def _serialize_to_tensors(self): + serialized_iterator = None + if (self._dataset and + self._dataset.options().experimental_external_state_policy): + serialized_iterator = gen_dataset_ops.serialize_iterator( + self._iterator_resource, + self._dataset.options().experimental_external_state_policy.value) + else: + serialized_iterator = gen_dataset_ops.serialize_iterator( + self._iterator_resource, + options_lib.ExternalStatePolicy.FAIL.value) + return {"_STATE": serialized_iterator} + + def _restore_from_tensors(self, restored_tensors): + with ops.colocate_with(self._iterator_resource): + return [gen_dataset_ops.deserialize_iterator( + self._iterator_resource, restored_tensors["_STATE"])] + + def _copy_trackable_to_cpu(self, object_map): + """Implements checkpointing protocols for `Trackable`.""" + # Generate values to copy over + if self not in object_map: + # If self is not populated in object_map yet, instantiate the copy + if self._dataset is None: + object_map[self] = OwnedIterator(components=self._components, + element_spec=self._element_spec) + else: + object_map[self] = OwnedIterator(dataset=self._dataset) + + # Copy values from `self` to copy of `self` + serialized = self._serialize_to_tensors() + object_map[self]._restore_from_tensors(serialized) # pylint: disable=protected-access + + def __tf_tracing_type__(self, _): + return self._type_spec + + +@tf_export("data.IteratorSpec", v1=[]) +class IteratorSpec(type_spec.TypeSpec): + """Type specification for `tf.data.Iterator`. + + For instance, `tf.data.IteratorSpec` can be used to define a tf.function that + takes `tf.data.Iterator` as an input argument: + + >>> @tf.function(input_signature=[tf.data.IteratorSpec( + ... tf.TensorSpec(shape=(), dtype=tf.int32, name=None))]) + ... def square(iterator): + ... x = iterator.get_next() + ... return x * x + >>> dataset = tf.data.Dataset.from_tensors(5) + >>> iterator = iter(dataset) + >>> print(square(iterator)) + tf.Tensor(25, shape=(), dtype=int32) + + Attributes: + element_spec: A (nested) structure of `tf.TypeSpec` objects that represents + the type specification of the iterator elements. + """ + + __slots__ = ["_element_spec"] + + def __init__(self, element_spec): + self._element_spec = element_spec + + @property + def value_type(self): + return OwnedIterator + + def _serialize(self): + return (self._element_spec,) + + @property + def _component_specs(self): + return (tensor.TensorSpec([], dtypes.resource),) + + def _to_components(self, value): + return (value._iterator_resource,) # pylint: disable=protected-access + + def _from_components(self, components): + return OwnedIterator( + dataset=None, + components=components, + element_spec=self._element_spec) + + @staticmethod + def from_value(value): + return IteratorSpec(value.element_spec) # pylint: disable=protected-access + + +# TODO(b/71645805): Expose trackable stateful objects from dataset. +class _IteratorSaveable(BaseSaverBuilder.SaveableObject): + """SaveableObject for saving/restoring iterator state.""" + + def __init__( + self, + iterator_resource, + name, + external_state_policy=options_lib.ExternalStatePolicy.FAIL): + serialized_iterator = gen_dataset_ops.serialize_iterator( + iterator_resource, external_state_policy=external_state_policy.value) + specs = [ + BaseSaverBuilder.SaveSpec( + serialized_iterator, + "", + name + "_STATE", + device=iterator_resource.device) + ] + super(_IteratorSaveable, self).__init__(iterator_resource, specs, name) + + def restore(self, restored_tensors, restored_shapes): + with ops.colocate_with(self.op): + return gen_dataset_ops.deserialize_iterator(self.op, restored_tensors[0]) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + IteratorSpec, struct_pb2.TypeSpecProto.DATA_ITERATOR_SPEC + ) +) + + +@deprecation.deprecated( + None, "Use `tf.data.Iterator.get_next_as_optional()` instead.") +@tf_export("data.experimental.get_next_as_optional") +def get_next_as_optional(iterator): + """Returns a `tf.experimental.Optional` with the next element of the iterator. + + If the iterator has reached the end of the sequence, the returned + `tf.experimental.Optional` will have no value. + + Args: + iterator: A `tf.data.Iterator`. + + Returns: + A `tf.experimental.Optional` object which either contains the next element + of the iterator (if it exists) or no value. + """ + return iterator.get_next_as_optional() + + +_pywrap_utils.RegisterType("OwnedIterator", OwnedIterator) +iterator_autograph.register_overrides() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/load_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/load_op.py new file mode 100644 index 0000000000000000000000000000000000000000..bb25e08feb7060649bdc5b4cc28bba41c874d116 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/load_op.py @@ -0,0 +1,178 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of LoadDataset in Python.""" +import multiprocessing +import os + +from google.protobuf import message +from google.protobuf import text_format +from tensorflow.core.protobuf import snapshot_pb2 +from tensorflow.python.data.experimental.service import _pywrap_snapshot_utils +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.platform import gfile +# TODO(b/238903802): Use TypeSpec serialization methods directly. +from tensorflow.python.saved_model import nested_structure_coder + + +def _load(path, element_spec, compression, reader_func): + """Loads dataset from tf.data snapshot.""" + + def _get_distributed_snapshot_metadata(): + """Reads the distributed snapshot metadata. + + Returns: + DistributedSnapshotMetadata if the snapshot is a distributed snapshot. + Returns None if it is a non-distributed snapshot. + """ + try: + with gfile.GFile( + _pywrap_snapshot_utils.TF_DATA_SnapshotMetadataFilePath(path), "r" + ) as f: + return text_format.ParseLines( + f, snapshot_pb2.DistributedSnapshotMetadata()) + except (text_format.ParseError, message.DecodeError, UnicodeDecodeError): + return None + + if reader_func is None: + reader_func = lambda datasets: datasets.interleave( # pylint:disable=g-long-lambda + lambda x: x, + cycle_length=multiprocessing.cpu_count(), + num_parallel_calls=dataset_ops.AUTOTUNE) + + if element_spec is None: + with gfile.GFile( + os.path.join(path, dataset_ops.DATASET_SPEC_FILENAME), "rb") as f: + encoded_spec = f.read() + element_spec = _parse_element_spec(encoded_spec) + + distributed_snapshot_metadata = _get_distributed_snapshot_metadata() + if distributed_snapshot_metadata: + _validate_snapshot( + path, distributed_snapshot_metadata, element_spec, compression) + return _load_distributed_snapshot( + path, distributed_snapshot_metadata, reader_func) + return _LoadDataset(path, element_spec, compression, reader_func) + + +def _load_distributed_snapshot(path, metadata, reader_func): + """Loads a distributed snapshot.""" + + chunks_dir = _pywrap_snapshot_utils.TF_DATA_CommittedChunksDirectory(path) + chunk_files = [ + os.path.join(chunks_dir, f) for f in gfile.ListDirectory(chunks_dir)] + dataset = dataset_ops.Dataset.from_tensor_slices(chunk_files) + dataset = dataset.map( + lambda chunk_file: _SnapshotChunkDataset( # pylint:disable=g-long-lambda + chunk_file, + element_spec=_parse_element_spec(metadata.element_spec), + compression=metadata.compression)) + return reader_func(dataset) + + +class _LoadDataset(dataset_ops.DatasetSource): + """A dataset that loads previously saved dataset.""" + + def __init__(self, path, element_spec, compression, reader_func): + self._path = path + self._element_spec = element_spec + self._compression = compression + self._reader_func = structured_function.StructuredFunctionWrapper( + reader_func, + "load()", + # Dataset of datasets of input elements + input_structure=dataset_ops.DatasetSpec( + dataset_ops.DatasetSpec(self._element_spec))) + + variant_tensor = ged_ops.load_dataset( + path, + reader_func_other_args=self._reader_func.function.captured_inputs, + compression=compression, + reader_func=self._reader_func.function, + **self._flat_structure) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +class _SnapshotChunkDataset(dataset_ops.DatasetSource): + """A dataset for one chunk file from a tf.data distributed snapshot.""" + + def __init__(self, chunk_file, element_spec, compression): + self._chunk_file = chunk_file + self._element_spec = element_spec + variant_tensor = ged_ops.snapshot_chunk_dataset( + chunk_file, + compression=compression, + **self._flat_structure) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return self._element_spec + + +def _validate_snapshot(path, metadata, element_spec, compression): + """Validates a tf.data distributed snapshot. + + Args: + path: Root path of the distributed snapshot. + metadata: The DistributedSnapshotMetadata of the snapshot. + element_spec: Dataset element_spec. + compression: Compression method used for saving. + + Raises: + ValueError if the snapshot is invalid. + """ + + if not gfile.Exists(path): + raise ValueError( + f"Failed to load tf.data snapshot at {path}: The snapshot directory " + "does not exist.") + + error_file = _pywrap_snapshot_utils.TF_DATA_SnapshotErrorFilePath(path) + if gfile.Exists(error_file): + with gfile.GFile(error_file, "r") as f: + raise ValueError( + f"Failed to load tf.data snapshot at {path}. The save job failed to " + f"write it. Status: {f.read()}") + + done_file = _pywrap_snapshot_utils.TF_DATA_SnapshotDoneFilePath(path) + if not gfile.Exists(done_file): + raise ValueError( + f"Failed to load tf.data snapshot at {path}. The save job has not " + "finished writing the snapshot.") + + snapshot_element_spec = _parse_element_spec(metadata.element_spec) + if element_spec and element_spec != snapshot_element_spec: + raise ValueError( + f"Failed to load tf.data snapshot at {path}. User specified " + f"element_spec {element_spec}, but the actual element_spec is " + f"{snapshot_element_spec}.") + + if compression and compression != metadata.compression: + raise ValueError( + f"Failed to load tf.data snapshot at {path}. User specified " + f"compression {compression}, but the actual compression is " + f"{metadata.compression}.") + + +def _parse_element_spec(encoded_element_spec): + struct_pb = nested_structure_coder.struct_pb2.StructuredValue() + struct_pb.ParseFromString(encoded_element_spec) + return nested_structure_coder.decode_proto(struct_pb) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/map_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/map_op.py new file mode 100644 index 0000000000000000000000000000000000000000..1751ac8d21948868d0f0495f8e32ead371d7ee2a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/map_op.py @@ -0,0 +1,182 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.map`.""" + +import warnings + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import debug_mode +from tensorflow.python.data.ops import structured_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _map_v2(input_dataset, # pylint: disable=unused-private-name + map_func, + num_parallel_calls=None, + deterministic=None, + name=None): + """See `Dataset.map()` for details.""" + if num_parallel_calls is None or debug_mode.DEBUG_MODE: + if deterministic is not None and not debug_mode.DEBUG_MODE: + warnings.warn("The `deterministic` argument has no effect unless the " + "`num_parallel_calls` argument is specified.") + return _MapDataset( + input_dataset, map_func, preserve_cardinality=True, name=name) + else: + return _ParallelMapDataset( + input_dataset, + map_func, + num_parallel_calls=num_parallel_calls, + deterministic=deterministic, + preserve_cardinality=True, + name=name) + + +def _map_v1(input_dataset, # pylint: disable=unused-private-name + map_func, + num_parallel_calls=None, + deterministic=None): + """See `Dataset.map()` for details.""" + if num_parallel_calls is None or debug_mode.DEBUG_MODE: + return dataset_ops.DatasetV1Adapter( + _MapDataset(input_dataset, map_func, preserve_cardinality=False)) + else: + return dataset_ops.DatasetV1Adapter( + _ParallelMapDataset( + input_dataset, + map_func, + num_parallel_calls, + deterministic, + preserve_cardinality=False)) + + +def _map_v1_with_legacy_function( # pylint: disable=unused-private-name + input_dataset, + map_func, + num_parallel_calls=None, + deterministic=None): + """See `Dataset.map()` for details.""" + if num_parallel_calls is None: + if deterministic is not None: + warnings.warn("The `deterministic` argument has no effect unless the " + "`num_parallel_calls` argument is specified.") + return dataset_ops.DatasetV1Adapter( + _MapDataset( + input_dataset, + map_func, + preserve_cardinality=False, + use_legacy_function=True)) + else: + return dataset_ops.DatasetV1Adapter( + _ParallelMapDataset( + input_dataset, + map_func, + num_parallel_calls, + deterministic, + preserve_cardinality=False, + use_legacy_function=True)) + + +class _MapDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over elements in its input.""" + + def __init__(self, + input_dataset, + map_func, + use_inter_op_parallelism=True, + preserve_cardinality=True, + use_legacy_function=False, + name=None): + self._input_dataset = input_dataset + self._use_inter_op_parallelism = use_inter_op_parallelism + self._preserve_cardinality = preserve_cardinality + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, + self._transformation_name(), + dataset=input_dataset, + use_legacy_function=use_legacy_function) + self._name = name + variant_tensor = gen_dataset_ops.map_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, + f=self._map_func.function, + use_inter_op_parallelism=self._use_inter_op_parallelism, + preserve_cardinality=self._preserve_cardinality, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._map_func.output_structure + + def _transformation_name(self): + return "Dataset.map()" + + +class _ParallelMapDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over elements in its input in parallel.""" + + def __init__(self, + input_dataset, + map_func, + num_parallel_calls, + deterministic, + use_inter_op_parallelism=True, + preserve_cardinality=False, + use_legacy_function=False, + name=None): + """See `Dataset.map()` for details.""" + self._input_dataset = input_dataset + self._use_inter_op_parallelism = use_inter_op_parallelism + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, + self._transformation_name(), + dataset=input_dataset, + use_legacy_function=use_legacy_function) + if deterministic is None: + self._deterministic = "default" + elif deterministic: + self._deterministic = "true" + else: + self._deterministic = "false" + self._preserve_cardinality = preserve_cardinality + self._num_parallel_calls = ops.convert_to_tensor( + num_parallel_calls, dtype=dtypes.int64, name="num_parallel_calls") + self._name = name + variant_tensor = gen_dataset_ops.parallel_map_dataset_v2( + input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, + f=self._map_func.function, + num_parallel_calls=self._num_parallel_calls, + deterministic=self._deterministic, + use_inter_op_parallelism=self._use_inter_op_parallelism, + preserve_cardinality=self._preserve_cardinality, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._map_func.output_structure + + def _transformation_name(self): + return "Dataset.map()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/multi_device_iterator_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/multi_device_iterator_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc5ed7a334f83f551f423324de667af71aaa460 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/multi_device_iterator_ops.py @@ -0,0 +1,582 @@ +# 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. +# ============================================================================== +"""Python wrapper for prefetching_ops.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import options as options_lib +from tensorflow.python.data.ops import prefetch_op +from tensorflow.python.data.util import structure +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_utils +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import functional_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import resource_variable_ops + + +class _PerDeviceGenerator(dataset_ops.DatasetV2): + """A `dummy` generator dataset.""" + + def __init__(self, shard_num, multi_device_iterator_resource, incarnation_id, + source_device, element_spec, iterator_is_anonymous): + self._element_spec = element_spec + + multi_device_iterator_string_handle = ( + gen_dataset_ops.multi_device_iterator_to_string_handle( + multi_device_iterator_resource)) + + # TODO(b/124254153): Enable autograph once the overhead is low enough. + @def_function.function(autograph=False) # Pure graph code. + def _init_func(): + return multi_device_iterator_string_handle + + init_func_concrete = _init_func.get_concrete_function() + + # TODO(b/124254153): Enable autograph once the overhead is low enough. + @def_function.function(autograph=False) # Pure graph code. + def _remote_init_func(): + return functional_ops.remote_call( + target=source_device, + args=init_func_concrete.captured_inputs, + Tout=[dtypes.string], + f=init_func_concrete) + + self._init_func = _remote_init_func.get_concrete_function() + self._init_captured_args = self._init_func.captured_inputs + + # TODO(b/124254153): Enable autograph once the overhead is low enough. + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)], + autograph=False) # Pure graph code. + def _next_func(string_handle): + # pylint: disable=protected-access + multi_device_iterator = ( + gen_dataset_ops.multi_device_iterator_from_string_handle( + string_handle=string_handle, + output_types=structure.get_flat_tensor_types(self._element_spec), + output_shapes=structure.get_flat_tensor_shapes( + self._element_spec))) + return gen_dataset_ops.multi_device_iterator_get_next_from_shard( + multi_device_iterator=multi_device_iterator, + shard_num=shard_num, + incarnation_id=incarnation_id, + output_types=structure.get_flat_tensor_types(self._element_spec), + output_shapes=structure.get_flat_tensor_shapes(self._element_spec)) + + next_func_concrete = _next_func.get_concrete_function() + + # TODO(b/124254153): Enable autograph once the overhead is low enough. + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)], + experimental_attributes={"experimental_ints_on_device": True}, + autograph=False) # Pure graph code. + def _remote_next_func(string_handle): + return_values = functional_ops.remote_call( + target=source_device, + args=[string_handle] + next_func_concrete.captured_inputs, + Tout=structure.get_flat_tensor_types(self._element_spec), + f=next_func_concrete) + # Add full type information to the graph so that the RemoteCall op + # can determine for each of its outputs whether or not they are ragged + # tensors (or other types that use variants) that contain strings + # (or other host memory types). Then RemoteCall can + # appropriately set AllocatorAttributes to control copies so + # strings/host memory types stay on CPU. + fulltype_list = type_utils.fulltypes_for_flat_tensors(self._element_spec) + fulltype = type_utils.fulltype_list_to_product(fulltype_list) + for return_value in return_values: + return_value.op.experimental_set_type(fulltype) + return return_values + + self._next_func = _remote_next_func.get_concrete_function() + self._next_captured_args = self._next_func.captured_inputs + + if iterator_is_anonymous: + self._next_captured_args = self._next_captured_args + [ + multi_device_iterator_resource + ] + + self._incarnation_id_index = -1 + for i, arg in enumerate(self._next_captured_args): + if arg is incarnation_id: + self._incarnation_id_index = i + + # TODO(b/124254153): Enable autograph once the overhead is low enough. + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)], + autograph=False) # Pure graph code. + def _finalize_func(unused_string_handle): + return array_ops.constant(0, dtypes.int64) + + finalize_func_concrete = _finalize_func.get_concrete_function() + + # TODO(b/124254153): Enable autograph once the overhead is low enough. + @def_function.function( + input_signature=[tensor_spec.TensorSpec([], dtypes.string)], + autograph=False) # Pure graph code. + def _remote_finalize_func(string_handle): + return functional_ops.remote_call( + target=source_device, + args=[string_handle] + finalize_func_concrete.captured_inputs, + Tout=[dtypes.int64], + f=finalize_func_concrete) + + self._finalize_func = _remote_finalize_func.get_concrete_function() + self._finalize_captured_args = self._finalize_func.captured_inputs + + variant_tensor = gen_dataset_ops.generator_dataset( + self._init_captured_args, + self._next_captured_args, + self._finalize_captured_args, + init_func=self._init_func, + next_func=self._next_func, + finalize_func=self._finalize_func, + **self._flat_structure) + super(_PerDeviceGenerator, self).__init__(variant_tensor) + + def _inputs(self): + # TODO(b/116506223): Determine which datasets should be used as inputs here. + return [] + + @property + def element_spec(self): + return self._element_spec + + +class _ReincarnatedPerDeviceGenerator(dataset_ops.DatasetV2): + """Creates a _PerDeviceGenerator-like dataset with a new incarnation_id. + + Re-uses the functions from the provided per_device_dataset and just switches + out the function argument corresponding to the incarnation_id. + """ + + def __init__(self, per_device_dataset, incarnation_id): + # pylint: disable=protected-access + self._element_spec = per_device_dataset.element_spec + self._init_func = per_device_dataset._init_func + self._init_captured_args = self._init_func.captured_inputs + + self._next_func = per_device_dataset._next_func + self._next_captured_args = per_device_dataset._next_captured_args + # The captured arguments to the next_func are string_handle, incarnation_id. + # We update the incarnation id to the new one. + self._next_captured_args[ + per_device_dataset._incarnation_id_index] = incarnation_id + + self._finalize_func = per_device_dataset._finalize_func + self._finalize_captured_args = per_device_dataset._finalize_captured_args + + variant_tensor = gen_dataset_ops.generator_dataset( + self._init_captured_args, + self._next_captured_args, + self._finalize_captured_args, + init_func=self._init_func, + next_func=self._next_func, + finalize_func=self._finalize_func, + **self._flat_structure) + super(_ReincarnatedPerDeviceGenerator, self).__init__(variant_tensor) + + def _inputs(self): + # TODO(b/116506223): Determine which datasets should be used as inputs here. + return [] + + @property + def element_spec(self): + return self._element_spec + + +def _create_device_dataset(prototype_ds, incarnation_id, prefetch_buffer_size, + experimental_slack): + """Uses _prototype_device_datasets[i] to build a dataset for the device.""" + ds = _ReincarnatedPerDeviceGenerator(prototype_ds, incarnation_id) + if prefetch_buffer_size > 0: + if experimental_slack: + ds = prefetch_op._PrefetchDataset( # pylint: disable=protected-access + ds, prefetch_buffer_size, slack_period=1) + else: + ds = ds.prefetch(prefetch_buffer_size) + return ds + + +class MultiDeviceIterator: + """An iterator over multiple devices.""" + + def __init__(self, + dataset, + devices, + max_buffer_size=1, + prefetch_buffer_size=1, + source_device="/cpu:0"): + """Constructs a MultiDeviceIterator. + + Args: + dataset: The input dataset to be iterated over. + devices: The list of devices to fetch data to. + max_buffer_size: Maximum size of the host side per device buffer to keep. + prefetch_buffer_size: if > 0, then we setup a buffer on each device to + prefetch into. + source_device: The host device to place the `dataset` on. In order to + prevent deadlocks, if the prefetch_buffer_size is greater than the + max_buffer_size, we set the max_buffer_size to prefetch_buffer_size. + """ + options = options_lib.Options() + options.experimental_distribute.num_devices = len(devices) + # If `prefetch_buffer_size` is 0, we turn off the `inject_prefetch` + # optimization to prevent potentially introducing asynchrony. + if prefetch_buffer_size == 0: + options.experimental_optimization.inject_prefetch = False + dataset = dataset.with_options(options) + self._dataset = dataset._apply_debug_options() # pylint: disable=protected-access + self._experimental_slack = dataset.options().experimental_slack + self._devices = devices + self._source_device = source_device + self._source_device_tensor = ops.convert_to_tensor(source_device) + self._max_buffer_size = max_buffer_size + self._prefetch_buffer_size = prefetch_buffer_size + + if self._prefetch_buffer_size > self._max_buffer_size: + self._max_buffer_size = self._prefetch_buffer_size + + # Create the MultiDeviceIterator. + with ops.device(self._source_device): + # TODO(b/121378567): Get rid of this shared_name hack. + shared_name = "" + if context.executing_eagerly(): + shared_name = context.anonymous_name() + self._multi_device_iterator_resource = ( + gen_dataset_ops.multi_device_iterator( + devices=self._devices, + shared_name=shared_name, + container="", + **self._dataset._flat_structure)) # pylint: disable=protected-access + if context.executing_eagerly(): + # Delete the resource when this object is deleted + self._resource_deleter = resource_variable_ops.EagerResourceDeleter( + handle=self._multi_device_iterator_resource, + handle_device=self._source_device) + + # The incarnation ID is used to ensure consistency between the per-device + # iterators and the multi-device iterator. + self._incarnation_id = gen_dataset_ops.multi_device_iterator_init( + self._dataset._variant_tensor, # pylint: disable=protected-access + self._multi_device_iterator_resource, + max_buffer_size=self._max_buffer_size) + + self._prototype_device_datasets = [] + for i, device in enumerate(self._devices): + with ops.device(device): + ds = _PerDeviceGenerator( + i, + self._multi_device_iterator_resource, + self._incarnation_id, + self._source_device_tensor, + self._dataset.element_spec, + iterator_is_anonymous=False) + self._prototype_device_datasets.append(ds) + + # TODO(rohanj): Explore the possibility of the MultiDeviceIterator to + # initialize the device side of the pipeline. This would allow the + # MultiDeviceIterator to choose, for example, to move some transformations + # into the device side from its input. It might be useful in rewriting. + # Create the per device iterators. + self._device_iterators = [] + for i, device in enumerate(self._devices): + with ops.device(device): + ds = _create_device_dataset(self._prototype_device_datasets[i], + self._incarnation_id, + self._prefetch_buffer_size, + self._experimental_slack) + if context.executing_eagerly(): + self._device_iterators.append(dataset_ops.make_one_shot_iterator(ds)) + else: + self._device_iterators.append( + dataset_ops.make_initializable_iterator(ds)) + + if not context.executing_eagerly(): + device_iterator_initializers = [ + iterator.initializer for iterator in self._device_iterators + ] + self._initializer = control_flow_ops.group(*device_iterator_initializers) + + def get_next(self, device=None): + """Returns the next element given a `device`, else returns all in a list.""" + if device is not None: + index = self._devices.index(device) + return self._device_iterators[index].get_next() + + result = [] + for i, device in enumerate(self._devices): + with ops.device(device): + result.append(self._device_iterators[i].get_next()) + return result + + def get_next_as_optional(self): + result = [] + for i, device in enumerate(self._devices): + with ops.device(device): + result.append(self._device_iterators[i].get_next_as_optional()) + return result + + @property + def initializer(self): + if context.executing_eagerly(): + return control_flow_ops.no_op() + return self._initializer + + def _eager_reset(self): + """Resets the MultiDeviceIterator in eager mode.""" + if not ops.executing_eagerly_outside_functions(): + raise ValueError( + "Resetting a multi-device iterator is only supported in the eager " + "mode.") + # pylint: disable=protected-access + self._incarnation_id = gen_dataset_ops.multi_device_iterator_init( + self._dataset._variant_tensor, + self._multi_device_iterator_resource, + max_buffer_size=self._max_buffer_size) + for i, device in enumerate(self._devices): + with ops.device(device): + ds = _create_device_dataset(self._prototype_device_datasets[i], + self._incarnation_id, + self._prefetch_buffer_size, + self._experimental_slack) + # Reset the device iterator resources with the new dataset. + ds_variant = ds._variant_tensor + gen_dataset_ops.make_iterator( + ds_variant, self._device_iterators[i]._iterator_resource) + + @property + def element_spec(self): + return self._dataset.element_spec + + +class MultiDeviceIteratorSpec(type_spec.TypeSpec): + """Type specification for `OwnedMultiDeviceIterator`.""" + + __slots__ = ["_devices", "_source_device", "_element_spec"] + + def __init__(self, devices, source_device, element_spec): + self._devices = devices + self._source_device = source_device + self._element_spec = element_spec + + @property + def value_type(self): + return OwnedMultiDeviceIterator + + def _serialize(self): + return (tuple(self._devices), self._source_device, self._element_spec) + + @property + def _component_specs(self): + specs = [ + tensor_spec.TensorSpec([], dtypes.resource), + ] + for _ in range(len(self._devices)): + specs.append(iterator_ops.IteratorSpec(self._element_spec)) + return specs + + def _to_components(self, value): + # pylint: disable=protected-access + c = [value._multi_device_iterator_resource] + c.extend(value._device_iterators) + return c + + def _from_components(self, components): + return OwnedMultiDeviceIterator( + dataset=None, + devices=self._devices, + source_device=self._source_device, + components=components, + element_spec=self._element_spec) + + @staticmethod + def from_value(value): + # pylint: disable=protected-access + return MultiDeviceIteratorSpec( + value._devices, + value._source_device, + value.element_spec) + + +class OwnedMultiDeviceIterator(composite_tensor.CompositeTensor): + """An iterator over multiple devices. + + The multi-device iterator resource created through `OwnedMultiDeviceIterator` + is owned by the Python object and the life time of the underlying resource is + tied to the life time of the `OwnedMultiDeviceIterator` object. This makes + `OwnedMultiDeviceIterator` appropriate for use in eager mode and inside of + tf.functions. + """ + + def __init__(self, + dataset=None, + devices=None, + max_buffer_size=1, + prefetch_buffer_size=1, + source_device="/cpu:0", + components=None, + element_spec=None): + """Constructs an owned MultiDeviceIterator object. + + Args: + dataset: The input dataset to be iterated over. + devices: (Required.) The list of devices to fetch data to. + max_buffer_size: Maximum size of the host side per device buffer to keep. + prefetch_buffer_size: if > 0, then we setup a buffer on each device to + prefetch into. + source_device: The host device to place the `dataset` on. In order to + prevent deadlocks, if the prefetch_buffer_size is greater than the + max_buffer_size, we set the max_buffer_size to prefetch_buffer_size. + components: Tensor components to construct the MultiDeviceIterator from. + element_spec: A (nested) structure of `tf.TypeSpec` objects that + represents the type specification of elements of the iterator. + + Raises: + RuntimeError: If executed in graph mode or outside of function building + mode. + ValueError: If any of the following happens: + - `devices` is `None` + - `dataset` is `None` and either `components` or `element_spec` is + `None` + - `dataset` is not None and either `components` or `element_spec` is + provided + """ + if not context.executing_eagerly() and not ops.inside_function(): + raise RuntimeError("OwnedMultiDeviceIterator is only supported inside of " + "tf.function or when eager execution is enabled.") + if devices is None: + raise ValueError("`devices` must be provided.") + + if dataset is None: + if (components is None or element_spec is None): + raise ValueError( + "When `dataset` is not provided, both `components` and " + "`element_spec` must be specified.") + self._element_spec = element_spec + self._devices = devices + self._source_device = source_device + self._multi_device_iterator_resource = components[0] + self._device_iterators = components[1:] + else: + if (components is not None or element_spec is not None): + raise ValueError( + "When `dataset` is provided, `element_spec` and `components` must " + "not be specified.") + options = options_lib.Options() + options.experimental_distribute.num_devices = len(devices) + # If `prefetch_buffer_size` is 0, we turn off the `inject_prefetch` + # optimization to prevent potentially introducing asynchrony. + if prefetch_buffer_size == 0: + options.experimental_optimization.inject_prefetch = False + dataset = dataset.with_options(options) + dataset = dataset._apply_debug_options() # pylint: disable=protected-access + self._element_spec = dataset.element_spec + experimental_slack = dataset.options().experimental_slack + self._devices = devices + self._source_device = source_device + source_device_tensor = ops.convert_to_tensor(self._source_device) + + if prefetch_buffer_size > max_buffer_size: + max_buffer_size = prefetch_buffer_size + + # Create the MultiDeviceIterator. + with ops.device(self._source_device): + self._multi_device_iterator_resource = ( + gen_dataset_ops.anonymous_multi_device_iterator_v3( + devices=self._devices, **dataset._flat_structure)) # pylint: disable=protected-access + + # The incarnation ID is used to ensure consistency between the + # per-device iterators and the multi-device iterator. + incarnation_id = gen_dataset_ops.multi_device_iterator_init( + dataset._variant_tensor, # pylint: disable=protected-access + self._multi_device_iterator_resource, + max_buffer_size=max_buffer_size) + + prototype_device_datasets = [] + for i, device in enumerate(self._devices): + with ops.device(device): + ds = _PerDeviceGenerator( + i, + self._multi_device_iterator_resource, + incarnation_id, + source_device_tensor, + dataset.element_spec, + iterator_is_anonymous=True, + ) + prototype_device_datasets.append(ds) + + # TODO(rohanj): Explore the possibility of the MultiDeviceIterator to + # initialize the device side of the pipeline. This would allow the + # MultiDeviceIterator to choose, for example, to move some transformations + # into the device side from its input. It might be useful in rewriting. + # Create the per device iterators. + self._device_iterators = [] + + for i, device in enumerate(self._devices): + with ops.device(device): + ds = _create_device_dataset(prototype_device_datasets[i], + incarnation_id, prefetch_buffer_size, + experimental_slack) + iterator = iter(ds) + self._device_iterators.append(iterator) + + def get_next(self, device=None): + """Returns the next element given a `device`, else returns all in a list.""" + if device is not None: + index = self._devices.index(device) + return self._device_iterators[index].get_next() + + result = [] + for i, device in enumerate(self._devices): + with ops.device(device): + result.append(self._device_iterators[i].get_next()) + return result + + def __iter__(self): + return self + + def next(self): + return self.__next__() + + def __next__(self): + try: + return self.get_next() + except errors.OutOfRangeError: + raise StopIteration + + def get_next_as_optional(self): + result = [] + for i, device in enumerate(self._devices): + with ops.device(device): + result.append(self._device_iterators[i].get_next_as_optional()) + return result + + @property + def element_spec(self): + return self._element_spec + + @property + def _type_spec(self): + return MultiDeviceIteratorSpec(self._devices, self._source_device, + self._element_spec) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/optional_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/optional_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..01ba395e3745166d1c57541129f478ef6c8c871c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/optional_ops.py @@ -0,0 +1,271 @@ +# 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. +# ============================================================================== +"""A type for representing values that may or may not exist.""" +import abc + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.data.util import structure +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import gen_optional_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("experimental.Optional", "data.experimental.Optional") +@deprecation.deprecated_endpoints("data.experimental.Optional") +class Optional(composite_tensor.CompositeTensor, metaclass=abc.ABCMeta): + """Represents a value that may or may not be present. + + A `tf.experimental.Optional` can represent the result of an operation that may + fail as a value, rather than raising an exception and halting execution. For + example, `tf.data.Iterator.get_next_as_optional()` returns a + `tf.experimental.Optional` that either contains the next element of an + iterator if one exists, or an "empty" value that indicates the end of the + sequence has been reached. + + `tf.experimental.Optional` can only be used with values that are convertible + to `tf.Tensor` or `tf.CompositeTensor`. + + One can create a `tf.experimental.Optional` from a value using the + `from_value()` method: + + >>> optional = tf.experimental.Optional.from_value(42) + >>> print(optional.has_value()) + tf.Tensor(True, shape=(), dtype=bool) + >>> print(optional.get_value()) + tf.Tensor(42, shape=(), dtype=int32) + + or without a value using the `empty()` method: + + >>> optional = tf.experimental.Optional.empty( + ... tf.TensorSpec(shape=(), dtype=tf.int32, name=None)) + >>> print(optional.has_value()) + tf.Tensor(False, shape=(), dtype=bool) + """ + + @abc.abstractmethod + def has_value(self, name=None): + """Returns a tensor that evaluates to `True` if this optional has a value. + + >>> optional = tf.experimental.Optional.from_value(42) + >>> print(optional.has_value()) + tf.Tensor(True, shape=(), dtype=bool) + + Args: + name: (Optional.) A name for the created operation. + + Returns: + A scalar `tf.Tensor` of type `tf.bool`. + """ + raise NotImplementedError("Optional.has_value()") + + @abc.abstractmethod + def get_value(self, name=None): + """Returns the value wrapped by this optional. + + If this optional does not have a value (i.e. `self.has_value()` evaluates to + `False`), this operation will raise `tf.errors.InvalidArgumentError` at + runtime. + + >>> optional = tf.experimental.Optional.from_value(42) + >>> print(optional.get_value()) + tf.Tensor(42, shape=(), dtype=int32) + + Args: + name: (Optional.) A name for the created operation. + + Returns: + The wrapped value. + """ + raise NotImplementedError("Optional.get_value()") + + @abc.abstractproperty + def element_spec(self): + """The type specification of an element of this optional. + + >>> optional = tf.experimental.Optional.from_value(42) + >>> print(optional.element_spec) + tf.TensorSpec(shape=(), dtype=tf.int32, name=None) + + Returns: + A (nested) structure of `tf.TypeSpec` objects matching the structure of an + element of this optional, specifying the type of individual components. + """ + raise NotImplementedError("Optional.element_spec") + + @staticmethod + def empty(element_spec): + """Returns an `Optional` that has no value. + + NOTE: This method takes an argument that defines the structure of the value + that would be contained in the returned `Optional` if it had a value. + + >>> optional = tf.experimental.Optional.empty( + ... tf.TensorSpec(shape=(), dtype=tf.int32, name=None)) + >>> print(optional.has_value()) + tf.Tensor(False, shape=(), dtype=bool) + + Args: + element_spec: A (nested) structure of `tf.TypeSpec` objects matching the + structure of an element of this optional. + + Returns: + A `tf.experimental.Optional` with no value. + """ + return _OptionalImpl(gen_optional_ops.optional_none(), element_spec) + + @staticmethod + def from_value(value): + """Returns a `tf.experimental.Optional` that wraps the given value. + + >>> optional = tf.experimental.Optional.from_value(42) + >>> print(optional.has_value()) + tf.Tensor(True, shape=(), dtype=bool) + >>> print(optional.get_value()) + tf.Tensor(42, shape=(), dtype=int32) + + Args: + value: A value to wrap. The value must be convertible to `tf.Tensor` or + `tf.CompositeTensor`. + + Returns: + A `tf.experimental.Optional` that wraps `value`. + """ + with ops.name_scope("optional") as scope: + with ops.name_scope("value"): + element_spec = structure.type_spec_from_value(value) + encoded_value = structure.to_tensor_list(element_spec, value) + + return _OptionalImpl( + gen_optional_ops.optional_from_value(encoded_value, name=scope), + element_spec, + ) + + +class _OptionalImpl(Optional): + """Concrete implementation of `tf.experimental.Optional`. + + NOTE(mrry): This implementation is kept private, to avoid defining + `Optional.__init__()` in the public API. + """ + + def __init__(self, variant_tensor, element_spec): + super().__init__() + self._variant_tensor = variant_tensor + self._element_spec = element_spec + + def has_value(self, name=None): + with ops.colocate_with(self._variant_tensor): + return gen_optional_ops.optional_has_value( + self._variant_tensor, name=name + ) + + def get_value(self, name=None): + # TODO(b/110122868): Consolidate the restructuring logic with similar logic + # in `Iterator.get_next()` and `StructuredFunctionWrapper`. + with ops.name_scope(name, "OptionalGetValue", + [self._variant_tensor]) as scope: + with ops.colocate_with(self._variant_tensor): + result = gen_optional_ops.optional_get_value( + self._variant_tensor, + name=scope, + output_types=structure.get_flat_tensor_types(self._element_spec), + output_shapes=structure.get_flat_tensor_shapes(self._element_spec), + ) + # NOTE: We do not colocate the deserialization of composite tensors + # because not all ops are guaranteed to have non-GPU kernels. + return structure.from_tensor_list(self._element_spec, result) + + @property + def element_spec(self): + return self._element_spec + + @property + def _type_spec(self): + return OptionalSpec.from_value(self) + + +@tf_export( + "OptionalSpec", v1=["OptionalSpec", "data.experimental.OptionalStructure"]) +class OptionalSpec(type_spec.TypeSpec): + """Type specification for `tf.experimental.Optional`. + + For instance, `tf.OptionalSpec` can be used to define a tf.function that takes + `tf.experimental.Optional` as an input argument: + + >>> @tf.function(input_signature=[tf.OptionalSpec( + ... tf.TensorSpec(shape=(), dtype=tf.int32, name=None))]) + ... def maybe_square(optional): + ... if optional.has_value(): + ... x = optional.get_value() + ... return x * x + ... return -1 + >>> optional = tf.experimental.Optional.from_value(5) + >>> print(maybe_square(optional)) + tf.Tensor(25, shape=(), dtype=int32) + + Attributes: + element_spec: A (nested) structure of `TypeSpec` objects that represents the + type specification of the optional element. + """ + + __slots__ = ["_element_spec"] + + def __init__(self, element_spec): + super().__init__() + self._element_spec = element_spec + + @property + def value_type(self): + return _OptionalImpl + + def _serialize(self): + return (self._element_spec,) + + @property + def _component_specs(self): + return [tensor_spec.TensorSpec((), dtypes.variant)] + + def _to_components(self, value): + return [value._variant_tensor] # pylint: disable=protected-access + + def _from_components(self, flat_value): + # pylint: disable=protected-access + return _OptionalImpl(flat_value[0], self._element_spec) + + @staticmethod + def from_value(value): + return OptionalSpec(value.element_spec) + + def _to_legacy_output_types(self): + return self + + def _to_legacy_output_shapes(self): + return self + + def _to_legacy_output_classes(self): + return self + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + OptionalSpec, struct_pb2.TypeSpecProto.OPTIONAL_SPEC + ) +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/options.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/options.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6727516f48fc1ae5e02e8a26772ba0b4b11530 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/options.py @@ -0,0 +1,705 @@ +# 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. +# ============================================================================== +"""API for specifying `tf.data` options.""" + +import enum +import platform + +from absl import logging + +from tensorflow.core.framework import dataset_options_pb2 +from tensorflow.core.framework import model_pb2 +from tensorflow.python.data.ops import test_mode +from tensorflow.python.data.util import options as options_lib +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("data.experimental.AutotuneAlgorithm") +class AutotuneAlgorithm(enum.Enum): + """Represents the type of autotuning algorithm to use. + + DEFAULT: The default behavior is implementation specific and may change over + time. + + HILL_CLIMB: In each optimization step, this algorithm chooses the optimial + parameter and increases its value by 1. + + GRADIENT_DESCENT: In each optimization step, this algorithm updates the + parameter values in the optimal direction. + + MAX_PARALLELISM: Similar to HILL_CLIMB but uses a relaxed stopping condition, + allowing the optimization to oversubscribe the CPU. + + STAGE_BASED: In each optimization step, this algorithm chooses the worst + bottleneck parameter and increases its value by 1. + """ + DEFAULT = 0 + HILL_CLIMB = 1 + GRADIENT_DESCENT = 2 + MAX_PARALLELISM = 3 + STAGE_BASED = 4 + + @classmethod + def _to_proto(cls, obj): + if obj == cls.DEFAULT: + return model_pb2.AutotuneAlgorithm.DEFAULT + if obj == cls.HILL_CLIMB: + return model_pb2.AutotuneAlgorithm.HILL_CLIMB + if obj == cls.GRADIENT_DESCENT: + return model_pb2.AutotuneAlgorithm.GRADIENT_DESCENT + if obj == cls.MAX_PARALLELISM: + return model_pb2.AutotuneAlgorithm.MAX_PARALLELISM + if obj == cls.STAGE_BASED: + return model_pb2.AutotuneAlgorithm.STAGE_BASED + raise ValueError( + f"Invalid `obj.` Supported values include `DEFAULT`, `HILL_CLIMB` " + f"`GRADIENT_DESCENT`, and `STAGE_BASED`. Got {obj.name}.") + + @classmethod + def _from_proto(cls, pb): + if pb == model_pb2.AutotuneAlgorithm.DEFAULT: + return cls.DEFAULT + if pb == model_pb2.AutotuneAlgorithm.HILL_CLIMB: + return cls.HILL_CLIMB + if pb == model_pb2.AutotuneAlgorithm.GRADIENT_DESCENT: + return cls.GRADIENT_DESCENT + if pb == model_pb2.AutotuneAlgorithm.MAX_PARALLELISM: + return cls.MAX_PARALLELISM + if pb == model_pb2.AutotuneAlgorithm.STAGE_BASED: + return cls.STAGE_BASED + raise ValueError( + f"Invalid `pb.` Supported values include `DEFAULT`, `HILL_CLIMB`, " + f"`GRADIENT_DESCENT` and `STAGE_BASED`. Got {pb}.") + + +@tf_export("data.experimental.AutoShardPolicy") +class AutoShardPolicy(enum.IntEnum): + """Represents the type of auto-sharding to use. + + OFF: No sharding will be performed. + + AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding. + + 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. + + 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. + + HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated as a + placeholder to replace with `shard(num_workers, worker_index)`. + """ + + # LINT.IfChange + OFF = -1 + AUTO = 0 + FILE = 1 + DATA = 2 + HINT = 3 + # LINT.ThenChange(//tensorflow/python/data/experimental/ops/data_service_ops.py:tf_data_service_sharding_policy) + + @classmethod + def _to_proto(cls, obj): + """Convert enum to proto.""" + if obj == cls.OFF: + return dataset_options_pb2.AutoShardPolicy.OFF + if obj == cls.FILE: + return dataset_options_pb2.AutoShardPolicy.FILE + if obj == cls.DATA: + return dataset_options_pb2.AutoShardPolicy.DATA + if obj == cls.AUTO: + return dataset_options_pb2.AutoShardPolicy.AUTO + if obj == cls.HINT: + return dataset_options_pb2.AutoShardPolicy.HINT + raise ValueError( + f"Invalid `obj.` Supported values include `OFF`, `FILE`, `DATA`," + f"`AUTO`, and `HINT`. Got {obj.name}." + ) + + @classmethod + def _from_proto(cls, pb): + """Convert proto to enum.""" + if pb == dataset_options_pb2.AutoShardPolicy.OFF: + return cls.OFF + if pb == dataset_options_pb2.AutoShardPolicy.FILE: + return cls.FILE + if pb == dataset_options_pb2.AutoShardPolicy.DATA: + return cls.DATA + if pb == dataset_options_pb2.AutoShardPolicy.AUTO: + return cls.AUTO + if pb == dataset_options_pb2.AutoShardPolicy.HINT: + return cls.HINT + raise ValueError( + f"Invalid `pb.` Supported values include `OFF`, `FILE`, `DATA`," + f"`AUTO`, and `HINT`. Got {pb}." + ) + + +@tf_export("data.experimental.ExternalStatePolicy") +class ExternalStatePolicy(enum.Enum): + """Represents how to handle external state during serialization. + + See the `tf.data.Options.experimental_external_state_policy` documentation + for more information. + """ + WARN = 0 + IGNORE = 1 + FAIL = 2 + + @classmethod + def _to_proto(cls, obj): + """Convert enum to proto.""" + if obj == cls.IGNORE: + return dataset_options_pb2.ExternalStatePolicy.POLICY_IGNORE + if obj == cls.FAIL: + return dataset_options_pb2.ExternalStatePolicy.POLICY_FAIL + if obj == cls.WARN: + return dataset_options_pb2.ExternalStatePolicy.POLICY_WARN + raise ValueError( + f"Invalid `obj.` Supported values include `POLICY_IGNORE`," + f"`POLICY_FAIL`, `POLICY_WARN`. Got {obj.name}.") + + @classmethod + def _from_proto(cls, pb): + """Convert proto to enum.""" + if pb == dataset_options_pb2.ExternalStatePolicy.POLICY_IGNORE: + return cls.IGNORE + if pb == dataset_options_pb2.ExternalStatePolicy.POLICY_FAIL: + return cls.FAIL + if pb == dataset_options_pb2.ExternalStatePolicy.POLICY_WARN: + return cls.WARN + raise ValueError( + f"Invalid `pb.` Supported values include `POLICY_IGNORE`," + f"`POLICY_FAIL`, `POLICY_WARN`. Got {pb}.") + + +@tf_export("data.experimental.AutotuneOptions") +class AutotuneOptions(options_lib.OptionsBase): + """Represents options for autotuning dataset performance. + + ```python + options = tf.data.Options() + options.autotune.enabled = False + dataset = dataset.with_options(options) + ``` + """ + + enabled = options_lib.create_option( + name="enabled", + ty=bool, + docstring="Whether to automatically tune performance knobs. If None, " + "defaults to True.") + + cpu_budget = options_lib.create_option( + name="cpu_budget", + ty=int, + docstring="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. If None, " + "defaults to the number of schedulable CPU cores.") + + ram_budget = options_lib.create_option( + name="ram_budget", + ty=int, + docstring="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 None, defaults to half of the available RAM in " + "bytes.") + + autotune_algorithm = options_lib.create_option( + name="autotune_algorithm", + ty=AutotuneAlgorithm, + docstring="When autotuning is enabled (through `autotune`), determines " + "the algorithm to use.") + + def _to_proto(self): + pb = dataset_options_pb2.AutotuneOptions() + if self.enabled is not None: + pb.enabled = self.enabled + if self.cpu_budget is not None: + pb.cpu_budget = self.cpu_budget + if self.ram_budget is not None: + pb.ram_budget = self.ram_budget + if self.autotune_algorithm is not None: + pb.autotune_algorithm = AutotuneAlgorithm._to_proto( # pylint: disable=protected-access + self.autotune_algorithm) + return pb + + def _from_proto(self, pb): + if pb.WhichOneof("optional_enabled") is not None: + self.enabled = pb.enabled + if pb.WhichOneof("optional_cpu_budget") is not None: + self.cpu_budget = pb.cpu_budget + if pb.WhichOneof("optional_ram_budget") is not None: + self.ram_budget = pb.ram_budget + if pb.WhichOneof("optional_autotune_algorithm") is not None: + self.autotune_algorithm = AutotuneAlgorithm._from_proto( # pylint: disable=protected-access + pb.autotune_algorithm) + + def _set_mutable(self, mutable): + """Change the mutability value to `mutable` on this options and children.""" + # pylint: disable=protected-access + object.__setattr__(self, "_mutable", mutable) + + +@tf_export("data.experimental.DistributeOptions") +class DistributeOptions(options_lib.OptionsBase): + """Represents options for distributed data processing. + + You can set the distribution options of a dataset through the + `experimental_distribute` property of `tf.data.Options`; the property is + an instance of `tf.data.experimental.DistributeOptions`. + + ```python + options = tf.data.Options() + options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF + dataset = dataset.with_options(options) + ``` + """ + + auto_shard_policy = options_lib.create_option( + name="auto_shard_policy", + ty=AutoShardPolicy, + docstring="The type of sharding to use. See " + "`tf.data.experimental.AutoShardPolicy` for additional information.", + default_factory=lambda: AutoShardPolicy.AUTO) + + num_devices = options_lib.create_option( + name="num_devices", + ty=int, + docstring= + "The number of devices attached to this input pipeline. This will be " + "automatically set by `MultiDeviceIterator`.") + + def _to_proto(self): + pb = dataset_options_pb2.DistributeOptions() + pb.auto_shard_policy = AutoShardPolicy._to_proto(self.auto_shard_policy) # pylint: disable=protected-access + if self.num_devices is not None: + pb.num_devices = self.num_devices + return pb + + def _from_proto(self, pb): + self.auto_shard_policy = AutoShardPolicy._from_proto(pb.auto_shard_policy) # pylint: disable=protected-access + if pb.WhichOneof("optional_num_devices") is not None: + self.num_devices = pb.num_devices + + +@tf_export("data.experimental.OptimizationOptions") +class OptimizationOptions(options_lib.OptionsBase): + """Represents options for dataset optimizations. + + You can set the optimization options of a dataset through the + `experimental_optimization` property of `tf.data.Options`; the property is + an instance of `tf.data.experimental.OptimizationOptions`. + + ```python + options = tf.data.Options() + options.experimental_optimization.noop_elimination = True + options.experimental_optimization.apply_default_optimizations = False + dataset = dataset.with_options(options) + ``` + """ + apply_default_optimizations = options_lib.create_option( + name="apply_default_optimizations", + ty=bool, + docstring= + "Whether to apply default graph optimizations. If False, only graph " + "optimizations that have been explicitly enabled will be applied.") + + filter_fusion = options_lib.create_option( + name="filter_fusion", + ty=bool, + docstring= + "Whether to fuse filter transformations. If None, defaults to False.") + + filter_parallelization = options_lib.create_option( + name="filter_parallelization", + ty=bool, + docstring= + "Whether to parallelize stateless filter transformations. If None, " + "defaults to False.") + + inject_prefetch = options_lib.create_option( + name="inject_prefetch", + ty=bool, + docstring= + "Whether to inject prefetch transformation as the last transformation " + "when the last transformation is a synchronous transformation. If None, " + "defaults to True.") + + map_and_batch_fusion = options_lib.create_option( + name="map_and_batch_fusion", + ty=bool, + docstring= + "Whether to fuse map and batch transformations. If None, defaults to " + "True.") + + map_and_filter_fusion = options_lib.create_option( + name="map_and_filter_fusion", + ty=bool, + docstring= + "Whether to fuse map and filter transformations. If None, defaults to " + "False.") + + map_fusion = options_lib.create_option( + name="map_fusion", + ty=bool, + docstring="Whether to fuse map transformations. If None, defaults to " + "False.") + + map_parallelization = options_lib.create_option( + name="map_parallelization", + ty=bool, + docstring= + "Whether to parallelize stateless map transformations. If None, defaults " + "to True.") + + noop_elimination = options_lib.create_option( + name="noop_elimination", + ty=bool, + docstring= + "Whether to eliminate no-op transformations. If None, defaults to True.") + + parallel_batch = options_lib.create_option( + name="parallel_batch", + ty=bool, + docstring="Whether to parallelize copying of batch elements. If None, " + "defaults to True.") + + shuffle_and_repeat_fusion = options_lib.create_option( + name="shuffle_and_repeat_fusion", + ty=bool, + docstring="Whether to fuse shuffle and repeat transformations. If None, " + "defaults to True.") + + def _to_proto(self): + pb = dataset_options_pb2.OptimizationOptions() + if self.apply_default_optimizations is not None: + pb.apply_default_optimizations = self.apply_default_optimizations + if self.filter_fusion is not None: + pb.filter_fusion = self.filter_fusion + if self.filter_parallelization is not None: + pb.filter_parallelization = self.filter_parallelization + if self.inject_prefetch is not None: + pb.inject_prefetch = self.inject_prefetch + if self.map_and_batch_fusion is not None: + pb.map_and_batch_fusion = self.map_and_batch_fusion + if self.map_and_filter_fusion is not None: + pb.map_and_filter_fusion = self.map_and_filter_fusion + if self.map_fusion is not None: + pb.map_fusion = self.map_fusion + if self.map_parallelization is not None: + pb.map_parallelization = self.map_parallelization + if self.noop_elimination is not None: + pb.noop_elimination = self.noop_elimination + if self.parallel_batch is not None: + pb.parallel_batch = self.parallel_batch + if self.shuffle_and_repeat_fusion is not None: + pb.shuffle_and_repeat_fusion = self.shuffle_and_repeat_fusion + return pb + + def _from_proto(self, pb): + if pb.WhichOneof("optional_apply_default_optimizations") is not None: + self.apply_default_optimizations = pb.apply_default_optimizations + if pb.WhichOneof("optional_filter_fusion") is not None: + self.filter_fusion = pb.filter_fusion + if pb.WhichOneof("optional_filter_parallelization") is not None: + self.filter_parallelization = pb.filter_parallelization + if pb.WhichOneof("optional_inject_prefetch") is not None: + self.inject_prefetch = pb.inject_prefetch + if pb.WhichOneof("optional_map_and_batch_fusion") is not None: + self.map_and_batch_fusion = pb.map_and_batch_fusion + if pb.WhichOneof("optional_map_and_filter_fusion") is not None: + self.map_and_filter_fusion = pb.map_and_filter_fusion + if pb.WhichOneof("optional_map_fusion") is not None: + self.map_fusion = pb.map_fusion + if pb.WhichOneof("optional_map_parallelization") is not None: + self.map_parallelization = pb.map_parallelization + if pb.WhichOneof("optional_noop_elimination") is not None: + self.noop_elimination = pb.noop_elimination + if pb.WhichOneof("optional_parallel_batch") is not None: + self.parallel_batch = pb.parallel_batch + if pb.WhichOneof("optional_shuffle_and_repeat_fusion") is not None: + self.shuffle_and_repeat_fusion = pb.shuffle_and_repeat_fusion + + def _set_mutable(self, mutable): + """Change the mutability value to `mutable` on this options and children.""" + # pylint: disable=protected-access + object.__setattr__(self, "_mutable", mutable) + + +@deprecation.deprecated_endpoints("data.experimental.ThreadingOptions") +@tf_export("data.experimental.ThreadingOptions", "data.ThreadingOptions") +class ThreadingOptions(options_lib.OptionsBase): + """Represents options for dataset threading. + + You can set the threading options of a dataset through the + `threading` property of `tf.data.Options`; the property is + an instance of `tf.data.ThreadingOptions`. + + ```python + options = tf.data.Options() + options.threading.private_threadpool_size = 10 + dataset = dataset.with_options(options) + ``` + """ + + max_intra_op_parallelism = options_lib.create_option( + name="max_intra_op_parallelism", + ty=int, + docstring= + "If set, it overrides the maximum degree of intra-op parallelism.") + + private_threadpool_size = options_lib.create_option( + name="private_threadpool_size", + ty=int, + docstring= + "If set, the dataset will use a private threadpool of the given size. " + "The value 0 can be used to indicate that the threadpool size should be " + "determined at runtime based on the number of available CPU cores.") + + def _to_proto(self): + pb = dataset_options_pb2.ThreadingOptions() + if self.max_intra_op_parallelism is not None: + pb.max_intra_op_parallelism = self.max_intra_op_parallelism + if self.private_threadpool_size is not None: + pb.private_threadpool_size = self.private_threadpool_size + return pb + + def _from_proto(self, pb): + if pb.WhichOneof("optional_max_intra_op_parallelism") is not None: + self.max_intra_op_parallelism = pb.max_intra_op_parallelism + if pb.WhichOneof("optional_private_threadpool_size") is not None: + self.private_threadpool_size = pb.private_threadpool_size + + +@tf_export("data.Options") +class Options(options_lib.OptionsBase): + """Represents options for `tf.data.Dataset`. + + A `tf.data.Options` object can be, for instance, used to control which static + optimizations to apply to the input pipeline graph or whether to use + performance modeling to dynamically tune the parallelism of operations such as + `tf.data.Dataset.map` or `tf.data.Dataset.interleave`. + + The options are set for the entire dataset and are carried over to datasets + created through tf.data transformations. + + The options can be set by constructing an `Options` object and using the + `tf.data.Dataset.with_options(options)` transformation, which returns a + dataset with the options set. + + >>> dataset = tf.data.Dataset.range(42) + >>> options = tf.data.Options() + >>> options.deterministic = False + >>> dataset = dataset.with_options(options) + >>> print(dataset.options().deterministic) + False + + Note: A known limitation of the `tf.data.Options` implementation is that the + options are not preserved across tf.function boundaries. In particular, to + set options for a dataset that is iterated within a tf.function, the options + need to be set within the same tf.function. + """ + + autotune = options_lib.create_option( + name="autotune", + ty=AutotuneOptions, + docstring="The autotuning options associated with the dataset. See " + "`tf.data.experimental.AutotuneOptions` for more details.", + default_factory=AutotuneOptions) + + deterministic = options_lib.create_option( + name="deterministic", + ty=bool, + docstring= + "Whether the outputs need to be produced in deterministic order. If None," + " defaults to True.") + + experimental_deterministic = options_lib.create_option( + name="experimental_deterministic", + ty=bool, + docstring="DEPRECATED. Use `deterministic` instead.") + + experimental_distribute = options_lib.create_option( + name="experimental_distribute", + ty=DistributeOptions, + docstring= + "The distribution strategy options associated with the dataset. See " + "`tf.data.experimental.DistributeOptions` for more details.", + default_factory=DistributeOptions) + + experimental_external_state_policy = options_lib.create_option( + name="experimental_external_state_policy", + ty=ExternalStatePolicy, + docstring="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.") + + experimental_optimization = options_lib.create_option( + name="experimental_optimization", + ty=OptimizationOptions, + docstring= + "The optimization options associated with the dataset. See " + "`tf.data.experimental.OptimizationOptions` for more details.", + default_factory=OptimizationOptions) + + experimental_slack = options_lib.create_option( + name="experimental_slack", + ty=bool, + docstring="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. If None, defaults to False.") + + experimental_symbolic_checkpoint = options_lib.create_option( + name="experimental_symbolic_checkpoint", + ty=bool, + docstring="Whether to checkpoint internal input pipeline state " + "maintaining cursors into data sources that identify last " + "element(s) produced as output to the tf.data consumer. This " + "is alternative to the default 'explicit' checkpointing which " + "stores the internal input pipeline state in the checkpoint. " + "Note that symbolic checkpointing is not supported for " + "transformations that can reorder elements.") + + experimental_threading = options_lib.create_option( + name="experimental_threading", + ty=ThreadingOptions, + docstring="DEPRECATED. Use `threading` instead.") + + experimental_warm_start = options_lib.create_option( + name="experimental_warm_start", + ty=bool, + docstring=( + "Whether to start background threads of asynchronous transformations " + "upon iterator creation, as opposed to during the first call to " + "`next()`. Defaults to `False`. " + "This improves the latency of the initial 'next()' calls at " + "the expense of requiring more memory to hold prefetched elements " + "between the time of iterator construction and usage." + ), + default_factory=lambda: True if test_mode.TEST_MODE else None, + ) + + threading = options_lib.create_option( + name="threading", + ty=ThreadingOptions, + docstring="The threading options associated with the dataset. See " + "`tf.data.ThreadingOptions` for more details.", + default_factory=ThreadingOptions) + + def __getattribute__(self, name): + if name == "experimental_threading": + logging.warning("options.experimental_threading is deprecated. " + "Use options.threading instead.") + return getattr(self, "threading") + if name == "experimental_deterministic": + # TODO(aaudibert): Uncomment after internal uses have been updated. + # logging.warning("options.experimental_deterministic is deprecated. " + # "Use options.deterministic instead.") + return getattr(self, "deterministic") + return super(Options, self).__getattribute__(name) + + def __setattr__(self, name, value): + if name == "experimental_threading": + logging.warning("options.experimental_threading is deprecated. " + "Use options.threading instead.") + super(Options, self).__setattr__("threading", value) + return + if name == "experimental_deterministic": + # TODO(aaudibert): Uncomment after internal uses have been updated. + # logging.warning("options.experimental_deterministic is deprecated. " + # "Use options.deterministic instead.") + super(Options, self).__setattr__("deterministic", value) + return + if name == "experimental_symbolic_checkpoint": + # TODO(b/276269493): Add support for MacOS. + if platform.system() == "Darwin": + logging.warning("Symbolic checkpointing is not supported on MacOS.") + return + super(Options, self).__setattr__(name, value) + + def _to_proto(self): + pb = dataset_options_pb2.Options() + if self.deterministic is not None: + pb.deterministic = self.deterministic + pb.autotune_options.CopyFrom(self.autotune._to_proto()) # pylint: disable=protected-access + pb.distribute_options.CopyFrom(self.experimental_distribute._to_proto()) # pylint: disable=protected-access + if self.experimental_external_state_policy is not None: + pb.external_state_policy = ( + ExternalStatePolicy._to_proto( # pylint: disable=protected-access + self.experimental_external_state_policy)) + pb.optimization_options.CopyFrom(self.experimental_optimization._to_proto()) # pylint: disable=protected-access + if self.experimental_slack is not None: + pb.slack = self.experimental_slack + if self.experimental_symbolic_checkpoint is not None: + pb.symbolic_checkpoint = self.experimental_symbolic_checkpoint + if self.experimental_warm_start is not None: + pb.warm_start = self.experimental_warm_start + pb.threading_options.CopyFrom(self.threading._to_proto()) # pylint: disable=protected-access + return pb + + def _from_proto(self, pb): + if pb.WhichOneof("optional_deterministic") is not None: + self.deterministic = pb.deterministic + self.autotune._from_proto(pb.autotune_options) # pylint: disable=protected-access + self.experimental_distribute._from_proto(pb.distribute_options) # pylint: disable=protected-access + if pb.WhichOneof("optional_external_state_policy") is not None: + self.experimental_external_state_policy = ( + ExternalStatePolicy._from_proto( # pylint: disable=protected-access + pb.external_state_policy)) + self.experimental_optimization._from_proto(pb.optimization_options) # pylint: disable=protected-access + if pb.WhichOneof("optional_slack") is not None: + self.experimental_slack = pb.slack + if pb.WhichOneof("optional_symbolic_checkpoint") is not None: + self.experimental_symbolic_checkpoint = pb.symbolic_checkpoint + if pb.WhichOneof("optional_warm_start") is not None: + self.experimental_warm_start = pb.warm_start + self.threading._from_proto(pb.threading_options) # pylint: disable=protected-access + + def _set_mutable(self, mutable): + """Change the mutability value to `mutable` on this options and children.""" + # pylint: disable=protected-access + object.__setattr__(self, "_mutable", mutable) + self.autotune._set_mutable(mutable) + self.experimental_distribute._set_mutable(mutable) + self.experimental_optimization._set_mutable(mutable) + self.threading._set_mutable(mutable) + + def merge(self, options): + """Merges itself with the given `tf.data.Options`. + + If this object and the `options` to merge set an option differently, a + warning is generated and this object's value is updated with the `options` + object's value. + + Args: + options: The `tf.data.Options` to merge with. + + Returns: + New `tf.data.Options` object which is the result of merging self with + the input `tf.data.Options`. + """ + return options_lib.merge_options(self, options) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/padded_batch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/padded_batch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..6d69d34dcfa68f92451bc5d8b7cea88e91301a28 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/padded_batch_op.py @@ -0,0 +1,262 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.padded_batch`.""" + +import numpy as np + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_dataset_ops + + +def _padded_batch(input_dataset, + batch_size, + padded_shapes=None, + padding_values=None, + drop_remainder=False, + name=None): + """See `tf.data.Dataset.padded_batch` for details.""" + if padded_shapes is None: + padded_shapes = dataset_ops.get_legacy_output_shapes(input_dataset) + for i, shape in enumerate(nest.flatten(padded_shapes)): + # A `tf.TensorShape` is only false if its *rank* is unknown. + if not shape: + raise ValueError(f"You must provide `padded_shapes` argument because " + f"component {i} has unknown rank.") + return _PaddedBatchDataset( + input_dataset, + batch_size, + padded_shapes, + padding_values, + drop_remainder, + name=name) + + +def _is_padded_shape_compatible_with(padded_shape, input_component_shape): + """Returns `True` if `input_component_shape` can be padded to `padded_shape`. + + Args: + padded_shape: A `tf.TensorShape`. + input_component_shape: A `tf.TensorShape`. + + Returns: + `True` if `input_component_shape` can be padded to `padded_shape`, otherwise + `False`. + """ + + if padded_shape.dims is None or input_component_shape.dims is None: + return True + if len(padded_shape.dims) != len(input_component_shape.dims): + return False + for padded_dim, input_dim in zip(padded_shape.dims, + input_component_shape.dims): + if (padded_dim.value is not None and input_dim.value is not None and + padded_dim.value < input_dim.value): + return False + return True + + +def _padded_shape_to_tensor(padded_shape, input_component_shape): + """Converts `padded_shape` to a `tf.Tensor` representing that shape. + + Args: + padded_shape: A shape-like object, which may be a `tf.TensorShape`, a Python + sequence, or a 1-D `tf.Tensor` of `tf.int64` elements. + input_component_shape: A `tf.TensorShape`, with which `padded_shape` must be + compatible. + + Returns: + A 1-D `tf.Tensor` of `tf.int64` elements, representing `padded_shape`. + + Raises: + ValueError: If `padded_shape` is not a shape or not compatible with + `input_component_shape`. + TypeError: If `padded_shape` is not convertible to a `tf.int64` tensor. + """ + try: + # Try to convert the `padded_shape` to a `tf.TensorShape` + padded_shape_as_shape = tensor_shape.as_shape(padded_shape) + # We will return the "canonical" tensor representation, which uses + # `-1` in place of `None`. + ret = ops.convert_to_tensor([ + dim if dim is not None else -1 + for dim in padded_shape_as_shape.as_list() + ], + dtype=dtypes.int64) + except (TypeError, ValueError) as e: + # The argument was not trivially convertible to a + # `tf.TensorShape`, so fall back on the conversion to tensor + # machinery. + ret = ops.convert_to_tensor(padded_shape, preferred_dtype=dtypes.int64) + if ret.shape.dims is not None and len(ret.shape.dims) != 1: + raise ValueError( + f"Padded shape {padded_shape} must be a `tf.int64` vector tensor, " + f"but its shape was {ret.shape}.") from e + if ret.dtype != dtypes.int64: + raise TypeError( + f"Padded shape {padded_shape} must be a `tf.int64` vector " + f"tensor, but its element type was {ret.dtype.name}.") from e + padded_shape_as_shape = tensor_util.constant_value_as_shape(ret) + + if not _is_padded_shape_compatible_with(padded_shape_as_shape, + input_component_shape): + raise ValueError(f"The padded shape {padded_shape_as_shape} is not " + f"compatible with the shape {input_component_shape} of " + f"the corresponding input component.") + + return ret + + +def _padding_values_or_default(padding_values, input_dataset): + """Returns padding values with None elements replaced with default values.""" + + def make_zero(t): + if t.base_dtype == dtypes.string: + return "" + elif t.base_dtype == dtypes.variant: + raise TypeError("Unable to create default padding value for a component " + "of type 'variant'.") + elif t.base_dtype == dtypes.bfloat16: + # Special case `bfloat16` because it is not supported by NumPy. + return constant_op.constant(0, dtype=dtypes.bfloat16) + else: + return np.zeros_like(t.as_numpy_dtype()) + + def value_or_default(value, default): + return default if value is None else value + + default_padding = nest.map_structure( + make_zero, dataset_ops.get_legacy_output_types(input_dataset)) + return nest.map_structure_up_to(padding_values, value_or_default, + padding_values, default_padding) + + +def _padding_value_to_tensor(value, output_type): + """Converts the padding value to a tensor. + + Args: + value: The padding value. + output_type: Its expected dtype. + + Returns: + A scalar `Tensor`. + + Raises: + ValueError: if the padding value is not a scalar. + TypeError: if the padding value's type does not match `output_type`. + """ + value = ops.convert_to_tensor(value, name="padding_value") + if not value.shape.is_compatible_with(tensor_shape.TensorShape([])): + raise ValueError(f"Invalid `padding_values`. `padding_values` values " + f"should be scalars, but got {value.shape}.") + if value.dtype != output_type: + raise TypeError(f"Invalid `padding_values`. `padding_values` values " + f"type {value.dtype} does not match type {output_type} " + f"of the corresponding input component.") + return value + + +class _PaddedBatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that batches and pads contiguous elements from its input.""" + + def __init__(self, + input_dataset, + batch_size, + padded_shapes, + padding_values, + drop_remainder, + name=None): + """See `Dataset.batch()` for details.""" + self._input_dataset = input_dataset + + def check_types(component_spec): + if not isinstance(component_spec, tensor_spec.TensorSpec): + if isinstance(component_spec, dataset_ops.DatasetSpec): + raise TypeError( + "`padded_batch` is not supported for datasets of datasets") + raise TypeError(f"`padded_batch` is only supported for datasets that " + f"produce tensor elements but type spec of elements in " + f"the input dataset is not a subclass of TensorSpec: " + f"`{component_spec}`.") + + nest.map_structure(check_types, input_dataset.element_spec) + self._input_dataset = input_dataset + self._batch_size = ops.convert_to_tensor( + batch_size, dtype=dtypes.int64, name="batch_size") + padding_values = _padding_values_or_default(padding_values, input_dataset) + + input_shapes = dataset_ops.get_legacy_output_shapes(input_dataset) + flat_padded_shapes = nest.flatten_up_to(input_shapes, padded_shapes) + + flat_padded_shapes_as_tensors = [] + + for input_component_shape, padded_shape in zip( + nest.flatten(input_shapes), flat_padded_shapes): + flat_padded_shapes_as_tensors.append( + _padded_shape_to_tensor(padded_shape, input_component_shape)) + + self._padded_shapes = nest.pack_sequence_as(input_shapes, + flat_padded_shapes_as_tensors) + + # If padding_values is a single element and input_shapes is a structure, + # "broadcast" padding_values to the same structure as input_shapes. + if nest.is_nested(input_shapes) and not nest.is_nested(padding_values): + padding_values = nest.map_structure(lambda _: padding_values, + input_shapes) + + self._padding_values = nest.map_structure_up_to( + input_shapes, _padding_value_to_tensor, padding_values, + dataset_ops.get_legacy_output_types(input_dataset)) + self._drop_remainder = ops.convert_to_tensor( + drop_remainder, dtype=dtypes.bool, name="drop_remainder") + + def _padded_shape_to_batch_shape(s): + return tensor_shape.TensorShape([ + tensor_util.constant_value(self._batch_size) + if smart_cond.smart_constant_value(self._drop_remainder) else None + ]).concatenate(tensor_util.constant_value_as_shape(s)) + + output_shapes = nest.map_structure(_padded_shape_to_batch_shape, + self._padded_shapes) + self._structure = structure.convert_legacy_structure( + dataset_ops.get_legacy_output_types(self._input_dataset), output_shapes, + dataset_ops.get_legacy_output_classes(self._input_dataset)) + + self._name = name + # pylint: disable=protected-access + variant_tensor = gen_dataset_ops.padded_batch_dataset_v2( + input_dataset._variant_tensor, # pylint: disable=protected-access + batch_size=self._batch_size, + padded_shapes=[ + ops.convert_to_tensor(s, dtype=dtypes.int64) + for s in nest.flatten(self._padded_shapes) + ], + padding_values=nest.flatten(self._padding_values), + drop_remainder=self._drop_remainder, + output_shapes=structure.get_flat_tensor_shapes(self._structure), + metadata=self._metadata.SerializeToString()) + super().__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/prefetch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/prefetch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..d4982c67e027bc86d2decb3aee58f3e1a3fdbb88 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/prefetch_op.py @@ -0,0 +1,51 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.prefetch`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import debug_mode +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _prefetch(input_dataset, buffer_size, name=None): # pylint: disable=unused-private-name + """See `Dataset.prefetch()` for details.""" + if debug_mode.DEBUG_MODE: + return input_dataset + return _PrefetchDataset(input_dataset, buffer_size, name=name) + + +class _PrefetchDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that asynchronously prefetches its input.""" + + def __init__(self, input_dataset, buffer_size, slack_period=None, name=None): + """See `Dataset.prefetch()` for details.""" + self._input_dataset = input_dataset + if buffer_size is None: + buffer_size = dataset_ops.AUTOTUNE + self._buffer_size = ops.convert_to_tensor( + buffer_size, dtype=dtypes.int64, name="buffer_size") + self._name = name + # pylint: disable=protected-access + # We colocate the prefetch dataset with its input as this collocation only + # happens automatically in graph mode. + with ops.colocate_with(input_dataset._variant_tensor): + variant_tensor = gen_dataset_ops.prefetch_dataset( + input_dataset._variant_tensor, + buffer_size=self._buffer_size, + slack_period=slack_period, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/ragged_batch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/ragged_batch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..bb886ca7bbd5ff721618a4cc564cab67f8fbdd46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/ragged_batch_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.ragged_batch`.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import nest +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor +from tensorflow.python.ops.ragged import ragged_tensor + + +def _ragged_batch(input_dataset, + batch_size, + drop_remainder=False, + row_splits_dtype=dtypes.int64, + name=None): + ragged_dataset = _DenseToRaggedDataset(input_dataset, row_splits_dtype, name) + return ragged_dataset.batch(batch_size, drop_remainder) + + +class _DenseToRaggedDataset(dataset_ops.UnaryDataset): + """A `Dataset` that encodes dense inputs as ragged (w/ ragged_rank=0). + + In particular: + + * Any tf.Tensor elements with rank>0 are encoded as ragged tensors with + ragged_rank=0. This allows tensors with varying shape to be batched + together. + * Any other elements are left as-is. + """ + + def __init__(self, input_dataset, row_splits_dtype, name=None): + """Constructs a new _DenseToRaggedDataset. + + Args: + input_dataset: The dataset whose tf.Tensor elements should be made ragged. + row_splits_dtype: The dtype that should be used for the `row_splits` of + any new ragged tensors. Existing `tf.RaggedTensor` elements do *not* + have their row_splits dtype changed. + name: (Optional.) A string indicating a name for the `tf.data` operation. + """ + # Replace each TensorSpec in the input dataset's structure with a + # corresponding RaggedTensorSpec. + def to_ragged_spec(spec): + """Returns the new spec based on RaggedTensors.""" + if (not isinstance(spec, tensor.TensorSpec) or + spec.shape.rank is None or + spec.shape.is_fully_defined()): + return spec + else: + ragged_rank = max([ + axis for (axis, size) in enumerate(spec.shape.as_list()) + if size is None + ]) + return ragged_tensor.RaggedTensorSpec( + shape=spec.shape, + dtype=spec.dtype, + ragged_rank=ragged_rank, + row_splits_dtype=row_splits_dtype) + + self._structure = nest.map_structure(to_ragged_spec, + input_dataset.element_spec) + + # Replace each tf.Tensor value in the input dataset with a variant-encoded + # RaggedTensor. Since we're updating the corresponding structure to be + # a RaggedTensorSpec, this variant-encoded tensor will be decoded with + # RaggedTensorSpec._from_tensor_list. + def to_ragged_variant(value): + """Re-encode Tensors as RaggedTensors.""" + if (not isinstance(value, tensor.Tensor) or + value.shape.rank is None or + value.shape.is_fully_defined()): + return value + else: + spec = to_ragged_spec(tensor.TensorSpec.from_tensor(value)) + if spec._ragged_rank > 0: # pylint: disable=protected-access + value = ragged_tensor.RaggedTensor.from_tensor( + value, ragged_rank=spec._ragged_rank) # pylint: disable=protected-access + return spec._to_tensor_list(value)[0] # pylint: disable=protected-access + + # Tuples are automatically unpacked by `dataset.map` so we repack them. + if structured_function._should_unpack(input_dataset.element_spec): # pylint: disable=protected-access + map_fn = lambda *value: nest.map_structure(to_ragged_variant, value) + else: + map_fn = lambda value: nest.map_structure(to_ragged_variant, value) + + self._mapped_dataset = input_dataset.map(map_fn) + self._name = name + variant = self._mapped_dataset._variant_tensor # pylint: disable=protected-access + super().__init__(input_dataset, variant) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/random_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/random_op.py new file mode 100644 index 0000000000000000000000000000000000000000..435f08ae3288dc233f6847f5a824731be1ca2a37 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/random_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.random`.""" + +import warnings + +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import random_seed +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _random( # pylint: disable=unused-private-name + seed=None, + rerandomize_each_iteration=None, + name=None): + """See `Dataset.random()` for details.""" + return _RandomDataset( + seed=seed, + rerandomize_each_iteration=rerandomize_each_iteration, + name=name) + + +class _RandomDataset(dataset_ops.DatasetSource): + """A `Dataset` of pseudorandom values.""" + + def __init__(self, seed=None, rerandomize_each_iteration=None, name=None): + """A `Dataset` of pseudorandom values.""" + self._seed, self._seed2 = random_seed.get_seed(seed) + self._rerandomize = rerandomize_each_iteration + self._name = name + if rerandomize_each_iteration: + if not tf2.enabled(): + warnings.warn("In TF 1, the `rerandomize_each_iteration=True` option " + "is only supported for repeat-based epochs.") + variant_tensor = ged_ops.random_dataset_v2( + seed=self._seed, + seed2=self._seed2, + seed_generator=gen_dataset_ops.dummy_seed_generator(), + rerandomize_each_iteration=self._rerandomize, + **self._common_args) + else: + variant_tensor = ged_ops.random_dataset( + seed=self._seed, seed2=self._seed2, **self._common_args) + super().__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.int64) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/range_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/range_op.py new file mode 100644 index 0000000000000000000000000000000000000000..5f0c463eace86a81f1a5c392293cbf39751638de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/range_op.py @@ -0,0 +1,70 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.range`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_dataset_ops + + +def _range(*args, **kwargs): # pylint: disable=unused-private-name + return _RangeDataset(*args, **kwargs) + + +class _RangeDataset(dataset_ops.DatasetSource): + """A `Dataset` of a step separated range of values.""" + + def __init__(self, *args, **kwargs): + """See `Dataset.range()` for details.""" + self._parse_args(*args, **kwargs) + self._structure = tensor_spec.TensorSpec([], self._output_type) + variant_tensor = gen_dataset_ops.range_dataset( + start=self._start, + stop=self._stop, + step=self._step, + **self._common_args) + super().__init__(variant_tensor) + + def _parse_args(self, *args, **kwargs): + """Parses arguments according to the same rules as the `range()` builtin.""" + if len(args) == 1: + self._start = self._build_tensor(0, "start") + self._stop = self._build_tensor(args[0], "stop") + self._step = self._build_tensor(1, "step") + elif len(args) == 2: + self._start = self._build_tensor(args[0], "start") + self._stop = self._build_tensor(args[1], "stop") + self._step = self._build_tensor(1, "step") + elif len(args) == 3: + self._start = self._build_tensor(args[0], "start") + self._stop = self._build_tensor(args[1], "stop") + self._step = self._build_tensor(args[2], "step") + else: + raise ValueError(f"Invalid `args`. The length of `args` should be " + f"between 1 and 3 but was {len(args)}.") + if "output_type" in kwargs: + self._output_type = kwargs["output_type"] + else: + self._output_type = dtypes.int64 + self._name = kwargs["name"] if "name" in kwargs else None + + def _build_tensor(self, int64_value, name): + return ops.convert_to_tensor(int64_value, dtype=dtypes.int64, name=name) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/readers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/readers.py new file mode 100644 index 0000000000000000000000000000000000000000..347b7a5c272973b6a6145ef8b7ee6b4cc5edfb59 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/readers.py @@ -0,0 +1,707 @@ +# 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. +# ============================================================================== +"""Python wrappers for reader Datasets.""" +import os + +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import from_tensor_slices_op +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import convert +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.types import data as data_types +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +_DEFAULT_READER_BUFFER_SIZE_BYTES = 256 * 1024 # 256 KB + + +def _normalise_fspath(path): + """Convert pathlib-like objects to str (__fspath__ compatibility, PEP 519).""" + return os.fspath(path) if isinstance(path, os.PathLike) else path + + +def _create_or_validate_filenames_dataset(filenames, name=None): + """Creates (or validates) a dataset of filenames. + + Args: + filenames: Either a list or dataset of filenames. If it is a list, it is + convert to a dataset. If it is a dataset, its type and shape is validated. + name: (Optional.) A name for the tf.data operation. + + Returns: + A dataset of filenames. + """ + if isinstance(filenames, data_types.DatasetV2): + element_type = dataset_ops.get_legacy_output_types(filenames) + if element_type != dtypes.string: + raise TypeError( + "The `filenames` argument must contain `tf.string` elements. Got a " + f"dataset of `{element_type!r}` elements.") + element_shape = dataset_ops.get_legacy_output_shapes(filenames) + if not element_shape.is_compatible_with(tensor_shape.TensorShape([])): + raise TypeError( + "The `filenames` argument must contain `tf.string` elements of shape " + "[] (i.e. scalars). Got a dataset of element shape " + f"{element_shape!r}.") + else: + filenames = nest.map_structure(_normalise_fspath, filenames) + filenames = ops.convert_to_tensor(filenames, dtype_hint=dtypes.string) + if filenames.dtype != dtypes.string: + raise TypeError( + "The `filenames` argument must contain `tf.string` elements. Got " + f"`{filenames.dtype!r}` elements.") + filenames = array_ops.reshape(filenames, [-1], name="flat_filenames") + filenames = from_tensor_slices_op._TensorSliceDataset( # pylint: disable=protected-access + filenames, + is_files=True, + name=name) + return filenames + + +def _create_dataset_reader(dataset_creator, + filenames, + num_parallel_reads=None, + name=None): + """Creates a dataset that reads the given files using the given reader. + + Args: + dataset_creator: A function that takes in a single file name and returns a + dataset. + filenames: A `tf.data.Dataset` containing one or more filenames. + num_parallel_reads: The number of parallel reads we should do. + name: (Optional.) A name for the tf.data operation. + + Returns: + A `Dataset` that reads data from `filenames`. + """ + + def read_one_file(filename): + filename = ops.convert_to_tensor(filename, dtypes.string, name="filename") + return dataset_creator(filename) + + if num_parallel_reads is None: + return filenames.flat_map(read_one_file, name=name) + elif num_parallel_reads == dataset_ops.AUTOTUNE: + return filenames.interleave( + read_one_file, num_parallel_calls=num_parallel_reads, name=name) + else: + return ParallelInterleaveDataset( + filenames, + read_one_file, + cycle_length=num_parallel_reads, + block_length=1, + sloppy=False, + buffer_output_elements=None, + prefetch_input_elements=None, + name=name) + + +def _get_type(value): + """Returns the type of `value` if it is a TypeSpec.""" + + if isinstance(value, type_spec.TypeSpec): + return value.value_type() + else: + return type(value) + + +class _TextLineDataset(dataset_ops.DatasetSource): + """A `Dataset` comprising records from one or more text files.""" + + def __init__(self, + filenames, + compression_type=None, + buffer_size=None, + name=None): + """Creates a `TextLineDataset`. + + Args: + filenames: A `tf.string` tensor containing one or more filenames. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. + buffer_size: (Optional.) A `tf.int64` scalar denoting the number of bytes + to buffer. A value of 0 results in the default buffering values chosen + based on the compression type. + name: (Optional.) A name for the tf.data operation. + """ + self._filenames = filenames + self._compression_type = convert.optional_param_to_tensor( + "compression_type", + compression_type, + argument_default="", + argument_dtype=dtypes.string) + self._buffer_size = convert.optional_param_to_tensor( + "buffer_size", + buffer_size, + argument_default=_DEFAULT_READER_BUFFER_SIZE_BYTES) + self._name = name + + variant_tensor = gen_dataset_ops.text_line_dataset( + self._filenames, + self._compression_type, + self._buffer_size, + metadata=self._metadata.SerializeToString()) + super(_TextLineDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) + + +@tf_export("data.TextLineDataset", v1=[]) +class TextLineDatasetV2(dataset_ops.DatasetSource): + r"""Creates a `Dataset` comprising lines from one or more text files. + + The `tf.data.TextLineDataset` loads text from text files and creates a dataset + where each line of the files becomes an element of the dataset. + + For example, suppose we have 2 files "text_lines0.txt" and "text_lines1.txt" + with the following lines: + + >>> with open('/tmp/text_lines0.txt', 'w') as f: + ... f.write('the cow\n') + ... f.write('jumped over\n') + ... f.write('the moon\n') + >>> with open('/tmp/text_lines1.txt', 'w') as f: + ... f.write('jack and jill\n') + ... f.write('went up\n') + ... f.write('the hill\n') + + We can construct a TextLineDataset from them as follows: + + >>> dataset = tf.data.TextLineDataset(['/tmp/text_lines0.txt', + ... '/tmp/text_lines1.txt']) + + The elements of the dataset are expected to be: + + >>> for element in dataset.as_numpy_iterator(): + ... print(element) + b'the cow' + b'jumped over' + b'the moon' + b'jack and jill' + b'went up' + b'the hill' + """ + + def __init__(self, + filenames, + compression_type=None, + buffer_size=None, + num_parallel_reads=None, + name=None): + r"""Creates a `TextLineDataset`. + + The elements of the dataset will be the lines of the input files, using + the newline character '\n' to denote line splits. The newline characters + will be stripped off of each element. + + Args: + filenames: A `tf.data.Dataset` whose elements are `tf.string` scalars, a + `tf.string` tensor, or a value that can be converted to a `tf.string` + tensor (such as a list of Python strings). + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. + buffer_size: (Optional.) A `tf.int64` scalar denoting the number of bytes + to buffer. A value of 0 results in the default buffering values chosen + based on the compression type. + num_parallel_reads: (Optional.) A `tf.int64` scalar representing the + number of files to read in parallel. If greater than one, the records of + files read in parallel are outputted in an interleaved order. If your + input pipeline is I/O bottlenecked, consider setting this parameter to a + value greater than one to parallelize the I/O. If `None`, files will be + read sequentially. + name: (Optional.) A name for the tf.data operation. + """ + filenames = _create_or_validate_filenames_dataset(filenames, name=name) + self._filenames = filenames + self._compression_type = compression_type + self._buffer_size = buffer_size + + def creator_fn(filename): + return _TextLineDataset( + filename, compression_type, buffer_size, name=name) + + self._impl = _create_dataset_reader( + creator_fn, filenames, num_parallel_reads, name=name) + variant_tensor = self._impl._variant_tensor # pylint: disable=protected-access + + super(TextLineDatasetV2, self).__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) + + +@tf_export(v1=["data.TextLineDataset"]) +class TextLineDatasetV1(dataset_ops.DatasetV1Adapter): + """A `Dataset` comprising lines from one or more text files.""" + + def __init__(self, + filenames, + compression_type=None, + buffer_size=None, + num_parallel_reads=None, + name=None): + wrapped = TextLineDatasetV2(filenames, compression_type, buffer_size, + num_parallel_reads, name) + super(TextLineDatasetV1, self).__init__(wrapped) + + __init__.__doc__ = TextLineDatasetV2.__init__.__doc__ + + @property + def _filenames(self): + return self._dataset._filenames # pylint: disable=protected-access + + @_filenames.setter + def _filenames(self, value): + self._dataset._filenames = value # pylint: disable=protected-access + + +class _TFRecordDataset(dataset_ops.DatasetSource): + """A `Dataset` comprising records from one or more TFRecord files.""" + + def __init__(self, + filenames, + compression_type=None, + buffer_size=None, + name=None): + """Creates a `TFRecordDataset`. + + Args: + filenames: A `tf.string` tensor containing one or more filenames. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. + buffer_size: (Optional.) A `tf.int64` scalar representing the number of + bytes in the read buffer. 0 means no buffering. + name: (Optional.) A name for the tf.data operation. + """ + self._filenames = filenames + self._compression_type = convert.optional_param_to_tensor( + "compression_type", + compression_type, + argument_default="", + argument_dtype=dtypes.string) + self._buffer_size = convert.optional_param_to_tensor( + "buffer_size", + buffer_size, + argument_default=_DEFAULT_READER_BUFFER_SIZE_BYTES) + self._name = name + + variant_tensor = gen_dataset_ops.tf_record_dataset( + self._filenames, self._compression_type, self._buffer_size, + metadata=self._metadata.SerializeToString()) + super(_TFRecordDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) + + +class ParallelInterleaveDataset(dataset_ops.UnaryDataset): + """A `Dataset` that maps a function over its input and flattens the result.""" + + def __init__(self, + input_dataset, + map_func, + cycle_length, + block_length, + sloppy, + buffer_output_elements, + prefetch_input_elements, + name=None): + """See `tf.data.experimental.parallel_interleave()` for details.""" + self._input_dataset = input_dataset + self._map_func = structured_function.StructuredFunctionWrapper( + map_func, self._transformation_name(), dataset=input_dataset) + if not isinstance(self._map_func.output_structure, dataset_ops.DatasetSpec): + raise TypeError( + "The `map_func` argument must return a `Dataset` object. Got " + f"{_get_type(self._map_func.output_structure)!r}.") + self._element_spec = self._map_func.output_structure._element_spec # pylint: disable=protected-access + self._cycle_length = ops.convert_to_tensor( + cycle_length, dtype=dtypes.int64, name="cycle_length") + self._block_length = ops.convert_to_tensor( + block_length, dtype=dtypes.int64, name="block_length") + self._buffer_output_elements = convert.optional_param_to_tensor( + "buffer_output_elements", + buffer_output_elements, + argument_default=2 * block_length) + self._prefetch_input_elements = convert.optional_param_to_tensor( + "prefetch_input_elements", + prefetch_input_elements, + argument_default=2 * cycle_length) + if sloppy is None: + self._deterministic = "default" + elif sloppy: + self._deterministic = "false" + else: + self._deterministic = "true" + self._name = name + + variant_tensor = ged_ops.legacy_parallel_interleave_dataset_v2( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._map_func.function.captured_inputs, + self._cycle_length, + self._block_length, + self._buffer_output_elements, + self._prefetch_input_elements, + f=self._map_func.function, + deterministic=self._deterministic, + **self._common_args) + super(ParallelInterleaveDataset, self).__init__(input_dataset, + variant_tensor) + + def _functions(self): + return [self._map_func] + + @property + def element_spec(self): + return self._element_spec + + def _transformation_name(self): + return "tf.data.experimental.parallel_interleave()" + + +@tf_export("data.TFRecordDataset", v1=[]) +class TFRecordDatasetV2(dataset_ops.DatasetV2): + """A `Dataset` comprising records from one or more TFRecord files. + + This dataset loads TFRecords from the files as bytes, exactly as they were + written.`TFRecordDataset` does not do any parsing or decoding on its own. + Parsing and decoding can be done by applying `Dataset.map` transformations + after the `TFRecordDataset`. + + A minimal example is given below: + + >>> import tempfile + >>> example_path = os.path.join(tempfile.gettempdir(), "example.tfrecords") + >>> np.random.seed(0) + + >>> # Write the records to a file. + ... with tf.io.TFRecordWriter(example_path) as file_writer: + ... for _ in range(4): + ... x, y = np.random.random(), np.random.random() + ... + ... record_bytes = tf.train.Example(features=tf.train.Features(feature={ + ... "x": tf.train.Feature(float_list=tf.train.FloatList(value=[x])), + ... "y": tf.train.Feature(float_list=tf.train.FloatList(value=[y])), + ... })).SerializeToString() + ... file_writer.write(record_bytes) + + >>> # Read the data back out. + >>> def decode_fn(record_bytes): + ... return tf.io.parse_single_example( + ... # Data + ... record_bytes, + ... + ... # Schema + ... {"x": tf.io.FixedLenFeature([], dtype=tf.float32), + ... "y": tf.io.FixedLenFeature([], dtype=tf.float32)} + ... ) + + >>> for batch in tf.data.TFRecordDataset([example_path]).map(decode_fn): + ... print("x = {x:.4f}, y = {y:.4f}".format(**batch)) + x = 0.5488, y = 0.7152 + x = 0.6028, y = 0.5449 + x = 0.4237, y = 0.6459 + x = 0.4376, y = 0.8918 + """ + + def __init__(self, + filenames, + compression_type=None, + buffer_size=None, + num_parallel_reads=None, + name=None): + """Creates a `TFRecordDataset` to read one or more TFRecord files. + + Each element of the dataset will contain a single TFRecord. + + Args: + filenames: A `tf.string` tensor or `tf.data.Dataset` containing one or + more filenames. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. + buffer_size: (Optional.) A `tf.int64` scalar representing the number of + bytes in the read buffer. If your input pipeline is I/O bottlenecked, + consider setting this parameter to a value 1-100 MBs. If `None`, a + sensible default for both local and remote file systems is used. + num_parallel_reads: (Optional.) A `tf.int64` scalar representing the + number of files to read in parallel. If greater than one, the records of + files read in parallel are outputted in an interleaved order. If your + input pipeline is I/O bottlenecked, consider setting this parameter to a + value greater than one to parallelize the I/O. If `None`, files will be + read sequentially. + name: (Optional.) A name for the tf.data operation. + + Raises: + TypeError: If any argument does not have the expected type. + ValueError: If any argument does not have the expected shape. + """ + filenames = _create_or_validate_filenames_dataset(filenames, name=name) + + self._filenames = filenames + self._compression_type = compression_type + self._buffer_size = buffer_size + self._num_parallel_reads = num_parallel_reads + + def creator_fn(filename): + return _TFRecordDataset( + filename, compression_type, buffer_size, name=name) + + self._impl = _create_dataset_reader( + creator_fn, filenames, num_parallel_reads, name=name) + variant_tensor = self._impl._variant_tensor # pylint: disable=protected-access + super(TFRecordDatasetV2, self).__init__(variant_tensor) + + def _inputs(self): + return self._impl._inputs() # pylint: disable=protected-access + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) + + +@tf_export(v1=["data.TFRecordDataset"]) +class TFRecordDatasetV1(dataset_ops.DatasetV1Adapter): + """A `Dataset` comprising records from one or more TFRecord files.""" + + def __init__(self, + filenames, + compression_type=None, + buffer_size=None, + num_parallel_reads=None, + name=None): + wrapped = TFRecordDatasetV2( + filenames, compression_type, buffer_size, num_parallel_reads, name=name) + super(TFRecordDatasetV1, self).__init__(wrapped) + + __init__.__doc__ = TFRecordDatasetV2.__init__.__doc__ + + @property + def _filenames(self): + return self._dataset._filenames # pylint: disable=protected-access + + @_filenames.setter + def _filenames(self, value): + self._dataset._filenames = value # pylint: disable=protected-access + + +class _FixedLengthRecordDataset(dataset_ops.DatasetSource): + """A `Dataset` of fixed-length records from one or more binary files.""" + + def __init__(self, + filenames, + record_bytes, + header_bytes=None, + footer_bytes=None, + buffer_size=None, + compression_type=None, + name=None): + """Creates a `FixedLengthRecordDataset`. + + Args: + filenames: A `tf.string` tensor containing one or more filenames. + record_bytes: A `tf.int64` scalar representing the number of bytes in each + record. + header_bytes: (Optional.) A `tf.int64` scalar representing the number of + bytes to skip at the start of a file. + footer_bytes: (Optional.) A `tf.int64` scalar representing the number of + bytes to ignore at the end of a file. + buffer_size: (Optional.) A `tf.int64` scalar representing the number of + bytes to buffer when reading. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. + name: (Optional.) A name for the tf.data operation. + """ + self._filenames = filenames + self._record_bytes = ops.convert_to_tensor( + record_bytes, dtype=dtypes.int64, name="record_bytes") + self._header_bytes = convert.optional_param_to_tensor( + "header_bytes", header_bytes) + self._footer_bytes = convert.optional_param_to_tensor( + "footer_bytes", footer_bytes) + self._buffer_size = convert.optional_param_to_tensor( + "buffer_size", buffer_size, _DEFAULT_READER_BUFFER_SIZE_BYTES) + self._compression_type = convert.optional_param_to_tensor( + "compression_type", + compression_type, + argument_default="", + argument_dtype=dtypes.string) + self._name = name + + variant_tensor = gen_dataset_ops.fixed_length_record_dataset_v2( + self._filenames, + self._header_bytes, + self._record_bytes, + self._footer_bytes, + self._buffer_size, + self._compression_type, + metadata=self._metadata.SerializeToString()) + super(_FixedLengthRecordDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) + + +@tf_export("data.FixedLengthRecordDataset", v1=[]) +class FixedLengthRecordDatasetV2(dataset_ops.DatasetSource): + """A `Dataset` of fixed-length records from one or more binary files. + + The `tf.data.FixedLengthRecordDataset` reads fixed length records from binary + files and creates a dataset where each record becomes an element of the + dataset. The binary files can have a fixed length header and a fixed length + footer, which will both be skipped. + + For example, suppose we have 2 files "fixed_length0.bin" and + "fixed_length1.bin" with the following content: + + >>> with open('/tmp/fixed_length0.bin', 'wb') as f: + ... f.write(b'HEADER012345FOOTER') + >>> with open('/tmp/fixed_length1.bin', 'wb') as f: + ... f.write(b'HEADER6789abFOOTER') + + We can construct a `FixedLengthRecordDataset` from them as follows: + + >>> dataset1 = tf.data.FixedLengthRecordDataset( + ... filenames=['/tmp/fixed_length0.bin', '/tmp/fixed_length1.bin'], + ... record_bytes=2, header_bytes=6, footer_bytes=6) + + The elements of the dataset are: + + >>> for element in dataset1.as_numpy_iterator(): + ... print(element) + b'01' + b'23' + b'45' + b'67' + b'89' + b'ab' + """ + + def __init__(self, + filenames, + record_bytes, + header_bytes=None, + footer_bytes=None, + buffer_size=None, + compression_type=None, + num_parallel_reads=None, + name=None): + """Creates a `FixedLengthRecordDataset`. + + Args: + filenames: A `tf.string` tensor or `tf.data.Dataset` containing one or + more filenames. + record_bytes: A `tf.int64` scalar representing the number of bytes in each + record. + header_bytes: (Optional.) A `tf.int64` scalar representing the number of + bytes to skip at the start of a file. + footer_bytes: (Optional.) A `tf.int64` scalar representing the number of + bytes to ignore at the end of a file. + buffer_size: (Optional.) A `tf.int64` scalar representing the number of + bytes to buffer when reading. + compression_type: (Optional.) A `tf.string` scalar evaluating to one of + `""` (no compression), `"ZLIB"`, or `"GZIP"`. + num_parallel_reads: (Optional.) A `tf.int64` scalar representing the + number of files to read in parallel. If greater than one, the records of + files read in parallel are outputted in an interleaved order. If your + input pipeline is I/O bottlenecked, consider setting this parameter to a + value greater than one to parallelize the I/O. If `None`, files will be + read sequentially. + name: (Optional.) A name for the tf.data operation. + """ + filenames = _create_or_validate_filenames_dataset(filenames, name=name) + + self._filenames = filenames + self._record_bytes = record_bytes + self._header_bytes = header_bytes + self._footer_bytes = footer_bytes + self._buffer_size = buffer_size + self._compression_type = compression_type + + def creator_fn(filename): + return _FixedLengthRecordDataset( + filename, + record_bytes, + header_bytes, + footer_bytes, + buffer_size, + compression_type, + name=name) + + self._impl = _create_dataset_reader( + creator_fn, filenames, num_parallel_reads, name=name) + variant_tensor = self._impl._variant_tensor # pylint: disable=protected-access + super(FixedLengthRecordDatasetV2, self).__init__(variant_tensor) + + @property + def element_spec(self): + return tensor_spec.TensorSpec([], dtypes.string) + + +@tf_export(v1=["data.FixedLengthRecordDataset"]) +class FixedLengthRecordDatasetV1(dataset_ops.DatasetV1Adapter): + """A `Dataset` of fixed-length records from one or more binary files.""" + + def __init__(self, + filenames, + record_bytes, + header_bytes=None, + footer_bytes=None, + buffer_size=None, + compression_type=None, + num_parallel_reads=None, + name=None): + wrapped = FixedLengthRecordDatasetV2( + filenames, + record_bytes, + header_bytes, + footer_bytes, + buffer_size, + compression_type, + num_parallel_reads, + name=name) + super(FixedLengthRecordDatasetV1, self).__init__(wrapped) + + __init__.__doc__ = FixedLengthRecordDatasetV2.__init__.__doc__ + + @property + def _filenames(self): + return self._dataset._filenames # pylint: disable=protected-access + + @_filenames.setter + def _filenames(self, value): + self._dataset._filenames = value # pylint: disable=protected-access + + +if tf2.enabled(): + FixedLengthRecordDataset = FixedLengthRecordDatasetV2 + TFRecordDataset = TFRecordDatasetV2 + TextLineDataset = TextLineDatasetV2 +else: + FixedLengthRecordDataset = FixedLengthRecordDatasetV1 + TFRecordDataset = TFRecordDatasetV1 + TextLineDataset = TextLineDatasetV1 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/rebatch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/rebatch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..527e2ba4389abc6562c2e9af964de4355e1a3885 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/rebatch_op.py @@ -0,0 +1,151 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.rebatch`.""" + +import numpy as np + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _rebatch(input_dataset, batch_size, drop_remainder=False, name=None): + return _RebatchDataset(input_dataset, batch_size, drop_remainder, name) + + +class _RebatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that rebatches elements from its input into new batch sizes. + + `_RebatchDataset(input_dataset, batch_sizes)` is functionally equivalent to + `input_dataset.unbatch().batch(N)`, where the value of N cycles through the + `batch_sizes` input list. The elements produced by this dataset have the same + rank as the elements of the input dataset. + """ + + def __init__(self, + input_dataset, + batch_sizes, + drop_remainder=False, + name=None): + """See `Dataset.rebatch` for details.""" + self._input_dataset = input_dataset + self._batch_sizes = ops.convert_to_tensor( + batch_sizes, dtype=dtypes.int64, name="batch_sizes") + self._drop_remainder = ops.convert_to_tensor( + drop_remainder, dtype=dtypes.bool, name="drop_remainder") + self._name = name + new_batch_dim = self._compute_static_batch_dim() + + # pylint: disable=protected-access + self._element_spec = nest.map_structure( + lambda ts: ts._unbatch()._batch(new_batch_dim), + dataset_ops.get_structure(input_dataset)) + # pylint: enable=protected-access + + # auto_shard rewrite assumes that there's normalize_to_dense before + # rebatch_dataset. + # LINT.IfChange + input_dataset = dataset_ops.normalize_to_dense(input_dataset) + variant_tensor = ged_ops.rebatch_dataset_v2( + input_dataset._variant_tensor, # pylint: disable=protected-access + batch_sizes=batch_sizes, + drop_remainder=drop_remainder, + **self._flat_structure) + # LINT.ThenChange(//tensorflow/core/grappler/optimizers/data/auto_shard.cc) + super().__init__(input_dataset, variant_tensor) + + def _compute_static_batch_dim(self): + """Computes the static batch dimension of a dataset if it can be determined. + + Given the RebatchDataset parameters, determines the batch dimension of this + dataset statically. Returns None if this cannot be determined or is + variable. + + Returns: + An integer representing the batch dimension of the dataset. If it cannot + be determined statically, returns None. + + Raises: + ValueError: The batch_sizes parameter is malformed, input_dataset is + not batched, or input_dataset batch sizes are incompatible with each + other. + """ + new_batch_dim = tensor_util.constant_value(self._batch_sizes) + if new_batch_dim is None: + return None + + if isinstance(new_batch_dim, np.ndarray): + if len(new_batch_dim.shape) == 1: + if np.all(new_batch_dim == new_batch_dim[0]): + new_batch_dim = new_batch_dim[0] + else: + return None + elif len(new_batch_dim.shape) > 1: + raise ValueError( + f"Invalid `batch_sizes`. Expected `batch_sizes` to be a scalar or " + f"a vector. Received `batch_sizes` of rank " + f"{len(new_batch_dim.shape)}.") + + if self._may_form_partial_batches(new_batch_dim): + return None + + return new_batch_dim + + def _may_form_partial_batches(self, desired_batch_size): + """Returns whether this dataset may form partial batches.""" + if tensor_util.constant_value(self._drop_remainder): + return False + + def get_batch_dim(type_spec): + try: + shape = type_spec._to_legacy_output_shapes() # pylint: disable=protected-access + except NotImplementedError: + return None + if not isinstance(shape, tensor_shape.TensorShape): + return None + if shape.rank is None: + return None + if len(shape) < 1: + raise ValueError("Invalid `batch_sizes`. Expected dataset with " + "rank of >= 1 but found a dataset with " + "scalar elements. Fix the issue by adding the `batch` " + "transformation to the dataset.") + return shape.dims[0].value + + input_batch_dims = [ + get_batch_dim(ts) + for ts in nest.flatten(dataset_ops.get_structure(self._input_dataset)) + ] + known_input_batch_dims = [d for d in input_batch_dims if d is not None] + + if not known_input_batch_dims: + return True + + known_input_batch_dims = np.asarray(known_input_batch_dims) + if not np.all(known_input_batch_dims == known_input_batch_dims[0]): + raise ValueError( + f"Invalid `input_dataset.` The batch dimension of component 0 " + f"is {known_input_batch_dims[0]}, while the batch dimension " + f"of component i is {known_input_batch_dims}.") + + return known_input_batch_dims[0] % desired_batch_size != 0 + + @property + def element_spec(self): + return self._element_spec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/repeat_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/repeat_op.py new file mode 100644 index 0000000000000000000000000000000000000000..f85e53638b3c6b9a38292b6605be73c9c46ad499 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/repeat_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.repeat`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _repeat(input_dataset, count, name): # pylint: disable=unused-private-name + return _RepeatDataset(input_dataset, count, name) + + +class _RepeatDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that repeats its input several times.""" + + def __init__(self, input_dataset, count, name=None): + """See `Dataset.repeat()` for details.""" + self._input_dataset = input_dataset + if count is None: + self._count = constant_op.constant(-1, dtype=dtypes.int64, name="count") + else: + self._count = ops.convert_to_tensor( + count, dtype=dtypes.int64, name="count") + self._name = name + variant_tensor = gen_dataset_ops.repeat_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + count=self._count, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/sample_from_datasets_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/sample_from_datasets_op.py new file mode 100644 index 0000000000000000000000000000000000000000..29fc0d627d1436eaa1a09c674017a969ba8c631a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/sample_from_datasets_op.py @@ -0,0 +1,123 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.sample_from_datasets`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import directed_interleave_op +from tensorflow.python.data.ops import map_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_stateless_random_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.types import data as data_types + + +def _sample_from_datasets(datasets, # pylint: disable=unused-private-name + weights=None, + seed=None, + stop_on_empty_dataset=False, + rerandomize_each_iteration=None): + """See `Dataset.sample_from_datasets()` for details.""" + + def _skip_datasets_with_zero_weight(datasets, weights): + datasets_and_weights = [(dataset, weight) + for (dataset, weight) in zip(datasets, weights) + if weight > 0] + return (zip(*datasets_and_weights) if datasets_and_weights else + ([datasets[0].take(0)], [1.])) + + if not datasets: + raise ValueError("Invalid `datasets`. `datasets` should not be empty.") + + if not isinstance(weights, data_types.DatasetV2): + if weights is None: + # Select inputs with uniform probability. + logits = [[1.0] * len(datasets)] + + else: + if isinstance(weights, tensor.Tensor): + if not weights.shape.is_compatible_with([len(datasets)]): + raise ValueError(f"Invalid `weights`. The shape of `weights` " + f"should be compatible with `[len(datasets)]` " + f"but is {weights.shape}.") + else: + if len(datasets) != len(weights): + raise ValueError(f"Invalid `weights`. `weights` should have the " + f"same length as `datasets` but got " + f"`len(weights)={len(weights)}` vs. " + f"`len(datasets)={len(datasets)}`.") + + # Use the given `weights` as the probability of choosing the respective + # input. + if not isinstance(weights, tensor.Tensor): + datasets, weights = _skip_datasets_with_zero_weight(datasets, weights) + weights = ops.convert_to_tensor(weights, name="weights") + if weights.dtype not in (dtypes.float32, dtypes.float64): + raise TypeError(f"Invalid `weights`. `weights` type must be either " + f"`tf.float32` or `tf.float64` but is " + f"{weights.dtype}.") + + # The `stateless_multinomial()` op expects log-probabilities, as opposed + # to weights. + logits = array_ops.expand_dims(math_ops.log(weights, name="logits"), 0) + + # NOTE(mrry): We only specialize when `weights` is not a `Dataset`. When + # it is a `Dataset`, it is possible that evaluating it has a side effect + # the user depends on. + if len(datasets) == 1: + return datasets[0] + + def select_dataset_constant_logits(seed): + return array_ops.squeeze( + gen_stateless_random_ops.stateless_multinomial( + logits, 1, seed=seed), + axis=[0, 1]) + + selector_input = map_op._MapDataset( # pylint: disable=protected-access + dataset_ops.Dataset.random( + seed=seed, + rerandomize_each_iteration=rerandomize_each_iteration).batch(2), + select_dataset_constant_logits, + use_inter_op_parallelism=False) + + else: # isinstance(weights, DatasetV2) + # Use each element of the given `weights` dataset as the probability of + # choosing the respective input. + # + # The `stateless_multinomial()` op expects log-probabilities, as opposed + # to weights. + logits_ds = weights.map(lambda *p: math_ops.log(p, name="logits")) + + def select_dataset_varying_logits(logits, seed): + return array_ops.squeeze( + gen_stateless_random_ops.stateless_multinomial( + logits, 1, seed=seed), + axis=[0, 1]) + + logits_and_seeds = dataset_ops.Dataset.zip( + (logits_ds, + dataset_ops.Dataset.random( + seed=seed, + rerandomize_each_iteration=rerandomize_each_iteration).batch(2))) + selector_input = map_op._MapDataset( # pylint: disable=protected-access + logits_and_seeds, + select_dataset_varying_logits, + use_inter_op_parallelism=False) + + return directed_interleave_op._directed_interleave( # pylint: disable=protected-access + selector_input, datasets, stop_on_empty_dataset + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/save_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/save_op.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a63477aeeb3f5353959dae9e2eeb6b9751ec14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/save_op.py @@ -0,0 +1,118 @@ +# 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. +# ============================================================================== +"""Implementation of SaveDataset in Python.""" +import os + +from tensorflow.python.checkpoint import checkpoint as checkpoint_lib +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import structure +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.platform import gfile +# TODO(b/238903802): Use TypeSpec serialization methods directly. +from tensorflow.python.saved_model import nested_structure_coder + + +def _save(input_dataset, + path, + compression=None, + shard_func=None, + checkpoint_args=None): + """Implements the save function and checkpoint functionality.""" + if context.executing_eagerly() and checkpoint_args: + save_dataset = _SaveDataset(input_dataset, path, shard_func, compression) + save_iterator = iter(save_dataset) + + if "checkpoint" in checkpoint_args: + raise ValueError( + "'Invalid `checkpoint_args`. `checkpoint_args` are not allowed " + "to include 'checkpoint'." + ) + checkpoint = checkpoint_lib.Checkpoint(iterator=save_iterator) + checkpoint_args["checkpoint"] = checkpoint + manager = checkpoint_management.CheckpointManager(**checkpoint_args) + checkpoint.restore(manager.latest_checkpoint) + + for _ in enumerate(save_iterator): + if "step_counter" in checkpoint_args: + checkpoint_args["step_counter"].assign_add(delta=1) + manager.save(check_interval=True) + else: + dataset, shard_func, use_shard_func, path = set_save_dataset_attributes( + input_dataset, shard_func, path) + return ged_ops.save_dataset( + dataset._variant_tensor, # pylint: disable=protected-access + path=path, + shard_func_other_args=shard_func.captured_inputs, + compression=compression, + shard_func=shard_func, + use_shard_func=use_shard_func) + + +class _SaveDataset(dataset_ops.UnaryDataset): + """"A dataset that loads previously saved dataset.""" + + def __init__(self, dataset, path, shard_func, compression): + self._element_spec = dataset.element_spec + self._shard_func = shard_func + dataset, shard_func, use_shard_func, path = set_save_dataset_attributes( + dataset, shard_func, path) + variant_tensor = ged_ops.save_dataset_v2( + dataset._variant_tensor, # pylint: disable=protected-access + path=path, + shard_func_other_args=shard_func.captured_inputs, + shard_func=shard_func, + use_shard_func=use_shard_func, + compression=compression, + output_types=structure.get_flat_tensor_types(dataset.element_spec), + output_shapes=structure.get_flat_tensor_shapes(dataset.element_spec), + ) + super().__init__(dataset, variant_tensor) + + def _functions(self): + return [self._shard_func] + + @property + def element_spec(self): + return self._element_spec + + +def set_save_dataset_attributes(dataset, shard_func, path): + """Sets parameters for SaveDatasetOp and SaveDatasetV2Op.""" + if shard_func is None: + use_shard_func = False + shard_func = lambda *x: None # a dummy function that will not be used + else: + use_shard_func = True + wrapped_func = structured_function.StructuredFunctionWrapper( + shard_func, + "save()", + input_structure=dataset.element_spec, + add_to_graph=False) + encoded = nested_structure_coder.encode_structure(dataset.element_spec) + gfile.MakeDirs(path) + with gfile.GFile(os.path.join(path, dataset_ops.DATASET_SPEC_FILENAME), + "wb") as f: + f.write(encoded.SerializeToString()) + path = ops.convert_to_tensor(path, dtype=dtypes.string, name="path") + shard_func = wrapped_func.function + shard_func.add_to_graph(ops.get_default_graph()) + # pylint: disable=protected-access + dataset._apply_debug_options() + return dataset, shard_func, use_shard_func, path diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/scan_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/scan_op.py new file mode 100644 index 0000000000000000000000000000000000000000..537eb6975c83fd0d4888409279f2db54b1f3d2e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/scan_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.shuffle`.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.util.compat import collections_abc + + +def _scan(input_dataset, + initial_state, + scan_func, + use_default_device=None, + name=None): + return _ScanDataset( + input_dataset, initial_state, scan_func, use_default_device, name=name) + + +class _ScanDataset(dataset_ops.UnaryDataset): + """A dataset that scans a function across its input.""" + + def __init__(self, + input_dataset, + initial_state, + scan_func, + use_default_device=None, + name=None): + """See `scan()` for details.""" + self._input_dataset = input_dataset + self._initial_state = structure.normalize_element(initial_state) + + # Compute initial values for the state classes, shapes and types based on + # the initial state. The shapes may be refined by running `tf_scan_func` one + # or more times below. + self._state_structure = structure.type_spec_from_value(self._initial_state) + + # Iteratively rerun the scan function until reaching a fixed point on + # `self._state_shapes`. + need_to_rerun = True + while need_to_rerun: + + wrapped_func = structured_function.StructuredFunctionWrapper( + scan_func, + self._transformation_name(), + input_structure=(self._state_structure, input_dataset.element_spec), + add_to_graph=False) + if not (isinstance(wrapped_func.output_types, collections_abc.Sequence) + and len(wrapped_func.output_types) == 2): + raise TypeError(f"Invalid `scan_func`. `scan_func` should return a " + f"pair consisting of new state and the output value " + f"but its return type is " + f"{wrapped_func.output_structure}.") + + new_state_classes, self._output_classes = wrapped_func.output_classes + + # Extract and validate class information from the returned values. + new_state_classes, output_classes = wrapped_func.output_classes + old_state_classes = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + self._state_structure) + for new_state_class, old_state_class in zip( + nest.flatten(new_state_classes), nest.flatten(old_state_classes)): + if not issubclass(new_state_class, old_state_class): + raise TypeError(f"Invalid `scan_func`. The element classes for the " + f"new state must match the initial state. Expected " + f"{old_state_classes}, got {new_state_classes}.") + + # Extract and validate type information from the returned values. + new_state_types, output_types = wrapped_func.output_types + old_state_types = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + self._state_structure) + for new_state_type, old_state_type in zip( + nest.flatten(new_state_types), nest.flatten(old_state_types)): + if new_state_type != old_state_type: + raise TypeError(f"Invalid `scan_func`. The element types for the " + f"new state must match the initial state. Expected " + f"{old_state_types}, got {new_state_types}.") + + # Extract shape information from the returned values. + new_state_shapes, output_shapes = wrapped_func.output_shapes + old_state_shapes = nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + self._state_structure) + self._element_spec = structure.convert_legacy_structure( + output_types, output_shapes, output_classes) + + flat_state_shapes = nest.flatten(old_state_shapes) + flat_new_state_shapes = nest.flatten(new_state_shapes) + weakened_state_shapes = [ + original.most_specific_compatible_shape(new) + for original, new in zip(flat_state_shapes, flat_new_state_shapes) + ] + + need_to_rerun = False + for original_shape, weakened_shape in zip(flat_state_shapes, + weakened_state_shapes): + if original_shape.ndims is not None and ( + weakened_shape.ndims is None or + original_shape.as_list() != weakened_shape.as_list()): + need_to_rerun = True + break + + if need_to_rerun: + # TODO(b/110122868): Support a "most specific compatible structure" + # method for combining structures, to avoid using legacy structures + # in this method. + self._state_structure = structure.convert_legacy_structure( + old_state_types, + nest.pack_sequence_as(old_state_shapes, weakened_state_shapes), + old_state_classes) + + self._scan_func = wrapped_func + self._scan_func.function.add_to_graph(ops.get_default_graph()) + + self._name = name + # pylint: disable=protected-access + if use_default_device is not None: + variant_tensor = ged_ops.scan_dataset( + self._input_dataset._variant_tensor, + structure.to_tensor_list(self._state_structure, self._initial_state), + self._scan_func.function.captured_inputs, + f=self._scan_func.function, + preserve_cardinality=True, + use_default_device=use_default_device, + **self._common_args) + else: + variant_tensor = ged_ops.scan_dataset( + self._input_dataset._variant_tensor, + structure.to_tensor_list(self._state_structure, self._initial_state), + self._scan_func.function.captured_inputs, + f=self._scan_func.function, + preserve_cardinality=True, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._scan_func] + + @property + def element_spec(self): + return self._element_spec + + def _transformation_name(self): + return "Dataset.scan()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/shard_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/shard_op.py new file mode 100644 index 0000000000000000000000000000000000000000..800af81a0484a9906e179a4fb977bddf84ccf9d6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/shard_op.py @@ -0,0 +1,43 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.shard`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _shard(input_dataset, num_shards, index, name): # pylint: disable=unused-private-name + """See `Dataset.shard()` for details.""" + return _ShardDataset(input_dataset, num_shards, index, name) + + +class _ShardDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` for sharding its input.""" + + def __init__(self, input_dataset, num_shards, index, name): + """See `Dataset.shard()` for details.""" + self._input_dataset = input_dataset + self._num_shards = ops.convert_to_tensor( + num_shards, dtype=dtypes.int64, name="num_shards") + self._index = ops.convert_to_tensor(index, dtype=dtypes.int64, name="index") + self._name = name + variant_tensor = gen_dataset_ops.shard_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + num_shards=self._num_shards, + index=self._index, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/shuffle_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/shuffle_op.py new file mode 100644 index 0000000000000000000000000000000000000000..a85bf09f4390986da7e17664812b1d5b0fb311d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/shuffle_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.shuffle`.""" +from tensorflow.python import tf2 +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import random_seed +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _shuffle( # pylint: disable=unused-private-name + input_dataset, + buffer_size, + seed=None, + reshuffle_each_iteration=None, + name=None): + return _ShuffleDataset( + input_dataset, buffer_size, seed, reshuffle_each_iteration, name=name) + + +class _ShuffleDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` that randomly shuffles the elements of its input.""" + + def __init__(self, + input_dataset, + buffer_size, + seed=None, + reshuffle_each_iteration=None, + name=None): + """See `Dataset.shuffle()` for details.""" + self._input_dataset = input_dataset + self._buffer_size = ops.convert_to_tensor( + buffer_size, dtype=dtypes.int64, name="buffer_size") + self._seed, self._seed2 = random_seed.get_seed(seed) + if reshuffle_each_iteration is None: + reshuffle_each_iteration = True + self._reshuffle_each_iteration = reshuffle_each_iteration + self._name = name + + if (tf2.enabled() and + (context.executing_eagerly() or ops.inside_function())): + variant_tensor = gen_dataset_ops.shuffle_dataset_v3( + input_dataset._variant_tensor, # pylint: disable=protected-access + buffer_size=self._buffer_size, + seed=self._seed, + seed2=self._seed2, + seed_generator=gen_dataset_ops.dummy_seed_generator(), + reshuffle_each_iteration=self._reshuffle_each_iteration, + **self._common_args) + else: + variant_tensor = gen_dataset_ops.shuffle_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + buffer_size=self._buffer_size, + seed=self._seed, + seed2=self._seed2, + reshuffle_each_iteration=self._reshuffle_each_iteration, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/skip_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/skip_op.py new file mode 100644 index 0000000000000000000000000000000000000000..9a2959b648d77400772db8c8071823fe71351474 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/skip_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.skip`.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _skip(self, count, name=None): # pylint: disable=unused-private-name + return _SkipDataset(self, count, name) + + +class _SkipDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` skipping the first `count` elements from its input.""" + + def __init__(self, input_dataset, count, name=None): + """See `Dataset.skip()` for details.""" + self._input_dataset = input_dataset + self._count = ops.convert_to_tensor(count, dtype=dtypes.int64, name="count") + self._name = name + variant_tensor = gen_dataset_ops.skip_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + count=self._count, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/snapshot_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/snapshot_op.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc93790051b62e03f530b0da72d2d6199d6cd69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/snapshot_op.py @@ -0,0 +1,119 @@ +# 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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.snapshot`.""" + +import multiprocessing + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _snapshot(input_dataset, # pylint: disable=unused-private-name + path, + compression="AUTO", + reader_func=None, + shard_func=None, + name=None): + """See `Dataset.snapshot()` for details.""" + + project_func = None + if shard_func is None: + input_dataset = input_dataset.enumerate(name=name) + # This sets the amount of parallelism based on the number of CPU cores on + # the machine where this Python code is executed, which may differ from + # the number of CPU cores where the input pipeline graph is actually + # executed (e.g. remote Cloud TPU workers). + local_shard_func = lambda index, _: index % multiprocessing.cpu_count() + project_func = lambda _, elem: elem + else: + local_shard_func = shard_func + dataset = _SnapshotDataset( + input_dataset=input_dataset, + path=path, + compression=compression, + reader_func=reader_func, + # This will not do the right thing where the graph is built on a + # different machine than the executor (e.g. Cloud TPUs). + shard_func=local_shard_func, + name=name) + if project_func is not None: + dataset = dataset.map(project_func, name=name) + return dataset + + +class _SnapshotDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A dataset that allows saving and re-use of already processed data.""" + + def __init__(self, + input_dataset, + path, + shard_func, + compression=None, + reader_func=None, + pending_snapshot_expiry_seconds=None, + use_legacy_function=False, + name=None): + + if reader_func is None: + reader_func = lambda datasets: datasets.interleave( # pylint:disable=g-long-lambda + lambda x: x, + cycle_length=multiprocessing.cpu_count(), + num_parallel_calls=dataset_ops.AUTOTUNE) + + self._input_dataset = input_dataset + self._path = path + self._compression = compression + + self._reader_func = structured_function.StructuredFunctionWrapper( + reader_func, + self._transformation_name() + ".reader_func", + # Dataset of datasets of input elements + input_structure=dataset_ops.DatasetSpec( + dataset_ops.DatasetSpec(input_dataset.element_spec)), + use_legacy_function=use_legacy_function) + self._shard_func = structured_function.StructuredFunctionWrapper( + shard_func, + self._transformation_name() + ".shard_func", + dataset=input_dataset, + use_legacy_function=use_legacy_function) + + if ((not self._shard_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.int32))) and + (not self._shard_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.int64)))): + raise TypeError(f"Invalid `shard_func`. `shard_func` must return " + f"`tf.int64` scalar tensor but its return type is " + f"{self._shard_func.output_structure}.") + + self._name = name + variant_tensor = ged_ops.snapshot_dataset_v2( + input_dataset._variant_tensor, # pylint: disable=protected-access + path, + self._reader_func.function.captured_inputs, + self._shard_func.function.captured_inputs, + compression=compression, + reader_func=self._reader_func.function, + shard_func=self._shard_func.function, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._reader_func, self._shard_func] + + def _transformation_name(self): + return "Dataset.snapshot()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/sparse_batch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/sparse_batch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..c274a9a35c282d9379d9b247cdefc1c710b77be2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/sparse_batch_op.py @@ -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. +# ============================================================================== +"""The implementation of `tf.data.Dataset.sparse_batch`.""" +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import convert +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _sparse_batch(input_dataset, batch_size, row_shape, name=None): + return _DenseToSparseBatchDataset(input_dataset, batch_size, row_shape, name) + + +class _DenseToSparseBatchDataset(dataset_ops.UnaryDataset): + """A `Dataset` that batches ragged dense elements into `tf.sparse.SparseTensor`s.""" + + def __init__(self, input_dataset, batch_size, row_shape, name=None): + """See `Dataset.dense_to_sparse_batch()` for more details.""" + if not isinstance( + dataset_ops.get_legacy_output_types(input_dataset), dtypes.DType): + raise TypeError("`dense_to_sparse_batch` requires an input dataset whose " + "elements have a single component, but the given dataset " + "has the following component types: " + f"{dataset_ops.get_legacy_output_types(input_dataset)}.") + self._input_dataset = input_dataset + self._batch_size = batch_size + self._row_shape = row_shape + self._element_spec = sparse_tensor.SparseTensorSpec( + tensor_shape.TensorShape([None]).concatenate(self._row_shape), + dataset_ops.get_legacy_output_types(input_dataset)) + self._name = name + variant_tensor = ged_ops.dense_to_sparse_batch_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + self._batch_size, + row_shape=convert.partial_shape_to_tensor(self._row_shape), + **self._flat_structure) + super(_DenseToSparseBatchDataset, self).__init__(input_dataset, + variant_tensor) + + @property + def element_spec(self): + return self._element_spec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/structured_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/structured_function.py new file mode 100644 index 0000000000000000000000000000000000000000..c67cecd39f8571372da2ee30d1483267301aa4c9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/structured_function.py @@ -0,0 +1,309 @@ +# 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. +# ============================================================================== +"""Utilities for managing tf.data user-defined functions.""" + +import warnings + +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.data.ops import debug_mode +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function + +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.ops import script_ops +from tensorflow.python.util import function_utils +from tensorflow.python.util import variable_utils + + +def _should_pack(arg): + """Determines whether the caller needs to pack the argument in a tuple. + + If user-defined function returns a list of tensors, `nest.flatten()` and + `ops.convert_to_tensor()` and would conspire to attempt to stack those tensors + into a single tensor because the tf.data version of `nest.flatten()` does + not recurse into lists. Since it is more likely that the list arose from + returning the result of an operation (such as `tf.numpy_function()`) that + returns a list of not-necessarily-stackable tensors, we treat the returned + value as a `tuple` instead. A user wishing to pack the return value into a + single tensor can use an explicit `tf.stack()` before returning. + + Args: + arg: argument to check + + Returns: + Indication of whether the caller needs to pack the argument in a tuple. + """ + return isinstance(arg, list) + + +def _should_unpack(arg): + """Determines whether the caller needs to unpack the argument from a tuple. + + Args: + arg: argument to check + + Returns: + Indication of whether the caller needs to unpack the argument from a tuple. + """ + return type(arg) is tuple # pylint: disable=unidiomatic-typecheck + + +class StructuredFunctionWrapper(): + """A function wrapper that supports structured arguments and return values.""" + + def __init__(self, + func, + transformation_name, + dataset=None, + input_classes=None, + input_shapes=None, + input_types=None, + input_structure=None, + add_to_graph=True, + use_legacy_function=False, + defun_kwargs=None): + """Creates a new `StructuredFunctionWrapper` for the given function. + + Args: + func: A function from a (nested) structure to another (nested) structure. + transformation_name: Human-readable name of the transformation in which + this function is being instantiated, for error messages. + dataset: (Optional.) A `tf.data.Dataset`. If given, the structure of this + dataset will be assumed as the structure for `func` arguments; otherwise + `input_classes`, `input_shapes`, and `input_types` must be defined. + input_classes: (Optional.) A (nested) structure of `type`. If given, this + argument defines the Python types for `func` arguments. + input_shapes: (Optional.) A (nested) structure of `tf.TensorShape`. If + given, this argument defines the shapes and structure for `func` + arguments. + input_types: (Optional.) A (nested) structure of `tf.DType`. If given, + this argument defines the element types and structure for `func` + arguments. + input_structure: (Optional.) A `Structure` object. If given, this argument + defines the element types and structure for `func` arguments. + add_to_graph: (Optional.) If `True`, the function will be added to the + default graph, if it exists. + use_legacy_function: (Optional.) A boolean that determines whether the + function be created using `tensorflow.python.eager.function.defun` + (default behavior) or `tensorflow.python.framework.function.Defun` + (legacy behavior). + defun_kwargs: (Optional.) A dictionary mapping string argument names to + values. If supplied, will be passed to `function` as keyword arguments. + + Raises: + ValueError: If an invalid combination of `dataset`, `input_classes`, + `input_shapes`, and `input_types` is passed. + """ + # pylint: disable=protected-access + if input_structure is None: + if dataset is None: + if input_classes is None or input_shapes is None or input_types is None: + raise ValueError("Either `dataset`, `input_structure` or all of " + "`input_classes`, `input_shapes`, and `input_types` " + "must be specified.") + self._input_structure = structure.convert_legacy_structure( + input_types, input_shapes, input_classes) + else: + if not (input_classes is None and input_shapes is None and + input_types is None): + raise ValueError("Either `dataset`, `input_structure` or all of " + "`input_classes`, `input_shapes`, and `input_types` " + "must be specified.") + self._input_structure = dataset.element_spec + else: + if not (dataset is None and input_classes is None and + input_shapes is None and input_types is None): + raise ValueError("Either `dataset`, `input_structure`, or all of " + "`input_classes`, `input_shapes`, and `input_types` " + "must be specified.") + self._input_structure = input_structure + + self._func = func + + if defun_kwargs is None: + defun_kwargs = {} + + readable_transformation_name = transformation_name.replace( + ".", "_")[:-2] if len(transformation_name) > 2 else "" + + func_name = "_".join( + [readable_transformation_name, + function_utils.get_func_name(func)]) + # Sanitize function name to remove symbols that interfere with graph + # construction. + for symbol in ["<", ">", "\\", "'", " "]: + func_name = func_name.replace(symbol, "") + + ag_ctx = autograph_ctx.control_status_ctx() + + def wrapper_helper(*args): + """Wrapper for passing nested structures to and from tf.data functions.""" + nested_args = structure.from_compatible_tensor_list( + self._input_structure, args) + if not _should_unpack(nested_args): + nested_args = (nested_args,) + ret = autograph.tf_convert(self._func, ag_ctx)(*nested_args) + ret = variable_utils.convert_variables_to_tensors(ret) + if _should_pack(ret): + ret = tuple(ret) + + try: + self._output_structure = structure.type_spec_from_value(ret) + except (ValueError, TypeError) as e: + raise TypeError(f"Unsupported return value from function passed to " + f"{transformation_name}: {ret}.") from e + return ret + + def trace_legacy_function(defun_kwargs): + + @function.Defun(*structure.get_flat_tensor_types(self._input_structure), + **defun_kwargs) + def wrapped_fn(*args): + ret = wrapper_helper(*args) + return structure.to_tensor_list(self._output_structure, ret) + + return lambda: wrapped_fn + + def trace_py_function(defun_kwargs): + # First we trace the function to infer the output structure. + def unused(*args): # pylint: disable=missing-docstring,unused-variable + ret = wrapper_helper(*args) + ret = structure.to_tensor_list(self._output_structure, ret) + return [ops.convert_to_tensor(t) for t in ret] + + func_name = defun_kwargs.pop("func_name", "unused") + tf_function = def_function.Function( + python_function=unused, + name=func_name, + input_signature=structure.get_flat_tensor_specs( + self._input_structure + ), + autograph=False, + experimental_attributes=defun_kwargs, + ) + + _ = tf_function.get_concrete_function() + + def py_function_wrapper(*args): + nested_args = structure.from_compatible_tensor_list( + self._input_structure, args) + if not _should_unpack(nested_args): + nested_args = (nested_args,) + ret = self._func(*nested_args) + if _should_pack(ret): + ret = tuple(ret) + ret = structure.to_tensor_list(self._output_structure, ret) + return [ops.convert_to_tensor(t) for t in ret] + + # Next we trace the function wrapped in `eager_py_func` to force eager + # execution. + @def_function.function( + input_signature=structure.get_flat_tensor_specs( + self._input_structure), + autograph=False, + experimental_attributes=defun_kwargs) + def wrapped_fn(*args): # pylint: disable=missing-docstring + return script_ops.eager_py_func( + py_function_wrapper, args, + structure.get_flat_tensor_types(self._output_structure)) + + return wrapped_fn.get_concrete_function + + def trace_tf_function(defun_kwargs): + # Note: wrapper_helper will apply autograph based on context. + def wrapped_fn(*args): # pylint: disable=missing-docstring + ret = wrapper_helper(*args) + ret = structure.to_tensor_list(self._output_structure, ret) + return [ops.convert_to_tensor(t) for t in ret] + + func_name = defun_kwargs.pop("func_name", "wrapped_fn") + tf_function = def_function.Function( + python_function=wrapped_fn, + name=func_name, + input_signature=structure.get_flat_tensor_specs( + self._input_structure + ), + autograph=False, + experimental_attributes=defun_kwargs, + ) + + return tf_function.get_concrete_function + + if use_legacy_function: + defun_kwargs.update({"func_name": func_name + "_" + str(ops.uid())}) + fn_factory = trace_legacy_function(defun_kwargs) + else: + defun_kwargs.update({"func_name": func_name}) + defun_kwargs.update({"_tf_data_function": True}) + if debug_mode.DEBUG_MODE: + fn_factory = trace_py_function(defun_kwargs) + else: + if def_function.functions_run_eagerly(): + warnings.warn( + "Even though the `tf.config.experimental_run_functions_eagerly` " + "option is set, this option does not apply to tf.data functions. " + "To force eager execution of tf.data functions, please use " + "`tf.data.experimental.enable_debug_mode()`.") + fn_factory = trace_tf_function(defun_kwargs) + + self._function = fn_factory() + # There is no graph to add in eager mode. + add_to_graph &= not context.executing_eagerly() + # There are some lifetime issues when a legacy function is not added to a + # out-living graph. It's already deprecated so de-prioritizing the fix. + add_to_graph |= use_legacy_function + if add_to_graph: + self._function.add_to_graph(ops.get_default_graph()) + + if not use_legacy_function: + outer_graph_seed = ops.get_default_graph().seed + if outer_graph_seed and self._function.graph.seed == outer_graph_seed: + if self._function.graph._seed_used: + warnings.warn( + "Seed %s from outer graph might be getting used by function %s, " + "if the random op has not been provided any seed. Explicitly set " + "the seed in the function if this is not the intended behavior." % + (outer_graph_seed, func_name), + stacklevel=4) + + @property + def output_structure(self): + return self._output_structure + + @property + def output_classes(self): + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + self._output_structure) + + @property + def output_shapes(self): + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + self._output_structure) + + @property + def output_types(self): + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + self._output_structure) + + @property + def function(self): + return self._function diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/take_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/take_op.py new file mode 100644 index 0000000000000000000000000000000000000000..ee86836c7386662be818c7adcbb411fa5f79e046 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/take_op.py @@ -0,0 +1,39 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.skip`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _take(self, count, name=None): # pylint: disable=unused-private-name + return _TakeDataset(self, count, name=name) + + +class _TakeDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A `Dataset` containing the first `count` elements from its input.""" + + def __init__(self, input_dataset, count, name=None): + """See `Dataset.take()` for details.""" + self._input_dataset = input_dataset + self._count = ops.convert_to_tensor(count, dtype=dtypes.int64, name="count") + self._name = name + variant_tensor = gen_dataset_ops.take_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + count=self._count, + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/take_while_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/take_while_op.py new file mode 100644 index 0000000000000000000000000000000000000000..de93101d327f5fa9233931d0887aa852b07f08f3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/take_while_op.py @@ -0,0 +1,58 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.take_while`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import structured_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _take_while(input_dataset, predicate, name=None): # pylint: disable=unused-private-name + """See `Dataset.take_while()` for details.""" + return _TakeWhileDataset(input_dataset, predicate, name=name) + + +class _TakeWhileDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A dataset that stops iteration when `predicate` returns false.""" + + def __init__(self, input_dataset, predicate, name=None): + """See `take_while()` for details.""" + + self._input_dataset = input_dataset + wrapped_func = structured_function.StructuredFunctionWrapper( + predicate, self._transformation_name(), dataset=self._input_dataset) + + if not wrapped_func.output_structure.is_compatible_with( + tensor_spec.TensorSpec([], dtypes.bool)): + raise ValueError(f"Invalid `predicate`. `predicate` must return a " + f"`tf.bool` scalar tensor but its return type is" + f"{wrapped_func.output_structure}.") + + self._predicate = wrapped_func + self._name = name + variant_tensor = ged_ops.take_while_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + other_arguments=self._predicate.function.captured_inputs, + predicate=self._predicate.function, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + def _functions(self): + return [self._predicate] + + def _transformation_name(self): + return "Dataset.take_while()" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/test_mode.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/test_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..941e7c70ff4017efa06cf6a028f47a5e57d15671 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/test_mode.py @@ -0,0 +1,32 @@ +# 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. +# ============================================================================== +"""Python test mode enabler. + +Enables test mode for tf.data. + +The test mode can be used to set up custom values for features and +experiments as required in the unit tests. + +For example, if `warm_start` feature needs to be enabled exclusively for the +unit tests, the tests can enable the test mode using `toggle_test_mode` and +the default value of `warm_start` can be set as per the value of `TEST_MODE`. +""" + +TEST_MODE = False + + +def toggle_test_mode(test_mode): + global TEST_MODE + TEST_MODE = test_mode diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/unbatch_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/unbatch_op.py new file mode 100644 index 0000000000000000000000000000000000000000..0e5b085aecc40ce5209e25021204e8f8206e431f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/unbatch_op.py @@ -0,0 +1,58 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.unbatch`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops + + +def _unbatch(input_dataset, name=None): # pylint: disable=unused-private-name + """See `Dataset.unbatch()` for details.""" + normalized_dataset = dataset_ops.normalize_to_dense(input_dataset) + return _UnbatchDataset(normalized_dataset, name=name) + + +class _UnbatchDataset(dataset_ops.UnaryDataset): + """A dataset that splits the elements of its input into multiple elements.""" + + def __init__(self, input_dataset, name=None): + """See `unbatch()` for more details.""" + flat_shapes = input_dataset._flat_shapes # pylint: disable=protected-access + if any(s.ndims == 0 for s in flat_shapes): + raise ValueError("Cannot unbatch an input with scalar components.") + known_batch_dim = tensor_shape.Dimension(None) + for s in flat_shapes: + try: + known_batch_dim = known_batch_dim.merge_with(s[0]) + except ValueError as e: + raise ValueError( + f"`unbatch()` is only supported for datasets of elements whose " + f"components have a matching leading dimension. Encountered both " + f"{known_batch_dim} and {s[0]}.") from e + self._input_dataset = input_dataset + self._structure = nest.map_structure( + lambda component_spec: component_spec._unbatch(), # pylint: disable=protected-access + dataset_ops.get_structure(input_dataset)) + self._name = name + variant_tensor = ged_ops.unbatch_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/unique_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/unique_op.py new file mode 100644 index 0000000000000000000000000000000000000000..a50a85b2ea6d95bb77a21c14260b200a98c1e320 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/unique_op.py @@ -0,0 +1,42 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.unique`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import gen_experimental_dataset_ops + + +def _unique(input_dataset, name): # pylint: disable=unused-private-name + return _UniqueDataset(input_dataset, name) + + +class _UniqueDataset(dataset_ops.UnaryUnchangedStructureDataset): + """A dataset containing the unique elements of an input dataset.""" + + def __init__(self, input_dataset, name=None): + """See `tf.data.Dataset.unique` for details.""" + self._input_dataset = input_dataset + for ty in nest.flatten(dataset_ops.get_legacy_output_types(input_dataset)): + if ty not in (dtypes.int32, dtypes.int64, dtypes.string): + raise TypeError( + f"`tf.data.Dataset.unique` does not support type {ty} -- only " + f"`tf.int32`, `tf.int64`, and `tf.string` are supported.") + self._name = name + variant_tensor = gen_experimental_dataset_ops.unique_dataset( + self._input_dataset._variant_tensor, # pylint: disable=protected-access + **self._common_args) + super().__init__(input_dataset, variant_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/window_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/window_op.py new file mode 100644 index 0000000000000000000000000000000000000000..5df4a4288145567c62985a515b3ff5ca392ae6d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/window_op.py @@ -0,0 +1,76 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.window`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.data.util import structure +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_dataset_ops + + +def _window(input_dataset, size, shift, stride, drop_remainder, name): + if shift is None: + shift = size + return _WindowDataset( + input_dataset, size, shift, stride, drop_remainder, name=name) + + +class _WindowDataset(dataset_ops.UnaryDataset): + """A dataset that creates window datasets from the input elements.""" + + def __init__(self, + input_dataset, + size, + shift, + stride, + drop_remainder, + name=None): + """See `window()` for more details.""" + self._input_dataset = input_dataset + self._size = ops.convert_to_tensor(size, dtype=dtypes.int64, name="size") + self._shift = ops.convert_to_tensor(shift, dtype=dtypes.int64, name="shift") + self._stride = ops.convert_to_tensor( + stride, dtype=dtypes.int64, name="stride") + self._drop_remainder = ops.convert_to_tensor( + drop_remainder, dtype=dtypes.bool, name="drop_remainder") + self._structure = nest.pack_sequence_as( + dataset_ops.get_legacy_output_classes(input_dataset), + [ + dataset_ops.DatasetSpec( # pylint: disable=g-complex-comprehension + structure.convert_legacy_structure(output_type, output_shape, + output_class)) + for output_class, output_shape, output_type in zip( + nest.flatten( + dataset_ops.get_legacy_output_classes(input_dataset)), + nest.flatten( + dataset_ops.get_legacy_output_shapes(input_dataset)), + nest.flatten( + dataset_ops.get_legacy_output_types(input_dataset))) + ]) + self._name = name + variant_tensor = gen_dataset_ops.window_dataset( + input_dataset._variant_tensor, # pylint: disable=protected-access + size=self._size, + shift=self._shift, + stride=self._stride, + drop_remainder=self._drop_remainder, + **self._common_args) + super().__init__(input_dataset, variant_tensor) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/zip_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/zip_op.py new file mode 100644 index 0000000000000000000000000000000000000000..b148cf014fd001ab176869feaf11dcf34fa2c5be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/ops/zip_op.py @@ -0,0 +1,62 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The implementation of `tf.data.Dataset.zip`.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.util import nest +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.types import data as data_types + + +def _zip(datasets, name): # pylint: disable=redefined-builtin + return _ZipDataset(datasets, name) + + +class _ZipDataset(dataset_ops.DatasetV2): + """A `Dataset` that zips its inputs together.""" + + def __init__(self, datasets, name=None): + """See `Dataset.zip()` for details.""" + for ds in nest.flatten(datasets): + if not isinstance(ds, data_types.DatasetV2): + if isinstance(ds, list): + raise TypeError( + "Invalid input to `zip`. Inputs are expected to be (nested)" + " structures of `tf.data.Dataset` objects. Python `list` is" + " not supported and you should use `tuple` instead." + ) + else: + raise TypeError( + "Invalid input to `zip`. Inputs are expected to be (nested)" + " structures of `tf.data.Dataset` objects but" + f" encountered object of type {type(ds)}." + ) + self._datasets = datasets + self._structure = nest.pack_sequence_as( + self._datasets, [ds.element_spec for ds in nest.flatten(self._datasets)] + ) + self._name = name + variant_tensor = gen_dataset_ops.zip_dataset( + [ds._variant_tensor for ds in nest.flatten(self._datasets)], + **self._common_args, + ) + super().__init__(variant_tensor) + + def _inputs(self): + return nest.flatten(self._datasets) + + @property + def element_spec(self): + return self._structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/convert.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/convert.py new file mode 100644 index 0000000000000000000000000000000000000000..1575493644696f4108ad5a37ded08773d7767deb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/convert.py @@ -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. +# ============================================================================== +"""Helpers constructing Datasets.""" +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape + + +def optional_param_to_tensor(argument_name, + argument_value, + argument_default=0, + argument_dtype=dtypes.int64): + if argument_value is not None: + return ops.convert_to_tensor( + argument_value, dtype=argument_dtype, name=argument_name) + else: + return constant_op.constant( + argument_default, dtype=argument_dtype, name=argument_name) + + +def partial_shape_to_tensor(shape_like): + """Returns a `tf.Tensor` that represents the given shape. + + Args: + shape_like: A value that can be converted to a `tf.TensorShape` or a + `tf.Tensor`. + + Returns: + A 1-D `tf.Tensor` of `tf.int64` elements representing the given shape, where + `-1` is substituted for any unknown dimensions. + """ + try: + # First attempt to convert the input to a shape, and return the + # "canonical" tensor representation, which uses `-1` in place of + # `None`. + shape_like = tensor_shape.as_shape(shape_like) + return ops.convert_to_tensor( + [dim if dim is not None else -1 for dim in shape_like.as_list()], + dtype=dtypes.int64) + except (TypeError, ValueError): + # The argument was not trivially convertible to a + # `tf.TensorShape`, so fall back on the conversion to tensor + # machinery. + ret = ops.convert_to_tensor(shape_like, preferred_dtype=dtypes.int64) + if ret.shape.dims is not None and len(ret.shape.dims) != 1: + raise ValueError("The given shape {} must be a 1-D tensor of `tf.int64` " + "values, but the shape was {}.".format( + shape_like, ret.shape)) + if ret.dtype != dtypes.int64: + raise TypeError("The given shape {} must be a 1-D tensor of `tf.int64` " + "values, but the element type was {}.".format( + shape_like, ret.dtype.name)) + + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/nest.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/nest.py new file mode 100644 index 0000000000000000000000000000000000000000..ece64dc2cea65c0c594dd9594241772cc6af25c4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/nest.py @@ -0,0 +1,305 @@ +# 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. +# ============================================================================== + +"""## Functions for working with arbitrarily nested sequences of elements. + +NOTE(mrry): This fork of the `tensorflow.python.util.nest` module +makes two changes: + +1. It removes support for lists as a level of nesting in nested structures. +2. It adds support for `SparseTensorValue` as an atomic element. + +The motivation for this change is twofold: + +1. It seems more natural for lists to be treated (e.g. in Dataset constructors) + as tensors, rather than lists of (lists of...) tensors. +2. This is needed because `SparseTensorValue` is implemented as a `namedtuple` + that would normally be flattened and we want to be able to create sparse + tensor from `SparseTensorValue's similarly to creating tensors from numpy + arrays. +""" + +from tensorflow.python.util import nest_util + + +def is_nested(structure): + return nest_util.is_nested(nest_util.Modality.DATA, structure) + + +def flatten(structure): + return nest_util.flatten(nest_util.Modality.DATA, structure) + + +def assert_same_structure(nest1, nest2, check_types=True): + """Asserts that two structures are nested in the same way. + + Args: + nest1: an arbitrarily nested structure. + nest2: an arbitrarily nested structure. + check_types: if `True` (default) types of sequences should be same as + well. For dictionary, "type" of dictionary is considered to include its + keys. In other words, two dictionaries with different keys are considered + to have a different "type". If set to `False`, two iterables are + considered same as long as they yield the elements that have same + structures. + + Raises: + ValueError: If the two structures do not have the same number of elements or + if the two structures are not nested in the same way. + TypeError: If the two structures differ in the type of sequence in any of + their substructures. Only possible if `check_types` is `True`. + """ + nest_util.assert_same_structure( + nest_util.Modality.DATA, nest1, nest2, check_types + ) + + +def pack_sequence_as(structure, flat_sequence): + """Returns a given flattened sequence packed into a nest. + + If `structure` is a scalar, `flat_sequence` must be a single-element list; + in this case the return value is `flat_sequence[0]`. + + Args: + structure: tuple or list constructed of scalars and/or other tuples/lists, + or a scalar. Note: numpy arrays are considered scalars. + flat_sequence: flat sequence to pack. + + Returns: + packed: `flat_sequence` converted to have the same recursive structure as + `structure`. + + Raises: + ValueError: If nest and structure have different element counts. + """ + return nest_util.pack_sequence_as( + nest_util.Modality.DATA, structure, flat_sequence, expand_composites=False + ) + + +def map_structure(func, *structure, **check_types_dict): + """Applies `func` to each entry in `structure` and returns a new structure. + + Applies `func(x[0], x[1], ...)` where x[i] is an entry in + `structure[i]`. All structures in `structure` must have the same arity, + and the return value will contain the results in the same structure. + + Args: + func: A callable that accepts as many arguments are there are structures. + *structure: scalar, or tuple or list of constructed scalars and/or other + tuples/lists, or scalars. Note: numpy arrays are considered scalars. + **check_types_dict: only valid keyword argument is `check_types`. If set to + `True` (default) the types of iterables within the structures have to be + same (e.g. `map_structure(func, [1], (1,))` raises a `TypeError` + exception). To allow this set this argument to `False`. + + Returns: + A new structure with the same arity as `structure`, whose values correspond + to `func(x[0], x[1], ...)` where `x[i]` is a value in the corresponding + location in `structure[i]`. If there are different sequence types and + `check_types` is `False` the sequence types of the first structure will be + used. + + Raises: + TypeError: If `func` is not callable or if the structures do not match + each other by depth tree. + ValueError: If no structure is provided or if the structures do not match + each other by type. + ValueError: If wrong keyword arguments are provided. + """ + return nest_util.map_structure( + nest_util.Modality.DATA, func, *structure, **check_types_dict + ) + + +def assert_shallow_structure(shallow_tree, input_tree, check_types=True): + """Asserts that `shallow_tree` is a shallow structure of `input_tree`. + + That is, this function tests if the `input_tree` structure can be created from + the `shallow_tree` structure by replacing its leaf nodes with deeper + tree structures. + + Examples: + + The following code will raise an exception: + ```python + shallow_tree = ["a", "b"] + input_tree = ["c", ["d", "e"], "f"] + assert_shallow_structure(shallow_tree, input_tree) + ``` + + The following code will not raise an exception: + ```python + shallow_tree = ["a", "b"] + input_tree = ["c", ["d", "e"]] + assert_shallow_structure(shallow_tree, input_tree) + ``` + + Args: + shallow_tree: an arbitrarily nested structure. + input_tree: an arbitrarily nested structure. + check_types: if `True` (default) the sequence types of `shallow_tree` and + `input_tree` have to be the same. + + Raises: + TypeError: If `shallow_tree` is a sequence but `input_tree` is not. + TypeError: If the sequence types of `shallow_tree` are different from + `input_tree`. Only raised if `check_types` is `True`. + ValueError: If the sequence lengths of `shallow_tree` are different from + `input_tree`. + """ + nest_util.assert_shallow_structure( + nest_util.Modality.DATA, shallow_tree, input_tree, check_types + ) + + +def flatten_up_to(shallow_tree, input_tree): + """Flattens `input_tree` up to `shallow_tree`. + + Any further depth in structure in `input_tree` is retained as elements in the + partially flatten output. + + If `shallow_tree` and `input_tree` are not sequences, this returns a + single-element list: `[input_tree]`. + + Use Case: + + Sometimes we may wish to partially flatten a nested sequence, retaining some + of the nested structure. We achieve this by specifying a shallow structure, + `shallow_tree`, we wish to flatten up to. + + The input, `input_tree`, can be thought of as having the same structure as + `shallow_tree`, but with leaf nodes that are themselves tree structures. + + Examples: + + ```python + input_tree = [[[2, 2], [3, 3]], [[4, 9], [5, 5]]] + shallow_tree = [[True, True], [False, True]] + + flattened_input_tree = flatten_up_to(shallow_tree, input_tree) + flattened_shallow_tree = flatten_up_to(shallow_tree, shallow_tree) + + # Output is: + # [[2, 2], [3, 3], [4, 9], [5, 5]] + # [True, True, False, True] + ``` + + ```python + input_tree = [[('a', 1), [('b', 2), [('c', 3), [('d', 4)]]]]] + shallow_tree = [['level_1', ['level_2', ['level_3', ['level_4']]]]] + + input_tree_flattened_as_shallow_tree = flatten_up_to(shallow_tree, input_tree) + input_tree_flattened = flatten(input_tree) + + # Output is: + # [('a', 1), ('b', 2), ('c', 3), ('d', 4)] + # ['a', 1, 'b', 2, 'c', 3, 'd', 4] + ``` + + Non-Sequence Edge Cases: + + ```python + flatten_up_to(0, 0) # Output: [0] + flatten_up_to(0, [0, 1, 2]) # Output: [[0, 1, 2]] + flatten_up_to([0, 1, 2], 0) # Output: TypeError + flatten_up_to([0, 1, 2], [0, 1, 2]) # Output: [0, 1, 2] + ``` + + Args: + shallow_tree: a possibly pruned structure of input_tree. + input_tree: an arbitrarily nested structure or a scalar object. + Note, numpy arrays are considered scalars. + + Returns: + A Python list, the partially flattened version of `input_tree` according to + the structure of `shallow_tree`. + + Raises: + TypeError: If `shallow_tree` is a sequence but `input_tree` is not. + TypeError: If the sequence types of `shallow_tree` are different from + `input_tree`. + ValueError: If the sequence lengths of `shallow_tree` are different from + `input_tree`. + """ + return nest_util.flatten_up_to( + nest_util.Modality.DATA, shallow_tree, input_tree + ) + + +def map_structure_up_to(shallow_tree, func, *inputs): + """Applies a function or op to a number of partially flattened inputs. + + The `inputs` are flattened up to `shallow_tree` before being mapped. + + Use Case: + + Sometimes we wish to apply a function to a partially flattened + sequence (for example when the function itself takes sequence inputs). We + achieve this by specifying a shallow structure, `shallow_tree` we wish to + flatten up to. + + The `inputs`, can be thought of as having the same structure as + `shallow_tree`, but with leaf nodes that are themselves tree structures. + + This function, therefore, will return something with the same base structure + as `shallow_tree`. + + Examples: + + ```python + ab_tuple = collections.namedtuple("ab_tuple", "a, b") + op_tuple = collections.namedtuple("op_tuple", "add, mul") + inp_val = ab_tuple(a=2, b=3) + inp_ops = ab_tuple(a=op_tuple(add=1, mul=2), b=op_tuple(add=2, mul=3)) + out = map_structure_up_to(inp_val, lambda val, ops: (val + ops.add) * ops.mul, + inp_val, inp_ops) + + # Output is: ab_tuple(a=6, b=15) + ``` + + ```python + data_list = [[2, 4, 6, 8], [[1, 3, 5, 7, 9], [3, 5, 7]]] + name_list = ['evens', ['odds', 'primes']] + out = map_structure_up_to( + name_list, + lambda name, sec: "first_{}_{}".format(len(sec), name), + name_list, data_list) + + # Output is: ['first_4_evens', ['first_5_odds', 'first_3_primes']] + ``` + + Args: + shallow_tree: a shallow tree, common to all the inputs. + func: callable which will be applied to each input individually. + *inputs: arbitrarily nested combination of objects that are compatible with + shallow_tree. The function `func` is applied to corresponding + partially flattened elements of each input, so the function must support + arity of `len(inputs)`. + + Raises: + TypeError: If `shallow_tree` is a sequence but `input_tree` is not. + TypeError: If the sequence types of `shallow_tree` are different from + `input_tree`. + ValueError: If the sequence lengths of `shallow_tree` are different from + `input_tree`. + + Returns: + result of repeatedly applying `func`, with same structure as + `shallow_tree`. + """ + return nest_util.map_structure_up_to( + nest_util.Modality.DATA, shallow_tree, func, *inputs + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/options.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/options.py new file mode 100644 index 0000000000000000000000000000000000000000..3ec1c53ff6508778f640885b403999cb7f0de224 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/options.py @@ -0,0 +1,173 @@ +# 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. +# ============================================================================== +"""Utilities for tf.data options.""" + +import collections + +from absl import logging + + +def _internal_attr_name(name): + return "_" + name + + +class OptionsBase: + """Base class for representing a set of tf.data options. + + Attributes: + _options: Stores the option values. + """ + + def __init__(self): + # NOTE: Cannot use `self._options` here as we override `__setattr__` + object.__setattr__(self, "_options", {}) + object.__setattr__(self, "_mutable", True) + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return NotImplemented + for name in set(self._options) | set(other._options): # pylint: disable=protected-access + if getattr(self, name) != getattr(other, name): + return False + return True + + def __ne__(self, other): + if isinstance(other, self.__class__): + return not self.__eq__(other) + else: + return NotImplemented + + def __setattr__(self, name, value): + if not self._mutable: + raise ValueError("Mutating `tf.data.Options()` returned by " + "`tf.data.Dataset.options()` has no effect. Use " + "`tf.data.Dataset.with_options(options)` to set or " + "update dataset options.") + if hasattr(self, name): + object.__setattr__(self, name, value) + else: + raise AttributeError("Cannot set the property {} on {}.".format( + name, + type(self).__name__)) + + def _set_mutable(self, mutable): + """Change the mutability property to `mutable`.""" + object.__setattr__(self, "_mutable", mutable) + + def _to_proto(self): + """Convert options to protocol buffer.""" + raise NotImplementedError("{}._to_proto()".format(type(self).__name__)) + + def _from_proto(self, pb): + """Convert protocol buffer to options.""" + raise NotImplementedError("{}._from_proto()".format(type(self).__name__)) + + +# Creates a namedtuple with three keys for optimization graph rewrites settings. +def graph_rewrites(): + return collections.namedtuple("GraphRewrites", + ["enabled", "disabled", "default"]) + + +def create_option(name, ty, docstring, default_factory=lambda: None): + """Creates a type-checked property. + + Args: + name: The name to use. + ty: The type to use. The type of the property will be validated when it + is set. + docstring: The docstring to use. + default_factory: A callable that takes no arguments and returns a default + value to use if not set. + + Returns: + A type-checked property. + """ + + def get_fn(option): + # pylint: disable=protected-access + if name not in option._options: + option._options[name] = default_factory() + return option._options.get(name) + + def set_fn(option, value): + if not isinstance(value, ty): + raise TypeError( + "Property \"{}\" must be of type {}, got: {} (type: {})".format( + name, ty, value, type(value))) + option._options[name] = value # pylint: disable=protected-access + + return property(get_fn, set_fn, None, docstring) + + +def merge_options(*options_list): + """Merges the given options, returning the result as a new options object. + + The input arguments are expected to have a matching type that derives from + `tf.data.OptionsBase` (and thus each represent a set of options). The method + outputs an object of the same type created by merging the sets of options + represented by the input arguments. + + If an option is set to different values by different options objects, the + result will match the setting of the options object that appears in the input + list last. + + If an option is an instance of `tf.data.OptionsBase` itself, then this method + is applied recursively to the set of options represented by this option. + + Args: + *options_list: options to merge + + Raises: + TypeError: if the input arguments are incompatible or not derived from + `tf.data.OptionsBase` + + Returns: + A new options object which is the result of merging the given options. + """ + if len(options_list) < 1: + raise ValueError("At least one options should be provided") + result_type = type(options_list[0]) + + for options in options_list: + if not isinstance(options, result_type): + raise TypeError( + "Could not merge incompatible options of type {} and {}.".format( + type(options), result_type)) + + if not isinstance(options_list[0], OptionsBase): + raise TypeError( + "All options to be merged should inherit from `OptionsBase` but found " + "option of type {} which does not.".format(type(options_list[0]))) + + default_options = result_type() + result = result_type() + for options in options_list: + # Iterate over all set options and merge them into the result. + for name in options._options: # pylint: disable=protected-access + this = getattr(result, name) + that = getattr(options, name) + default = getattr(default_options, name) + if that == default: + continue + elif this == default: + setattr(result, name, that) + elif isinstance(this, OptionsBase): + setattr(result, name, merge_options(this, that)) + elif this != that: + logging.warning("Changing the value of option %s from %r to %r.", name, + this, that) + setattr(result, name, that) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/random_seed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/random_seed.py new file mode 100644 index 0000000000000000000000000000000000000000..8910a8323627376659253582e2a39af00734e8d2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/random_seed.py @@ -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. +# ============================================================================== +"""Utilities for generating Tensor-valued random seeds.""" + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops + + +def get_seed(seed): + """Returns the local seeds an operation should use given an op-specific seed. + + See `random_seed.get_seed` for more details. This wrapper adds support for + the case where `seed` may be a tensor. + + Args: + seed: An integer or a `tf.int64` scalar tensor. + + Returns: + A tuple of two `tf.int64` scalar tensors that should be used for the local + seed of the calling dataset. + """ + seed, seed2 = random_seed.get_seed(seed) + if seed is None: + seed = constant_op.constant(0, dtype=dtypes.int64, name="seed") + else: + seed = ops.convert_to_tensor(seed, dtype=dtypes.int64, name="seed") + if seed2 is None: + seed2 = constant_op.constant(0, dtype=dtypes.int64, name="seed2") + else: + with ops.name_scope("seed2") as scope: + seed2 = ops.convert_to_tensor(seed2, dtype=dtypes.int64) + seed2 = array_ops.where_v2( + math_ops.logical_and( + math_ops.equal(seed, 0), math_ops.equal(seed2, 0)), + constant_op.constant(2**31 - 1, dtype=dtypes.int64), + seed2, + name=scope) + return seed, seed2 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/sparse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1f1fc794b1ebaebab57f0e5c55007c3d47160ce3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/sparse.py @@ -0,0 +1,148 @@ +# 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. +# ============================================================================== +"""Python dataset sparse tensor utility functions.""" +from tensorflow.python.data.util import nest +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import sparse_ops + + +def any_sparse(classes): + """Checks for sparse tensor. + + Args: + classes: a structure of objects that identify the dataset item classes + + Returns: + `True` if `classes` contains a sparse tensor type and `False` otherwise. + """ + return any(c is sparse_tensor.SparseTensor for c in nest.flatten(classes)) + + +def as_dense_shapes(shapes, classes): + """Converts sparse tensor shapes to their physical shapes. + + Args: + shapes: a structure of shapes to convert. + classes: a structure of objects that identify the dataset item classes + + Returns: + a structure matching the nested structure of `shapes`, containing + `tensor_shape.unknown_shape()` at positions where `classes` contains + `tf.sparse.SparseTensor` and matching contents of `shapes` otherwise + """ + ret = nest.pack_sequence_as(shapes, [ + tensor_shape.unknown_shape() if c is sparse_tensor.SparseTensor else shape + for shape, c in zip(nest.flatten(shapes), nest.flatten(classes)) + ]) + return ret + + +def as_dense_types(types, classes): + """Converts sparse tensor types to `dtypes.variant`. + + Args: + types: a structure of types to convert. + classes: a structure of objects that identify the dataset item classes + + Returns: + a structure matching the nested structure of `types`, containing + `dtypes.variant` at positions where `classes` contains + `tf.sparse.SparseTensor` and matching contents of `types` otherwise + """ + ret = nest.pack_sequence_as(types, [ + dtypes.variant if c is sparse_tensor.SparseTensor else ty + for ty, c in zip(nest.flatten(types), nest.flatten(classes)) + ]) + return ret + + +def deserialize_sparse_tensors(tensors, types, shapes, classes): + """Deserializes sparse tensors. + + Args: + tensors: a structure of tensors to deserialize. + types: a structure that holds information about types of `tensors` + shapes: a structure that holds information about shapes of `tensors` + classes: a structure of objects that identify the dataset item classes + + Returns: + `tensors` with any serialized sparse tensors replaced by their deserialized + version. + """ + ret = nest.pack_sequence_as(types, [ + sparse_ops.deserialize_sparse(tensor, dtype=ty, rank=shape.ndims) + if c is sparse_tensor.SparseTensor else tensor + for (tensor, ty, shape, c) in zip( + nest.flatten(tensors), nest.flatten(types), nest.flatten(shapes), + nest.flatten(classes)) + ]) + return ret + + +def get_classes(tensors): + """Gets classes for a structure of tensors. + + Args: + tensors: the tensor structure to get classes for. + + Returns: + a structure matching the nested structure of `tensors`, containing + `tf.sparse.SparseTensor` at positions where `tensors` contains a sparse + tensor and `tf.Tensor` otherwise. + """ + return nest.pack_sequence_as(tensors, [ + sparse_tensor.SparseTensor + if isinstance(tensor, sparse_tensor.SparseTensor) else tensor_lib.Tensor + for tensor in nest.flatten(tensors) + ]) + + +def serialize_many_sparse_tensors(tensors): + """Serializes many sparse tensors into a batch. + + Args: + tensors: a tensor structure to serialize. + + Returns: + `tensors` with any sparse tensors replaced by the serialized batch. + """ + + ret = nest.pack_sequence_as(tensors, [ + sparse_ops.serialize_many_sparse(tensor, out_type=dtypes.variant) + if sparse_tensor.is_sparse(tensor) else tensor + for tensor in nest.flatten(tensors) + ]) + return ret + + +def serialize_sparse_tensors(tensors): + """Serializes sparse tensors. + + Args: + tensors: a tensor structure to serialize. + + Returns: + `tensors` with any sparse tensors replaced by their serialized version. + """ + + ret = nest.pack_sequence_as(tensors, [ + sparse_ops.serialize_sparse(tensor, out_type=dtypes.variant) + if isinstance(tensor, sparse_tensor.SparseTensor) else tensor + for tensor in nest.flatten(tensors) + ]) + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/structure.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/structure.py new file mode 100644 index 0000000000000000000000000000000000000000..52fadac4faef798e84dd166ab257ad619950328d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/structure.py @@ -0,0 +1,521 @@ +# 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. +# ============================================================================== +"""Utilities for describing the structure of a `tf.data` type.""" +import collections +import functools +import itertools + +import wrapt + +from tensorflow.python.data.util import nest +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import none_tensor +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import internal +from tensorflow.python.util import deprecation +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.nest_util import CustomNestProtocol +from tensorflow.python.util.tf_export import tf_export + + +# pylint: disable=invalid-name +@tf_export(v1=["data.experimental.TensorStructure"]) +@deprecation.deprecated(None, "Use `tf.TensorSpec` instead.") +def _TensorStructure(dtype, shape): + return tensor_lib.TensorSpec(shape, dtype) + + +@tf_export(v1=["data.experimental.SparseTensorStructure"]) +@deprecation.deprecated(None, "Use `tf.SparseTensorSpec` instead.") +def _SparseTensorStructure(dtype, shape): + return sparse_tensor.SparseTensorSpec(shape, dtype) + + +@tf_export(v1=["data.experimental.TensorArrayStructure"]) +@deprecation.deprecated(None, "Use `tf.TensorArraySpec` instead.") +def _TensorArrayStructure(dtype, element_shape, dynamic_size, infer_shape): + return tensor_array_ops.TensorArraySpec(element_shape, dtype, + dynamic_size, infer_shape) + + +@tf_export(v1=["data.experimental.RaggedTensorStructure"]) +@deprecation.deprecated(None, "Use `tf.RaggedTensorSpec` instead.") +def _RaggedTensorStructure(dtype, shape, ragged_rank): + return ragged_tensor.RaggedTensorSpec(shape, dtype, ragged_rank) +# pylint: enable=invalid-name + + +# TODO(jsimsa): Remove the special-case for `TensorArray` pass-through once +# it is a subclass of `CompositeTensor`. +def normalize_element(element, element_signature=None): + """Normalizes a nested structure of element components. + + * Components matching `SparseTensorSpec` are converted to `SparseTensor`. + * Components matching `RaggedTensorSpec` are converted to `RaggedTensor`. + * Components matching `VariableSpec` are converted to `Tensor`. + * Components matching `DatasetSpec` or `TensorArraySpec` are passed through. + * `CompositeTensor` components are passed through. + * All other components are converted to `Tensor`. + + Args: + element: A nested structure of individual components. + element_signature: (Optional.) A nested structure of `tf.DType` objects + corresponding to each component of `element`. If specified, it will be + used to set the exact type of output tensor when converting input + components which are not tensors themselves (e.g. numpy arrays, native + python types, etc.) + + Returns: + A nested structure of `Tensor`, `Variable`, `Dataset`, `SparseTensor`, + `RaggedTensor`, or `TensorArray` objects. + """ + normalized_components = [] + if element_signature is None: + components = nest.flatten(element) + flattened_signature = [None] * len(components) + pack_as = element + else: + flattened_signature = nest.flatten(element_signature) + components = nest.flatten_up_to(element_signature, element) + pack_as = element_signature + with ops.name_scope("normalize_element"): + for i, (t, spec) in enumerate(zip(components, flattened_signature)): + try: + if spec is None: + spec = type_spec_from_value(t, use_fallback=False) + except TypeError: + # TypeError indicates it was not possible to compute a `TypeSpec` for + # the value. As a fallback try converting the value to a tensor. + normalized_components.append( + ops.convert_to_tensor(t, name="component_%d" % i)) + else: + # To avoid a circular dependency between dataset_ops and structure, + # we check the class name instead of using `isinstance`. + if spec.__class__.__name__ == "DatasetSpec": + normalized_components.append(t) + elif isinstance(spec, sparse_tensor.SparseTensorSpec): + normalized_components.append(sparse_tensor.SparseTensor.from_value(t)) + elif isinstance(spec, ragged_tensor.RaggedTensorSpec): + normalized_components.append( + ragged_tensor.convert_to_tensor_or_ragged_tensor( + t, name="component_%d" % i)) + elif isinstance(spec, (tensor_array_ops.TensorArraySpec)): + normalized_components.append(t) + elif isinstance(spec, none_tensor.NoneTensorSpec): + normalized_components.append(none_tensor.NoneTensor()) + elif isinstance(spec, resource_variable_ops.VariableSpec): + normalized_components.append( + ops.convert_to_tensor(t, name=f"component_{i}", dtype=spec.dtype)) + elif isinstance(t, composite_tensor.CompositeTensor): + normalized_components.append(t) + else: + dtype = getattr(spec, "dtype", None) + normalized_components.append( + ops.convert_to_tensor(t, name="component_%d" % i, dtype=dtype)) + return nest.pack_sequence_as(pack_as, normalized_components) + + +def convert_legacy_structure(output_types, output_shapes, output_classes): + """Returns a `Structure` that represents the given legacy structure. + + This method provides a way to convert from the existing `Dataset` and + `Iterator` structure-related properties to a `Structure` object. A "legacy" + structure is represented by the `tf.data.Dataset.output_types`, + `tf.data.Dataset.output_shapes`, and `tf.data.Dataset.output_classes` + properties. + + TODO(b/110122868): Remove this function once `Structure` is used throughout + `tf.data`. + + Args: + output_types: A nested structure of `tf.DType` objects corresponding to + each component of a structured value. + output_shapes: A nested structure of `tf.TensorShape` objects + corresponding to each component a structured value. + output_classes: A nested structure of Python `type` objects corresponding + to each component of a structured value. + + Returns: + A `Structure`. + + Raises: + TypeError: If a structure cannot be built from the arguments, because one of + the component classes in `output_classes` is not supported. + """ + flat_types = nest.flatten(output_types) + flat_shapes = nest.flatten(output_shapes) + flat_classes = nest.flatten(output_classes) + flat_ret = [] + for flat_type, flat_shape, flat_class in zip(flat_types, flat_shapes, + flat_classes): + if isinstance(flat_class, type_spec.TypeSpec): + flat_ret.append(flat_class) + elif issubclass(flat_class, sparse_tensor.SparseTensor): + flat_ret.append(sparse_tensor.SparseTensorSpec(flat_shape, flat_type)) + elif issubclass(flat_class, tensor_lib.Tensor): + flat_ret.append(tensor_lib.TensorSpec(flat_shape, flat_type)) + elif issubclass(flat_class, tensor_array_ops.TensorArray): + # We sneaked the dynamic_size and infer_shape into the legacy shape. + flat_ret.append( + tensor_array_ops.TensorArraySpec( + flat_shape[2:], flat_type, + dynamic_size=tensor_shape.dimension_value(flat_shape[0]), + infer_shape=tensor_shape.dimension_value(flat_shape[1]))) + else: + # NOTE(mrry): Since legacy structures produced by iterators only + # comprise Tensors, SparseTensors, and nests, we do not need to + # support all structure types here. + raise TypeError( + "Could not build a structure for output class {}. Make sure any " + "component class in `output_classes` inherits from one of the " + "following classes: `tf.TypeSpec`, `tf.sparse.SparseTensor`, " + "`tf.Tensor`, `tf.TensorArray`.".format(flat_class.__name__)) + + return nest.pack_sequence_as(output_classes, flat_ret) + + +def _from_tensor_list_helper(decode_fn, element_spec, tensor_list): + """Returns an element constructed from the given spec and tensor list. + + Args: + decode_fn: Method that constructs an element component from the element spec + component and a tensor list. + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + tensor_list: A list of tensors to use for constructing the value. + + Returns: + An element constructed from the given spec and tensor list. + + Raises: + ValueError: If the number of tensors needed to construct an element for + the given spec does not match the given number of tensors. + """ + + # pylint: disable=protected-access + + flat_specs = nest.flatten(element_spec) + flat_spec_lengths = [len(spec._flat_tensor_specs) for spec in flat_specs] + if sum(flat_spec_lengths) != len(tensor_list): + raise ValueError("Expected {} tensors but got {}.".format( + sum(flat_spec_lengths), len(tensor_list))) + + i = 0 + flat_ret = [] + for (component_spec, num_flat_values) in zip(flat_specs, flat_spec_lengths): + value = tensor_list[i:i + num_flat_values] + flat_ret.append(decode_fn(component_spec, value)) + i += num_flat_values + return nest.pack_sequence_as(element_spec, flat_ret) + + +def from_compatible_tensor_list(element_spec, tensor_list): + """Returns an element constructed from the given spec and tensor list. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + tensor_list: A list of tensors to use for constructing the value. + + Returns: + An element constructed from the given spec and tensor list. + + Raises: + ValueError: If the number of tensors needed to construct an element for + the given spec does not match the given number of tensors. + """ + + # pylint: disable=protected-access + # pylint: disable=g-long-lambda + return _from_tensor_list_helper( + lambda spec, value: spec._from_compatible_tensor_list(value), + element_spec, tensor_list) + + +def from_tensor_list(element_spec, tensor_list): + """Returns an element constructed from the given spec and tensor list. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + tensor_list: A list of tensors to use for constructing the value. + + Returns: + An element constructed from the given spec and tensor list. + + Raises: + ValueError: If the number of tensors needed to construct an element for + the given spec does not match the given number of tensors or the given + spec is not compatible with the tensor list. + """ + + # pylint: disable=protected-access + # pylint: disable=g-long-lambda + return _from_tensor_list_helper( + lambda spec, value: spec._from_tensor_list(value), element_spec, + tensor_list) + + +def get_flat_tensor_specs(element_spec): + """Returns a list `tf.TypeSpec`s for the element tensor representation. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + + Returns: + A list `tf.TypeSpec`s for the element tensor representation. + """ + + # pylint: disable=protected-access + return list( + itertools.chain.from_iterable( + spec._flat_tensor_specs for spec in nest.flatten(element_spec))) + + +def get_flat_tensor_shapes(element_spec): + """Returns a list `tf.TensorShapes`s for the element tensor representation. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + + Returns: + A list `tf.TensorShapes`s for the element tensor representation. + """ + return [spec.shape for spec in get_flat_tensor_specs(element_spec)] + + +def get_flat_tensor_types(element_spec): + """Returns a list `tf.DType`s for the element tensor representation. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + + Returns: + A list `tf.DType`s for the element tensor representation. + """ + return [spec.dtype for spec in get_flat_tensor_specs(element_spec)] + + +def _to_tensor_list_helper(encode_fn, element_spec, element): + """Returns a tensor list representation of the element. + + Args: + encode_fn: Method that constructs a tensor list representation from the + given element spec and element. + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + element: The element to convert to tensor list representation. + + Returns: + A tensor list representation of `element`. + + Raises: + ValueError: If `element_spec` and `element` do not have the same number of + elements or if the two structures are not nested in the same way. + TypeError: If `element_spec` and `element` differ in the type of sequence + in any of their substructures. + """ + + nest.assert_same_structure(element_spec, element) + + def reduce_fn(state, value): + spec, component = value + if isinstance(spec, internal.TensorSpec): + try: + component = ops.convert_to_tensor(component, spec.dtype) + except (TypeError, ValueError): + raise ValueError( + f"Value {component} is not convertible to a tensor with " + f"dtype {spec.dtype} and shape {spec.shape}." + ) + if not component.shape.is_compatible_with(spec.shape): + raise ValueError( + f"Value {component} is not convertible to a tensor with " + f"dtype {spec.dtype} and shape {spec.shape}." + ) + return encode_fn(state, spec, component) + + return functools.reduce( + reduce_fn, zip(nest.flatten(element_spec), nest.flatten(element)), []) + + +def to_batched_tensor_list(element_spec, element): + """Returns a tensor list representation of the element. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + element: The element to convert to tensor list representation. + + Returns: + A tensor list representation of `element`. + + Raises: + ValueError: If `element_spec` and `element` do not have the same number of + elements or if the two structures are not nested in the same way or the + rank of any of the tensors in the tensor list representation is 0. + TypeError: If `element_spec` and `element` differ in the type of sequence + in any of their substructures. + """ + + # pylint: disable=protected-access + # pylint: disable=g-long-lambda + return _to_tensor_list_helper( + lambda state, spec, component: state + spec._to_batched_tensor_list( + component), element_spec, element) + + +def to_tensor_list(element_spec, element): + """Returns a tensor list representation of the element. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing to + element type specification. + element: The element to convert to tensor list representation. + + Returns: + A tensor list representation of `element`. + + Raises: + ValueError: If `element_spec` and `element` do not have the same number of + elements or if the two structures are not nested in the same way. + TypeError: If `element_spec` and `element` differ in the type of sequence + in any of their substructures. + """ + + # pylint: disable=protected-access + # pylint: disable=g-long-lambda + return _to_tensor_list_helper( + lambda state, spec, component: state + spec._to_tensor_list(component), + element_spec, element) + + +def are_compatible(spec1, spec2): + """Indicates whether two type specifications are compatible. + + Two type specifications are compatible if they have the same nested structure + and the their individual components are pair-wise compatible. + + Args: + spec1: A `tf.TypeSpec` object to compare. + spec2: A `tf.TypeSpec` object to compare. + + Returns: + `True` if the two type specifications are compatible and `False` otherwise. + """ + + try: + nest.assert_same_structure(spec1, spec2) + except TypeError: + return False + except ValueError: + return False + + for s1, s2 in zip(nest.flatten(spec1), nest.flatten(spec2)): + if not s1.is_compatible_with(s2) or not s2.is_compatible_with(s1): + return False + return True + + +def type_spec_from_value(element, use_fallback=True): + """Creates a type specification for the given value. + + Args: + element: The element to create the type specification for. + use_fallback: Whether to fall back to converting the element to a tensor + in order to compute its `TypeSpec`. + + Returns: + A nested structure of `TypeSpec`s that represents the type specification + of `element`. + + Raises: + TypeError: If a `TypeSpec` cannot be built for `element`, because its type + is not supported. + """ + spec = type_spec._type_spec_from_value(element) # pylint: disable=protected-access + if spec is not None: + return spec + + if isinstance(element, collections_abc.Mapping): + # We create a shallow copy in an attempt to preserve the key order. + # + # Note that we do not guarantee that the key order is preserved, which is + # a limitation inherited from `copy()`. As a consequence, callers of + # `type_spec_from_value` should not assume that the key order of a `dict` + # in the returned nested structure matches the key order of the + # corresponding `dict` in the input value. + if isinstance(element, collections.defaultdict): + ctor = lambda items: type(element)(element.default_factory, items) + else: + ctor = type(element) + return ctor([(k, type_spec_from_value(v)) for k, v in element.items()]) + + if isinstance(element, tuple): + if hasattr(element, "_fields") and isinstance( + element._fields, collections_abc.Sequence) and all( + isinstance(f, str) for f in element._fields): + if isinstance(element, wrapt.ObjectProxy): + element_type = type(element.__wrapped__) + else: + element_type = type(element) + # `element` is a namedtuple + return element_type(*[type_spec_from_value(v) for v in element]) + # `element` is not a namedtuple + return tuple([type_spec_from_value(v) for v in element]) + + if hasattr(element.__class__, "__attrs_attrs__"): + # `element` is an `attr.s` decorated class + attrs = getattr(element.__class__, "__attrs_attrs__") + return type(element)(*[ + type_spec_from_value(getattr(element, a.name)) for a in attrs + ]) + + if isinstance(element, CustomNestProtocol): + # pylint: disable=protected-access + metadata, children = element.__tf_flatten__() + return element.__tf_unflatten__(metadata, type_spec_from_value(children)) + # pylint: enable=protected-access + + if use_fallback: + # As a fallback try converting the element to a tensor. + try: + tensor = ops.convert_to_tensor(element) + spec = type_spec_from_value(tensor) + if spec is not None: + return spec + except (ValueError, TypeError) as e: + logging.vlog( + 3, "Failed to convert %r to tensor: %s" % (type(element).__name__, e)) + + raise TypeError("Could not build a `TypeSpec` for {} with type {}".format( + element, + type(element).__name__)) + + +# TODO(b/149584798): remove legacy forwarding references +NoneTensor = none_tensor.NoneTensor +NoneTensorSpec = none_tensor.NoneTensorSpec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/traverse.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/traverse.py new file mode 100644 index 0000000000000000000000000000000000000000..213a213a29675194dee53278b8e7b3137e61ce38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/data/util/traverse.py @@ -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. +# ============================================================================== +"""Helpers to traverse the Dataset dependency structure.""" +import queue + +from tensorflow.python.framework import dtypes + + +OP_TYPES_ALLOWLIST = ["DummyIterationCounter"] +# We allowlist all ops that produce variant tensors as output. This is a bit +# of overkill but the other dataset _inputs() traversal strategies can't +# cover the case of function inputs that capture dataset variants. +TENSOR_TYPES_ALLOWLIST = [dtypes.variant] + + +def _traverse(dataset, op_filter_fn): + """Traverse a dataset graph, returning nodes matching `op_filter_fn`.""" + result = [] + bfs_q = queue.Queue() + bfs_q.put(dataset._variant_tensor.op) # pylint: disable=protected-access + visited = [] + while not bfs_q.empty(): + op = bfs_q.get() + visited.append(op) + if op_filter_fn(op): + result.append(op) + for i in op.inputs: + input_op = i.op + if input_op not in visited: + bfs_q.put(input_op) + return result + + +def obtain_capture_by_value_ops(dataset): + """Given an input dataset, finds all allowlisted ops used for construction. + + Allowlisted ops are stateful ops which are known to be safe to capture by + value. + + Args: + dataset: Dataset to find allowlisted stateful ops for. + + Returns: + A list of variant_tensor producing dataset ops used to construct this + dataset. + """ + + def capture_by_value(op): + return (op.outputs[0].dtype in TENSOR_TYPES_ALLOWLIST or + op.type in OP_TYPES_ALLOWLIST) + + return _traverse(dataset, capture_by_value) + + +def obtain_all_variant_tensor_ops(dataset): + """Given an input dataset, finds all dataset ops used for construction. + + A series of transformations would have created this dataset with each + transformation including zero or more Dataset ops, each producing a dataset + variant tensor. This method outputs all of them. + + Args: + dataset: Dataset to find variant tensors for. + + Returns: + A list of variant_tensor producing dataset ops used to construct this + dataset. + """ + return _traverse(dataset, lambda op: op.outputs[0].dtype == dtypes.variant) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2ceb2d1bce0604e3f5897d2c95b07195572fbaed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/__init__.py @@ -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. +# ============================================================================== +"""Public Python API of TensorFlow Debugger (tfdbg). + +See the [TFDBG](https://www.tensorflow.org/guide/debugger) guide. + +@@add_debug_tensor_watch +@@watch_graph +@@watch_graph_with_denylists +@@DebugTensorDatum +@@DebugDumpDir +@@load_tensor_from_event +@@load_tensor_from_event_file +@@has_inf_or_nan +@@DumpingDebugHook +@@DumpingDebugWrapperSession +@@GrpcDebugHook +@@GrpcDebugWrapperSession +@@LocalCLIDebugHook +@@LocalCLIDebugWrapperSession +@@TensorBoardDebugHook +@@TensorBoardDebugWrapperSession +@@WatchOptions + +@@reconstruct_non_debug_graph_def + +@@GradientsDebugger +@@clear_gradient_debuggers +""" + +# pylint: disable=unused-imports +from tensorflow.python.debug.lib.debug_data import DebugDumpDir +from tensorflow.python.debug.lib.debug_data import DebugTensorDatum +from tensorflow.python.debug.lib.debug_data import has_inf_or_nan +from tensorflow.python.debug.lib.debug_data import load_tensor_from_event +from tensorflow.python.debug.lib.debug_data import load_tensor_from_event_file + +from tensorflow.python.debug.lib.debug_gradients import GradientsDebugger + +from tensorflow.python.debug.lib.debug_graphs import reconstruct_non_debug_graph_def + +from tensorflow.python.debug.lib.debug_utils import add_debug_tensor_watch +from tensorflow.python.debug.lib.debug_utils import watch_graph +from tensorflow.python.debug.lib.debug_utils import watch_graph_with_denylists + +from tensorflow.python.debug.wrappers.dumping_wrapper import DumpingDebugWrapperSession +from tensorflow.python.debug.wrappers.framework import WatchOptions +from tensorflow.python.debug.wrappers.grpc_wrapper import GrpcDebugWrapperSession +from tensorflow.python.debug.wrappers.grpc_wrapper import TensorBoardDebugWrapperSession +from tensorflow.python.debug.wrappers.hooks import DumpingDebugHook +from tensorflow.python.debug.wrappers.hooks import GrpcDebugHook +from tensorflow.python.debug.wrappers.hooks import LocalCLIDebugHook +from tensorflow.python.debug.wrappers.hooks import TensorBoardDebugHook +from tensorflow.python.debug.wrappers.local_cli_wrapper import LocalCLIDebugWrapperSession + +from tensorflow.python.util import all_util as _all_util + + +_all_util.remove_undocumented(__name__) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/analyzer_cli.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/analyzer_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..7131a1df441562bd185d92bd7d1546b69d1f1681 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/analyzer_cli.py @@ -0,0 +1,1655 @@ +# 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. +# ============================================================================== +"""CLI Backend for the Analyzer Part of the Debugger. + +The analyzer performs post hoc analysis of dumped intermediate tensors and +graph structure information from debugged Session.run() calls. +""" +import argparse +import copy +import re + + +from tensorflow.python.debug.cli import cli_config +from tensorflow.python.debug.cli import cli_shared +from tensorflow.python.debug.cli import command_parser +from tensorflow.python.debug.cli import debugger_cli_common +from tensorflow.python.debug.cli import evaluator +from tensorflow.python.debug.cli import ui_factory +from tensorflow.python.debug.lib import debug_graphs +from tensorflow.python.debug.lib import source_utils + +RL = debugger_cli_common.RichLine + +# String constants for the depth-dependent hanging indent at the beginning +# of each line. +HANG_UNFINISHED = "| " # Used for unfinished recursion depths. +HANG_FINISHED = " " +HANG_SUFFIX = "|- " + +# String constant for displaying depth and op type. +DEPTH_TEMPLATE = "(%d) " +OP_TYPE_TEMPLATE = "[%s] " + +# String constants for control inputs/outputs, etc. +CTRL_LABEL = "(Ctrl) " +ELLIPSIS = "..." + +SORT_TENSORS_BY_TIMESTAMP = "timestamp" +SORT_TENSORS_BY_DUMP_SIZE = "dump_size" +SORT_TENSORS_BY_OP_TYPE = "op_type" +SORT_TENSORS_BY_TENSOR_NAME = "tensor_name" + + +def _add_main_menu(output, + node_name=None, + enable_list_tensors=True, + enable_node_info=True, + enable_print_tensor=True, + enable_list_inputs=True, + enable_list_outputs=True): + """Generate main menu for the screen output from a command. + + Args: + output: (debugger_cli_common.RichTextLines) the output object to modify. + node_name: (str or None) name of the node involved (if any). If None, + the menu items node_info, list_inputs and list_outputs will be + automatically disabled, overriding the values of arguments + enable_node_info, enable_list_inputs and enable_list_outputs. + enable_list_tensors: (bool) whether the list_tensor menu item will be + enabled. + enable_node_info: (bool) whether the node_info item will be enabled. + enable_print_tensor: (bool) whether the print_tensor item will be enabled. + enable_list_inputs: (bool) whether the item list_inputs will be enabled. + enable_list_outputs: (bool) whether the item list_outputs will be enabled. + """ + + menu = debugger_cli_common.Menu() + + menu.append( + debugger_cli_common.MenuItem( + "list_tensors", "list_tensors", enabled=enable_list_tensors)) + + if node_name: + menu.append( + debugger_cli_common.MenuItem( + "node_info", + "node_info -a -d -t %s" % node_name, + enabled=enable_node_info)) + menu.append( + debugger_cli_common.MenuItem( + "print_tensor", + "print_tensor %s" % node_name, + enabled=enable_print_tensor)) + menu.append( + debugger_cli_common.MenuItem( + "list_inputs", + "list_inputs -c -r %s" % node_name, + enabled=enable_list_inputs)) + menu.append( + debugger_cli_common.MenuItem( + "list_outputs", + "list_outputs -c -r %s" % node_name, + enabled=enable_list_outputs)) + else: + menu.append( + debugger_cli_common.MenuItem( + "node_info", None, enabled=False)) + menu.append( + debugger_cli_common.MenuItem("print_tensor", None, enabled=False)) + menu.append( + debugger_cli_common.MenuItem("list_inputs", None, enabled=False)) + menu.append( + debugger_cli_common.MenuItem("list_outputs", None, enabled=False)) + + menu.append( + debugger_cli_common.MenuItem("run_info", "run_info")) + menu.append( + debugger_cli_common.MenuItem("help", "help")) + + output.annotations[debugger_cli_common.MAIN_MENU_KEY] = menu + + +class DebugAnalyzer(object): + """Analyzer for debug data from dump directories.""" + + _TIMESTAMP_COLUMN_HEAD = "t (ms)" + _DUMP_SIZE_COLUMN_HEAD = "Size (B)" + _OP_TYPE_COLUMN_HEAD = "Op type" + _TENSOR_NAME_COLUMN_HEAD = "Tensor name" + + # Op types to be omitted when generating descriptions of graph structure. + _GRAPH_STRUCT_OP_TYPE_DENYLIST = ("_Send", "_Recv", "_HostSend", "_HostRecv", + "_Retval") + + def __init__(self, debug_dump, config): + """DebugAnalyzer constructor. + + Args: + debug_dump: A DebugDumpDir object. + config: A `cli_config.CLIConfig` object that carries user-facing + configurations. + """ + + self._debug_dump = debug_dump + self._evaluator = evaluator.ExpressionEvaluator(self._debug_dump) + + # Initialize tensor filters state. + self._tensor_filters = {} + + self._build_argument_parsers(config) + config.set_callback("graph_recursion_depth", + self._build_argument_parsers) + + # TODO(cais): Implement list_nodes. + + def _build_argument_parsers(self, config): + """Build argument parsers for DebugAnalayzer. + + Args: + config: A `cli_config.CLIConfig` object. + + Returns: + A dict mapping command handler name to `ArgumentParser` instance. + """ + # Argument parsers for command handlers. + self._arg_parsers = {} + + # Parser for list_tensors. + ap = argparse.ArgumentParser( + description="List dumped intermediate tensors.", + usage=argparse.SUPPRESS) + ap.add_argument( + "-f", + "--tensor_filter", + dest="tensor_filter", + type=str, + default="", + help="List only Tensors passing the filter of the specified name") + ap.add_argument( + "-fenn", + "--filter_exclude_node_names", + dest="filter_exclude_node_names", + type=str, + default="", + help="When applying the tensor filter, exclude node with names " + "matching the regular expression. Applicable only if --tensor_filter " + "or -f is used.") + ap.add_argument( + "-n", + "--node_name_filter", + dest="node_name_filter", + type=str, + default="", + help="filter node name by regex.") + ap.add_argument( + "-t", + "--op_type_filter", + dest="op_type_filter", + type=str, + default="", + help="filter op type by regex.") + ap.add_argument( + "-s", + "--sort_by", + dest="sort_by", + type=str, + default=SORT_TENSORS_BY_TIMESTAMP, + help=("the field to sort the data by: (%s | %s | %s | %s)" % + (SORT_TENSORS_BY_TIMESTAMP, SORT_TENSORS_BY_DUMP_SIZE, + SORT_TENSORS_BY_OP_TYPE, SORT_TENSORS_BY_TENSOR_NAME))) + ap.add_argument( + "-r", + "--reverse", + dest="reverse", + action="store_true", + help="sort the data in reverse (descending) order") + self._arg_parsers["list_tensors"] = ap + + # Parser for node_info. + ap = argparse.ArgumentParser( + description="Show information about a node.", usage=argparse.SUPPRESS) + ap.add_argument( + "node_name", + type=str, + help="Name of the node or an associated tensor, e.g., " + "hidden1/Wx_plus_b/MatMul, hidden1/Wx_plus_b/MatMul:0") + ap.add_argument( + "-a", + "--attributes", + dest="attributes", + action="store_true", + help="Also list attributes of the node.") + ap.add_argument( + "-d", + "--dumps", + dest="dumps", + action="store_true", + help="Also list dumps available from the node.") + ap.add_argument( + "-t", + "--traceback", + dest="traceback", + action="store_true", + help="Also include the traceback of the node's creation " + "(if available in Python).") + self._arg_parsers["node_info"] = ap + + # Parser for list_inputs. + ap = argparse.ArgumentParser( + description="Show inputs to a node.", usage=argparse.SUPPRESS) + ap.add_argument( + "node_name", + type=str, + help="Name of the node or an output tensor from the node, e.g., " + "hidden1/Wx_plus_b/MatMul, hidden1/Wx_plus_b/MatMul:0") + ap.add_argument( + "-c", "--control", action="store_true", help="Include control inputs.") + ap.add_argument( + "-d", + "--depth", + dest="depth", + type=int, + default=config.get("graph_recursion_depth"), + help="Maximum depth of recursion used when showing the input tree.") + ap.add_argument( + "-r", + "--recursive", + dest="recursive", + action="store_true", + help="Show inputs to the node recursively, i.e., the input tree.") + ap.add_argument( + "-t", + "--op_type", + action="store_true", + help="Show op types of input nodes.") + self._arg_parsers["list_inputs"] = ap + + # Parser for list_outputs. + ap = argparse.ArgumentParser( + description="Show the nodes that receive the outputs of given node.", + usage=argparse.SUPPRESS) + ap.add_argument( + "node_name", + type=str, + help="Name of the node or an output tensor from the node, e.g., " + "hidden1/Wx_plus_b/MatMul, hidden1/Wx_plus_b/MatMul:0") + ap.add_argument( + "-c", "--control", action="store_true", help="Include control inputs.") + ap.add_argument( + "-d", + "--depth", + dest="depth", + type=int, + default=config.get("graph_recursion_depth"), + help="Maximum depth of recursion used when showing the output tree.") + ap.add_argument( + "-r", + "--recursive", + dest="recursive", + action="store_true", + help="Show recipients of the node recursively, i.e., the output " + "tree.") + ap.add_argument( + "-t", + "--op_type", + action="store_true", + help="Show op types of recipient nodes.") + self._arg_parsers["list_outputs"] = ap + + # Parser for print_tensor. + self._arg_parsers["print_tensor"] = ( + command_parser.get_print_tensor_argparser( + "Print the value of a dumped tensor.")) + + # Parser for print_source. + ap = argparse.ArgumentParser( + description="Print a Python source file with overlaid debug " + "information, including the nodes (ops) or Tensors created at the " + "source lines.", + usage=argparse.SUPPRESS) + ap.add_argument( + "source_file_path", + type=str, + help="Path to the source file.") + ap.add_argument( + "-t", + "--tensors", + dest="tensors", + action="store_true", + help="Label lines with dumped Tensors, instead of ops.") + ap.add_argument( + "-m", + "--max_elements_per_line", + type=int, + default=10, + help="Maximum number of elements (ops or Tensors) to show per source " + "line.") + ap.add_argument( + "-b", + "--line_begin", + type=int, + default=1, + help="Print source beginning at line number (1-based.)") + self._arg_parsers["print_source"] = ap + + # Parser for list_source. + ap = argparse.ArgumentParser( + description="List source files responsible for constructing nodes and " + "tensors present in the run().", + usage=argparse.SUPPRESS) + ap.add_argument( + "-p", + "--path_filter", + type=str, + default="", + help="Regular expression filter for file path.") + ap.add_argument( + "-n", + "--node_name_filter", + type=str, + default="", + help="Regular expression filter for node name.") + self._arg_parsers["list_source"] = ap + + # Parser for eval. + ap = argparse.ArgumentParser( + description="""Evaluate an arbitrary expression. Can use tensor values + from the current debug dump. The debug tensor names should be enclosed + in pairs of backticks. Expressions with spaces should be enclosed in + a pair of double quotes or a pair of single quotes. By default, numpy + is imported as np and can be used in the expressions. E.g., + 1) eval np.argmax(`Softmax:0`), + 2) eval 'np.sum(`Softmax:0`, axis=1)', + 3) eval "np.matmul((`output/Identity:0`/`Softmax:0`).T, `Softmax:0`)". + """, + usage=argparse.SUPPRESS) + ap.add_argument( + "expression", + type=str, + help="""Expression to be evaluated. + 1) in the simplest case, use :, e.g., + hidden_0/MatMul:0. + + 2) if the default debug op "DebugIdentity" is to be overridden, use + ::, e.g., + hidden_0/MatMul:0:DebugNumericSummary. + + 3) if the tensor of the same name exists on more than one device, use + ::[:], e.g., + /job:worker/replica:0/task:0/gpu:0:hidden_0/MatMul:0 + /job:worker/replica:0/task:2/cpu:0:hidden_0/MatMul:0:DebugNanCount. + + 4) if the tensor is executed multiple times in a given `Session.run` + call, specify the execution index with a 0-based integer enclose in a + pair of brackets at the end, e.g., + RNN/tanh:0[0] + /job:worker/replica:0/task:0/gpu:0:RNN/tanh:0[0].""") + ap.add_argument( + "-a", + "--all", + dest="print_all", + action="store_true", + help="Print the tensor in its entirety, i.e., do not use ellipses " + "(may be slow for large results).") + ap.add_argument( + "-w", + "--write_path", + default="", + help="Path of the numpy file to write the evaluation result to, " + "using numpy.save()") + self._arg_parsers["eval"] = ap + + def add_tensor_filter(self, filter_name, filter_callable): + """Add a tensor filter. + + A tensor filter is a named callable of the signature: + filter_callable(dump_datum, tensor), + + wherein dump_datum is an instance of debug_data.DebugTensorDatum carrying + metadata about the dumped tensor, including tensor name, timestamps, etc. + tensor is the value of the dumped tensor as an numpy.ndarray object. + The return value of the function is a bool. + This is the same signature as the input argument to + debug_data.DebugDumpDir.find(). + + Args: + filter_name: (str) name of the filter. Cannot be empty. + filter_callable: (callable) a filter function of the signature described + as above. + + Raises: + ValueError: If filter_name is an empty str. + TypeError: If filter_name is not a str. + Or if filter_callable is not callable. + """ + + if not isinstance(filter_name, str): + raise TypeError("Input argument filter_name is expected to be str, " + "but is not.") + + # Check that filter_name is not an empty str. + if not filter_name: + raise ValueError("Input argument filter_name cannot be empty.") + + # Check that filter_callable is callable. + if not callable(filter_callable): + raise TypeError( + "Input argument filter_callable is expected to be callable, " + "but is not.") + + self._tensor_filters[filter_name] = filter_callable + + def get_tensor_filter(self, filter_name): + """Retrieve filter function by name. + + Args: + filter_name: Name of the filter set during add_tensor_filter() call. + + Returns: + The callable associated with the filter name. + + Raises: + ValueError: If there is no tensor filter of the specified filter name. + """ + + if filter_name not in self._tensor_filters: + raise ValueError("There is no tensor filter named \"%s\"" % filter_name) + + return self._tensor_filters[filter_name] + + def get_help(self, handler_name): + return self._arg_parsers[handler_name].format_help() + + def list_tensors(self, args, screen_info=None): + """Command handler for list_tensors. + + List tensors dumped during debugged Session.run() call. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + + Raises: + ValueError: If `--filter_exclude_node_names` is used without `-f` or + `--tensor_filter` being used. + """ + + # TODO(cais): Add annotations of substrings for dumped tensor names, to + # facilitate on-screen highlighting/selection of node names. + _ = screen_info + + parsed = self._arg_parsers["list_tensors"].parse_args(args) + + output = [] + + filter_strs = [] + if parsed.op_type_filter: + op_type_regex = re.compile(parsed.op_type_filter) + filter_strs.append("Op type regex filter: \"%s\"" % parsed.op_type_filter) + else: + op_type_regex = None + + if parsed.node_name_filter: + node_name_regex = re.compile(parsed.node_name_filter) + filter_strs.append("Node name regex filter: \"%s\"" % + parsed.node_name_filter) + else: + node_name_regex = None + + output = debugger_cli_common.RichTextLines(filter_strs) + output.append("") + + if parsed.tensor_filter: + try: + filter_callable = self.get_tensor_filter(parsed.tensor_filter) + except ValueError: + output = cli_shared.error("There is no tensor filter named \"%s\"." % + parsed.tensor_filter) + _add_main_menu(output, node_name=None, enable_list_tensors=False) + return output + + data_to_show = self._debug_dump.find( + filter_callable, + exclude_node_names=parsed.filter_exclude_node_names) + else: + if parsed.filter_exclude_node_names: + raise ValueError( + "The flag --filter_exclude_node_names is valid only when " + "the flag -f or --tensor_filter is used.") + + data_to_show = self._debug_dump.dumped_tensor_data + + # TODO(cais): Implement filter by lambda on tensor value. + + max_timestamp_width, max_dump_size_width, max_op_type_width = ( + self._measure_tensor_list_column_widths(data_to_show)) + + # Sort the data. + data_to_show = self._sort_dump_data_by( + data_to_show, parsed.sort_by, parsed.reverse) + + output.extend( + self._tensor_list_column_heads(parsed, max_timestamp_width, + max_dump_size_width, max_op_type_width)) + + dump_count = 0 + for dump in data_to_show: + if node_name_regex and not node_name_regex.match(dump.node_name): + continue + + if op_type_regex: + op_type = self._debug_dump.node_op_type(dump.node_name) + if not op_type_regex.match(op_type): + continue + + rel_time = (dump.timestamp - self._debug_dump.t0) / 1000.0 + dump_size_str = cli_shared.bytes_to_readable_str(dump.dump_size_bytes) + dumped_tensor_name = "%s:%d" % (dump.node_name, dump.output_slot) + op_type = self._debug_dump.node_op_type(dump.node_name) + + line = "[%.3f]" % rel_time + line += " " * (max_timestamp_width - len(line)) + line += dump_size_str + line += " " * (max_timestamp_width + max_dump_size_width - len(line)) + line += op_type + line += " " * (max_timestamp_width + max_dump_size_width + + max_op_type_width - len(line)) + line += dumped_tensor_name + + output.append( + line, + font_attr_segs=[( + len(line) - len(dumped_tensor_name), len(line), + debugger_cli_common.MenuItem("", "pt %s" % dumped_tensor_name))]) + dump_count += 1 + + if parsed.tensor_filter: + output.prepend([ + "%d dumped tensor(s) passing filter \"%s\":" % + (dump_count, parsed.tensor_filter) + ]) + else: + output.prepend(["%d dumped tensor(s):" % dump_count]) + + _add_main_menu(output, node_name=None, enable_list_tensors=False) + return output + + def _measure_tensor_list_column_widths(self, data): + """Determine the maximum widths of the timestamp and op-type column. + + This method assumes that data is sorted in the default order, i.e., + by ascending timestamps. + + Args: + data: (list of DebugTensorDaum) the data based on which the maximum + column widths will be determined. + + Returns: + (int) maximum width of the timestamp column. 0 if data is empty. + (int) maximum width of the dump size column. 0 if data is empty. + (int) maximum width of the op type column. 0 if data is empty. + """ + + max_timestamp_width = 0 + if data: + max_rel_time_ms = (data[-1].timestamp - self._debug_dump.t0) / 1000.0 + max_timestamp_width = len("[%.3f] " % max_rel_time_ms) + 1 + max_timestamp_width = max(max_timestamp_width, + len(self._TIMESTAMP_COLUMN_HEAD) + 1) + + max_dump_size_width = 0 + for dump in data: + dump_size_str = cli_shared.bytes_to_readable_str(dump.dump_size_bytes) + if len(dump_size_str) + 1 > max_dump_size_width: + max_dump_size_width = len(dump_size_str) + 1 + max_dump_size_width = max(max_dump_size_width, + len(self._DUMP_SIZE_COLUMN_HEAD) + 1) + + max_op_type_width = 0 + for dump in data: + op_type = self._debug_dump.node_op_type(dump.node_name) + if len(op_type) + 1 > max_op_type_width: + max_op_type_width = len(op_type) + 1 + max_op_type_width = max(max_op_type_width, + len(self._OP_TYPE_COLUMN_HEAD) + 1) + + return max_timestamp_width, max_dump_size_width, max_op_type_width + + def _sort_dump_data_by(self, data, sort_by, reverse): + """Sort a list of DebugTensorDatum in specified order. + + Args: + data: (list of DebugTensorDatum) the data to be sorted. + sort_by: The field to sort data by. + reverse: (bool) Whether to use reversed (descending) order. + + Returns: + (list of DebugTensorDatum) in sorted order. + + Raises: + ValueError: given an invalid value of sort_by. + """ + + if sort_by == SORT_TENSORS_BY_TIMESTAMP: + return sorted( + data, + reverse=reverse, + key=lambda x: x.timestamp) + elif sort_by == SORT_TENSORS_BY_DUMP_SIZE: + return sorted(data, reverse=reverse, key=lambda x: x.dump_size_bytes) + elif sort_by == SORT_TENSORS_BY_OP_TYPE: + return sorted( + data, + reverse=reverse, + key=lambda x: self._debug_dump.node_op_type(x.node_name)) + elif sort_by == SORT_TENSORS_BY_TENSOR_NAME: + return sorted( + data, + reverse=reverse, + key=lambda x: "%s:%d" % (x.node_name, x.output_slot)) + else: + raise ValueError("Unsupported key to sort tensors by: %s" % sort_by) + + def _tensor_list_column_heads(self, parsed, max_timestamp_width, + max_dump_size_width, max_op_type_width): + """Generate a line containing the column heads of the tensor list. + + Args: + parsed: Parsed arguments (by argparse) of the list_tensors command. + max_timestamp_width: (int) maximum width of the timestamp column. + max_dump_size_width: (int) maximum width of the dump size column. + max_op_type_width: (int) maximum width of the op type column. + + Returns: + A RichTextLines object. + """ + + base_command = "list_tensors" + if parsed.tensor_filter: + base_command += " -f %s" % parsed.tensor_filter + if parsed.op_type_filter: + base_command += " -t %s" % parsed.op_type_filter + if parsed.node_name_filter: + base_command += " -n %s" % parsed.node_name_filter + + attr_segs = {0: []} + row = self._TIMESTAMP_COLUMN_HEAD + command = "%s -s %s" % (base_command, SORT_TENSORS_BY_TIMESTAMP) + if parsed.sort_by == SORT_TENSORS_BY_TIMESTAMP and not parsed.reverse: + command += " -r" + attr_segs[0].append( + (0, len(row), [debugger_cli_common.MenuItem(None, command), "bold"])) + row += " " * (max_timestamp_width - len(row)) + + prev_len = len(row) + row += self._DUMP_SIZE_COLUMN_HEAD + command = "%s -s %s" % (base_command, SORT_TENSORS_BY_DUMP_SIZE) + if parsed.sort_by == SORT_TENSORS_BY_DUMP_SIZE and not parsed.reverse: + command += " -r" + attr_segs[0].append((prev_len, len(row), + [debugger_cli_common.MenuItem(None, command), "bold"])) + row += " " * (max_dump_size_width + max_timestamp_width - len(row)) + + prev_len = len(row) + row += self._OP_TYPE_COLUMN_HEAD + command = "%s -s %s" % (base_command, SORT_TENSORS_BY_OP_TYPE) + if parsed.sort_by == SORT_TENSORS_BY_OP_TYPE and not parsed.reverse: + command += " -r" + attr_segs[0].append((prev_len, len(row), + [debugger_cli_common.MenuItem(None, command), "bold"])) + row += " " * ( + max_op_type_width + max_dump_size_width + max_timestamp_width - len(row) + ) + + prev_len = len(row) + row += self._TENSOR_NAME_COLUMN_HEAD + command = "%s -s %s" % (base_command, SORT_TENSORS_BY_TENSOR_NAME) + if parsed.sort_by == SORT_TENSORS_BY_TENSOR_NAME and not parsed.reverse: + command += " -r" + attr_segs[0].append((prev_len, len(row), + [debugger_cli_common.MenuItem("", command), "bold"])) + row += " " * ( + max_op_type_width + max_dump_size_width + max_timestamp_width - len(row) + ) + + return debugger_cli_common.RichTextLines([row], font_attr_segs=attr_segs) + + def node_info(self, args, screen_info=None): + """Command handler for node_info. + + Query information about a given node. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + """ + + # TODO(cais): Add annotation of substrings for node names, to facilitate + # on-screen highlighting/selection of node names. + _ = screen_info + + parsed = self._arg_parsers["node_info"].parse_args(args) + + # Get a node name, regardless of whether the input is a node name (without + # output slot attached) or a tensor name (with output slot attached). + node_name, unused_slot = debug_graphs.parse_node_or_tensor_name( + parsed.node_name) + + if not self._debug_dump.node_exists(node_name): + output = cli_shared.error( + "There is no node named \"%s\" in the partition graphs" % node_name) + _add_main_menu( + output, + node_name=None, + enable_list_tensors=True, + enable_node_info=False, + enable_list_inputs=False, + enable_list_outputs=False) + return output + + # TODO(cais): Provide UI glossary feature to explain to users what the + # term "partition graph" means and how it is related to TF graph objects + # in Python. The information can be along the line of: + # "A tensorflow graph defined in Python is stripped of unused ops + # according to the feeds and fetches and divided into a number of + # partition graphs that may be distributed among multiple devices and + # hosts. The partition graphs are what's actually executed by the C++ + # runtime during a run() call." + + lines = ["Node %s" % node_name] + font_attr_segs = { + 0: [(len(lines[-1]) - len(node_name), len(lines[-1]), "bold")] + } + lines.append("") + lines.append(" Op: %s" % self._debug_dump.node_op_type(node_name)) + lines.append(" Device: %s" % self._debug_dump.node_device(node_name)) + output = debugger_cli_common.RichTextLines( + lines, font_attr_segs=font_attr_segs) + + # List node inputs (non-control and control). + inputs = self._exclude_denylisted_ops( + self._debug_dump.node_inputs(node_name)) + ctrl_inputs = self._exclude_denylisted_ops( + self._debug_dump.node_inputs(node_name, is_control=True)) + output.extend(self._format_neighbors("input", inputs, ctrl_inputs)) + + # List node output recipients (non-control and control). + recs = self._exclude_denylisted_ops( + self._debug_dump.node_recipients(node_name)) + ctrl_recs = self._exclude_denylisted_ops( + self._debug_dump.node_recipients(node_name, is_control=True)) + output.extend(self._format_neighbors("recipient", recs, ctrl_recs)) + + # Optional: List attributes of the node. + if parsed.attributes: + output.extend(self._list_node_attributes(node_name)) + + # Optional: List dumps available from the node. + if parsed.dumps: + output.extend(self._list_node_dumps(node_name)) + + if parsed.traceback: + output.extend(self._render_node_traceback(node_name)) + + _add_main_menu(output, node_name=node_name, enable_node_info=False) + return output + + def _exclude_denylisted_ops(self, node_names): + """Exclude all nodes whose op types are in _GRAPH_STRUCT_OP_TYPE_DENYLIST. + + Args: + node_names: An iterable of node or graph element names. + + Returns: + A list of node names that are not denylisted. + """ + return [ + node_name for node_name in node_names + if self._debug_dump.node_op_type(debug_graphs.get_node_name(node_name)) + not in self._GRAPH_STRUCT_OP_TYPE_DENYLIST + ] + + def _render_node_traceback(self, node_name): + """Render traceback of a node's creation in Python, if available. + + Args: + node_name: (str) name of the node. + + Returns: + A RichTextLines object containing the stack trace of the node's + construction. + """ + + lines = [RL(""), RL(""), RL("Traceback of node construction:", "bold")] + + try: + node_stack = self._debug_dump.node_traceback(node_name) + for depth, (file_path, line, function_name, text) in enumerate( + node_stack): + lines.append("%d: %s" % (depth, file_path)) + + attribute = debugger_cli_common.MenuItem( + "", "ps %s -b %d" % (file_path, line)) if text else None + line_number_line = RL(" ") + line_number_line += RL("Line: %d" % line, attribute) + lines.append(line_number_line) + + lines.append(" Function: %s" % function_name) + lines.append(" Text: " + (("\"%s\"" % text) if text else "None")) + lines.append("") + except KeyError: + lines.append("(Node unavailable in the loaded Python graph)") + except LookupError: + lines.append("(Unavailable because no Python graph has been loaded)") + + return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) + + def list_inputs(self, args, screen_info=None): + """Command handler for inputs. + + Show inputs to a given node. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + """ + + # Screen info not currently used by this handler. Include this line to + # mute pylint. + _ = screen_info + # TODO(cais): Use screen info to format the output lines more prettily, + # e.g., hanging indent of long node names. + + parsed = self._arg_parsers["list_inputs"].parse_args(args) + + output = self._list_inputs_or_outputs( + parsed.recursive, + parsed.node_name, + parsed.depth, + parsed.control, + parsed.op_type, + do_outputs=False) + + node_name = debug_graphs.get_node_name(parsed.node_name) + _add_main_menu(output, node_name=node_name, enable_list_inputs=False) + + return output + + def print_tensor(self, args, screen_info=None): + """Command handler for print_tensor. + + Print value of a given dumped tensor. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + """ + + parsed = self._arg_parsers["print_tensor"].parse_args(args) + + np_printoptions = cli_shared.numpy_printoptions_from_screen_info( + screen_info) + + # Determine if any range-highlighting is required. + highlight_options = cli_shared.parse_ranges_highlight(parsed.ranges) + + tensor_name, tensor_slicing = ( + command_parser.parse_tensor_name_with_slicing(parsed.tensor_name)) + + node_name, output_slot = debug_graphs.parse_node_or_tensor_name(tensor_name) + if (self._debug_dump.loaded_partition_graphs() and + not self._debug_dump.node_exists(node_name)): + output = cli_shared.error( + "Node \"%s\" does not exist in partition graphs" % node_name) + _add_main_menu( + output, + node_name=None, + enable_list_tensors=True, + enable_print_tensor=False) + return output + + watch_keys = self._debug_dump.debug_watch_keys(node_name) + if output_slot is None: + output_slots = set() + for watch_key in watch_keys: + output_slots.add(int(watch_key.split(":")[1])) + + if len(output_slots) == 1: + # There is only one dumped tensor from this node, so there is no + # ambiguity. Proceed to show the only dumped tensor. + output_slot = list(output_slots)[0] + else: + # There are more than one dumped tensors from this node. Indicate as + # such. + # TODO(cais): Provide an output screen with command links for + # convenience. + lines = [ + "Node \"%s\" generated debug dumps from %s output slots:" % + (node_name, len(output_slots)), + "Please specify the output slot: %s:x." % node_name + ] + output = debugger_cli_common.RichTextLines(lines) + _add_main_menu( + output, + node_name=node_name, + enable_list_tensors=True, + enable_print_tensor=False) + return output + + # Find debug dump data that match the tensor name (node name + output + # slot). + matching_data = [] + for watch_key in watch_keys: + debug_tensor_data = self._debug_dump.watch_key_to_data(watch_key) + for datum in debug_tensor_data: + if datum.output_slot == output_slot: + matching_data.append(datum) + + if not matching_data: + # No dump for this tensor. + output = cli_shared.error("Tensor \"%s\" did not generate any dumps." % + parsed.tensor_name) + elif len(matching_data) == 1: + # There is only one dump for this tensor. + if parsed.number <= 0: + output = cli_shared.format_tensor( + matching_data[0].get_tensor(), + matching_data[0].watch_key, + np_printoptions, + print_all=parsed.print_all, + tensor_slicing=tensor_slicing, + highlight_options=highlight_options, + include_numeric_summary=parsed.numeric_summary, + write_path=parsed.write_path) + else: + output = cli_shared.error( + "Invalid number (%d) for tensor %s, which generated one dump." % + (parsed.number, parsed.tensor_name)) + + _add_main_menu(output, node_name=node_name, enable_print_tensor=False) + else: + # There are more than one dumps for this tensor. + if parsed.number < 0: + lines = [ + "Tensor \"%s\" generated %d dumps:" % (parsed.tensor_name, + len(matching_data)) + ] + font_attr_segs = {} + + for i, datum in enumerate(matching_data): + rel_time = (datum.timestamp - self._debug_dump.t0) / 1000.0 + lines.append("#%d [%.3f ms] %s" % (i, rel_time, datum.watch_key)) + command = "print_tensor %s -n %d" % (parsed.tensor_name, i) + font_attr_segs[len(lines) - 1] = [( + len(lines[-1]) - len(datum.watch_key), len(lines[-1]), + debugger_cli_common.MenuItem(None, command))] + + lines.append("") + lines.append( + "You can use the -n (--number) flag to specify which dump to " + "print.") + lines.append("For example:") + lines.append(" print_tensor %s -n 0" % parsed.tensor_name) + + output = debugger_cli_common.RichTextLines( + lines, font_attr_segs=font_attr_segs) + elif parsed.number >= len(matching_data): + output = cli_shared.error( + "Specified number (%d) exceeds the number of available dumps " + "(%d) for tensor %s" % + (parsed.number, len(matching_data), parsed.tensor_name)) + else: + output = cli_shared.format_tensor( + matching_data[parsed.number].get_tensor(), + matching_data[parsed.number].watch_key + " (dump #%d)" % + parsed.number, + np_printoptions, + print_all=parsed.print_all, + tensor_slicing=tensor_slicing, + highlight_options=highlight_options, + write_path=parsed.write_path) + _add_main_menu(output, node_name=node_name, enable_print_tensor=False) + + return output + + def list_outputs(self, args, screen_info=None): + """Command handler for inputs. + + Show inputs to a given node. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + """ + + # Screen info not currently used by this handler. Include this line to + # mute pylint. + _ = screen_info + # TODO(cais): Use screen info to format the output lines more prettily, + # e.g., hanging indent of long node names. + + parsed = self._arg_parsers["list_outputs"].parse_args(args) + + output = self._list_inputs_or_outputs( + parsed.recursive, + parsed.node_name, + parsed.depth, + parsed.control, + parsed.op_type, + do_outputs=True) + + node_name = debug_graphs.get_node_name(parsed.node_name) + _add_main_menu(output, node_name=node_name, enable_list_outputs=False) + + return output + + def evaluate_expression(self, args, screen_info=None): + parsed = self._arg_parsers["eval"].parse_args(args) + + eval_res = self._evaluator.evaluate(parsed.expression) + + np_printoptions = cli_shared.numpy_printoptions_from_screen_info( + screen_info) + return cli_shared.format_tensor( + eval_res, + "from eval of expression '%s'" % parsed.expression, + np_printoptions, + print_all=parsed.print_all, + include_numeric_summary=True, + write_path=parsed.write_path) + + def _reconstruct_print_source_command(self, + parsed, + line_begin, + max_elements_per_line_increase=0): + return "ps %s %s -b %d -m %d" % ( + parsed.source_file_path, "-t" if parsed.tensors else "", line_begin, + parsed.max_elements_per_line + max_elements_per_line_increase) + + def print_source(self, args, screen_info=None): + """Print the content of a source file.""" + del screen_info # Unused. + + parsed = self._arg_parsers["print_source"].parse_args(args) + + source_annotation = source_utils.annotate_source( + self._debug_dump, + parsed.source_file_path, + do_dumped_tensors=parsed.tensors) + + source_lines, line_num_width = source_utils.load_source( + parsed.source_file_path) + + labeled_source_lines = [] + actual_initial_scroll_target = 0 + for i, line in enumerate(source_lines): + annotated_line = RL("L%d" % (i + 1), cli_shared.COLOR_YELLOW) + annotated_line += " " * (line_num_width - len(annotated_line)) + annotated_line += line + labeled_source_lines.append(annotated_line) + + if i + 1 == parsed.line_begin: + actual_initial_scroll_target = len(labeled_source_lines) - 1 + + if i + 1 in source_annotation: + sorted_elements = sorted(source_annotation[i + 1]) + for k, element in enumerate(sorted_elements): + if k >= parsed.max_elements_per_line: + omitted_info_line = RL(" (... Omitted %d of %d %s ...) " % ( + len(sorted_elements) - parsed.max_elements_per_line, + len(sorted_elements), + "tensor(s)" if parsed.tensors else "op(s)")) + omitted_info_line += RL( + "+5", + debugger_cli_common.MenuItem( + None, + self._reconstruct_print_source_command( + parsed, i + 1, max_elements_per_line_increase=5))) + labeled_source_lines.append(omitted_info_line) + break + + label = RL(" " * 4) + if self._debug_dump.debug_watch_keys( + debug_graphs.get_node_name(element)): + attribute = debugger_cli_common.MenuItem("", "pt %s" % element) + else: + attribute = cli_shared.COLOR_BLUE + + label += RL(element, attribute) + labeled_source_lines.append(label) + + output = debugger_cli_common.rich_text_lines_from_rich_line_list( + labeled_source_lines, + annotations={debugger_cli_common.INIT_SCROLL_POS_KEY: + actual_initial_scroll_target}) + _add_main_menu(output, node_name=None) + return output + + def _make_source_table(self, source_list, is_tf_py_library): + """Make a table summarizing the source files that create nodes and tensors. + + Args: + source_list: List of source files and related information as a list of + tuples (file_path, is_tf_library, num_nodes, num_tensors, num_dumps, + first_line). + is_tf_py_library: (`bool`) whether this table is for files that belong + to the TensorFlow Python library. + + Returns: + The table as a `debugger_cli_common.RichTextLines` object. + """ + path_head = "Source file path" + num_nodes_head = "#(nodes)" + num_tensors_head = "#(tensors)" + num_dumps_head = "#(tensor dumps)" + + if is_tf_py_library: + # Use color to mark files that are guessed to belong to TensorFlow Python + # library. + color = cli_shared.COLOR_GRAY + lines = [RL("TensorFlow Python library file(s):", color)] + else: + color = cli_shared.COLOR_WHITE + lines = [RL("File(s) outside TensorFlow Python library:", color)] + + if not source_list: + lines.append(RL("[No files.]")) + lines.append(RL()) + return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) + + path_column_width = max( + max(len(item[0]) for item in source_list), len(path_head)) + 1 + num_nodes_column_width = max( + max(len(str(item[2])) for item in source_list), + len(num_nodes_head)) + 1 + num_tensors_column_width = max( + max(len(str(item[3])) for item in source_list), + len(num_tensors_head)) + 1 + + head = RL(path_head + " " * (path_column_width - len(path_head)), color) + head += RL(num_nodes_head + " " * ( + num_nodes_column_width - len(num_nodes_head)), color) + head += RL(num_tensors_head + " " * ( + num_tensors_column_width - len(num_tensors_head)), color) + head += RL(num_dumps_head, color) + + lines.append(head) + + for (file_path, _, num_nodes, num_tensors, num_dumps, + first_line_num) in source_list: + path_attributes = [color] + if source_utils.is_extension_uncompiled_python_source(file_path): + path_attributes.append( + debugger_cli_common.MenuItem(None, "ps %s -b %d" % + (file_path, first_line_num))) + + line = RL(file_path, path_attributes) + line += " " * (path_column_width - len(line)) + line += RL( + str(num_nodes) + " " * (num_nodes_column_width - len(str(num_nodes))), + color) + line += RL( + str(num_tensors) + " " * + (num_tensors_column_width - len(str(num_tensors))), color) + line += RL(str(num_dumps), color) + lines.append(line) + lines.append(RL()) + + return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) + + def list_source(self, args, screen_info=None): + """List Python source files that constructed nodes and tensors.""" + del screen_info # Unused. + + parsed = self._arg_parsers["list_source"].parse_args(args) + source_list = source_utils.list_source_files_against_dump( + self._debug_dump, + path_regex_allowlist=parsed.path_filter, + node_name_regex_allowlist=parsed.node_name_filter) + + top_lines = [ + RL("List of source files that created nodes in this run", "bold")] + if parsed.path_filter: + top_lines.append( + RL("File path regex filter: \"%s\"" % parsed.path_filter)) + if parsed.node_name_filter: + top_lines.append( + RL("Node name regex filter: \"%s\"" % parsed.node_name_filter)) + top_lines.append(RL()) + output = debugger_cli_common.rich_text_lines_from_rich_line_list(top_lines) + if not source_list: + output.append("[No source file information.]") + return output + + output.extend(self._make_source_table( + [item for item in source_list if not item[1]], False)) + output.extend(self._make_source_table( + [item for item in source_list if item[1]], True)) + _add_main_menu(output, node_name=None) + return output + + def _list_inputs_or_outputs(self, + recursive, + node_name, + depth, + control, + op_type, + do_outputs=False): + """Helper function used by list_inputs and list_outputs. + + Format a list of lines to display the inputs or output recipients of a + given node. + + Args: + recursive: Whether the listing is to be done recursively, as a boolean. + node_name: The name of the node in question, as a str. + depth: Maximum recursion depth, applies only if recursive == True, as an + int. + control: Whether control inputs or control recipients are included, as a + boolean. + op_type: Whether the op types of the nodes are to be included, as a + boolean. + do_outputs: Whether recipients, instead of input nodes are to be + listed, as a boolean. + + Returns: + Input or recipient tree formatted as a RichTextLines object. + """ + + if do_outputs: + tracker = self._debug_dump.node_recipients + type_str = "Recipients of" + short_type_str = "recipients" + else: + tracker = self._debug_dump.node_inputs + type_str = "Inputs to" + short_type_str = "inputs" + + lines = [] + font_attr_segs = {} + + # Check if this is a tensor name, instead of a node name. + node_name, _ = debug_graphs.parse_node_or_tensor_name(node_name) + + # Check if node exists. + if not self._debug_dump.node_exists(node_name): + return cli_shared.error( + "There is no node named \"%s\" in the partition graphs" % node_name) + + if recursive: + max_depth = depth + else: + max_depth = 1 + + if control: + include_ctrls_str = ", control %s included" % short_type_str + else: + include_ctrls_str = "" + + line = "%s node \"%s\"" % (type_str, node_name) + font_attr_segs[0] = [(len(line) - 1 - len(node_name), len(line) - 1, "bold") + ] + lines.append(line + " (Depth limit = %d%s):" % (max_depth, include_ctrls_str + )) + + command_template = "lo -c -r %s" if do_outputs else "li -c -r %s" + self._dfs_from_node( + lines, + font_attr_segs, + node_name, + tracker, + max_depth, + 1, [], + control, + op_type, + command_template=command_template) + + # Include legend. + lines.append("") + lines.append("Legend:") + lines.append(" (d): recursion depth = d.") + + if control: + lines.append(" (Ctrl): Control input.") + if op_type: + lines.append(" [Op]: Input node has op type Op.") + + # TODO(cais): Consider appending ":0" at the end of 1st outputs of nodes. + + return debugger_cli_common.RichTextLines( + lines, font_attr_segs=font_attr_segs) + + def _dfs_from_node(self, + lines, + attr_segs, + node_name, + tracker, + max_depth, + depth, + unfinished, + include_control=False, + show_op_type=False, + command_template=None): + """Perform depth-first search (DFS) traversal of a node's input tree. + + It recursively tracks the inputs (or output recipients) of the node called + node_name, and append these inputs (or output recipients) to a list of text + lines (lines) with proper indentation that reflects the recursion depth, + together with some formatting attributes (to attr_segs). The formatting + attributes can include command shortcuts, for example. + + Args: + lines: Text lines to append to, as a list of str. + attr_segs: (dict) Attribute segments dictionary to append to. + node_name: Name of the node, as a str. This arg is updated during the + recursion. + tracker: A callable that takes one str as the node name input and + returns a list of str as the inputs/outputs. + This makes it this function general enough to be used with both + node-input and node-output tracking. + max_depth: Maximum recursion depth, as an int. + depth: Current recursion depth. This arg is updated during the + recursion. + unfinished: A stack of unfinished recursion depths, as a list of int. + include_control: Whether control dependencies are to be included as + inputs (and marked as such). + show_op_type: Whether op type of the input nodes are to be displayed + alongside the nodes' names. + command_template: (str) Template for command shortcut of the node names. + """ + + # Make a shallow copy of the list because it may be extended later. + all_inputs = self._exclude_denylisted_ops( + copy.copy(tracker(node_name, is_control=False))) + is_ctrl = [False] * len(all_inputs) + if include_control: + # Sort control inputs or recipients in alphabetical order of the node + # names. + ctrl_inputs = self._exclude_denylisted_ops( + sorted(tracker(node_name, is_control=True))) + all_inputs.extend(ctrl_inputs) + is_ctrl.extend([True] * len(ctrl_inputs)) + + if not all_inputs: + if depth == 1: + lines.append(" [None]") + + return + + unfinished.append(depth) + + # Create depth-dependent hanging indent for the line. + hang = "" + for k in range(depth): + if k < depth - 1: + if k + 1 in unfinished: + hang += HANG_UNFINISHED + else: + hang += HANG_FINISHED + else: + hang += HANG_SUFFIX + + if all_inputs and depth > max_depth: + lines.append(hang + ELLIPSIS) + unfinished.pop() + return + + hang += DEPTH_TEMPLATE % depth + + for i, inp in enumerate(all_inputs): + op_type = self._debug_dump.node_op_type(debug_graphs.get_node_name(inp)) + if op_type in self._GRAPH_STRUCT_OP_TYPE_DENYLIST: + continue + + if is_ctrl[i]: + ctrl_str = CTRL_LABEL + else: + ctrl_str = "" + + op_type_str = "" + if show_op_type: + op_type_str = OP_TYPE_TEMPLATE % op_type + + if i == len(all_inputs) - 1: + unfinished.pop() + + line = hang + ctrl_str + op_type_str + inp + lines.append(line) + if command_template: + attr_segs[len(lines) - 1] = [( + len(line) - len(inp), len(line), + debugger_cli_common.MenuItem(None, command_template % inp))] + + # Recursive call. + # The input's/output's name can be a tensor name, in the case of node + # with >1 output slots. + inp_node_name, _ = debug_graphs.parse_node_or_tensor_name(inp) + self._dfs_from_node( + lines, + attr_segs, + inp_node_name, + tracker, + max_depth, + depth + 1, + unfinished, + include_control=include_control, + show_op_type=show_op_type, + command_template=command_template) + + def _format_neighbors(self, neighbor_type, non_ctrls, ctrls): + """List neighbors (inputs or recipients) of a node. + + Args: + neighbor_type: ("input" | "recipient") + non_ctrls: Non-control neighbor node names, as a list of str. + ctrls: Control neighbor node names, as a list of str. + + Returns: + A RichTextLines object. + """ + + # TODO(cais): Return RichTextLines instead, to allow annotation of node + # names. + lines = [] + font_attr_segs = {} + + lines.append("") + lines.append(" %d %s(s) + %d control %s(s):" % + (len(non_ctrls), neighbor_type, len(ctrls), neighbor_type)) + lines.append(" %d %s(s):" % (len(non_ctrls), neighbor_type)) + for non_ctrl in non_ctrls: + line = " [%s] %s" % (self._debug_dump.node_op_type(non_ctrl), + non_ctrl) + lines.append(line) + font_attr_segs[len(lines) - 1] = [( + len(line) - len(non_ctrl), len(line), + debugger_cli_common.MenuItem(None, "ni -a -d -t %s" % non_ctrl))] + + if ctrls: + lines.append("") + lines.append(" %d control %s(s):" % (len(ctrls), neighbor_type)) + for ctrl in ctrls: + line = " [%s] %s" % (self._debug_dump.node_op_type(ctrl), ctrl) + lines.append(line) + font_attr_segs[len(lines) - 1] = [( + len(line) - len(ctrl), len(line), + debugger_cli_common.MenuItem(None, "ni -a -d -t %s" % ctrl))] + + return debugger_cli_common.RichTextLines( + lines, font_attr_segs=font_attr_segs) + + def _list_node_attributes(self, node_name): + """List neighbors (inputs or recipients) of a node. + + Args: + node_name: Name of the node of which the attributes are to be listed. + + Returns: + A RichTextLines object. + """ + + lines = [] + lines.append("") + lines.append("Node attributes:") + + attrs = self._debug_dump.node_attributes(node_name) + for attr_key in attrs: + lines.append(" %s:" % attr_key) + attr_val_str = repr(attrs[attr_key]).strip().replace("\n", " ") + lines.append(" %s" % attr_val_str) + lines.append("") + + return debugger_cli_common.RichTextLines(lines) + + def _list_node_dumps(self, node_name): + """List dumped tensor data from a node. + + Args: + node_name: Name of the node of which the attributes are to be listed. + + Returns: + A RichTextLines object. + """ + + lines = [] + font_attr_segs = {} + + watch_keys = self._debug_dump.debug_watch_keys(node_name) + + dump_count = 0 + for watch_key in watch_keys: + debug_tensor_data = self._debug_dump.watch_key_to_data(watch_key) + for datum in debug_tensor_data: + line = " Slot %d @ %s @ %.3f ms" % ( + datum.output_slot, datum.debug_op, + (datum.timestamp - self._debug_dump.t0) / 1000.0) + lines.append(line) + command = "pt %s:%d -n %d" % (node_name, datum.output_slot, dump_count) + font_attr_segs[len(lines) - 1] = [( + 2, len(line), debugger_cli_common.MenuItem(None, command))] + dump_count += 1 + + output = debugger_cli_common.RichTextLines( + lines, font_attr_segs=font_attr_segs) + output_with_header = debugger_cli_common.RichTextLines( + ["%d dumped tensor(s):" % dump_count, ""]) + output_with_header.extend(output) + return output_with_header + + +def create_analyzer_ui(debug_dump, + tensor_filters=None, + ui_type="readline", + on_ui_exit=None, + config=None): + """Create an instance of ReadlineUI based on a DebugDumpDir object. + + Args: + debug_dump: (debug_data.DebugDumpDir) The debug dump to use. + tensor_filters: (dict) A dict mapping tensor filter name (str) to tensor + filter (Callable). + ui_type: (str) requested UI type, only "readline" is supported. + on_ui_exit: (`Callable`) the callback to be called when the UI exits. + config: A `cli_config.CLIConfig` object. + + Returns: + (base_ui.BaseUI) A BaseUI subtype object with a set of standard analyzer + commands and tab-completions registered. + """ + if config is None: + config = cli_config.CLIConfig() + + analyzer = DebugAnalyzer(debug_dump, config=config) + if tensor_filters: + for tensor_filter_name in tensor_filters: + analyzer.add_tensor_filter( + tensor_filter_name, tensor_filters[tensor_filter_name]) + + cli = ui_factory.get_ui(ui_type, on_ui_exit=on_ui_exit, config=config) + cli.register_command_handler( + "list_tensors", + analyzer.list_tensors, + analyzer.get_help("list_tensors"), + prefix_aliases=["lt"]) + cli.register_command_handler( + "node_info", + analyzer.node_info, + analyzer.get_help("node_info"), + prefix_aliases=["ni"]) + cli.register_command_handler( + "list_inputs", + analyzer.list_inputs, + analyzer.get_help("list_inputs"), + prefix_aliases=["li"]) + cli.register_command_handler( + "list_outputs", + analyzer.list_outputs, + analyzer.get_help("list_outputs"), + prefix_aliases=["lo"]) + cli.register_command_handler( + "print_tensor", + analyzer.print_tensor, + analyzer.get_help("print_tensor"), + prefix_aliases=["pt"]) + cli.register_command_handler( + "print_source", + analyzer.print_source, + analyzer.get_help("print_source"), + prefix_aliases=["ps"]) + cli.register_command_handler( + "list_source", + analyzer.list_source, + analyzer.get_help("list_source"), + prefix_aliases=["ls"]) + cli.register_command_handler( + "eval", + analyzer.evaluate_expression, + analyzer.get_help("eval"), + prefix_aliases=["ev"]) + + dumped_tensor_names = [] + for datum in debug_dump.dumped_tensor_data: + dumped_tensor_names.append("%s:%d" % (datum.node_name, datum.output_slot)) + + # Tab completions for command "print_tensors". + cli.register_tab_comp_context(["print_tensor", "pt"], dumped_tensor_names) + + return cli diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/base_ui.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/base_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad05c55050538a778bf3f881dbfcbc41065e209 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/base_ui.py @@ -0,0 +1,211 @@ +# 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. +# ============================================================================== +"""Base Class of TensorFlow Debugger (tfdbg) Command-Line Interface.""" +import argparse + +from tensorflow.python.debug.cli import cli_config +from tensorflow.python.debug.cli import command_parser +from tensorflow.python.debug.cli import debugger_cli_common + + +class BaseUI(object): + """Base class of tfdbg user interface.""" + + CLI_PROMPT = "tfdbg> " + CLI_EXIT_COMMANDS = ["exit", "quit"] + ERROR_MESSAGE_PREFIX = "ERROR: " + INFO_MESSAGE_PREFIX = "INFO: " + + def __init__(self, on_ui_exit=None, config=None): + """Constructor of the base class. + + Args: + on_ui_exit: (`Callable`) the callback to be called when the UI exits. + config: An instance of `cli_config.CLIConfig()` carrying user-facing + configurations. + """ + + self._on_ui_exit = on_ui_exit + + self._command_handler_registry = ( + debugger_cli_common.CommandHandlerRegistry()) + + self._tab_completion_registry = debugger_cli_common.TabCompletionRegistry() + + # Create top-level tab-completion context and register the exit and help + # commands. + self._tab_completion_registry.register_tab_comp_context( + [""], self.CLI_EXIT_COMMANDS + + [debugger_cli_common.CommandHandlerRegistry.HELP_COMMAND] + + debugger_cli_common.CommandHandlerRegistry.HELP_COMMAND_ALIASES) + + self._config = config or cli_config.CLIConfig() + self._config_argparser = argparse.ArgumentParser( + description="config command", usage=argparse.SUPPRESS) + subparsers = self._config_argparser.add_subparsers() + set_parser = subparsers.add_parser("set") + set_parser.add_argument("property_name", type=str) + set_parser.add_argument("property_value", type=str) + set_parser = subparsers.add_parser("show") + self.register_command_handler( + "config", + self._config_command_handler, + self._config_argparser.format_help(), + prefix_aliases=["cfg"]) + + def set_help_intro(self, help_intro): + """Set an introductory message to the help output of the command registry. + + Args: + help_intro: (RichTextLines) Rich text lines appended to the beginning of + the output of the command "help", as introductory information. + """ + + self._command_handler_registry.set_help_intro(help_intro=help_intro) + + def register_command_handler(self, + prefix, + handler, + help_info, + prefix_aliases=None): + """A wrapper around CommandHandlerRegistry.register_command_handler(). + + In addition to calling the wrapped register_command_handler() method, this + method also registers the top-level tab-completion context based on the + command prefixes and their aliases. + + See the doc string of the wrapped method for more details on the args. + + Args: + prefix: (str) command prefix. + handler: (callable) command handler. + help_info: (str) help information. + prefix_aliases: (list of str) aliases of the command prefix. + """ + + self._command_handler_registry.register_command_handler( + prefix, handler, help_info, prefix_aliases=prefix_aliases) + + self._tab_completion_registry.extend_comp_items("", [prefix]) + if prefix_aliases: + self._tab_completion_registry.extend_comp_items("", prefix_aliases) + + def register_tab_comp_context(self, *args, **kwargs): + """Wrapper around TabCompletionRegistry.register_tab_comp_context().""" + + self._tab_completion_registry.register_tab_comp_context(*args, **kwargs) + + def run_ui(self, + init_command=None, + title=None, + title_color=None, + enable_mouse_on_start=True): + """Run the UI until user- or command- triggered exit. + + Args: + init_command: (str) Optional command to run on CLI start up. + title: (str) Optional title to display in the CLI. + title_color: (str) Optional color of the title, e.g., "yellow". + enable_mouse_on_start: (bool) Whether the mouse mode is to be enabled on + start-up. + + Returns: + An exit token of arbitrary type. Can be None. + """ + + raise NotImplementedError("run_ui() is not implemented in BaseUI") + + def _parse_command(self, command): + """Parse a command string into prefix and arguments. + + Args: + command: (str) Command string to be parsed. + + Returns: + prefix: (str) The command prefix. + args: (list of str) The command arguments (i.e., not including the + prefix). + output_file_path: (str or None) The path to save the screen output + to (if any). + """ + command = command.strip() + if not command: + return "", [], None + + command_items = command_parser.parse_command(command) + command_items, output_file_path = command_parser.extract_output_file_path( + command_items) + + return command_items[0], command_items[1:], output_file_path + + def _analyze_tab_complete_input(self, text): + """Analyze raw input to tab-completer. + + Args: + text: (str) the full, raw input text to be tab-completed. + + Returns: + context: (str) the context str. For example, + If text == "print_tensor softmax", returns "print_tensor". + If text == "print", returns "". + If text == "", returns "". + prefix: (str) the prefix to be tab-completed, from the last word. + For example, if text == "print_tensor softmax", returns "softmax". + If text == "print", returns "print". + If text == "", returns "". + except_last_word: (str) the input text, except the last word. + For example, if text == "print_tensor softmax", returns "print_tensor". + If text == "print_tensor -a softmax", returns "print_tensor -a". + If text == "print", returns "". + If text == "", returns "". + """ + text = text.lstrip() + if not text: + # Empty (top-level) context. + context = "" + prefix = "" + except_last_word = "" + else: + items = text.split(" ") + if len(items) == 1: + # Single word: top-level context. + context = "" + prefix = items[0] + except_last_word = "" + else: + # Multiple words. + context = items[0] + prefix = items[-1] + except_last_word = " ".join(items[:-1]) + " " + + return context, prefix, except_last_word + + @property + def config(self): + """Obtain the CLIConfig of this `BaseUI` instance.""" + return self._config + + def _config_command_handler(self, args, screen_info=None): + """Command handler for the "config" command.""" + del screen_info # Currently unused. + + parsed = self._config_argparser.parse_args(args) + if hasattr(parsed, "property_name") and hasattr(parsed, "property_value"): + # set. + self._config.set(parsed.property_name, parsed.property_value) + return self._config.summarize(highlight=parsed.property_name) + else: + # show. + return self._config.summarize() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb040f6846bb3c55b25582bf0687c38a69e8da4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_config.py @@ -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. +# ============================================================================== +"""Configurations for TensorFlow Debugger (TFDBG) command-line interfaces.""" +import collections +import json +import os + +from tensorflow.python.debug.cli import debugger_cli_common +from tensorflow.python.platform import gfile + +RL = debugger_cli_common.RichLine + + +class CLIConfig(object): + """Client-facing configurations for TFDBG command-line interfaces.""" + + _CONFIG_FILE_NAME = ".tfdbg_config" + + _DEFAULT_CONFIG = [ + ("graph_recursion_depth", 20), + ("mouse_mode", True), + ] + + def __init__(self, config_file_path=None): + self._config_file_path = (config_file_path or + self._default_config_file_path()) + self._config = collections.OrderedDict(self._DEFAULT_CONFIG) + if gfile.Exists(self._config_file_path): + config = self._load_from_file() + for key, value in config.items(): + self._config[key] = value + self._save_to_file() + + self._set_callbacks = {} + + def get(self, property_name): + if property_name not in self._config: + raise KeyError("%s is not a valid property name." % property_name) + return self._config[property_name] + + def set(self, property_name, property_val): + """Set the value of a property. + + Supports limitd property value types: `bool`, `int` and `str`. + + Args: + property_name: Name of the property. + property_val: Value of the property. If the property has `bool` type and + this argument has `str` type, the `str` value will be parsed as a `bool` + + Raises: + ValueError: if a `str` property_value fails to be parsed as a `bool`. + KeyError: if `property_name` is an invalid property name. + """ + if property_name not in self._config: + raise KeyError("%s is not a valid property name." % property_name) + + orig_val = self._config[property_name] + if isinstance(orig_val, bool): + if isinstance(property_val, str): + if property_val.lower() in ("1", "true", "t", "yes", "y", "on"): + property_val = True + elif property_val.lower() in ("0", "false", "f", "no", "n", "off"): + property_val = False + else: + raise ValueError( + "Invalid string value for bool type: %s" % property_val) + else: + property_val = bool(property_val) + elif isinstance(orig_val, int): + property_val = int(property_val) + elif isinstance(orig_val, str): + property_val = str(property_val) + else: + raise TypeError("Unsupported property type: %s" % type(orig_val)) + self._config[property_name] = property_val + self._save_to_file() + + # Invoke set-callback. + if property_name in self._set_callbacks: + self._set_callbacks[property_name](self._config) + + def set_callback(self, property_name, callback): + """Set a set-callback for given property. + + Args: + property_name: Name of the property. + callback: The callback as a `callable` of signature: + def cbk(config): + where config is the config after it is set to the new value. + The callback is invoked each time the set() method is called with the + matching property_name. + + Raises: + KeyError: If property_name does not exist. + TypeError: If `callback` is not callable. + """ + if property_name not in self._config: + raise KeyError("%s is not a valid property name." % property_name) + if not callable(callback): + raise TypeError("The callback object provided is not callable.") + self._set_callbacks[property_name] = callback + + def _default_config_file_path(self): + return os.path.join(os.path.expanduser("~"), self._CONFIG_FILE_NAME) + + def _save_to_file(self): + try: + with gfile.Open(self._config_file_path, "w") as config_file: + json.dump(self._config, config_file) + except IOError: + pass + + def summarize(self, highlight=None): + """Get a text summary of the config. + + Args: + highlight: A property name to highlight in the output. + + Returns: + A `RichTextLines` output. + """ + lines = [RL("Command-line configuration:", "bold"), RL("")] + for name, val in self._config.items(): + highlight_attr = "bold" if name == highlight else None + line = RL(" ") + line += RL(name, ["underline", highlight_attr]) + line += RL(": ") + line += RL(str(val), font_attr=highlight_attr) + lines.append(line) + return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) + + def _load_from_file(self): + try: + with gfile.Open(self._config_file_path, "r") as config_file: + config_dict = json.load(config_file) + config = collections.OrderedDict() + for key in sorted(config_dict.keys()): + config[key] = config_dict[key] + return config + except (IOError, ValueError): + # The reading of the config file may fail due to IO issues or file + # corruption. We do not want tfdbg to error out just because of that. + return dict() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_shared.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..69466d446c14691ea45137f4618b4996239e1c15 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_shared.py @@ -0,0 +1,491 @@ +# 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. +# ============================================================================== +"""Shared functions and classes for tfdbg command-line interface.""" +import math + +import numpy as np + +from tensorflow.python.debug.cli import command_parser +from tensorflow.python.debug.cli import debugger_cli_common +from tensorflow.python.debug.cli import tensor_format +from tensorflow.python.debug.lib import common +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile + +RL = debugger_cli_common.RichLine + +# Default threshold number of elements above which ellipses will be used +# when printing the value of the tensor. +DEFAULT_NDARRAY_DISPLAY_THRESHOLD = 2000 + +COLOR_BLACK = "black" +COLOR_BLUE = "blue" +COLOR_CYAN = "cyan" +COLOR_GRAY = "gray" +COLOR_GREEN = "green" +COLOR_MAGENTA = "magenta" +COLOR_RED = "red" +COLOR_WHITE = "white" +COLOR_YELLOW = "yellow" + +TIME_UNIT_US = "us" +TIME_UNIT_MS = "ms" +TIME_UNIT_S = "s" +TIME_UNITS = [TIME_UNIT_US, TIME_UNIT_MS, TIME_UNIT_S] + + +def bytes_to_readable_str(num_bytes, include_b=False): + """Generate a human-readable string representing number of bytes. + + The units B, kB, MB and GB are used. + + Args: + num_bytes: (`int` or None) Number of bytes. + include_b: (`bool`) Include the letter B at the end of the unit. + + Returns: + (`str`) A string representing the number of bytes in a human-readable way, + including a unit at the end. + """ + + if num_bytes is None: + return str(num_bytes) + if num_bytes < 1024: + result = "%d" % num_bytes + elif num_bytes < 1048576: + result = "%.2fk" % (num_bytes / 1024.0) + elif num_bytes < 1073741824: + result = "%.2fM" % (num_bytes / 1048576.0) + else: + result = "%.2fG" % (num_bytes / 1073741824.0) + + if include_b: + result += "B" + return result + + +def time_to_readable_str(value_us, force_time_unit=None): + """Convert time value to human-readable string. + + Args: + value_us: time value in microseconds. + force_time_unit: force the output to use the specified time unit. Must be + in TIME_UNITS. + + Returns: + Human-readable string representation of the time value. + + Raises: + ValueError: if force_time_unit value is not in TIME_UNITS. + """ + if not value_us: + return "0" + if force_time_unit: + if force_time_unit not in TIME_UNITS: + raise ValueError("Invalid time unit: %s" % force_time_unit) + order = TIME_UNITS.index(force_time_unit) + time_unit = force_time_unit + return "{:.10g}{}".format(value_us / math.pow(10.0, 3*order), time_unit) + else: + order = min(len(TIME_UNITS) - 1, int(math.log(value_us, 10) / 3)) + time_unit = TIME_UNITS[order] + return "{:.3g}{}".format(value_us / math.pow(10.0, 3*order), time_unit) + + +def parse_ranges_highlight(ranges_string): + """Process ranges highlight string. + + Args: + ranges_string: (str) A string representing a numerical range of a list of + numerical ranges. See the help info of the -r flag of the print_tensor + command for more details. + + Returns: + An instance of tensor_format.HighlightOptions, if range_string is a valid + representation of a range or a list of ranges. + """ + + ranges = None + + def ranges_filter(x): + r = np.zeros(x.shape, dtype=bool) + for range_start, range_end in ranges: + r = np.logical_or(r, np.logical_and(x >= range_start, x <= range_end)) + + return r + + if ranges_string: + ranges = command_parser.parse_ranges(ranges_string) + return tensor_format.HighlightOptions( + ranges_filter, description=ranges_string) + else: + return None + + +def numpy_printoptions_from_screen_info(screen_info): + if screen_info and "cols" in screen_info: + return {"linewidth": screen_info["cols"]} + else: + return {} + + +def format_tensor(tensor, + tensor_name, + np_printoptions, + print_all=False, + tensor_slicing=None, + highlight_options=None, + include_numeric_summary=False, + write_path=None): + """Generate formatted str to represent a tensor or its slices. + + Args: + tensor: (numpy ndarray) The tensor value. + tensor_name: (str) Name of the tensor, e.g., the tensor's debug watch key. + np_printoptions: (dict) Numpy tensor formatting options. + print_all: (bool) Whether the tensor is to be displayed in its entirety, + instead of printing ellipses, even if its number of elements exceeds + the default numpy display threshold. + (Note: Even if this is set to true, the screen output can still be cut + off by the UI frontend if it consist of more lines than the frontend + can handle.) + tensor_slicing: (str or None) Slicing of the tensor, e.g., "[:, 1]". If + None, no slicing will be performed on the tensor. + highlight_options: (tensor_format.HighlightOptions) options to highlight + elements of the tensor. See the doc of tensor_format.format_tensor() + for more details. + include_numeric_summary: Whether a text summary of the numeric values (if + applicable) will be included. + write_path: A path to save the tensor value (after any slicing) to + (optional). `numpy.save()` is used to save the value. + + Returns: + An instance of `debugger_cli_common.RichTextLines` representing the + (potentially sliced) tensor. + """ + + if tensor_slicing: + # Validate the indexing. + value = command_parser.evaluate_tensor_slice(tensor, tensor_slicing) + sliced_name = tensor_name + tensor_slicing + else: + value = tensor + sliced_name = tensor_name + + auxiliary_message = None + if write_path: + with gfile.Open(write_path, "wb") as output_file: + np.save(output_file, value) + line = debugger_cli_common.RichLine("Saved value to: ") + line += debugger_cli_common.RichLine(write_path, font_attr="bold") + line += " (%sB)" % bytes_to_readable_str(gfile.Stat(write_path).length) + auxiliary_message = debugger_cli_common.rich_text_lines_from_rich_line_list( + [line, debugger_cli_common.RichLine("")]) + + if print_all: + np_printoptions["threshold"] = value.size + else: + np_printoptions["threshold"] = DEFAULT_NDARRAY_DISPLAY_THRESHOLD + + return tensor_format.format_tensor( + value, + sliced_name, + include_metadata=True, + include_numeric_summary=include_numeric_summary, + auxiliary_message=auxiliary_message, + np_printoptions=np_printoptions, + highlight_options=highlight_options) + + +def error(msg): + """Generate a RichTextLines output for error. + + Args: + msg: (str) The error message. + + Returns: + (debugger_cli_common.RichTextLines) A representation of the error message + for screen output. + """ + + return debugger_cli_common.rich_text_lines_from_rich_line_list([ + RL("ERROR: " + msg, COLOR_RED)]) + + +def _recommend_command(command, description, indent=2, create_link=False): + """Generate a RichTextLines object that describes a recommended command. + + Args: + command: (str) The command to recommend. + description: (str) A description of what the command does. + indent: (int) How many spaces to indent in the beginning. + create_link: (bool) Whether a command link is to be applied to the command + string. + + Returns: + (RichTextLines) Formatted text (with font attributes) for recommending the + command. + """ + + indent_str = " " * indent + + if create_link: + font_attr = [debugger_cli_common.MenuItem("", command), "bold"] + else: + font_attr = "bold" + + lines = [RL(indent_str) + RL(command, font_attr) + ":", + indent_str + " " + description] + + return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) + + +def get_tfdbg_logo(): + """Make an ASCII representation of the tfdbg logo.""" + + lines = [ + "", + "TTTTTT FFFF DDD BBBB GGG ", + " TT F D D B B G ", + " TT FFF D D BBBB G GG", + " TT F D D B B G G", + " TT F DDD BBBB GGG ", + "", + ] + return debugger_cli_common.RichTextLines(lines) + + +_HORIZONTAL_BAR = "======================================" + + +def get_run_start_intro(run_call_count, + fetches, + feed_dict, + tensor_filters, + is_callable_runner=False): + """Generate formatted intro for run-start UI. + + Args: + run_call_count: (int) Run call counter. + fetches: Fetches of the `Session.run()` call. See doc of `Session.run()` + for more details. + feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()` + for more details. + tensor_filters: (dict) A dict from tensor-filter name to tensor-filter + callable. + is_callable_runner: (bool) whether a runner returned by + Session.make_callable is being run. + + Returns: + (RichTextLines) Formatted intro message about the `Session.run()` call. + """ + + fetch_lines = common.get_flattened_names(fetches) + + if not feed_dict: + feed_dict_lines = [debugger_cli_common.RichLine(" (Empty)")] + else: + feed_dict_lines = [] + for feed_key in feed_dict: + feed_key_name = common.get_graph_element_name(feed_key) + feed_dict_line = debugger_cli_common.RichLine(" ") + feed_dict_line += debugger_cli_common.RichLine( + feed_key_name, + debugger_cli_common.MenuItem(None, "pf '%s'" % feed_key_name)) + # Surround the name string with quotes, because feed_key_name may contain + # spaces in some cases, e.g., SparseTensors. + feed_dict_lines.append(feed_dict_line) + feed_dict_lines = debugger_cli_common.rich_text_lines_from_rich_line_list( + feed_dict_lines) + + out = debugger_cli_common.RichTextLines(_HORIZONTAL_BAR) + if is_callable_runner: + out.append("Running a runner returned by Session.make_callable()") + else: + out.append("Session.run() call #%d:" % run_call_count) + out.append("") + out.append("Fetch(es):") + out.extend(debugger_cli_common.RichTextLines( + [" " + line for line in fetch_lines])) + out.append("") + out.append("Feed dict:") + out.extend(feed_dict_lines) + out.append(_HORIZONTAL_BAR) + out.append("") + out.append("Select one of the following commands to proceed ---->") + + out.extend( + _recommend_command( + "run", + "Execute the run() call with debug tensor-watching", + create_link=True)) + out.extend( + _recommend_command( + "run -n", + "Execute the run() call without debug tensor-watching", + create_link=True)) + out.extend( + _recommend_command( + "run -t ", + "Execute run() calls (T - 1) times without debugging, then " + "execute run() once more with debugging and drop back to the CLI")) + out.extend( + _recommend_command( + "run -f ", + "Keep executing run() calls until a dumped tensor passes a given, " + "registered filter (conditional breakpoint mode)")) + + more_lines = [" Registered filter(s):"] + if tensor_filters: + filter_names = [] + for filter_name in tensor_filters: + filter_names.append(filter_name) + command_menu_node = debugger_cli_common.MenuItem( + "", "run -f %s" % filter_name) + more_lines.append(RL(" * ") + RL(filter_name, command_menu_node)) + else: + more_lines.append(" (None)") + + out.extend( + debugger_cli_common.rich_text_lines_from_rich_line_list(more_lines)) + + out.append("") + + out.append_rich_line(RL("For more details, see ") + + RL("help.", debugger_cli_common.MenuItem("", "help")) + + ".") + out.append("") + + # Make main menu for the run-start intro. + menu = debugger_cli_common.Menu() + menu.append(debugger_cli_common.MenuItem("run", "run")) + menu.append(debugger_cli_common.MenuItem("exit", "exit")) + out.annotations[debugger_cli_common.MAIN_MENU_KEY] = menu + + return out + + +def get_run_short_description(run_call_count, + fetches, + feed_dict, + is_callable_runner=False): + """Get a short description of the run() call. + + Args: + run_call_count: (int) Run call counter. + fetches: Fetches of the `Session.run()` call. See doc of `Session.run()` + for more details. + feed_dict: Feeds to the `Session.run()` call. See doc of `Session.run()` + for more details. + is_callable_runner: (bool) whether a runner returned by + Session.make_callable is being run. + + Returns: + (str) A short description of the run() call, including information about + the fetche(s) and feed(s). + """ + if is_callable_runner: + return "runner from make_callable()" + + description = "run #%d: " % run_call_count + + if isinstance( + fetches, (tensor_lib.Tensor, ops.Operation, variables.Variable) + ): + description += "1 fetch (%s); " % common.get_graph_element_name(fetches) + else: + # Could be (nested) list, tuple, dict or namedtuple. + num_fetches = len(common.get_flattened_names(fetches)) + if num_fetches > 1: + description += "%d fetches; " % num_fetches + else: + description += "%d fetch; " % num_fetches + + if not feed_dict: + description += "0 feeds" + else: + if len(feed_dict) == 1: + for key in feed_dict: + description += "1 feed (%s)" % ( + key + if isinstance(key, str) or not hasattr(key, "name") else key.name) + else: + description += "%d feeds" % len(feed_dict) + + return description + + +def get_error_intro(tf_error): + """Generate formatted intro for TensorFlow run-time error. + + Args: + tf_error: (errors.OpError) TensorFlow run-time error object. + + Returns: + (RichTextLines) Formatted intro message about the run-time OpError, with + sample commands for debugging. + """ + + if hasattr(tf_error, "op") and hasattr(tf_error.op, "name"): + op_name = tf_error.op.name + else: + op_name = None + + intro_lines = [ + "--------------------------------------", + RL("!!! An error occurred during the run !!!", "blink"), + "", + ] + + out = debugger_cli_common.rich_text_lines_from_rich_line_list(intro_lines) + + if op_name is not None: + out.extend(debugger_cli_common.RichTextLines( + ["You may use the following commands to debug:"])) + out.extend( + _recommend_command("ni -a -d -t %s" % op_name, + "Inspect information about the failing op.", + create_link=True)) + out.extend( + _recommend_command("li -r %s" % op_name, + "List inputs to the failing op, recursively.", + create_link=True)) + + out.extend( + _recommend_command( + "lt", + "List all tensors dumped during the failing run() call.", + create_link=True)) + else: + out.extend(debugger_cli_common.RichTextLines([ + "WARNING: Cannot determine the name of the op that caused the error."])) + + more_lines = [ + "", + "Op name: %s" % op_name, + "Error type: " + str(type(tf_error)), + "", + "Details:", + str(tf_error), + "", + "--------------------------------------", + "", + ] + + out.extend(debugger_cli_common.RichTextLines(more_lines)) + + return out diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_test_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..003d70e3917bc22808b33b5d45c77da9db3a9a1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/cli_test_utils.py @@ -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. +# ============================================================================== +"""Testing utilities for tfdbg command-line interface.""" +import re + +import numpy as np + + +def assert_lines_equal_ignoring_whitespace(test, expected_lines, actual_lines): + """Assert equality in lines, ignoring all whitespace. + + Args: + test: An instance of unittest.TestCase or its subtypes (e.g., + TensorFlowTestCase). + expected_lines: Expected lines as an iterable of strings. + actual_lines: Actual lines as an iterable of strings. + """ + test.assertEqual( + len(expected_lines), len(actual_lines), + "Mismatch in the number of lines: %d vs %d" % ( + len(expected_lines), len(actual_lines))) + for expected_line, actual_line in zip(expected_lines, actual_lines): + test.assertEqual("".join(expected_line.split()), + "".join(actual_line.split())) + + +# Regular expression for separators between values in a string representation +# of an ndarray, exclusing whitespace. +_ARRAY_VALUE_SEPARATOR_REGEX = re.compile(r"(array|\(|\[|\]|\)|\||,)") + + +def assert_array_lines_close(test, expected_array, array_lines): + """Assert that the array value represented by lines is close to expected. + + Note that the shape of the array represented by the `array_lines` is ignored. + + Args: + test: An instance of TensorFlowTestCase. + expected_array: Expected value of the array. + array_lines: A list of strings representing the array. + E.g., "array([[ 1.0, 2.0 ], [ 3.0, 4.0 ]])" + Assumes that values are separated by commas, parentheses, brackets, "|" + characters and whitespace. + """ + elements = [] + for line in array_lines: + line = re.sub(_ARRAY_VALUE_SEPARATOR_REGEX, " ", line) + elements.extend(float(s) for s in line.split()) + test.assertAllClose(np.array(expected_array).flatten(), elements) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/command_parser.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/command_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..dc49c4a27ad2ef3b6cf64dde23a8c2859c2186e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/command_parser.py @@ -0,0 +1,546 @@ +# 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. +# ============================================================================== +"""Command parsing module for TensorFlow Debugger (tfdbg).""" +import argparse +import ast +import re +import sys + + +_BRACKETS_PATTERN = re.compile(r"\[[^\]]*\]") +_QUOTES_PATTERN = re.compile(r"(\"[^\"]*\"|\'[^\']*\')") +_WHITESPACE_PATTERN = re.compile(r"\s+") + +_NUMBER_PATTERN = re.compile(r"[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?") + + +class Interval(object): + """Represents an interval between a start and end value.""" + + def __init__(self, start, start_included, end, end_included): + self.start = start + self.start_included = start_included + self.end = end + self.end_included = end_included + + def contains(self, value): + if value < self.start or value == self.start and not self.start_included: + return False + if value > self.end or value == self.end and not self.end_included: + return False + return True + + def __eq__(self, other): + return (self.start == other.start and + self.start_included == other.start_included and + self.end == other.end and + self.end_included == other.end_included) + + +def parse_command(command): + """Parse command string into a list of arguments. + + - Disregards whitespace inside double quotes and brackets. + - Strips paired leading and trailing double quotes in arguments. + - Splits the command at whitespace. + + Nested double quotes and brackets are not handled. + + Args: + command: (str) Input command. + + Returns: + (list of str) List of arguments. + """ + + command = command.strip() + if not command: + return [] + + brackets_intervals = [f.span() for f in _BRACKETS_PATTERN.finditer(command)] + quotes_intervals = [f.span() for f in _QUOTES_PATTERN.finditer(command)] + whitespaces_intervals = [ + f.span() for f in _WHITESPACE_PATTERN.finditer(command) + ] + + if not whitespaces_intervals: + return [command] + + arguments = [] + idx0 = 0 + for start, end in whitespaces_intervals + [(len(command), None)]: + # Skip whitespace stretches enclosed in brackets or double quotes. + + if not any(interval[0] < start < interval[1] + for interval in brackets_intervals + quotes_intervals): + argument = command[idx0:start] + + # Strip leading and trailing double quote if they are paired. + if (argument.startswith("\"") and argument.endswith("\"") or + argument.startswith("'") and argument.endswith("'")): + argument = argument[1:-1] + arguments.append(argument) + idx0 = end + + return arguments + + +def extract_output_file_path(args): + """Extract output file path from command arguments. + + Args: + args: (list of str) command arguments. + + Returns: + (list of str) Command arguments with the output file path part stripped. + (str or None) Output file path (if any). + + Raises: + SyntaxError: If there is no file path after the last ">" character. + """ + + if args and args[-1].endswith(">"): + raise SyntaxError("Redirect file path is empty") + elif args and args[-1].startswith(">"): + try: + _parse_interval(args[-1]) + if len(args) > 1 and args[-2].startswith("-"): + output_file_path = None + else: + output_file_path = args[-1][1:] + args = args[:-1] + except ValueError: + output_file_path = args[-1][1:] + args = args[:-1] + elif len(args) > 1 and args[-2] == ">": + output_file_path = args[-1] + args = args[:-2] + elif args and args[-1].count(">") == 1: + gt_index = args[-1].index(">") + if gt_index > 0 and args[-1][gt_index - 1] == "=": + output_file_path = None + else: + output_file_path = args[-1][gt_index + 1:] + args[-1] = args[-1][:gt_index] + elif len(args) > 1 and args[-2].endswith(">"): + output_file_path = args[-1] + args = args[:-1] + args[-1] = args[-1][:-1] + else: + output_file_path = None + + return args, output_file_path + + +def parse_tensor_name_with_slicing(in_str): + """Parse tensor name, potentially suffixed by slicing string. + + Args: + in_str: (str) Input name of the tensor, potentially followed by a slicing + string. E.g.: Without slicing string: "hidden/weights/Variable:0", with + slicing string: "hidden/weights/Variable:0[1, :]" + + Returns: + (str) name of the tensor + (str) slicing string, if any. If no slicing string is present, return "". + """ + + if in_str.count("[") == 1 and in_str.endswith("]"): + tensor_name = in_str[:in_str.index("[")] + tensor_slicing = in_str[in_str.index("["):] + else: + tensor_name = in_str + tensor_slicing = "" + + return tensor_name, tensor_slicing + + +def validate_slicing_string(slicing_string): + """Validate a slicing string. + + Check if the input string contains only brackets, digits, commas and + colons that are valid characters in numpy-style array slicing. + + Args: + slicing_string: (str) Input slicing string to be validated. + + Returns: + (bool) True if and only if the slicing string is valid. + """ + + return bool(re.search(r"^\[(\d|,|\s|:)+\]$", slicing_string)) + + +def _parse_slices(slicing_string): + """Construct a tuple of slices from the slicing string. + + The string must be a valid slicing string. + + Args: + slicing_string: (str) Input slicing string to be parsed. + + Returns: + tuple(slice1, slice2, ...) + + Raises: + ValueError: If tensor_slicing is not a valid numpy ndarray slicing str. + """ + parsed = [] + for slice_string in slicing_string[1:-1].split(","): + indices = slice_string.split(":") + if len(indices) == 1: + parsed.append(int(indices[0].strip())) + elif 2 <= len(indices) <= 3: + parsed.append( + slice(*[ + int(index.strip()) if index.strip() else None for index in indices + ])) + else: + raise ValueError("Invalid tensor-slicing string.") + return tuple(parsed) + + +def parse_indices(indices_string): + """Parse a string representing indices. + + For example, if the input is "[1, 2, 3]", the return value will be a list of + indices: [1, 2, 3] + + Args: + indices_string: (str) a string representing indices. Can optionally be + surrounded by a pair of brackets. + + Returns: + (list of int): Parsed indices. + """ + + # Strip whitespace. + indices_string = re.sub(r"\s+", "", indices_string) + + # Strip any brackets at the two ends. + if indices_string.startswith("[") and indices_string.endswith("]"): + indices_string = indices_string[1:-1] + + return [int(element) for element in indices_string.split(",")] + + +def parse_ranges(range_string): + """Parse a string representing numerical range(s). + + Args: + range_string: (str) A string representing a numerical range or a list of + them. For example: + "[-1.0,1.0]", "[-inf, 0]", "[[-inf, -1.0], [1.0, inf]]" + + Returns: + (list of list of float) A list of numerical ranges parsed from the input + string. + + Raises: + ValueError: If the input doesn't represent a range or a list of ranges. + """ + + range_string = range_string.strip() + if not range_string: + return [] + + if "inf" in range_string: + range_string = re.sub(r"inf", repr(sys.float_info.max), range_string) + + ranges = ast.literal_eval(range_string) + if isinstance(ranges, list) and not isinstance(ranges[0], list): + ranges = [ranges] + + # Verify that ranges is a list of list of numbers. + for item in ranges: + if len(item) != 2: + raise ValueError("Incorrect number of elements in range") + elif not isinstance(item[0], (int, float)): + raise ValueError("Incorrect type in the 1st element of range: %s" % + type(item[0])) + elif not isinstance(item[1], (int, float)): + raise ValueError("Incorrect type in the 2nd element of range: %s" % + type(item[0])) + + return ranges + + +def parse_memory_interval(interval_str): + """Convert a human-readable memory interval to a tuple of start and end value. + + Args: + interval_str: (`str`) A human-readable str representing an interval + (e.g., "[10kB, 20kB]", "<100M", ">100G"). Only the units "kB", "MB", "GB" + are supported. The "B character at the end of the input `str` may be + omitted. + + Returns: + `Interval` object where start and end are in bytes. + + Raises: + ValueError: if the input is not valid. + """ + str_interval = _parse_interval(interval_str) + interval_start = 0 + interval_end = float("inf") + if str_interval.start: + interval_start = parse_readable_size_str(str_interval.start) + if str_interval.end: + interval_end = parse_readable_size_str(str_interval.end) + if interval_start > interval_end: + raise ValueError( + "Invalid interval %s. Start of interval must be less than or equal " + "to end of interval." % interval_str) + return Interval(interval_start, str_interval.start_included, + interval_end, str_interval.end_included) + + +def parse_time_interval(interval_str): + """Convert a human-readable time interval to a tuple of start and end value. + + Args: + interval_str: (`str`) A human-readable str representing an interval + (e.g., "[10us, 20us]", "<100s", ">100ms"). Supported time suffixes are + us, ms, s. + + Returns: + `Interval` object where start and end are in microseconds. + + Raises: + ValueError: if the input is not valid. + """ + str_interval = _parse_interval(interval_str) + interval_start = 0 + interval_end = float("inf") + if str_interval.start: + interval_start = parse_readable_time_str(str_interval.start) + if str_interval.end: + interval_end = parse_readable_time_str(str_interval.end) + if interval_start > interval_end: + raise ValueError( + "Invalid interval %s. Start must be before end of interval." % + interval_str) + return Interval(interval_start, str_interval.start_included, + interval_end, str_interval.end_included) + + +def _parse_interval(interval_str): + """Convert a human-readable interval to a tuple of start and end value. + + Args: + interval_str: (`str`) A human-readable str representing an interval + (e.g., "[1M, 2M]", "<100k", ">100ms"). The items following the ">", "<", + ">=" and "<=" signs have to start with a number (e.g., 3.0, -2, .98). + The same requirement applies to the items in the parentheses or brackets. + + Returns: + Interval object where start or end can be None + if the range is specified as "N" respectively. + + Raises: + ValueError: if the input is not valid. + """ + interval_str = interval_str.strip() + if interval_str.startswith("<="): + if _NUMBER_PATTERN.match(interval_str[2:].strip()): + return Interval(start=None, start_included=False, + end=interval_str[2:].strip(), end_included=True) + else: + raise ValueError("Invalid value string after <= in '%s'" % interval_str) + if interval_str.startswith("<"): + if _NUMBER_PATTERN.match(interval_str[1:].strip()): + return Interval(start=None, start_included=False, + end=interval_str[1:].strip(), end_included=False) + else: + raise ValueError("Invalid value string after < in '%s'" % interval_str) + if interval_str.startswith(">="): + if _NUMBER_PATTERN.match(interval_str[2:].strip()): + return Interval(start=interval_str[2:].strip(), start_included=True, + end=None, end_included=False) + else: + raise ValueError("Invalid value string after >= in '%s'" % interval_str) + if interval_str.startswith(">"): + if _NUMBER_PATTERN.match(interval_str[1:].strip()): + return Interval(start=interval_str[1:].strip(), start_included=False, + end=None, end_included=False) + else: + raise ValueError("Invalid value string after > in '%s'" % interval_str) + + if (not interval_str.startswith(("[", "(")) + or not interval_str.endswith(("]", ")"))): + raise ValueError( + "Invalid interval format: %s. Valid formats are: [min, max], " + "(min, max), min" % interval_str) + interval = interval_str[1:-1].split(",") + if len(interval) != 2: + raise ValueError( + "Incorrect interval format: %s. Interval should specify two values: " + "[min, max] or (min, max)." % interval_str) + + start_item = interval[0].strip() + if not _NUMBER_PATTERN.match(start_item): + raise ValueError("Invalid first item in interval: '%s'" % start_item) + end_item = interval[1].strip() + if not _NUMBER_PATTERN.match(end_item): + raise ValueError("Invalid second item in interval: '%s'" % end_item) + + return Interval(start=start_item, + start_included=(interval_str[0] == "["), + end=end_item, + end_included=(interval_str[-1] == "]")) + + +def parse_readable_size_str(size_str): + """Convert a human-readable str representation to number of bytes. + + Only the units "kB", "MB", "GB" are supported. The "B character at the end + of the input `str` may be omitted. + + Args: + size_str: (`str`) A human-readable str representing a number of bytes + (e.g., "0", "1023", "1.1kB", "24 MB", "23GB", "100 G". + + Returns: + (`int`) The parsed number of bytes. + + Raises: + ValueError: on failure to parse the input `size_str`. + """ + + size_str = size_str.strip() + if size_str.endswith("B"): + size_str = size_str[:-1] + + if size_str.isdigit(): + return int(size_str) + elif size_str.endswith("k"): + return int(float(size_str[:-1]) * 1024) + elif size_str.endswith("M"): + return int(float(size_str[:-1]) * 1048576) + elif size_str.endswith("G"): + return int(float(size_str[:-1]) * 1073741824) + else: + raise ValueError("Failed to parsed human-readable byte size str: \"%s\"" % + size_str) + + +def parse_readable_time_str(time_str): + """Parses a time string in the format N, Nus, Nms, Ns. + + Args: + time_str: (`str`) string consisting of an integer time value optionally + followed by 'us', 'ms', or 's' suffix. If suffix is not specified, + value is assumed to be in microseconds. (e.g. 100us, 8ms, 5s, 100). + + Returns: + Microseconds value. + """ + def parse_positive_float(value_str): + value = float(value_str) + if value < 0: + raise ValueError( + "Invalid time %s. Time value must be positive." % value_str) + return value + + time_str = time_str.strip() + if time_str.endswith("us"): + return int(parse_positive_float(time_str[:-2])) + elif time_str.endswith("ms"): + return int(parse_positive_float(time_str[:-2]) * 1e3) + elif time_str.endswith("s"): + return int(parse_positive_float(time_str[:-1]) * 1e6) + return int(parse_positive_float(time_str)) + + +def evaluate_tensor_slice(tensor, tensor_slicing): + """Call eval on the slicing of a tensor, with validation. + + Args: + tensor: (numpy ndarray) The tensor value. + tensor_slicing: (str or None) Slicing of the tensor, e.g., "[:, 1]". If + None, no slicing will be performed on the tensor. + + Returns: + (numpy ndarray) The sliced tensor. + + Raises: + ValueError: If tensor_slicing is not a valid numpy ndarray slicing str. + """ + + _ = tensor + + if not validate_slicing_string(tensor_slicing): + raise ValueError("Invalid tensor-slicing string.") + + return tensor[_parse_slices(tensor_slicing)] + + +def get_print_tensor_argparser(description): + """Get an ArgumentParser for a command that prints tensor values. + + Examples of such commands include print_tensor and print_feed. + + Args: + description: Description of the ArgumentParser. + + Returns: + An instance of argparse.ArgumentParser. + """ + + ap = argparse.ArgumentParser( + description=description, usage=argparse.SUPPRESS) + ap.add_argument( + "tensor_name", + type=str, + help="Name of the tensor, followed by any slicing indices, " + "e.g., hidden1/Wx_plus_b/MatMul:0, " + "hidden1/Wx_plus_b/MatMul:0[1, :]") + ap.add_argument( + "-n", + "--number", + dest="number", + type=int, + default=-1, + help="0-based dump number for the specified tensor. " + "Required for tensor with multiple dumps.") + ap.add_argument( + "-r", + "--ranges", + dest="ranges", + type=str, + default="", + help="Numerical ranges to highlight tensor elements in. " + "Examples: -r 0,1e-8, -r [-0.1,0.1], " + "-r \"[[-inf, -0.1], [0.1, inf]]\"") + ap.add_argument( + "-a", + "--all", + dest="print_all", + action="store_true", + help="Print the tensor in its entirety, i.e., do not use ellipses.") + ap.add_argument( + "-s", + "--numeric_summary", + action="store_true", + help="Include summary for non-empty tensors of numeric (int*, float*, " + "complex*) and Boolean types.") + ap.add_argument( + "-w", + "--write_path", + type=str, + default="", + help="Path of the numpy file to write the tensor data to, using " + "numpy.save().") + return ap diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/debugger_cli_common.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/debugger_cli_common.py new file mode 100644 index 0000000000000000000000000000000000000000..e6abc7d356214475fc37db0e53f95734d71c707e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/debugger_cli_common.py @@ -0,0 +1,1241 @@ +# 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. +# ============================================================================== +"""Building Blocks of TensorFlow Debugger Command-Line Interface.""" +import copy +import os +import re +import traceback + +import numpy as np + +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.platform import gfile + +HELP_INDENT = " " + +EXPLICIT_USER_EXIT = "explicit_user_exit" +REGEX_MATCH_LINES_KEY = "regex_match_lines" +INIT_SCROLL_POS_KEY = "init_scroll_pos" + +MAIN_MENU_KEY = "mm:" + + +class CommandLineExit(Exception): + + def __init__(self, exit_token=None): + Exception.__init__(self) + self._exit_token = exit_token + + @property + def exit_token(self): + return self._exit_token + + +class RichLine: + """Rich single-line text. + + Attributes: + text: A plain string, the raw text represented by this object. Should not + contain newlines. + font_attr_segs: A list of (start, end, font attribute) triples, representing + richness information applied to substrings of text. + """ + + def __init__(self, text="", font_attr=None): + """Construct a RichLine with no rich attributes or a single attribute. + + Args: + text: Raw text string + font_attr: If specified, a single font attribute to be applied to the + entire text. Extending this object via concatenation allows creation + of text with varying attributes. + """ + # TODO(ebreck) Make .text and .font_attr protected members when we no + # longer need public access. + self.text = text + if font_attr: + self.font_attr_segs = [(0, len(text), font_attr)] + else: + self.font_attr_segs = [] + + def __add__(self, other): + """Concatenate two chunks of maybe rich text to make a longer rich line. + + Does not modify self. + + Args: + other: Another piece of text to concatenate with this one. + If it is a plain str, it will be appended to this string with no + attributes. If it is a RichLine, it will be appended to this string + with its attributes preserved. + + Returns: + A new RichLine comprising both chunks of text, with appropriate + attributes applied to the corresponding substrings. + """ + ret = RichLine() + if isinstance(other, str): + ret.text = self.text + other + ret.font_attr_segs = self.font_attr_segs[:] + return ret + elif isinstance(other, RichLine): + ret.text = self.text + other.text + ret.font_attr_segs = self.font_attr_segs[:] + old_len = len(self.text) + for start, end, font_attr in other.font_attr_segs: + ret.font_attr_segs.append((old_len + start, old_len + end, font_attr)) + return ret + else: + raise TypeError("%r cannot be concatenated with a RichLine" % other) + + def __len__(self): + return len(self.text) + + +def rich_text_lines_from_rich_line_list(rich_text_list, annotations=None): + """Convert a list of RichLine objects or strings to a RichTextLines object. + + Args: + rich_text_list: a list of RichLine objects or strings + annotations: annotations for the resultant RichTextLines object. + + Returns: + A corresponding RichTextLines object. + """ + lines = [] + font_attr_segs = {} + for i, rl in enumerate(rich_text_list): + if isinstance(rl, RichLine): + lines.append(rl.text) + if rl.font_attr_segs: + font_attr_segs[i] = rl.font_attr_segs + else: + lines.append(rl) + return RichTextLines(lines, font_attr_segs, annotations=annotations) + + +def get_tensorflow_version_lines(include_dependency_versions=False): + """Generate RichTextLines with TensorFlow version info. + + Args: + include_dependency_versions: Include the version of TensorFlow's key + dependencies, such as numpy. + + Returns: + A formatted, multi-line `RichTextLines` object. + """ + lines = ["TensorFlow version: %s" % pywrap_tf_session.__version__] + lines.append("") + if include_dependency_versions: + lines.append("Dependency version(s):") + lines.append(" numpy: %s" % np.__version__) + lines.append("") + return RichTextLines(lines) + + +class RichTextLines: + """Rich multi-line text. + + Line-by-line text output, with font attributes (e.g., color) and annotations + (e.g., indices in a multi-dimensional tensor). Used as the text output of CLI + commands. Can be rendered on terminal environments such as curses. + + This is not to be confused with Rich Text Format (RTF). This class is for text + lines only. + """ + + def __init__(self, lines, font_attr_segs=None, annotations=None): + """Constructor of RichTextLines. + + Args: + lines: A list of str or a single str, representing text output to + screen. The latter case is for convenience when the text output is + single-line. + font_attr_segs: A map from 0-based row index to a list of 3-tuples. + It lists segments in each row that have special font attributes, such + as colors, that are not the default attribute. For example: + {1: [(0, 3, "red"), (4, 7, "green")], 2: [(10, 20, "yellow")]} + + In each tuple, the 1st element is the start index of the segment. The + 2nd element is the end index, in an "open interval" fashion. The 3rd + element is an object or a list of objects that represents the font + attribute. Colors are represented as strings as in the examples above. + annotations: A map from 0-based row index to any object for annotating + the row. A typical use example is annotating rows of the output as + indices in a multi-dimensional tensor. For example, consider the + following text representation of a 3x2x2 tensor: + [[[0, 0], [0, 0]], + [[0, 0], [0, 0]], + [[0, 0], [0, 0]]] + The annotation can indicate the indices of the first element shown in + each row, i.e., + {0: [0, 0, 0], 1: [1, 0, 0], 2: [2, 0, 0]} + This information can make display of tensors on screen clearer and can + help the user navigate (scroll) to the desired location in a large + tensor. + + Raises: + ValueError: If lines is of invalid type. + """ + if isinstance(lines, list): + self._lines = lines + elif isinstance(lines, str): + self._lines = [lines] + else: + raise ValueError("Unexpected type in lines: %s" % type(lines)) + + self._font_attr_segs = font_attr_segs + if not self._font_attr_segs: + self._font_attr_segs = {} + # TODO(cais): Refactor to collections.defaultdict(list) to simplify code. + + self._annotations = annotations + if not self._annotations: + self._annotations = {} + # TODO(cais): Refactor to collections.defaultdict(list) to simplify code. + + @property + def lines(self): + return self._lines + + @property + def font_attr_segs(self): + return self._font_attr_segs + + @property + def annotations(self): + return self._annotations + + def num_lines(self): + return len(self._lines) + + def slice(self, begin, end): + """Slice a RichTextLines object. + + The object itself is not changed. A sliced instance is returned. + + Args: + begin: (int) Beginning line index (inclusive). Must be >= 0. + end: (int) Ending line index (exclusive). Must be >= 0. + + Returns: + (RichTextLines) Sliced output instance of RichTextLines. + + Raises: + ValueError: If begin or end is negative. + """ + + if begin < 0 or end < 0: + raise ValueError("Encountered negative index.") + + # Copy lines. + lines = self.lines[begin:end] + + # Slice font attribute segments. + font_attr_segs = {} + for key in self.font_attr_segs: + if key >= begin and key < end: + font_attr_segs[key - begin] = self.font_attr_segs[key] + + # Slice annotations. + annotations = {} + for key in self.annotations: + if not isinstance(key, int): + # Annotations can contain keys that are not line numbers. + annotations[key] = self.annotations[key] + elif key >= begin and key < end: + annotations[key - begin] = self.annotations[key] + + return RichTextLines( + lines, font_attr_segs=font_attr_segs, annotations=annotations) + + def extend(self, other): + """Extend this instance of RichTextLines with another instance. + + The extension takes effect on the text lines, the font attribute segments, + as well as the annotations. The line indices in the font attribute + segments and the annotations are adjusted to account for the existing + lines. If there are duplicate, non-line-index fields in the annotations, + the value from the input argument "other" will override that in this + instance. + + Args: + other: (RichTextLines) The other RichTextLines instance to be appended at + the end of this instance. + """ + + orig_num_lines = self.num_lines() # Record original number of lines. + + # Merge the lines. + self._lines.extend(other.lines) + + # Merge the font_attr_segs. + for line_index in other.font_attr_segs: + self._font_attr_segs[orig_num_lines + line_index] = ( + other.font_attr_segs[line_index]) + + # Merge the annotations. + for key in other.annotations: + if isinstance(key, int): + self._annotations[orig_num_lines + key] = (other.annotations[key]) + else: + self._annotations[key] = other.annotations[key] + + def _extend_before(self, other): + """Add another RichTextLines object to the front. + + Args: + other: (RichTextLines) The other object to add to the front to this + object. + """ + + other_num_lines = other.num_lines() # Record original number of lines. + + # Merge the lines. + self._lines = other.lines + self._lines + + # Merge the font_attr_segs. + new_font_attr_segs = {} + for line_index in self.font_attr_segs: + new_font_attr_segs[other_num_lines + line_index] = ( + self.font_attr_segs[line_index]) + new_font_attr_segs.update(other.font_attr_segs) + self._font_attr_segs = new_font_attr_segs + + # Merge the annotations. + new_annotations = {} + for key in self._annotations: + if isinstance(key, int): + new_annotations[other_num_lines + key] = (self.annotations[key]) + else: + new_annotations[key] = other.annotations[key] + + new_annotations.update(other.annotations) + self._annotations = new_annotations + + def append(self, line, font_attr_segs=None): + """Append a single line of text. + + Args: + line: (str) The text to be added to the end. + font_attr_segs: (list of tuples) Font attribute segments of the appended + line. + """ + + self._lines.append(line) + if font_attr_segs: + self._font_attr_segs[len(self._lines) - 1] = font_attr_segs + + def append_rich_line(self, rich_line): + self.append(rich_line.text, rich_line.font_attr_segs) + + def prepend(self, line, font_attr_segs=None): + """Prepend (i.e., add to the front) a single line of text. + + Args: + line: (str) The text to be added to the front. + font_attr_segs: (list of tuples) Font attribute segments of the appended + line. + """ + + other = RichTextLines(line) + if font_attr_segs: + other.font_attr_segs[0] = font_attr_segs + self._extend_before(other) + + def write_to_file(self, file_path): + """Write the object itself to file, in a plain format. + + The font_attr_segs and annotations are ignored. + + Args: + file_path: (str) path of the file to write to. + """ + + with gfile.Open(file_path, "w") as f: + for line in self._lines: + f.write(line + "\n") + + # TODO(cais): Add a method to allow appending to a line in RichTextLines with + # both text and font_attr_segs. + + +def regex_find(orig_screen_output, regex, font_attr): + """Perform regex match in rich text lines. + + Produces a new RichTextLines object with font_attr_segs containing highlighted + regex matches. + + Example use cases include: + 1) search for specific items in a large list of items, and + 2) search for specific numerical values in a large tensor. + + Args: + orig_screen_output: The original RichTextLines, in which the regex find + is to be performed. + regex: The regex used for matching. + font_attr: Font attribute used for highlighting the found result. + + Returns: + A modified copy of orig_screen_output. + + Raises: + ValueError: If input str regex is not a valid regular expression. + """ + new_screen_output = RichTextLines( + orig_screen_output.lines, + font_attr_segs=copy.deepcopy(orig_screen_output.font_attr_segs), + annotations=orig_screen_output.annotations) + + try: + re_prog = re.compile(regex) + except re.error: + raise ValueError("Invalid regular expression: \"%s\"" % regex) + + regex_match_lines = [] + for i, line in enumerate(new_screen_output.lines): + find_it = re_prog.finditer(line) + + match_segs = [] + for match in find_it: + match_segs.append((match.start(), match.end(), font_attr)) + + if match_segs: + if i not in new_screen_output.font_attr_segs: + new_screen_output.font_attr_segs[i] = match_segs + else: + new_screen_output.font_attr_segs[i].extend(match_segs) + new_screen_output.font_attr_segs[i] = sorted( + new_screen_output.font_attr_segs[i], key=lambda x: x[0]) + regex_match_lines.append(i) + + new_screen_output.annotations[REGEX_MATCH_LINES_KEY] = regex_match_lines + return new_screen_output + + +def wrap_rich_text_lines(inp, cols): + """Wrap RichTextLines according to maximum number of columns. + + Produces a new RichTextLines object with the text lines, font_attr_segs and + annotations properly wrapped. This ought to be used sparingly, as in most + cases, command handlers producing RichTextLines outputs should know the + screen/panel width via the screen_info kwarg and should produce properly + length-limited lines in the output accordingly. + + Args: + inp: Input RichTextLines object. + cols: Number of columns, as an int. + + Returns: + 1) A new instance of RichTextLines, with line lengths limited to cols. + 2) A list of new (wrapped) line index. For example, if the original input + consists of three lines and only the second line is wrapped, and it's + wrapped into two lines, this return value will be: [0, 1, 3]. + Raises: + ValueError: If inputs have invalid types. + """ + + new_line_indices = [] + + if not isinstance(inp, RichTextLines): + raise ValueError("Invalid type of input screen_output") + + if not isinstance(cols, int): + raise ValueError("Invalid type of input cols") + + out = RichTextLines([]) + + row_counter = 0 # Counter for new row index + for i, line in enumerate(inp.lines): + new_line_indices.append(out.num_lines()) + + if i in inp.annotations: + out.annotations[row_counter] = inp.annotations[i] + + if len(line) <= cols: + # No wrapping. + out.lines.append(line) + if i in inp.font_attr_segs: + out.font_attr_segs[row_counter] = inp.font_attr_segs[i] + + row_counter += 1 + else: + # Wrap. + wlines = [] # Wrapped lines. + + osegs = [] + if i in inp.font_attr_segs: + osegs = inp.font_attr_segs[i] + + idx = 0 + while idx < len(line): + if idx + cols > len(line): + rlim = len(line) + else: + rlim = idx + cols + + wlines.append(line[idx:rlim]) + for seg in osegs: + if (seg[0] < rlim) and (seg[1] >= idx): + # Calculate left bound within wrapped line. + if seg[0] >= idx: + lb = seg[0] - idx + else: + lb = 0 + + # Calculate right bound within wrapped line. + if seg[1] < rlim: + rb = seg[1] - idx + else: + rb = rlim - idx + + if rb > lb: # Omit zero-length segments. + wseg = (lb, rb, seg[2]) + if row_counter not in out.font_attr_segs: + out.font_attr_segs[row_counter] = [wseg] + else: + out.font_attr_segs[row_counter].append(wseg) + + idx += cols + row_counter += 1 + + out.lines.extend(wlines) + + # Copy over keys of annotation that are not row indices. + for key in inp.annotations: + if not isinstance(key, int): + out.annotations[key] = inp.annotations[key] + + return out, new_line_indices + + +class CommandHandlerRegistry: + """Registry of command handlers for CLI. + + Handler methods (callables) for user commands can be registered with this + class, which then is able to dispatch commands to the correct handlers and + retrieve the RichTextLines output. + + For example, suppose you have the following handler defined: + def echo(argv, screen_info=None): + return RichTextLines(["arguments = %s" % " ".join(argv), + "screen_info = " + repr(screen_info)]) + + you can register the handler with the command prefix "echo" and alias "e": + registry = CommandHandlerRegistry() + registry.register_command_handler("echo", echo, + "Echo arguments, along with screen info", prefix_aliases=["e"]) + + then to invoke this command handler with some arguments and screen_info, do: + registry.dispatch_command("echo", ["foo", "bar"], screen_info={"cols": 80}) + + or with the prefix alias: + registry.dispatch_command("e", ["foo", "bar"], screen_info={"cols": 80}) + + The call will return a RichTextLines object which can be rendered by a CLI. + """ + + HELP_COMMAND = "help" + HELP_COMMAND_ALIASES = ["h"] + VERSION_COMMAND = "version" + VERSION_COMMAND_ALIASES = ["ver"] + + def __init__(self): + # A dictionary from command prefix to handler. + self._handlers = {} + + # A dictionary from prefix alias to prefix. + self._alias_to_prefix = {} + + # A dictionary from prefix to aliases. + self._prefix_to_aliases = {} + + # A dictionary from command prefix to help string. + self._prefix_to_help = {} + + # Introductory text to help information. + self._help_intro = None + + # Register a default handler for the command "help". + self.register_command_handler( + self.HELP_COMMAND, + self._help_handler, + "Print this help message.", + prefix_aliases=self.HELP_COMMAND_ALIASES) + + # Register a default handler for the command "version". + self.register_command_handler( + self.VERSION_COMMAND, + self._version_handler, + "Print the versions of TensorFlow and its key dependencies.", + prefix_aliases=self.VERSION_COMMAND_ALIASES) + + def register_command_handler(self, + prefix, + handler, + help_info, + prefix_aliases=None): + """Register a callable as a command handler. + + Args: + prefix: Command prefix, i.e., the first word in a command, e.g., + "print" as in "print tensor_1". + handler: A callable of the following signature: + foo_handler(argv, screen_info=None), + where argv is the argument vector (excluding the command prefix) and + screen_info is a dictionary containing information about the screen, + such as number of columns, e.g., {"cols": 100}. + The callable should return: + 1) a RichTextLines object representing the screen output. + + The callable can also raise an exception of the type CommandLineExit, + which if caught by the command-line interface, will lead to its exit. + The exception can optionally carry an exit token of arbitrary type. + help_info: A help string. + prefix_aliases: Aliases for the command prefix, as a list of str. E.g., + shorthands for the command prefix: ["p", "pr"] + + Raises: + ValueError: If + 1) the prefix is empty, or + 2) handler is not callable, or + 3) a handler is already registered for the prefix, or + 4) elements in prefix_aliases clash with existing aliases. + 5) help_info is not a str. + """ + + if not prefix: + raise ValueError("Empty command prefix") + + if prefix in self._handlers: + raise ValueError( + "A handler is already registered for command prefix \"%s\"" % prefix) + + # Make sure handler is callable. + if not callable(handler): + raise ValueError("handler is not callable") + + # Make sure that help info is a string. + if not isinstance(help_info, str): + raise ValueError("help_info is not a str") + + # Process prefix aliases. + if prefix_aliases: + for alias in prefix_aliases: + if self._resolve_prefix(alias): + raise ValueError( + "The prefix alias \"%s\" clashes with existing prefixes or " + "aliases." % alias) + self._alias_to_prefix[alias] = prefix + + self._prefix_to_aliases[prefix] = prefix_aliases + + # Store handler. + self._handlers[prefix] = handler + + # Store help info. + self._prefix_to_help[prefix] = help_info + + def dispatch_command(self, prefix, argv, screen_info=None): + """Handles a command by dispatching it to a registered command handler. + + Args: + prefix: Command prefix, as a str, e.g., "print". + argv: Command argument vector, excluding the command prefix, represented + as a list of str, e.g., + ["tensor_1"] + screen_info: A dictionary containing screen info, e.g., {"cols": 100}. + + Returns: + An instance of RichTextLines or None. If any exception is caught during + the invocation of the command handler, the RichTextLines will wrap the + error type and message. + + Raises: + ValueError: If + 1) prefix is empty, or + 2) no command handler is registered for the command prefix, or + 3) the handler is found for the prefix, but it fails to return a + RichTextLines or raise any exception. + CommandLineExit: + If the command handler raises this type of exception, this method will + simply pass it along. + """ + if not prefix: + raise ValueError("Prefix is empty") + + resolved_prefix = self._resolve_prefix(prefix) + if not resolved_prefix: + raise ValueError("No handler is registered for command prefix \"%s\"" % + prefix) + + handler = self._handlers[resolved_prefix] + try: + output = handler(argv, screen_info=screen_info) + except CommandLineExit as e: + raise e + except SystemExit as e: + # Special case for syntax errors caught by argparse. + lines = ["Syntax error for command: %s" % prefix, + "For help, do \"help %s\"" % prefix] + output = RichTextLines(lines) + + except BaseException as e: # pylint: disable=broad-except + lines = ["Error occurred during handling of command: %s %s:" % + (resolved_prefix, " ".join(argv)), "%s: %s" % (type(e), str(e))] + + # Include traceback of the exception. + lines.append("") + lines.extend(traceback.format_exc().split("\n")) + + output = RichTextLines(lines) + + if not isinstance(output, RichTextLines) and output is not None: + raise ValueError( + "Return value from command handler %s is not None or a RichTextLines " + "instance" % str(handler)) + + return output + + def is_registered(self, prefix): + """Test if a command prefix or its alias is has a registered handler. + + Args: + prefix: A prefix or its alias, as a str. + + Returns: + True iff a handler is registered for prefix. + """ + return self._resolve_prefix(prefix) is not None + + def get_help(self, cmd_prefix=None): + """Compile help information into a RichTextLines object. + + Args: + cmd_prefix: Optional command prefix. As the prefix itself or one of its + aliases. + + Returns: + A RichTextLines object containing the help information. If cmd_prefix + is None, the return value will be the full command-line help. Otherwise, + it will be the help information for the specified command. + """ + if not cmd_prefix: + # Print full help information, in sorted order of the command prefixes. + help_info = RichTextLines([]) + if self._help_intro: + # If help intro is available, show it at the beginning. + help_info.extend(self._help_intro) + + sorted_prefixes = sorted(self._handlers) + for cmd_prefix in sorted_prefixes: + lines = self._get_help_for_command_prefix(cmd_prefix) + lines.append("") + lines.append("") + help_info.extend(RichTextLines(lines)) + + return help_info + else: + return RichTextLines(self._get_help_for_command_prefix(cmd_prefix)) + + def set_help_intro(self, help_intro): + """Set an introductory message to help output. + + Args: + help_intro: (RichTextLines) Rich text lines appended to the + beginning of the output of the command "help", as introductory + information. + """ + self._help_intro = help_intro + + def _help_handler(self, args, screen_info=None): + """Command handler for "help". + + "help" is a common command that merits built-in support from this class. + + Args: + args: Command line arguments to "help" (not including "help" itself). + screen_info: (dict) Information regarding the screen, e.g., the screen + width in characters: {"cols": 80} + + Returns: + (RichTextLines) Screen text output. + """ + + _ = screen_info # Unused currently. + + if not args: + return self.get_help() + elif len(args) == 1: + return self.get_help(args[0]) + else: + return RichTextLines(["ERROR: help takes only 0 or 1 input argument."]) + + def _version_handler(self, args, screen_info=None): + del args # Unused currently. + del screen_info # Unused currently. + return get_tensorflow_version_lines(include_dependency_versions=True) + + def _resolve_prefix(self, token): + """Resolve command prefix from the prefix itself or its alias. + + Args: + token: a str to be resolved. + + Returns: + If resolvable, the resolved command prefix. + If not resolvable, None. + """ + if token in self._handlers: + return token + elif token in self._alias_to_prefix: + return self._alias_to_prefix[token] + else: + return None + + def _get_help_for_command_prefix(self, cmd_prefix): + """Compile the help information for a given command prefix. + + Args: + cmd_prefix: Command prefix, as the prefix itself or one of its aliases. + + Returns: + A list of str as the help information for cmd_prefix. If the cmd_prefix + does not exist, the returned list of str will indicate that. + """ + lines = [] + + resolved_prefix = self._resolve_prefix(cmd_prefix) + if not resolved_prefix: + lines.append("Invalid command prefix: \"%s\"" % cmd_prefix) + return lines + + lines.append(resolved_prefix) + + if resolved_prefix in self._prefix_to_aliases: + lines.append(HELP_INDENT + "Aliases: " + ", ".join( + self._prefix_to_aliases[resolved_prefix])) + + lines.append("") + help_lines = self._prefix_to_help[resolved_prefix].split("\n") + for line in help_lines: + lines.append(HELP_INDENT + line) + + return lines + + +class TabCompletionRegistry: + """Registry for tab completion responses.""" + + def __init__(self): + self._comp_dict = {} + + # TODO(cais): Rename method names with "comp" to "*completion*" to avoid + # confusion. + + def register_tab_comp_context(self, context_words, comp_items): + """Register a tab-completion context. + + Register that, for each word in context_words, the potential tab-completions + are the words in comp_items. + + A context word is a pre-existing, completed word in the command line that + determines how tab-completion works for another, incomplete word in the same + command line. + Completion items consist of potential candidates for the incomplete word. + + To give a general example, a context word can be "drink", and the completion + items can be ["coffee", "tea", "water"] + + Note: A context word can be empty, in which case the context is for the + top-level commands. + + Args: + context_words: A list of context words belonging to the context being + registered. It is a list of str, instead of a single string, to support + synonym words triggering the same tab-completion context, e.g., + both "drink" and the short-hand "dr" can trigger the same context. + comp_items: A list of completion items, as a list of str. + + Raises: + TypeError: if the input arguments are not all of the correct types. + """ + + if not isinstance(context_words, list): + raise TypeError("Incorrect type in context_list: Expected list, got %s" % + type(context_words)) + + if not isinstance(comp_items, list): + raise TypeError("Incorrect type in comp_items: Expected list, got %s" % + type(comp_items)) + + # Sort the completion items on registration, so that later during + # get_completions calls, no sorting will be necessary. + sorted_comp_items = sorted(comp_items) + + for context_word in context_words: + self._comp_dict[context_word] = sorted_comp_items + + def deregister_context(self, context_words): + """Deregister a list of context words. + + Args: + context_words: A list of context words to deregister, as a list of str. + + Raises: + KeyError: if there are word(s) in context_words that do not correspond + to any registered contexts. + """ + + for context_word in context_words: + if context_word not in self._comp_dict: + raise KeyError("Cannot deregister unregistered context word \"%s\"" % + context_word) + + for context_word in context_words: + del self._comp_dict[context_word] + + def extend_comp_items(self, context_word, new_comp_items): + """Add a list of completion items to a completion context. + + Args: + context_word: A single completion word as a string. The extension will + also apply to all other context words of the same context. + new_comp_items: (list of str) New completion items to add. + + Raises: + KeyError: if the context word has not been registered. + """ + + if context_word not in self._comp_dict: + raise KeyError("Context word \"%s\" has not been registered" % + context_word) + + self._comp_dict[context_word].extend(new_comp_items) + self._comp_dict[context_word] = sorted(self._comp_dict[context_word]) + + def remove_comp_items(self, context_word, comp_items): + """Remove a list of completion items from a completion context. + + Args: + context_word: A single completion word as a string. The removal will + also apply to all other context words of the same context. + comp_items: Completion items to remove. + + Raises: + KeyError: if the context word has not been registered. + """ + + if context_word not in self._comp_dict: + raise KeyError("Context word \"%s\" has not been registered" % + context_word) + + for item in comp_items: + self._comp_dict[context_word].remove(item) + + def get_completions(self, context_word, prefix): + """Get the tab completions given a context word and a prefix. + + Args: + context_word: The context word. + prefix: The prefix of the incomplete word. + + Returns: + (1) None if no registered context matches the context_word. + A list of str for the matching completion items. Can be an empty list + of a matching context exists, but no completion item matches the + prefix. + (2) Common prefix of all the words in the first return value. If the + first return value is None, this return value will be None, too. If + the first return value is not None, i.e., a list, this return value + will be a str, which can be an empty str if there is no common + prefix among the items of the list. + """ + + if context_word not in self._comp_dict: + return None, None + + comp_items = self._comp_dict[context_word] + comp_items = sorted( + [item for item in comp_items if item.startswith(prefix)]) + + return comp_items, self._common_prefix(comp_items) + + def _common_prefix(self, m): + """Given a list of str, returns the longest common prefix. + + Args: + m: (list of str) A list of strings. + + Returns: + (str) The longest common prefix. + """ + if not m: + return "" + + s1 = min(m) + s2 = max(m) + for i, c in enumerate(s1): + if c != s2[i]: + return s1[:i] + + return s1 + + +class CommandHistory: + """Keeps command history and supports lookup.""" + + _HISTORY_FILE_NAME = ".tfdbg_history" + + def __init__(self, limit=100, history_file_path=None): + """CommandHistory constructor. + + Args: + limit: Maximum number of the most recent commands that this instance + keeps track of, as an int. + history_file_path: (str) Manually specified path to history file. Used in + testing. + """ + + self._commands = [] + self._limit = limit + self._history_file_path = ( + history_file_path or self._get_default_history_file_path()) + self._load_history_from_file() + + def _load_history_from_file(self): + if os.path.isfile(self._history_file_path): + try: + with open(self._history_file_path, "rt") as history_file: + commands = history_file.readlines() + self._commands = [command.strip() for command in commands + if command.strip()] + + # Limit the size of the history file. + if len(self._commands) > self._limit: + self._commands = self._commands[-self._limit:] + with open(self._history_file_path, "wt") as history_file: + for command in self._commands: + history_file.write(command + "\n") + except IOError: + print("WARNING: writing history file failed.") + + def _add_command_to_history_file(self, command): + try: + with open(self._history_file_path, "at") as history_file: + history_file.write(command + "\n") + except IOError: + pass + + @classmethod + def _get_default_history_file_path(cls): + return os.path.join(os.path.expanduser("~"), cls._HISTORY_FILE_NAME) + + def add_command(self, command): + """Add a command to the command history. + + Args: + command: The history command, as a str. + + Raises: + TypeError: if command is not a str. + """ + + if self._commands and command == self._commands[-1]: + # Ignore repeating commands in a row. + return + + if not isinstance(command, str): + raise TypeError("Attempt to enter non-str entry to command history") + + self._commands.append(command) + + if len(self._commands) > self._limit: + self._commands = self._commands[-self._limit:] + + self._add_command_to_history_file(command) + + def most_recent_n(self, n): + """Look up the n most recent commands. + + Args: + n: Number of most recent commands to look up. + + Returns: + A list of n most recent commands, or all available most recent commands, + if n exceeds size of the command history, in chronological order. + """ + + return self._commands[-n:] + + def lookup_prefix(self, prefix, n): + """Look up the n most recent commands that starts with prefix. + + Args: + prefix: The prefix to lookup. + n: Number of most recent commands to look up. + + Returns: + A list of n most recent commands that have the specified prefix, or all + available most recent commands that have the prefix, if n exceeds the + number of history commands with the prefix. + """ + + commands = [cmd for cmd in self._commands if cmd.startswith(prefix)] + + return commands[-n:] + + # TODO(cais): Lookup by regex. + + +class MenuItem: + """A class for an item in a text-based menu.""" + + def __init__(self, caption, content, enabled=True): + """Menu constructor. + + TODO(cais): Nested menu is currently not supported. Support it. + + Args: + caption: (str) caption of the menu item. + content: Content of the menu item. For a menu item that triggers + a command, for example, content is the command string. + enabled: (bool) whether this menu item is enabled. + """ + + self._caption = caption + self._content = content + self._enabled = enabled + + @property + def caption(self): + return self._caption + + @property + def type(self): + return self._node_type + + @property + def content(self): + return self._content + + def is_enabled(self): + return self._enabled + + def disable(self): + self._enabled = False + + def enable(self): + self._enabled = True + + +class Menu: + """A class for text-based menu.""" + + def __init__(self, name=None): + """Menu constructor. + + Args: + name: (str or None) name of this menu. + """ + + self._name = name + self._items = [] + + def append(self, item): + """Append an item to the Menu. + + Args: + item: (MenuItem) the item to be appended. + """ + self._items.append(item) + + def insert(self, index, item): + self._items.insert(index, item) + + def num_items(self): + return len(self._items) + + def captions(self): + return [item.caption for item in self._items] + + def caption_to_item(self, caption): + """Get a MenuItem from the caption. + + Args: + caption: (str) The caption to look up. + + Returns: + (MenuItem) The first-match menu item with the caption, if any. + + Raises: + LookupError: If a menu item with the caption does not exist. + """ + + captions = self.captions() + if caption not in captions: + raise LookupError("There is no menu item with the caption \"%s\"" % + caption) + + return self._items[captions.index(caption)] + + def format_as_single_line(self, + prefix=None, + divider=" | ", + enabled_item_attrs=None, + disabled_item_attrs=None): + """Format the menu as a single-line RichTextLines object. + + Args: + prefix: (str) String added to the beginning of the line. + divider: (str) The dividing string between the menu items. + enabled_item_attrs: (list or str) Attributes applied to each enabled + menu item, e.g., ["bold", "underline"]. + disabled_item_attrs: (list or str) Attributes applied to each + disabled menu item, e.g., ["red"]. + + Returns: + (RichTextLines) A single-line output representing the menu, with + font_attr_segs marking the individual menu items. + """ + + if (enabled_item_attrs is not None and + not isinstance(enabled_item_attrs, list)): + enabled_item_attrs = [enabled_item_attrs] + + if (disabled_item_attrs is not None and + not isinstance(disabled_item_attrs, list)): + disabled_item_attrs = [disabled_item_attrs] + + menu_line = prefix if prefix is not None else "" + attr_segs = [] + + for item in self._items: + menu_line += item.caption + item_name_begin = len(menu_line) - len(item.caption) + + if item.is_enabled(): + final_attrs = [item] + if enabled_item_attrs: + final_attrs.extend(enabled_item_attrs) + attr_segs.append((item_name_begin, len(menu_line), final_attrs)) + else: + if disabled_item_attrs: + attr_segs.append( + (item_name_begin, len(menu_line), disabled_item_attrs)) + + menu_line += divider + + return RichTextLines(menu_line, font_attr_segs={0: attr_segs}) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/evaluator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..56b6e143371f8c9f6337bb45eac9f39f85d13d58 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/evaluator.py @@ -0,0 +1,148 @@ +# 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. +# ============================================================================== +"""Library for arbitrary expression evaluation based on a debugger data dump.""" +import re + +import numpy as np # pylint: disable=unused-import + +from tensorflow.python.debug.lib import debug_data + +_DUMP_TENSOR_PATTERN = re.compile(r"`.*?`") +_DEVICE_NAME_PREFIX_PATTERN = re.compile( + r"/job:(\w)+/replica:(\d)+/task:(\d)+/(\w)+:(\d)+:") +_EXEC_INDEX_SUFFIX_PATTERN = re.compile(r"\[(\d)*\]$") + +_DEFAULT_DEBUG_OP = "DebugIdentity" + + +def _parse_debug_tensor_name(debug_tensor_name): + # pylint: disable=line-too-long + """Parse a debug tensor name in a to-be-evaluated expression. + + Args: + debug_tensor_name: name of the debug tensor, with or without + device name as a prefix, with or without debug op, with or + without '[]' as a suffix. + E.g., without device name prefix, without debug op suffix: + "hidden_0/MatMul:0" + E.g., with device name prefix: + "/job:worker/replica:0/task:1/gpu:0:hidden_0/MatMul:0" + E.g., with debug op suffix: + "hidden_0/MatMul:0:DebugNumericSummary" + E.g., with device name prefix and debug op suffix: + "/job:worker/replica:0/task:1/gpu:0:hidden_0/MatMul:0:DebugNumericSummary" + E.g., with device name prefix, debug op and an exec index: + "/job:worker/replica:0/task:1/gpu:0:hidden_0/MatMul:0:DebugNumericSummary[1]" + + Returns: + device_name: If device name prefix exists, the device name; otherwise, + `None`. + node_name: Name of the node. + output_slot: Output slot index as an `int`. + debug_op: If the debug op suffix exists, the debug op name; otherwise, + `None`. + exec_index: Execution index (applicable to cases in which a debug tensor + is computed multiple times in a `tf.Session.run` call, e.g., due to + `tf.while_loop`). If the exec_index suffix does not exist, this value + defaults to `0`. + + Raises: + ValueError: If the input `debug_tensor_name` is malformed. + """ + # pylint: enable=line-too-long + device_prefix_match = re.match(_DEVICE_NAME_PREFIX_PATTERN, debug_tensor_name) + if device_prefix_match: + device_name = debug_tensor_name[ + device_prefix_match.start() : device_prefix_match.end() - 1] + debug_tensor_name = debug_tensor_name[device_prefix_match.end():] + else: + device_name = None + + split_items = debug_tensor_name.split(":") + if len(split_items) not in (2, 3): + raise ValueError( + "The debug tensor name in the to-be-evaluated expression is malformed: " + "'%s'" % debug_tensor_name) + # TODO(cais): Provide examples of good debug tensor names in the error + # message. + + exec_index_match = re.search(_EXEC_INDEX_SUFFIX_PATTERN, split_items[-1]) + if exec_index_match: + exec_index = int(split_items[-1][ + exec_index_match.start() + 1 : exec_index_match.end() - 1]) + split_items[-1] = split_items[-1][:exec_index_match.start()] + else: + exec_index = 0 + + if len(split_items) == 2: + node_name = split_items[0] + output_slot = int(split_items[1]) + debug_op = _DEFAULT_DEBUG_OP + else: + split_items = debug_tensor_name.split(":") + node_name = split_items[0] + output_slot = int(split_items[1]) + debug_op = split_items[2] + + return device_name, node_name, output_slot, debug_op, exec_index + + +class ExpressionEvaluator(object): + """Evaluates Python expressions using debug tensor values from a dump.""" + + def __init__(self, dump): + """Constructor of ExpressionEvaluator. + + Args: + dump: an instance of `DebugDumpDir`. + """ + self._dump = dump + self._cached_tensor_values = {} + + def evaluate(self, expression): + """Parse an expression. + + Args: + expression: the expression to be parsed. + + Returns: + The result of the evaluation. + + Raises: + ValueError: If the value of one or more of the debug tensors in the + expression are not available. + """ + dump_tensors_iter = re.finditer(_DUMP_TENSOR_PATTERN, expression) + rewritten_expression = expression + for match in reversed(list(dump_tensors_iter)): + tensor_name = match.group(0)[1:-1].strip() + device_name, node_name, output_slot, debug_op, exec_index = ( + _parse_debug_tensor_name(tensor_name)) + if tensor_name not in self._cached_tensor_values: + try: + value = self._dump.get_tensors( + node_name, output_slot, debug_op, + device_name=device_name)[exec_index] + except debug_data.WatchKeyDoesNotExistInDebugDumpDirError: + raise ValueError( + "Eval failed due to the value of %s:%d:DebugIdentity being " + "unavailable" % (node_name, output_slot)) + self._cached_tensor_values[tensor_name] = value + rewritten_expression = ( + rewritten_expression[:match.start(0)] + + "self._cached_tensor_values['" + tensor_name + "']" + + rewritten_expression[match.end(0):]) + + return eval(rewritten_expression) # pylint: disable=eval-used diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/offline_analyzer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/offline_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..897ef7e7b74931836cc43bbe037623b4f99ea086 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/offline_analyzer.py @@ -0,0 +1,70 @@ +# 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. +# ============================================================================== +"""Offline dump analyzer of TensorFlow Debugger (tfdbg).""" +import argparse +import sys + +from absl import app + +from tensorflow.python.debug.cli import analyzer_cli +from tensorflow.python.debug.lib import debug_data + + +def main(_): + if not FLAGS.dump_dir: + print("ERROR: dump_dir flag is empty.", file=sys.stderr) + sys.exit(1) + + print("tfdbg offline: FLAGS.dump_dir = %s" % FLAGS.dump_dir) + + debug_dump = debug_data.DebugDumpDir( + FLAGS.dump_dir, validate=FLAGS.validate_graph) + cli = analyzer_cli.create_analyzer_ui( + debug_dump, + tensor_filters={"has_inf_or_nan": debug_data.has_inf_or_nan}, + ui_type=FLAGS.ui_type) + + title = "tfdbg offline @ %s" % FLAGS.dump_dir + cli.run_ui(title=title, title_color="black_on_white", init_command="lt") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--dump_dir", type=str, default="", help="tfdbg dump directory to load") + parser.add_argument( + "--log_usage", + type="bool", + nargs="?", + const=True, + default=True, + help="Whether the usage of this tool is to be logged") + parser.add_argument( + "--ui_type", + type=str, + default="readline", + help="Command-line user interface type (only readline is supported)") + parser.add_argument( + "--validate_graph", + nargs="?", + const=True, + type="bool", + default=True, + help="""\ + Whether the dumped tensors will be validated against the GraphDefs\ + """) + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/profile_analyzer_cli.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/profile_analyzer_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..dc699ce79409461550a296080d9e56813abdbdf4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/profile_analyzer_cli.py @@ -0,0 +1,798 @@ +# 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. +# ============================================================================== +"""Formats and displays profiling information.""" + +import argparse +import os +import re + +import numpy as np + +from tensorflow.python.debug.cli import cli_shared +from tensorflow.python.debug.cli import command_parser +from tensorflow.python.debug.cli import debugger_cli_common +from tensorflow.python.debug.cli import ui_factory +from tensorflow.python.debug.lib import profiling +from tensorflow.python.debug.lib import source_utils + +RL = debugger_cli_common.RichLine + +SORT_OPS_BY_OP_NAME = "node" +SORT_OPS_BY_OP_TYPE = "op_type" +SORT_OPS_BY_OP_TIME = "op_time" +SORT_OPS_BY_EXEC_TIME = "exec_time" +SORT_OPS_BY_START_TIME = "start_time" +SORT_OPS_BY_LINE = "line" + +_DEVICE_NAME_FILTER_FLAG = "device_name_filter" +_NODE_NAME_FILTER_FLAG = "node_name_filter" +_OP_TYPE_FILTER_FLAG = "op_type_filter" + + +class ProfileDataTableView(object): + """Table View of profiling data.""" + + def __init__(self, profile_datum_list, time_unit=cli_shared.TIME_UNIT_US): + """Constructor. + + Args: + profile_datum_list: List of `ProfileDatum` objects. + time_unit: must be in cli_shared.TIME_UNITS. + """ + self._profile_datum_list = profile_datum_list + self.formatted_start_time = [ + datum.start_time for datum in profile_datum_list] + self.formatted_op_time = [ + cli_shared.time_to_readable_str(datum.op_time, + force_time_unit=time_unit) + for datum in profile_datum_list] + self.formatted_exec_time = [ + cli_shared.time_to_readable_str( + datum.node_exec_stats.all_end_rel_micros, + force_time_unit=time_unit) + for datum in profile_datum_list] + + self._column_names = ["Node", + "Op Type", + "Start Time (us)", + "Op Time (%s)" % time_unit, + "Exec Time (%s)" % time_unit, + "Filename:Lineno(function)"] + self._column_sort_ids = [SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE, + SORT_OPS_BY_START_TIME, SORT_OPS_BY_OP_TIME, + SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_LINE] + + def value(self, + row, + col, + device_name_filter=None, + node_name_filter=None, + op_type_filter=None): + """Get the content of a cell of the table. + + Args: + row: (int) row index. + col: (int) column index. + device_name_filter: Regular expression to filter by device name. + node_name_filter: Regular expression to filter by node name. + op_type_filter: Regular expression to filter by op type. + + Returns: + A debuggre_cli_common.RichLine object representing the content of the + cell, potentially with a clickable MenuItem. + + Raises: + IndexError: if row index is out of range. + """ + menu_item = None + if col == 0: + text = self._profile_datum_list[row].node_exec_stats.node_name + elif col == 1: + text = self._profile_datum_list[row].op_type + elif col == 2: + text = str(self.formatted_start_time[row]) + elif col == 3: + text = str(self.formatted_op_time[row]) + elif col == 4: + text = str(self.formatted_exec_time[row]) + elif col == 5: + command = "ps" + if device_name_filter: + command += " --%s %s" % (_DEVICE_NAME_FILTER_FLAG, + device_name_filter) + if node_name_filter: + command += " --%s %s" % (_NODE_NAME_FILTER_FLAG, node_name_filter) + if op_type_filter: + command += " --%s %s" % (_OP_TYPE_FILTER_FLAG, op_type_filter) + command += " %s --init_line %d" % ( + self._profile_datum_list[row].file_path, + self._profile_datum_list[row].line_number) + menu_item = debugger_cli_common.MenuItem(None, command) + text = self._profile_datum_list[row].file_line_func + else: + raise IndexError("Invalid column index %d." % col) + + return RL(text, font_attr=menu_item) + + def row_count(self): + return len(self._profile_datum_list) + + def column_count(self): + return len(self._column_names) + + def column_names(self): + return self._column_names + + def column_sort_id(self, col): + return self._column_sort_ids[col] + + +def _list_profile_filter( + profile_datum, + node_name_regex, + file_path_regex, + op_type_regex, + op_time_interval, + exec_time_interval, + min_lineno=-1, + max_lineno=-1): + """Filter function for list_profile command. + + Args: + profile_datum: A `ProfileDatum` object. + node_name_regex: Regular expression pattern object to filter by name. + file_path_regex: Regular expression pattern object to filter by file path. + op_type_regex: Regular expression pattern object to filter by op type. + op_time_interval: `Interval` for filtering op time. + exec_time_interval: `Interval` for filtering exec time. + min_lineno: Lower bound for 1-based line number, inclusive. + If <= 0, has no effect. + max_lineno: Upper bound for 1-based line number, exclusive. + If <= 0, has no effect. + # TODO(cais): Maybe filter by function name. + + Returns: + True iff profile_datum should be included. + """ + if node_name_regex and not node_name_regex.match( + profile_datum.node_exec_stats.node_name): + return False + if file_path_regex: + if (not profile_datum.file_path or + not file_path_regex.match(profile_datum.file_path)): + return False + if (min_lineno > 0 and profile_datum.line_number and + profile_datum.line_number < min_lineno): + return False + if (max_lineno > 0 and profile_datum.line_number and + profile_datum.line_number >= max_lineno): + return False + if (profile_datum.op_type is not None and op_type_regex and + not op_type_regex.match(profile_datum.op_type)): + return False + if op_time_interval is not None and not op_time_interval.contains( + profile_datum.op_time): + return False + if exec_time_interval and not exec_time_interval.contains( + profile_datum.node_exec_stats.all_end_rel_micros): + return False + return True + + +def _list_profile_sort_key(profile_datum, sort_by): + """Get a profile_datum property to sort by in list_profile command. + + Args: + profile_datum: A `ProfileDatum` object. + sort_by: (string) indicates a value to sort by. + Must be one of SORT_BY* constants. + + Returns: + profile_datum property to sort by. + """ + if sort_by == SORT_OPS_BY_OP_NAME: + return profile_datum.node_exec_stats.node_name + elif sort_by == SORT_OPS_BY_OP_TYPE: + return profile_datum.op_type + elif sort_by == SORT_OPS_BY_LINE: + return profile_datum.file_line_func + elif sort_by == SORT_OPS_BY_OP_TIME: + return profile_datum.op_time + elif sort_by == SORT_OPS_BY_EXEC_TIME: + return profile_datum.node_exec_stats.all_end_rel_micros + else: # sort by start time + return profile_datum.node_exec_stats.all_start_micros + + +class ProfileAnalyzer(object): + """Analyzer for profiling data.""" + + def __init__(self, graph, run_metadata): + """ProfileAnalyzer constructor. + + Args: + graph: (tf.Graph) Python graph object. + run_metadata: A `RunMetadata` protobuf object. + + Raises: + ValueError: If run_metadata is None. + """ + self._graph = graph + if not run_metadata: + raise ValueError("No RunMetadata passed for profile analysis.") + self._run_metadata = run_metadata + self._arg_parsers = {} + ap = argparse.ArgumentParser( + description="List nodes profile information.", + usage=argparse.SUPPRESS) + ap.add_argument( + "-d", + "--%s" % _DEVICE_NAME_FILTER_FLAG, + dest=_DEVICE_NAME_FILTER_FLAG, + type=str, + default="", + help="filter device name by regex.") + ap.add_argument( + "-n", + "--%s" % _NODE_NAME_FILTER_FLAG, + dest=_NODE_NAME_FILTER_FLAG, + type=str, + default="", + help="filter node name by regex.") + ap.add_argument( + "-t", + "--%s" % _OP_TYPE_FILTER_FLAG, + dest=_OP_TYPE_FILTER_FLAG, + type=str, + default="", + help="filter op type by regex.") + # TODO(annarev): allow file filtering at non-stack top position. + ap.add_argument( + "-f", + "--file_path_filter", + dest="file_path_filter", + type=str, + default="", + help="filter by file name at the top position of node's creation " + "stack that does not belong to TensorFlow library.") + ap.add_argument( + "--min_lineno", + dest="min_lineno", + type=int, + default=-1, + help="(Inclusive) lower bound for 1-based line number in source file. " + "If <= 0, has no effect.") + ap.add_argument( + "--max_lineno", + dest="max_lineno", + type=int, + default=-1, + help="(Exclusive) upper bound for 1-based line number in source file. " + "If <= 0, has no effect.") + ap.add_argument( + "-e", + "--execution_time", + dest="execution_time", + type=str, + default="", + help="Filter by execution time interval " + "(includes compute plus pre- and post -processing time). " + "Supported units are s, ms and us (default). " + "E.g. -e >100s, -e <100, -e [100us,1000ms]") + ap.add_argument( + "-o", + "--op_time", + dest="op_time", + type=str, + default="", + help="Filter by op time interval (only includes compute time). " + "Supported units are s, ms and us (default). " + "E.g. -e >100s, -e <100, -e [100us,1000ms]") + ap.add_argument( + "-s", + "--sort_by", + dest="sort_by", + type=str, + default=SORT_OPS_BY_START_TIME, + help=("the field to sort the data by: (%s)" % + " | ".join([SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE, + SORT_OPS_BY_START_TIME, SORT_OPS_BY_OP_TIME, + SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_LINE]))) + ap.add_argument( + "-r", + "--reverse", + dest="reverse", + action="store_true", + help="sort the data in reverse (descending) order") + ap.add_argument( + "--time_unit", + dest="time_unit", + type=str, + default=cli_shared.TIME_UNIT_US, + help="Time unit (" + " | ".join(cli_shared.TIME_UNITS) + ")") + + self._arg_parsers["list_profile"] = ap + + ap = argparse.ArgumentParser( + description="Print a Python source file with line-level profile " + "information", + usage=argparse.SUPPRESS) + ap.add_argument( + "source_file_path", + type=str, + help="Path to the source_file_path") + ap.add_argument( + "--cost_type", + type=str, + choices=["exec_time", "op_time"], + default="exec_time", + help="Type of cost to display") + ap.add_argument( + "--time_unit", + dest="time_unit", + type=str, + default=cli_shared.TIME_UNIT_US, + help="Time unit (" + " | ".join(cli_shared.TIME_UNITS) + ")") + ap.add_argument( + "-d", + "--%s" % _DEVICE_NAME_FILTER_FLAG, + dest=_DEVICE_NAME_FILTER_FLAG, + type=str, + default="", + help="Filter device name by regex.") + ap.add_argument( + "-n", + "--%s" % _NODE_NAME_FILTER_FLAG, + dest=_NODE_NAME_FILTER_FLAG, + type=str, + default="", + help="Filter node name by regex.") + ap.add_argument( + "-t", + "--%s" % _OP_TYPE_FILTER_FLAG, + dest=_OP_TYPE_FILTER_FLAG, + type=str, + default="", + help="Filter op type by regex.") + ap.add_argument( + "--init_line", + dest="init_line", + type=int, + default=0, + help="The 1-based line number to scroll to initially.") + + self._arg_parsers["print_source"] = ap + + def list_profile(self, args, screen_info=None): + """Command handler for list_profile. + + List per-operation profile information. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + """ + screen_cols = 80 + if screen_info and "cols" in screen_info: + screen_cols = screen_info["cols"] + + parsed = self._arg_parsers["list_profile"].parse_args(args) + op_time_interval = (command_parser.parse_time_interval(parsed.op_time) + if parsed.op_time else None) + exec_time_interval = ( + command_parser.parse_time_interval(parsed.execution_time) + if parsed.execution_time else None) + node_name_regex = (re.compile(parsed.node_name_filter) + if parsed.node_name_filter else None) + file_path_regex = (re.compile(parsed.file_path_filter) + if parsed.file_path_filter else None) + op_type_regex = (re.compile(parsed.op_type_filter) + if parsed.op_type_filter else None) + + output = debugger_cli_common.RichTextLines([""]) + device_name_regex = (re.compile(parsed.device_name_filter) + if parsed.device_name_filter else None) + data_generator = self._get_profile_data_generator() + device_count = len(self._run_metadata.step_stats.dev_stats) + for index in range(device_count): + device_stats = self._run_metadata.step_stats.dev_stats[index] + if not device_name_regex or device_name_regex.match(device_stats.device): + profile_data = [ + datum for datum in data_generator(device_stats) + if _list_profile_filter( + datum, node_name_regex, file_path_regex, op_type_regex, + op_time_interval, exec_time_interval, + min_lineno=parsed.min_lineno, max_lineno=parsed.max_lineno)] + profile_data = sorted( + profile_data, + key=lambda datum: _list_profile_sort_key(datum, parsed.sort_by), + reverse=parsed.reverse) + output.extend( + self._get_list_profile_lines( + device_stats.device, index, device_count, + profile_data, parsed.sort_by, parsed.reverse, parsed.time_unit, + device_name_filter=parsed.device_name_filter, + node_name_filter=parsed.node_name_filter, + op_type_filter=parsed.op_type_filter, + screen_cols=screen_cols)) + return output + + def _get_profile_data_generator(self): + """Get function that generates `ProfileDatum` objects. + + Returns: + A function that generates `ProfileDatum` objects. + """ + node_to_file_path = {} + node_to_line_number = {} + node_to_func_name = {} + node_to_op_type = {} + for op in self._graph.get_operations(): + for trace_entry in reversed(op.traceback): + file_path = trace_entry[0] + line_num = trace_entry[1] + func_name = trace_entry[2] + if not source_utils.guess_is_tensorflow_py_library(file_path): + break + node_to_file_path[op.name] = file_path + node_to_line_number[op.name] = line_num + node_to_func_name[op.name] = func_name + node_to_op_type[op.name] = op.type + + def profile_data_generator(device_step_stats): + for node_stats in device_step_stats.node_stats: + if node_stats.node_name == "_SOURCE" or node_stats.node_name == "_SINK": + continue + yield profiling.ProfileDatum( + device_step_stats.device, + node_stats, + node_to_file_path.get(node_stats.node_name, ""), + node_to_line_number.get(node_stats.node_name, 0), + node_to_func_name.get(node_stats.node_name, ""), + node_to_op_type.get(node_stats.node_name, "")) + return profile_data_generator + + def _get_list_profile_lines( + self, device_name, device_index, device_count, + profile_datum_list, sort_by, sort_reverse, time_unit, + device_name_filter=None, node_name_filter=None, op_type_filter=None, + screen_cols=80): + """Get `RichTextLines` object for list_profile command for a given device. + + Args: + device_name: (string) Device name. + device_index: (int) Device index. + device_count: (int) Number of devices. + profile_datum_list: List of `ProfileDatum` objects. + sort_by: (string) Identifier of column to sort. Sort identifier + must match value of SORT_OPS_BY_OP_NAME, SORT_OPS_BY_OP_TYPE, + SORT_OPS_BY_EXEC_TIME, SORT_OPS_BY_MEMORY or SORT_OPS_BY_LINE. + sort_reverse: (bool) Whether to sort in descending instead of default + (ascending) order. + time_unit: time unit, must be in cli_shared.TIME_UNITS. + device_name_filter: Regular expression to filter by device name. + node_name_filter: Regular expression to filter by node name. + op_type_filter: Regular expression to filter by op type. + screen_cols: (int) Number of columns available on the screen (i.e., + available screen width). + + Returns: + `RichTextLines` object containing a table that displays profiling + information for each op. + """ + profile_data = ProfileDataTableView(profile_datum_list, time_unit=time_unit) + + # Calculate total time early to calculate column widths. + total_op_time = sum(datum.op_time for datum in profile_datum_list) + total_exec_time = sum(datum.node_exec_stats.all_end_rel_micros + for datum in profile_datum_list) + device_total_row = [ + "Device Total", "", + cli_shared.time_to_readable_str(total_op_time, + force_time_unit=time_unit), + cli_shared.time_to_readable_str(total_exec_time, + force_time_unit=time_unit)] + + # Calculate column widths. + column_widths = [ + len(column_name) for column_name in profile_data.column_names()] + for col in range(len(device_total_row)): + column_widths[col] = max(column_widths[col], len(device_total_row[col])) + for col in range(len(column_widths)): + for row in range(profile_data.row_count()): + column_widths[col] = max( + column_widths[col], len(profile_data.value( + row, + col, + device_name_filter=device_name_filter, + node_name_filter=node_name_filter, + op_type_filter=op_type_filter))) + column_widths[col] += 2 # add margin between columns + + # Add device name. + output = [RL("-" * screen_cols)] + device_row = "Device %d of %d: %s" % ( + device_index + 1, device_count, device_name) + output.append(RL(device_row)) + output.append(RL()) + + # Add headers. + base_command = "list_profile" + row = RL() + for col in range(profile_data.column_count()): + column_name = profile_data.column_names()[col] + sort_id = profile_data.column_sort_id(col) + command = "%s -s %s" % (base_command, sort_id) + if sort_by == sort_id and not sort_reverse: + command += " -r" + head_menu_item = debugger_cli_common.MenuItem(None, command) + row += RL(column_name, font_attr=[head_menu_item, "bold"]) + row += RL(" " * (column_widths[col] - len(column_name))) + + output.append(row) + + # Add data rows. + for row in range(profile_data.row_count()): + new_row = RL() + for col in range(profile_data.column_count()): + new_cell = profile_data.value( + row, + col, + device_name_filter=device_name_filter, + node_name_filter=node_name_filter, + op_type_filter=op_type_filter) + new_row += new_cell + new_row += RL(" " * (column_widths[col] - len(new_cell))) + output.append(new_row) + + # Add stat totals. + row_str = "" + for width, row in zip(column_widths, device_total_row): + row_str += ("{:<%d}" % width).format(row) + output.append(RL()) + output.append(RL(row_str)) + return debugger_cli_common.rich_text_lines_from_rich_line_list(output) + + def _measure_list_profile_column_widths(self, profile_data): + """Determine the maximum column widths for each data list. + + Args: + profile_data: list of ProfileDatum objects. + + Returns: + List of column widths in the same order as columns in data. + """ + num_columns = len(profile_data.column_names()) + widths = [len(column_name) for column_name in profile_data.column_names()] + for row in range(profile_data.row_count()): + for col in range(num_columns): + widths[col] = max( + widths[col], len(str(profile_data.row_values(row)[col])) + 2) + return widths + + _LINE_COST_ATTR = cli_shared.COLOR_CYAN + _LINE_NUM_ATTR = cli_shared.COLOR_YELLOW + _NUM_NODES_HEAD = "#nodes" + _NUM_EXECS_SUB_HEAD = "(#execs)" + _LINENO_HEAD = "lineno" + _SOURCE_HEAD = "source" + + def print_source(self, args, screen_info=None): + """Print a Python source file with line-level profile information. + + Args: + args: Command-line arguments, excluding the command prefix, as a list of + str. + screen_info: Optional dict input containing screen information such as + cols. + + Returns: + Output text lines as a RichTextLines object. + """ + del screen_info + + parsed = self._arg_parsers["print_source"].parse_args(args) + + device_name_regex = (re.compile(parsed.device_name_filter) + if parsed.device_name_filter else None) + + profile_data = [] + data_generator = self._get_profile_data_generator() + device_count = len(self._run_metadata.step_stats.dev_stats) + for index in range(device_count): + device_stats = self._run_metadata.step_stats.dev_stats[index] + if device_name_regex and not device_name_regex.match(device_stats.device): + continue + profile_data.extend(data_generator(device_stats)) + + source_annotation = source_utils.annotate_source_against_profile( + profile_data, + os.path.expanduser(parsed.source_file_path), + node_name_filter=parsed.node_name_filter, + op_type_filter=parsed.op_type_filter) + if not source_annotation: + return debugger_cli_common.RichTextLines( + ["The source file %s does not contain any profile information for " + "the previous Session run under the following " + "filters:" % parsed.source_file_path, + " --%s: %s" % (_DEVICE_NAME_FILTER_FLAG, parsed.device_name_filter), + " --%s: %s" % (_NODE_NAME_FILTER_FLAG, parsed.node_name_filter), + " --%s: %s" % (_OP_TYPE_FILTER_FLAG, parsed.op_type_filter)]) + + max_total_cost = 0 + for line_index in source_annotation: + total_cost = self._get_total_cost(source_annotation[line_index], + parsed.cost_type) + max_total_cost = max(max_total_cost, total_cost) + + source_lines, line_num_width = source_utils.load_source( + parsed.source_file_path) + + cost_bar_max_length = 10 + total_cost_head = parsed.cost_type + column_widths = { + "cost_bar": cost_bar_max_length + 3, + "total_cost": len(total_cost_head) + 3, + "num_nodes_execs": len(self._NUM_EXECS_SUB_HEAD) + 1, + "line_number": line_num_width, + } + + head = RL( + " " * column_widths["cost_bar"] + + total_cost_head + + " " * (column_widths["total_cost"] - len(total_cost_head)) + + self._NUM_NODES_HEAD + + " " * (column_widths["num_nodes_execs"] - len(self._NUM_NODES_HEAD)), + font_attr=self._LINE_COST_ATTR) + head += RL(self._LINENO_HEAD, font_attr=self._LINE_NUM_ATTR) + sub_head = RL( + " " * (column_widths["cost_bar"] + + column_widths["total_cost"]) + + self._NUM_EXECS_SUB_HEAD + + " " * (column_widths["num_nodes_execs"] - + len(self._NUM_EXECS_SUB_HEAD)) + + " " * column_widths["line_number"], + font_attr=self._LINE_COST_ATTR) + sub_head += RL(self._SOURCE_HEAD, font_attr="bold") + lines = [head, sub_head] + + output_annotations = {} + for i, line in enumerate(source_lines): + lineno = i + 1 + if lineno in source_annotation: + annotation = source_annotation[lineno] + cost_bar = self._render_normalized_cost_bar( + self._get_total_cost(annotation, parsed.cost_type), max_total_cost, + cost_bar_max_length) + annotated_line = cost_bar + annotated_line += " " * (column_widths["cost_bar"] - len(cost_bar)) + + total_cost = RL(cli_shared.time_to_readable_str( + self._get_total_cost(annotation, parsed.cost_type), + force_time_unit=parsed.time_unit), + font_attr=self._LINE_COST_ATTR) + total_cost += " " * (column_widths["total_cost"] - len(total_cost)) + annotated_line += total_cost + + file_path_filter = re.escape(parsed.source_file_path) + "$" + command = "lp --file_path_filter %s --min_lineno %d --max_lineno %d" % ( + file_path_filter, lineno, lineno + 1) + if parsed.device_name_filter: + command += " --%s %s" % (_DEVICE_NAME_FILTER_FLAG, + parsed.device_name_filter) + if parsed.node_name_filter: + command += " --%s %s" % (_NODE_NAME_FILTER_FLAG, + parsed.node_name_filter) + if parsed.op_type_filter: + command += " --%s %s" % (_OP_TYPE_FILTER_FLAG, + parsed.op_type_filter) + menu_item = debugger_cli_common.MenuItem(None, command) + num_nodes_execs = RL("%d(%d)" % (annotation.node_count, + annotation.node_exec_count), + font_attr=[self._LINE_COST_ATTR, menu_item]) + num_nodes_execs += " " * ( + column_widths["num_nodes_execs"] - len(num_nodes_execs)) + annotated_line += num_nodes_execs + else: + annotated_line = RL( + " " * sum(column_widths[col_name] for col_name in column_widths + if col_name != "line_number")) + + line_num_column = RL(" L%d" % (lineno), self._LINE_NUM_ATTR) + line_num_column += " " * ( + column_widths["line_number"] - len(line_num_column)) + annotated_line += line_num_column + annotated_line += line + lines.append(annotated_line) + + if parsed.init_line == lineno: + output_annotations[ + debugger_cli_common.INIT_SCROLL_POS_KEY] = len(lines) - 1 + + return debugger_cli_common.rich_text_lines_from_rich_line_list( + lines, annotations=output_annotations) + + def _get_total_cost(self, aggregated_profile, cost_type): + if cost_type == "exec_time": + return aggregated_profile.total_exec_time + elif cost_type == "op_time": + return aggregated_profile.total_op_time + else: + raise ValueError("Unsupported cost type: %s" % cost_type) + + def _render_normalized_cost_bar(self, cost, max_cost, length): + """Render a text bar representing a normalized cost. + + Args: + cost: the absolute value of the cost. + max_cost: the maximum cost value to normalize the absolute cost with. + length: (int) length of the cost bar, in number of characters, excluding + the brackets on the two ends. + + Returns: + An instance of debugger_cli_common.RichTextLine. + """ + num_ticks = int(np.ceil(float(cost) / max_cost * length)) + num_ticks = num_ticks or 1 # Minimum is 1 tick. + output = RL("[", font_attr=self._LINE_COST_ATTR) + output += RL("|" * num_ticks + " " * (length - num_ticks), + font_attr=["bold", self._LINE_COST_ATTR]) + output += RL("]", font_attr=self._LINE_COST_ATTR) + return output + + def get_help(self, handler_name): + return self._arg_parsers[handler_name].format_help() + + +def create_profiler_ui(graph, + run_metadata, + ui_type="readline", + on_ui_exit=None, + config=None): + """Create an instance of ReadlineUI based on a `tf.Graph` and `RunMetadata`. + + Args: + graph: Python `Graph` object. + run_metadata: A `RunMetadata` protobuf object. + ui_type: (str) requested UI type, e.g., "readline". + on_ui_exit: (`Callable`) the callback to be called when the UI exits. + config: An instance of `cli_config.CLIConfig`. + + Returns: + (base_ui.BaseUI) A BaseUI subtype object with a set of standard analyzer + commands and tab-completions registered. + """ + del config # Currently unused. + + analyzer = ProfileAnalyzer(graph, run_metadata) + + cli = ui_factory.get_ui(ui_type, on_ui_exit=on_ui_exit) + cli.register_command_handler( + "list_profile", + analyzer.list_profile, + analyzer.get_help("list_profile"), + prefix_aliases=["lp"]) + cli.register_command_handler( + "print_source", + analyzer.print_source, + analyzer.get_help("print_source"), + prefix_aliases=["ps"]) + + return cli diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/readline_ui.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/readline_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..37be6feb607ccbaf83a5db703f4578f34bfeb85e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/readline_ui.py @@ -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. +# ============================================================================== +"""Readline-Based Command-Line Interface of TensorFlow Debugger (tfdbg).""" +import readline + +from tensorflow.python.debug.cli import base_ui +from tensorflow.python.debug.cli import debugger_cli_common + + +class ReadlineUI(base_ui.BaseUI): + """Readline-based Command-line UI.""" + + def __init__(self, on_ui_exit=None, config=None): + base_ui.BaseUI.__init__(self, on_ui_exit=on_ui_exit, config=config) + self._init_input() + + def _init_input(self): + readline.parse_and_bind("set editing-mode emacs") + + # Disable default readline delimiter in order to receive the full text + # (not just the last word) in the completer. + readline.set_completer_delims("\n") + readline.set_completer(self._readline_complete) + readline.parse_and_bind("tab: complete") + + self._input = input + + def _readline_complete(self, text, state): + context, prefix, except_last_word = self._analyze_tab_complete_input(text) + candidates, _ = self._tab_completion_registry.get_completions(context, + prefix) + candidates = [(except_last_word + candidate) for candidate in candidates] + return candidates[state] + + def run_ui(self, + init_command=None, + title=None, + title_color=None, + enable_mouse_on_start=True): + """Run the CLI: See the doc of base_ui.BaseUI.run_ui for more details.""" + + print(title) + + if init_command is not None: + self._dispatch_command(init_command) + + exit_token = self._ui_loop() + + if self._on_ui_exit: + self._on_ui_exit() + + return exit_token + + def _ui_loop(self): + while True: + command = self._get_user_command() + + exit_token = self._dispatch_command(command) + if exit_token is not None: + return exit_token + + def _get_user_command(self): + print("") + return self._input(self.CLI_PROMPT).strip() + + def _dispatch_command(self, command): + """Dispatch user command. + + Args: + command: (str) Command to dispatch. + + Returns: + An exit token object. None value means that the UI loop should not exit. + A non-None value means the UI loop should exit. + """ + + if command in self.CLI_EXIT_COMMANDS: + # Explicit user command-triggered exit: EXPLICIT_USER_EXIT as the exit + # token. + return debugger_cli_common.EXPLICIT_USER_EXIT + + try: + prefix, args, output_file_path = self._parse_command(command) + except SyntaxError as e: + print(str(e)) + return + + if self._command_handler_registry.is_registered(prefix): + try: + screen_output = self._command_handler_registry.dispatch_command( + prefix, args, screen_info=None) + except debugger_cli_common.CommandLineExit as e: + return e.exit_token + else: + screen_output = debugger_cli_common.RichTextLines([ + self.ERROR_MESSAGE_PREFIX + "Invalid command prefix \"%s\"" % prefix + ]) + + self._display_output(screen_output) + if output_file_path: + try: + screen_output.write_to_file(output_file_path) + print("Wrote output to %s" % output_file_path) + except Exception: # pylint: disable=broad-except + print("Failed to write output to %s" % output_file_path) + + def _display_output(self, screen_output): + for line in screen_output.lines: + print(line) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/tensor_format.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/tensor_format.py new file mode 100644 index 0000000000000000000000000000000000000000..ea333b64fe1c783dbab1c8bcba75b820f01c04ed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/tensor_format.py @@ -0,0 +1,564 @@ +# 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. +# ============================================================================== +"""Format tensors (ndarrays) for screen display and navigation.""" +import copy +import re + +import numpy as np + +from tensorflow.python.debug.cli import debugger_cli_common +from tensorflow.python.debug.lib import debug_data + +_NUMPY_OMISSION = "...," +_NUMPY_DEFAULT_EDGE_ITEMS = 3 + +_NUMBER_REGEX = re.compile(r"[-+]?([0-9][-+0-9eE\.]+|nan|inf)(\s|,|\])") + +BEGIN_INDICES_KEY = "i0" +OMITTED_INDICES_KEY = "omitted" + +DEFAULT_TENSOR_ELEMENT_HIGHLIGHT_FONT_ATTR = "bold" + + +class HighlightOptions(object): + """Options for highlighting elements of a tensor.""" + + def __init__(self, + criterion, + description=None, + font_attr=DEFAULT_TENSOR_ELEMENT_HIGHLIGHT_FONT_ATTR): + """Constructor of HighlightOptions. + + Args: + criterion: (callable) A callable of the following signature: + def to_highlight(X): + # Args: + # X: The tensor to highlight elements in. + # + # Returns: + # (boolean ndarray) A boolean ndarray of the same shape as X + # indicating which elements are to be highlighted (iff True). + This callable will be used as the argument of np.argwhere() to + determine which elements of the tensor are to be highlighted. + description: (str) Description of the highlight criterion embodied by + criterion. + font_attr: (str) Font attribute to be applied to the + highlighted elements. + + """ + + self.criterion = criterion + self.description = description + self.font_attr = font_attr + + +def format_tensor(tensor, + tensor_label, + include_metadata=False, + auxiliary_message=None, + include_numeric_summary=False, + np_printoptions=None, + highlight_options=None): + """Generate a RichTextLines object showing a tensor in formatted style. + + Args: + tensor: The tensor to be displayed, as a numpy ndarray or other + appropriate format (e.g., None representing uninitialized tensors). + tensor_label: A label for the tensor, as a string. If set to None, will + suppress the tensor name line in the return value. + include_metadata: Whether metadata such as dtype and shape are to be + included in the formatted text. + auxiliary_message: An auxiliary message to display under the tensor label, + dtype and shape information lines. + include_numeric_summary: Whether a text summary of the numeric values (if + applicable) will be included. + np_printoptions: A dictionary of keyword arguments that are passed to a + call of np.set_printoptions() to set the text format for display numpy + ndarrays. + highlight_options: (HighlightOptions) options for highlighting elements + of the tensor. + + Returns: + A RichTextLines object. Its annotation field has line-by-line markups to + indicate which indices in the array the first element of each line + corresponds to. + """ + lines = [] + font_attr_segs = {} + + if tensor_label is not None: + lines.append("Tensor \"%s\":" % tensor_label) + suffix = tensor_label.split(":")[-1] + if suffix.isdigit(): + # Suffix is a number. Assume it is the output slot index. + font_attr_segs[0] = [(8, 8 + len(tensor_label), "bold")] + else: + # Suffix is not a number. It is auxiliary information such as the debug + # op type. In this case, highlight the suffix with a different color. + debug_op_len = len(suffix) + proper_len = len(tensor_label) - debug_op_len - 1 + font_attr_segs[0] = [ + (8, 8 + proper_len, "bold"), + (8 + proper_len + 1, 8 + proper_len + 1 + debug_op_len, "yellow") + ] + + if isinstance(tensor, debug_data.InconvertibleTensorProto): + if lines: + lines.append("") + lines.extend(str(tensor).split("\n")) + return debugger_cli_common.RichTextLines(lines) + elif not isinstance(tensor, np.ndarray): + # If tensor is not a np.ndarray, return simple text-line representation of + # the object without annotations. + if lines: + lines.append("") + lines.extend(repr(tensor).split("\n")) + return debugger_cli_common.RichTextLines(lines) + + if include_metadata: + lines.append(" dtype: %s" % str(tensor.dtype)) + lines.append(" shape: %s" % str(tensor.shape).replace("L", "")) + + if lines: + lines.append("") + formatted = debugger_cli_common.RichTextLines( + lines, font_attr_segs=font_attr_segs) + + if auxiliary_message: + formatted.extend(auxiliary_message) + + if include_numeric_summary: + formatted.append("Numeric summary:") + formatted.extend(numeric_summary(tensor)) + formatted.append("") + + # Apply custom string formatting options for numpy ndarray. + if np_printoptions is not None: + np.set_printoptions(**np_printoptions) + + array_lines = repr(tensor).split("\n") + if tensor.dtype.type is not np.string_: + # Parse array lines to get beginning indices for each line. + + # TODO(cais): Currently, we do not annotate string-type tensors due to + # difficulty in escaping sequences. Address this issue. + annotations = _annotate_ndarray_lines( + array_lines, tensor, np_printoptions=np_printoptions) + else: + annotations = None + formatted_array = debugger_cli_common.RichTextLines( + array_lines, annotations=annotations) + formatted.extend(formatted_array) + + # Perform optional highlighting. + if highlight_options is not None: + indices_list = list(np.argwhere(highlight_options.criterion(tensor))) + + total_elements = np.size(tensor) + highlight_summary = "Highlighted%s: %d of %d element(s) (%.2f%%)" % ( + "(%s)" % highlight_options.description if highlight_options.description + else "", len(indices_list), total_elements, + len(indices_list) / float(total_elements) * 100.0) + + formatted.lines[0] += " " + highlight_summary + + if indices_list: + indices_list = [list(indices) for indices in indices_list] + + are_omitted, rows, start_cols, end_cols = locate_tensor_element( + formatted, indices_list) + for is_omitted, row, start_col, end_col in zip(are_omitted, rows, + start_cols, end_cols): + if is_omitted or start_col is None or end_col is None: + continue + + if row in formatted.font_attr_segs: + formatted.font_attr_segs[row].append( + (start_col, end_col, highlight_options.font_attr)) + else: + formatted.font_attr_segs[row] = [(start_col, end_col, + highlight_options.font_attr)] + + return formatted + + +def _annotate_ndarray_lines( + array_lines, tensor, np_printoptions=None, offset=0): + """Generate annotations for line-by-line begin indices of tensor text. + + Parse the numpy-generated text representation of a numpy ndarray to + determine the indices of the first element of each text line (if any + element is present in the line). + + For example, given the following multi-line ndarray text representation: + ["array([[ 0. , 0.0625, 0.125 , 0.1875],", + " [ 0.25 , 0.3125, 0.375 , 0.4375],", + " [ 0.5 , 0.5625, 0.625 , 0.6875],", + " [ 0.75 , 0.8125, 0.875 , 0.9375]])"] + the generate annotation will be: + {0: {BEGIN_INDICES_KEY: [0, 0]}, + 1: {BEGIN_INDICES_KEY: [1, 0]}, + 2: {BEGIN_INDICES_KEY: [2, 0]}, + 3: {BEGIN_INDICES_KEY: [3, 0]}} + + Args: + array_lines: Text lines representing the tensor, as a list of str. + tensor: The tensor being formatted as string. + np_printoptions: A dictionary of keyword arguments that are passed to a + call of np.set_printoptions(). + offset: Line number offset applied to the line indices in the returned + annotation. + + Returns: + An annotation as a dict. + """ + + if np_printoptions and "edgeitems" in np_printoptions: + edge_items = np_printoptions["edgeitems"] + else: + edge_items = _NUMPY_DEFAULT_EDGE_ITEMS + + annotations = {} + + # Put metadata about the tensor in the annotations["tensor_metadata"]. + annotations["tensor_metadata"] = { + "dtype": tensor.dtype, "shape": tensor.shape} + + dims = np.shape(tensor) + ndims = len(dims) + if ndims == 0: + # No indices for a 0D tensor. + return annotations + + curr_indices = [0] * len(dims) + curr_dim = 0 + for i, raw_line in enumerate(array_lines): + line = raw_line.strip() + + if not line: + # Skip empty lines, which can appear for >= 3D arrays. + continue + + if line == _NUMPY_OMISSION: + annotations[offset + i] = {OMITTED_INDICES_KEY: copy.copy(curr_indices)} + curr_indices[curr_dim - 1] = dims[curr_dim - 1] - edge_items + else: + num_lbrackets = line.count("[") # TODO(cais): String array escaping. + num_rbrackets = line.count("]") + + curr_dim += num_lbrackets - num_rbrackets + + annotations[offset + i] = {BEGIN_INDICES_KEY: copy.copy(curr_indices)} + if num_rbrackets == 0: + line_content = line[line.rfind("[") + 1:] + num_elements = line_content.count(",") + curr_indices[curr_dim - 1] += num_elements + else: + if curr_dim > 0: + curr_indices[curr_dim - 1] += 1 + for k in range(curr_dim, ndims): + curr_indices[k] = 0 + + return annotations + + +def locate_tensor_element(formatted, indices): + """Locate a tensor element in formatted text lines, given element indices. + + Given a RichTextLines object representing a tensor and indices of the sought + element, return the row number at which the element is located (if exists). + + Args: + formatted: A RichTextLines object containing formatted text lines + representing the tensor. + indices: Indices of the sought element, as a list of int or a list of list + of int. The former case is for a single set of indices to look up, + whereas the latter case is for looking up a batch of indices sets at once. + In the latter case, the indices must be in ascending order, or a + ValueError will be raised. + + Returns: + 1) A boolean indicating whether the element falls into an omitted line. + 2) Row index. + 3) Column start index, i.e., the first column in which the representation + of the specified tensor starts, if it can be determined. If it cannot + be determined (e.g., due to ellipsis), None. + 4) Column end index, i.e., the column right after the last column that + represents the specified tensor. Iff it cannot be determined, None. + + For return values described above are based on a single set of indices to + look up. In the case of batch mode (multiple sets of indices), the return + values will be lists of the types described above. + + Raises: + AttributeError: If: + Input argument "formatted" does not have the required annotations. + ValueError: If: + 1) Indices do not match the dimensions of the tensor, or + 2) Indices exceed sizes of the tensor, or + 3) Indices contain negative value(s). + 4) If in batch mode, and if not all sets of indices are in ascending + order. + """ + + if isinstance(indices[0], list): + indices_list = indices + input_batch = True + else: + indices_list = [indices] + input_batch = False + + # Check that tensor_metadata is available. + if "tensor_metadata" not in formatted.annotations: + raise AttributeError("tensor_metadata is not available in annotations.") + + # Sanity check on input argument. + _validate_indices_list(indices_list, formatted) + + dims = formatted.annotations["tensor_metadata"]["shape"] + batch_size = len(indices_list) + lines = formatted.lines + annot = formatted.annotations + prev_r = 0 + prev_line = "" + prev_indices = [0] * len(dims) + + # Initialize return values + are_omitted = [None] * batch_size + row_indices = [None] * batch_size + start_columns = [None] * batch_size + end_columns = [None] * batch_size + + batch_pos = 0 # Current position in the batch. + + for r in range(len(lines)): + if r not in annot: + continue + + if BEGIN_INDICES_KEY in annot[r]: + indices_key = BEGIN_INDICES_KEY + elif OMITTED_INDICES_KEY in annot[r]: + indices_key = OMITTED_INDICES_KEY + + matching_indices_list = [ + ind for ind in indices_list[batch_pos:] + if prev_indices <= ind < annot[r][indices_key] + ] + + if matching_indices_list: + num_matches = len(matching_indices_list) + + match_start_columns, match_end_columns = _locate_elements_in_line( + prev_line, matching_indices_list, prev_indices) + + start_columns[batch_pos:batch_pos + num_matches] = match_start_columns + end_columns[batch_pos:batch_pos + num_matches] = match_end_columns + are_omitted[batch_pos:batch_pos + num_matches] = [ + OMITTED_INDICES_KEY in annot[prev_r] + ] * num_matches + row_indices[batch_pos:batch_pos + num_matches] = [prev_r] * num_matches + + batch_pos += num_matches + if batch_pos >= batch_size: + break + + prev_r = r + prev_line = lines[r] + prev_indices = annot[r][indices_key] + + if batch_pos < batch_size: + matching_indices_list = indices_list[batch_pos:] + num_matches = len(matching_indices_list) + + match_start_columns, match_end_columns = _locate_elements_in_line( + prev_line, matching_indices_list, prev_indices) + + start_columns[batch_pos:batch_pos + num_matches] = match_start_columns + end_columns[batch_pos:batch_pos + num_matches] = match_end_columns + are_omitted[batch_pos:batch_pos + num_matches] = [ + OMITTED_INDICES_KEY in annot[prev_r] + ] * num_matches + row_indices[batch_pos:batch_pos + num_matches] = [prev_r] * num_matches + + if input_batch: + return are_omitted, row_indices, start_columns, end_columns + else: + return are_omitted[0], row_indices[0], start_columns[0], end_columns[0] + + +def _validate_indices_list(indices_list, formatted): + prev_ind = None + for ind in indices_list: + # Check indices match tensor dimensions. + dims = formatted.annotations["tensor_metadata"]["shape"] + if len(ind) != len(dims): + raise ValueError("Dimensions mismatch: requested: %d; actual: %d" % + (len(ind), len(dims))) + + # Check indices is within size limits. + for req_idx, siz in zip(ind, dims): + if req_idx >= siz: + raise ValueError("Indices exceed tensor dimensions.") + if req_idx < 0: + raise ValueError("Indices contain negative value(s).") + + # Check indices are in ascending order. + if prev_ind and ind < prev_ind: + raise ValueError("Input indices sets are not in ascending order.") + + prev_ind = ind + + +def _locate_elements_in_line(line, indices_list, ref_indices): + """Determine the start and end indices of an element in a line. + + Args: + line: (str) the line in which the element is to be sought. + indices_list: (list of list of int) list of indices of the element to + search for. Assumes that the indices in the batch are unique and sorted + in ascending order. + ref_indices: (list of int) reference indices, i.e., the indices of the + first element represented in the line. + + Returns: + start_columns: (list of int) start column indices, if found. If not found, + None. + end_columns: (list of int) end column indices, if found. If not found, + None. + If found, the element is represented in the left-closed-right-open interval + [start_column, end_column]. + """ + + batch_size = len(indices_list) + offsets = [indices[-1] - ref_indices[-1] for indices in indices_list] + + start_columns = [None] * batch_size + end_columns = [None] * batch_size + + if _NUMPY_OMISSION in line: + ellipsis_index = line.find(_NUMPY_OMISSION) + else: + ellipsis_index = len(line) + + matches_iter = re.finditer(_NUMBER_REGEX, line) + + batch_pos = 0 + + offset_counter = 0 + for match in matches_iter: + if match.start() > ellipsis_index: + # Do not attempt to search beyond ellipsis. + break + + if offset_counter == offsets[batch_pos]: + start_columns[batch_pos] = match.start() + # Remove the final comma, right bracket, or whitespace. + end_columns[batch_pos] = match.end() - 1 + + batch_pos += 1 + if batch_pos >= batch_size: + break + + offset_counter += 1 + + return start_columns, end_columns + + +def _pad_string_to_length(string, length): + return " " * (length - len(string)) + string + + +def numeric_summary(tensor): + """Get a text summary of a numeric tensor. + + This summary is only available for numeric (int*, float*, complex*) and + Boolean tensors. + + Args: + tensor: (`numpy.ndarray`) the tensor value object to be summarized. + + Returns: + The summary text as a `RichTextLines` object. If the type of `tensor` is not + numeric or Boolean, a single-line `RichTextLines` object containing a + warning message will reflect that. + """ + + def _counts_summary(counts, skip_zeros=True, total_count=None): + """Format values as a two-row table.""" + if skip_zeros: + counts = [(count_key, count_val) for count_key, count_val in counts + if count_val] + max_common_len = 0 + for count_key, count_val in counts: + count_val_str = str(count_val) + common_len = max(len(count_key) + 1, len(count_val_str) + 1) + max_common_len = max(common_len, max_common_len) + + key_line = debugger_cli_common.RichLine("|") + val_line = debugger_cli_common.RichLine("|") + for count_key, count_val in counts: + count_val_str = str(count_val) + key_line += _pad_string_to_length(count_key, max_common_len) + val_line += _pad_string_to_length(count_val_str, max_common_len) + key_line += " |" + val_line += " |" + + if total_count is not None: + total_key_str = "total" + total_val_str = str(total_count) + max_common_len = max(len(total_key_str) + 1, len(total_val_str)) + total_key_str = _pad_string_to_length(total_key_str, max_common_len) + total_val_str = _pad_string_to_length(total_val_str, max_common_len) + key_line += total_key_str + " |" + val_line += total_val_str + " |" + + return debugger_cli_common.rich_text_lines_from_rich_line_list( + [key_line, val_line]) + + if not isinstance(tensor, np.ndarray) or not np.size(tensor): + return debugger_cli_common.RichTextLines([ + "No numeric summary available due to empty tensor."]) + elif (np.issubdtype(tensor.dtype, np.floating) or + np.issubdtype(tensor.dtype, np.complexfloating) or + np.issubdtype(tensor.dtype, np.integer)): + counts = [ + ("nan", np.sum(np.isnan(tensor))), + ("-inf", np.sum(np.isneginf(tensor))), + ("-", np.sum(np.logical_and( + tensor < 0.0, np.logical_not(np.isneginf(tensor))))), + ("0", np.sum(tensor == 0.0)), + ("+", np.sum(np.logical_and( + tensor > 0.0, np.logical_not(np.isposinf(tensor))))), + ("+inf", np.sum(np.isposinf(tensor)))] + output = _counts_summary(counts, total_count=np.size(tensor)) + + valid_array = tensor[ + np.logical_not(np.logical_or(np.isinf(tensor), np.isnan(tensor)))] + if np.size(valid_array): + stats = [ + ("min", np.min(valid_array)), + ("max", np.max(valid_array)), + ("mean", np.mean(valid_array)), + ("std", np.std(valid_array))] + output.extend(_counts_summary(stats, skip_zeros=False)) + return output + elif tensor.dtype == np.bool_: + counts = [ + ("False", np.sum(tensor == 0)), + ("True", np.sum(tensor > 0)),] + return _counts_summary(counts, total_count=np.size(tensor)) + else: + return debugger_cli_common.RichTextLines([ + "No numeric summary available due to tensor dtype: %s." % tensor.dtype]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/ui_factory.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/ui_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..d066e3ad66e5347a071d207f371587563e9e2e55 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/cli/ui_factory.py @@ -0,0 +1,63 @@ +# 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. +# ============================================================================== +"""TensorFlow Debugger (tfdbg) User-Interface Factory.""" +import copy + + +SUPPORTED_UI_TYPES = ["readline"] + + +def get_ui(ui_type, + on_ui_exit=None, + available_ui_types=None, + config=None): + """Create a `base_ui.BaseUI` subtype. + + This factory method attempts to fallback to other available ui_types on + ImportError. + + Args: + ui_type: (`str`) requested UI type. Currently supported: + ( readline) + on_ui_exit: (`Callable`) the callback to be called when the UI exits. + available_ui_types: (`None` or `list` of `str`) Manually-set available + ui_types. + config: An instance of `cli_config.CLIConfig()` carrying user-facing + configurations. + + Returns: + A `base_ui.BaseUI` subtype object. + + Raises: + ValueError: on invalid ui_type or on exhausting or fallback ui_types. + """ + if available_ui_types is None: + available_ui_types = copy.deepcopy(SUPPORTED_UI_TYPES) + + if ui_type and (ui_type not in available_ui_types): + raise ValueError("Invalid ui_type: '%s'" % ui_type) + + try: + # pylint: disable=g-import-not-at-top + if ui_type == "readline": + from tensorflow.python.debug.cli import readline_ui + return readline_ui.ReadlineUI(on_ui_exit=on_ui_exit, config=config) + # pylint: enable=g-import-not-at-top + except ImportError: + available_ui_types.remove(ui_type) + if not available_ui_types: + raise ValueError("Exhausted all fallback ui_types.") + return get_ui(available_ui_types[0], + available_ui_types=available_ui_types) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/check_numerics_callback.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/check_numerics_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..7c8b2e4e93466c4b0a8f271eb463b69b07c341b2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/check_numerics_callback.py @@ -0,0 +1,469 @@ +# 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. +# ============================================================================== +"""Eager-graph unified check numerics callback.""" + +import collections +import threading + +import numpy as np + +from tensorflow.core.protobuf import debug_event_pb2 +from tensorflow.python.debug.lib import op_callbacks_common +from tensorflow.python.debug.lib import source_utils +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_debug_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +# Many ops have benign NaN outputs, and running them with check_numerics +# on will create unwanted errors +# TODO(b/142497024): Replace this allowlist with function decorators in the ops +IGNORE_OP_OUTPUTS = ( + # For FusedBatchNorm, if the input tensor is empty then batch_mean and + # batch_variance will be NaN. reserve_space holds intermediate values + # derived from batch_mean and batch_variance used for gradient calculation + (b"FusedBatchNorm", 1), # batch_mean + (b"FusedBatchNorm", 2), # batch_variance + (b"FusedBatchNorm", 3), # reserve_space_1 + (b"FusedBatchNorm", 4), # reserve_space_2 + + # Same as above + (b"FusedBatchNormV2", 1), # batch_mean + (b"FusedBatchNormV2", 2), # batch_variance + (b"FusedBatchNormV2", 3), # reserve_space_1 + (b"FusedBatchNormV2", 4), # reserve_space_2 + + # Same as above, but reserve_space_3 holds additional intermediate values + (b"FusedBatchNormV3", 1), # batch_mean + (b"FusedBatchNormV3", 2), # batch_variance + (b"FusedBatchNormV3", 3), # reserve_space_1 + (b"FusedBatchNormV3", 4), # reserve_space_2 + (b"FusedBatchNormV3", 5), # reserve_space_3 +) + +# Some frequently used ops are generally safe and we can skip them to reduce +# overhead. NOTE: This list is compiled by observing operations called by +# models in practice and is not a comprehensive list of safe operations. +SAFE_OPS = ( + b"Concat", + b"ConcatV2", + b"ExpandDims", + b"Fill", + b"Gather", + b"Maximum", + b"Minimum", + b"Reshape", + b"Slice", + b"Squeeze", + b"Stack", + b"StridedSlice", + b"StridedSliceGrad", + b"TensorListConcatV2", + b"TensorListGather", + b"TensorListGetItem", + b"TensorListPopBack", + b"TensorListStack", + b"Transpose", + b"Unpack", +) + +_state = threading.local() + +_check_numerics_callback_create_counter = monitoring.Counter( + "/tensorflow/api/python/debugging/check_numerics_callback_create_counter", + "Counter for number of times the check_numerics op callback is created.") + + +def limit_string_length(string, max_len=50): + """Limit the length of input string. + + Args: + string: Input string. + max_len: (int or None) If int, the length limit. If None, no limit. + + Returns: + Possibly length-limited string. + """ + if max_len is None or len(string) <= max_len: + return string + else: + return "..." + string[len(string) - max_len:] + + +# A dictionary that supports looking up the original input tensor names. +_CHECK_NUMERICS_INPUT_LOOKUP = collections.defaultdict(dict) + + +def _maybe_lookup_original_input_tensor(graph, tensor): + if (graph and + graph in _CHECK_NUMERICS_INPUT_LOOKUP and + tensor.name in _CHECK_NUMERICS_INPUT_LOOKUP[graph]): + return _CHECK_NUMERICS_INPUT_LOOKUP[graph][tensor.name] + else: + return tensor + + +def get_check_numerics_error_message(slot, + num_outputs, + op_type, + tensor, + inputs, + graph=None, + traceback=None, + stack_height_limit=30, + path_length_limit=50): + """Create a meaningful and user-friendly error message about offending tensor. + + The error message reveals the following info about the op that outputs + NaN/Infinity: dtype, shape (to the extent known at graph-construction time), + input tensors, stack trace for op creation (if is graph mode). + + Args: + slot: (int) slot index of the tensor output. + num_outputs: (int) total number of outputs of the op. + op_type: (str) Type of the that generates `tensor`. + tensor: (Tensor) the offending tensor, i.e., the tensor that contains + Infinities or NaNs. + inputs: (array of Tensor) inputs to the op that generates `tensor`. + graph: (tf.Graph) the graph object that `tensor` belongs to. Available only + under graph mode. + traceback: (list of trace frames) the stack trace of the op's creation. + Available only under graph model. + stack_height_limit: (int or None) If int, limit to the height of the stack + trace printed in the error message. If None, no limit to the height. + path_length_limit: (int or None) Length limit for file paths included in the + formatted stack trace. + + Returns: + (str) A formatted error message. + """ + eager_vs_graph_qualifier = "graph" if graph else "eagerly-executing" + message = "\n" + message += ( + "\n!!! Detected Infinity or NaN in output %d of " + "%s op \"%s\" (# of outputs: %d) !!!\n" % + (slot, eager_vs_graph_qualifier, op_type, num_outputs)) + + message += " dtype: %s\n" % tensor.dtype + message += " shape: %s\n" % (tensor.shape,) + + if not graph: + # This is an eager tensor. We can get its numpy value and count + # NaNs and Infs. + is_inf = np.isinf(tensor) + + num_neg_inf = np.sum(np.logical_and(np.less(tensor, 0.), is_inf)) + num_pos_inf = np.sum(np.logical_and(np.greater(tensor, 0.), is_inf)) + num_nan = np.sum(np.isnan(tensor)) + if num_neg_inf > 0: + message += " # of -Inf elements: %s\n" % num_neg_inf + if num_pos_inf > 0: + message += " # of +Inf elements: %s\n" % num_pos_inf + if num_nan: + message += " # of +NaN elements: %s\n" % num_nan + + if len(inputs) > 1: + message += "\n Input tensors (%d):\n" % len(inputs) + for slot, input_tensor in enumerate(inputs): + message += " %d: %s\n" % ( + slot, _maybe_lookup_original_input_tensor(graph, input_tensor)) + elif len(inputs) == 1: + message += "\n Input tensor: %s\n" % ( + _maybe_lookup_original_input_tensor(graph, inputs[0])) + if graph and hasattr(graph, "name") and graph.name: + message += " Graph name: \"%s\"\n" % graph.name + + # Format the stack trace for the op's creation. We omit files that + # belong to tensorflow itself. + if graph and traceback: + message += ( + "\n Stack trace of op's creation (\"->\": inferred user code):\n") + if stack_height_limit is not None and len(traceback) > stack_height_limit: + num_omitted_frames = len(traceback) - stack_height_limit + message += " + ... (Omitted %d frames)\n" % num_omitted_frames + for filepath, lineno, function_name, source_line in traceback[ + -stack_height_limit:]: + user_code_indicator = " " + if not source_utils.guess_is_tensorflow_py_library(filepath): + user_code_indicator = " -> " + + message += " + %s (L%d) %s\n" % ( + limit_string_length(filepath, path_length_limit), lineno, + function_name) + if source_line is not None: + message += "%s| %s\n" % (user_code_indicator, source_line) + message += "\n" + return message + + +def _debug_summary(x): + return gen_debug_ops.debug_numeric_summary_v2( + x, + tensor_debug_mode=( + debug_event_pb2.TensorDebugMode.REDUCE_INF_NAN_THREE_SLOTS)) + + +class CheckNumericsCallback(object): + """Wrapper for the numerics-checking callback for thread locality.""" + + def __init__(self, stack_height_limit, path_length_limit): + self._stack_height_limit = stack_height_limit + self._path_length_limit = path_length_limit + # A dict mapping Placeholder tensors to their instrumenting debug tensors. + # Used only under V1 graph mode, where we can't rely on auto control + # dependency to execute the debug tensors and hence need to attach the debug + # tensors as control dependencies of the ops that consume the Placeholder. + self._placeholder_to_debug_tensor = ( + object_identity.ObjectIdentityDictionary()) + + def callback(self, + op_type, + inputs, + attrs, + outputs, + op_name=None, + graph=None): + """Eager-function unified callback for checking numerics.""" + del attrs, op_name # Unused + op_type_bytes = compat.as_bytes(op_type) + is_v1_graph_mode = not ops.executing_eagerly_outside_functions() + if (op_type_bytes in op_callbacks_common.OP_CALLBACK_SKIP_OPS or + op_type_bytes in SAFE_OPS): + return None + if graph: + # Under graph mode. Insert check_numerics op. + instrumented_outputs = [] + if is_v1_graph_mode: + for input_tensor in inputs: + if input_tensor in self._placeholder_to_debug_tensor and outputs: + outputs[0].op._add_control_input( # pylint: disable=protected-access + self._placeholder_to_debug_tensor[input_tensor].op) + for slot, output in enumerate(outputs): + if (output.dtype.is_floating and + (op_type_bytes, slot) not in IGNORE_OP_OUTPUTS): + checked_output = array_ops.check_numerics_v2( + # TF v2 has automatic control dependencies added to stateful async + # ops, which allows us to run check_numerics asynchronously. + # In the above case we use debug_summary to reduce all output + # tensors asynchronously from the op being checked and then + # process the tensor summary with check_numerics. + output if is_v1_graph_mode else _debug_summary(output), + get_check_numerics_error_message( + slot, + len(outputs), + op_type, + output, + inputs, + graph=graph, + traceback=output.op.traceback, + stack_height_limit=self._stack_height_limit, + path_length_limit=self._path_length_limit)) + _CHECK_NUMERICS_INPUT_LOOKUP[graph][checked_output.name] = output + instrumented_outputs.append(self._get_output_tensor( + op_type_bytes, output, checked_output, is_v1_graph_mode)) + else: + instrumented_outputs.append(output) + return instrumented_outputs + else: + if op_type_bytes == b"CheckNumericsV2": + # TODO(b/140334369): Remove this special casing logic once op_callback. + # automatically prevents infinite recursion in eager mode. + return None + # Under eager mode. Eagerly execute check_numerics op. + for slot, output in enumerate(outputs): + if (output.dtype.is_floating and + (op_type_bytes, slot) not in IGNORE_OP_OUTPUTS): + array_ops.check_numerics_v2( + output, + get_check_numerics_error_message( + slot, len(outputs), op_type, output, inputs, + stack_height_limit=self._stack_height_limit, + path_length_limit=self._path_length_limit)) + + def _get_output_tensor(self, + op_type, + tensor, + checked_tensor, + is_v1_graph_mode): + """Determine what tensor to output from callback. + + Args: + op_type: Type of the op that outputs the original symbolic tensor, as + `bytes`. + tensor: The original output symbolic tensor. + checked_tensor: The debugger-instrumented, numerics-checking tensor. + is_v1_graph_mode: Whether the debugged proggram is running under V1 graph + mode. + + Returns: + A symbolic tensor to be returned by the dumping op_callback. + """ + if is_v1_graph_mode: + # Placeholders need special treatment under V1 graph mode. The + # callback can't simply override the Placeholder tensor to the debug + # tensor, as that would cause the Placeholder op to lack a value. + # The debug tensor is remembered and will be attached as control + # inputs to ops that consumer the Placeholders later. + if op_type == b"Placeholder": + self._placeholder_to_debug_tensor[tensor] = checked_tensor + return tensor + else: + return checked_tensor + else: + # Under non-v1 graph mode, rely on auto control dependency to run the + # checked tensor. + return tensor + + +@tf_export("debugging.enable_check_numerics") +def enable_check_numerics(stack_height_limit=30, + path_length_limit=50): + r"""Enable tensor numerics checking in an eager/graph unified fashion. + + The numerics checking mechanism will cause any TensorFlow eager execution or + graph execution to error out as soon as an op's output tensor contains + infinity or NaN. + + This method is idempotent. Calling it multiple times has the same effect + as calling it once. + + This method takes effect only on the thread in which it is called. + + When a op's float-type output tensor contains any Infinity or NaN, an + `tf.errors.InvalidArgumentError` will be thrown, with an error message that + reveals the following information: + - The type of the op that generated the tensor with bad numerics. + - Data type (dtype) of the tensor. + - Shape of the tensor (to the extent known at the time of eager execution + or graph construction). + - Name of the containing graph (if available). + - (Graph mode only): The stack trace of the intra-graph op's creation, + with a stack-height limit and a path-length limit for visual clarity. + The stack frames that belong to the user's code (as opposed to + tensorflow's internal code) are highlighted with a text arrow ("->"). + - (Eager mode only): How many of the offending tensor's elements are + `Infinity` and `NaN`, respectively. + + Once enabled, the check-numerics mechanism can be disabled by using + `tf.debugging.disable_check_numerics()`. + + Example usage: + + 1. Catching infinity during the execution of a `tf.function` graph: + + ```py + import tensorflow as tf + + tf.debugging.enable_check_numerics() + + @tf.function + def square_log_x_plus_1(x): + v = tf.math.log(x + 1) + return tf.math.square(v) + + x = -1.0 + + # When the following line runs, a function graph will be compiled + # from the Python function `square_log_x_plus_1()`. Due to the + # `enable_check_numerics()` call above, the graph will contain + # numerics checking ops that will run during the function graph's + # execution. The function call generates an -infinity when the Log + # (logarithm) op operates on the output tensor of the Add op. + # The program errors out at this line, printing an error message. + y = square_log_x_plus_1(x) + z = -y + ``` + + 2. Catching NaN during eager execution: + + ```py + import numpy as np + import tensorflow as tf + + tf.debugging.enable_check_numerics() + + x = np.array([[0.0, -1.0], [4.0, 3.0]]) + + # The following line executes the Sqrt op eagerly. Due to the negative + # element in the input array, a NaN is generated. Due to the + # `enable_check_numerics()` call above, the program errors immediately + # at this line, printing an error message. + y = tf.math.sqrt(x) + z = tf.matmul(y, y) + ``` + + NOTE: If your code is running on TPUs, be sure to call + `tf.config.set_soft_device_placement(True)` before calling + `tf.debugging.enable_check_numerics()` as this API uses automatic outside + compilation on TPUs. For example: + + ```py + tf.config.set_soft_device_placement(True) + tf.debugging.enable_check_numerics() + + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + strategy = tf.distribute.TPUStrategy(resolver) + with strategy.scope(): + # ... + ``` + + Args: + stack_height_limit: Limit to the height of the printed stack trace. + Applicable only to ops in `tf.function`s (graphs). + path_length_limit: Limit to the file path included in the printed stack + trace. Applicable only to ops in `tf.function`s (graphs). + """ + if not hasattr(_state, "check_numerics_callback"): + _state.check_numerics_callback = CheckNumericsCallback( + stack_height_limit, path_length_limit) + op_callbacks.add_op_callback(_state.check_numerics_callback.callback) + + logging.info( + "Enabled check-numerics callback in thread %s", + threading.current_thread().name) + _check_numerics_callback_create_counter.get_cell().increase_by(1) + + +@tf_export("debugging.disable_check_numerics") +def disable_check_numerics(): + """Disable the eager/graph unified numerics checking mechanism. + + This method can be used after a call to `tf.debugging.enable_check_numerics()` + to disable the numerics-checking mechanism that catches infinity and NaN + values output by ops executed eagerly or in tf.function-compiled graphs. + + This method is idempotent. Calling it multiple times has the same effect + as calling it once. + + This method takes effect only on the thread in which it is called. + """ + if not hasattr(_state, "check_numerics_callback"): + return + try: + op_callbacks.remove_op_callback(_state.check_numerics_callback.callback) + delattr(_state, "check_numerics_callback") + logging.info( + "Disabled check-numerics callback in thread %s", + threading.current_thread().name) + except KeyError: + # Tolerate disabling the check numerics callback without + # enable_check_numerics() being called first. + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/common.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/common.py new file mode 100644 index 0000000000000000000000000000000000000000..98618abba1b3b3a5380f957a97da075f8eb02f29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/common.py @@ -0,0 +1,83 @@ +# 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. +# ============================================================================== +"""Common values and methods for TensorFlow Debugger.""" +import collections +import json + +GRPC_URL_PREFIX = "grpc://" + +# A key for a Session.run() call. +RunKey = collections.namedtuple("RunKey", ["feed_names", "fetch_names"]) + + +def get_graph_element_name(elem): + """Obtain the name or string representation of a graph element. + + If the graph element has the attribute "name", return name. Otherwise, return + a __str__ representation of the graph element. Certain graph elements, such as + `SparseTensor`s, do not have the attribute "name". + + Args: + elem: The graph element in question. + + Returns: + If the attribute 'name' is available, return the name. Otherwise, return + str(fetch). + """ + + return elem.name if hasattr(elem, "name") else str(elem) + + +def get_flattened_names(feeds_or_fetches): + """Get a flattened list of the names in run() call feeds or fetches. + + Args: + feeds_or_fetches: Feeds or fetches of the `Session.run()` call. It maybe + a Tensor, an Operation or a Variable. It may also be nested lists, tuples + or dicts. See doc of `Session.run()` for more details. + + Returns: + (list of str) A flattened list of fetch names from `feeds_or_fetches`. + """ + + lines = [] + if isinstance(feeds_or_fetches, (list, tuple)): + for item in feeds_or_fetches: + lines.extend(get_flattened_names(item)) + elif isinstance(feeds_or_fetches, dict): + for key in feeds_or_fetches: + lines.extend(get_flattened_names(feeds_or_fetches[key])) + else: + # This ought to be a Tensor, an Operation or a Variable, for which the name + # attribute should be available. (Bottom-out condition of the recursion.) + lines.append(get_graph_element_name(feeds_or_fetches)) + + return lines + + +def get_run_key(feed_dict, fetches): + """Summarize the names of feeds and fetches as a RunKey JSON string. + + Args: + feed_dict: The feed_dict given to the `Session.run()` call. + fetches: The fetches from the `Session.run()` call. + + Returns: + A JSON Array consisting of two items. They first items is a flattened + Array of the names of the feeds. The second item is a flattened Array of + the names of the fetches. + """ + return json.dumps(RunKey(get_flattened_names(feed_dict), + get_flattened_names(fetches))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_data.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2269fa6e65b068d8171ffda07ed4328eeba087c8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_data.py @@ -0,0 +1,1620 @@ +# 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 and functions to handle debug-dump data of TensorFlow Debugger.""" + +import collections +import glob +import json +import os +import platform +import re + +import numpy as np + +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import types_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.debug.lib import debug_graphs +from tensorflow.python.framework import tensor_util +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat + + +# TODO(cais): Tie these string constants in with C++? +METADATA_FILE_PREFIX = "_tfdbg_" +CORE_METADATA_TAG = "core_metadata_" +GRAPH_FILE_TAG = "graph_" +DEVICE_TAG = "device_" +HASH_TAG = "hash" + +FETCHES_INFO_FILE_TAG = "fetches_info_" +FEED_KEYS_INFO_FILE_TAG = "feed_keys_info_" + + +def _glob(glob_pattern): + if platform.system() == "Windows": + return glob.glob(glob_pattern) + else: + return gfile.Glob(glob_pattern) + + +class InconvertibleTensorProto: + """Represents a TensorProto that cannot be converted to np.ndarray.""" + + def __init__(self, tensor_proto, initialized=True): + """Constructor. + + Args: + tensor_proto: the `TensorProto` object that cannot be represented as a + `np.ndarray` object. + initialized: (`bool`) whether the Tensor is initialized. + """ + self._tensor_proto = tensor_proto + self._initialized = initialized + + def __str__(self): + output = "" if self._initialized else "Uninitialized tensor:\n" + output += str(self._tensor_proto) + return output + + @property + def initialized(self): + return self._initialized + + +def load_tensor_from_event_file(event_file_path): + """Load a tensor from an event file. + + Assumes that the event file contains a `Event` protobuf and the `Event` + protobuf contains a `Tensor` value. + + Args: + event_file_path: (`str`) path to the event file. + + Returns: + The tensor value loaded from the event file, as a `numpy.ndarray`. For + uninitialized Tensors, returns `None`. For Tensors of data types that + cannot be converted to `numpy.ndarray` (e.g., `tf.resource`), return + `None`. + """ + + event = event_pb2.Event() + with gfile.Open(event_file_path, "rb") as f: + event.ParseFromString(f.read()) + return load_tensor_from_event(event) + + +def load_tensor_from_event(event): + """Load a tensor from an Event proto. + + Args: + event: The Event proto, assumed to hold a tensor value in its + summary.value[0] field. + + Returns: + The tensor value loaded from the event file, as a `numpy.ndarray`, if + representation of the tensor value by a `numpy.ndarray` is possible. + For uninitialized Tensors, returns `None`. For Tensors of data types that + cannot be represented as `numpy.ndarray` (e.g., `tf.resource`), return + the `TensorProto` protobuf object without converting it to a + `numpy.ndarray`. + """ + + tensor_proto = event.summary.value[0].tensor + shape = tensor_util.TensorShapeProtoToList(tensor_proto.tensor_shape) + num_elements = 1 + for shape_dim in shape: + num_elements *= shape_dim + + if tensor_proto.tensor_content or tensor_proto.string_val or not num_elements: + # Initialized tensor or empty tensor. + if tensor_proto.dtype == types_pb2.DT_RESOURCE: + tensor_value = InconvertibleTensorProto(tensor_proto) + else: + try: + tensor_value = tensor_util.MakeNdarray(tensor_proto) + except KeyError: + tensor_value = InconvertibleTensorProto(tensor_proto) + else: + # Uninitialized tensor or tensor of unconvertible data type. + tensor_value = InconvertibleTensorProto(tensor_proto, False) + + return tensor_value + + +def _load_graph_def_from_event_file(event_file_path): + event = event_pb2.Event() + with gfile.Open(event_file_path, "rb") as f: + event.ParseFromString(f.read()) + + return graph_pb2.GraphDef.FromString(event.graph_def) + + +def _load_log_message_from_event_file(event_file_path): + event = event_pb2.Event() + with gfile.Open(event_file_path, "rb") as f: + event.ParseFromString(f.read()) + + return event.log_message.message + + +def _is_graph_file(file_name): + return file_name.startswith(METADATA_FILE_PREFIX + GRAPH_FILE_TAG) + + +def _is_run_fetches_info_file(file_name): + return file_name == METADATA_FILE_PREFIX + FETCHES_INFO_FILE_TAG + + +def _is_run_feed_keys_info_file(file_name): + return file_name == METADATA_FILE_PREFIX + FEED_KEYS_INFO_FILE_TAG + + +def _get_tensor_name(node_name, output_slot): + """Get tensor name given node name and output slot index. + + Args: + node_name: Name of the node that outputs the tensor, as a string. + output_slot: Output slot index of the tensor, as an integer. + + Returns: + Name of the tensor, as a string. + """ + + return "%s:%d" % (node_name, output_slot) + + +def _get_tensor_watch_key(node_name, output_slot, debug_op): + """Get the string representation of a debug watch on a tensor. + + Args: + node_name: Name of the node by which the watched tensor is produced, as a + string. + output_slot: Output slot index of the tensor, as an integer. + debug_op: Name of the debug op that is used to watch the tensor, as a + string. + + Returns: + A string representing the debug watch on the tensor (i.e., the "watch + key"). + """ + return "%s:%s" % (_get_tensor_name(node_name, output_slot), debug_op) + + +def has_inf_or_nan(datum, tensor): + """A predicate for whether a tensor consists of any bad numerical values. + + This predicate is common enough to merit definition in this module. + Bad numerical values include `nan`s and `inf`s. + The signature of this function follows the requirement of the method + `DebugDumpDir.find()`. + + Args: + datum: (`DebugTensorDatum`) Datum metadata. + tensor: (`numpy.ndarray` or None) Value of the tensor. None represents + an uninitialized tensor. + + Returns: + (`bool`) True if and only if tensor consists of any nan or inf values. + """ + + _ = datum # Datum metadata is unused in this predicate. + + if isinstance(tensor, InconvertibleTensorProto): + # Uninitialized tensor doesn't have bad numerical values. + # Also return False for data types that cannot be represented as numpy + # arrays. + return False + elif (np.issubdtype(tensor.dtype, np.floating) or + np.issubdtype(tensor.dtype, np.complexfloating) or + np.issubdtype(tensor.dtype, np.integer)): + return np.any(np.isnan(tensor)) or np.any(np.isinf(tensor)) + else: + return False + + +_CoreMetadata = collections.namedtuple("CoreMetadata", [ + "global_step", "session_run_index", "executor_step_index", "input_names", + "output_names", "target_nodes" +]) + + +def extract_core_metadata_from_event_proto(event): + json_metadata = json.loads(event.log_message.message) + return _CoreMetadata(json_metadata["global_step"], + json_metadata["session_run_index"], + json_metadata["executor_step_index"], + json_metadata["input_names"], + json_metadata["output_names"], + json_metadata["target_nodes"]) + + +def device_name_to_device_path(device_name): + """Convert device name to device path.""" + device_name_items = compat.as_text(device_name).split("/") + device_name_items = [item.replace(":", "_") for item in device_name_items] + return METADATA_FILE_PREFIX + DEVICE_TAG + ",".join(device_name_items) + + +def device_path_to_device_name(device_dir): + """Parse device name from device path. + + Args: + device_dir: (str) a directory name for the device. + + Returns: + (str) parsed device name. + """ + path_items = os.path.basename(device_dir)[ + len(METADATA_FILE_PREFIX) + len(DEVICE_TAG):].split(",") + return "/".join([ + path_item.replace("device_", "device:").replace("_", ":", 1) + for path_item in path_items]) + + +class DebugTensorDatum: + """A single tensor dumped by TensorFlow Debugger (tfdbg). + + Contains metadata about the dumped tensor, including `timestamp`, + `node_name`, `output_slot`, `debug_op`, and path to the dump file + (`file_path`). + + This type does not hold the generally space-expensive tensor value (numpy + array). Instead, it points to the file from which the tensor value can be + loaded (with the `get_tensor` method) if needed. + """ + + def __init__(self, dump_root, debug_dump_rel_path): + """`DebugTensorDatum` constructor. + + Args: + dump_root: (`str`) Debug dump root directory. This path should not include + the path component that represents the device name (see also below). + debug_dump_rel_path: (`str`) Path to a debug dump file, relative to the + `dump_root`. The first item of this relative path is assumed to be + a path representing the name of the device that the Tensor belongs to. + See `device_path_to_device_name` for more details on the device path. + For example, suppose the debug dump root + directory is `/tmp/tfdbg_1` and the dump file is at + `/tmp/tfdbg_1//>ns_1/node_a_0_DebugIdentity_123456789`, + then the value of the debug_dump_rel_path should be + `/ns_1/node_a_0_DebugIdentity_1234456789`. + + Raises: + ValueError: If the base file name of the dump file does not conform to + the dump file naming pattern: + `node_name`_`output_slot`_`debug_op`_`timestamp` + """ + + path_components = os.path.normpath(debug_dump_rel_path).split(os.sep) + self._device_name = device_path_to_device_name(path_components[0]) + base = path_components[-1] + if base.count("_") < 3: + raise ValueError( + "Dump file path does not conform to the naming pattern: %s" % base) + + self._extended_timestamp = base.split("_")[-1] + # It may include an index suffix at the end if file path collision happened + # due to identical timestamps. + if "-" in self._extended_timestamp: + self._timestamp = int( + self._extended_timestamp[:self._extended_timestamp.find("-")]) + else: + self._timestamp = int(self._extended_timestamp) + + self._debug_op = base.split("_")[-2] + self._output_slot = int(base.split("_")[-3]) + + node_base_name = "_".join(base.split("_")[:-3]) + self._node_name = "/".join(path_components[1:-1] + [node_base_name]) + + self._file_path = os.path.join(dump_root, debug_dump_rel_path) + self._dump_size_bytes = (gfile.Stat(self._file_path).length if + gfile.Exists(self._file_path) else None) + + def __str__(self): + return "{DebugTensorDatum (%s) %s:%d @ %s @ %d}" % (self.device_name, + self.node_name, + self.output_slot, + self.debug_op, + self.timestamp) + + def __repr__(self): + return self.__str__() + + def get_tensor(self): + """Get tensor from the dump (`Event`) file. + + Returns: + The tensor loaded from the dump (`Event`) file. + """ + + return load_tensor_from_event_file(self.file_path) + + # TODO(cais): Add time unit suffix to timestamp and t0 (us). + @property + def timestamp(self): + """Timestamp of when this tensor value was dumped. + + Returns: + (`int`) The timestamp in microseconds. + """ + + return self._timestamp + + @property + def extended_timestamp(self): + """Extended timestamp, possibly with an index suffix. + + The index suffix, e.g., "-1", is for disambiguating multiple dumps of the + same tensor with the same timestamp, which can occur if the dumping events + are spaced by shorter than the temporal resolution of the timestamps. + + Returns: + (`str`) The extended timestamp. + """ + + return self._extended_timestamp + + @property + def debug_op(self): + """Name of the debug op. + + Returns: + (`str`) debug op name (e.g., `DebugIdentity`). + """ + + return self._debug_op + + @property + def device_name(self): + """Name of the device that the tensor belongs to. + + Returns: + (`str`) device name. + """ + + return self._device_name + + @property + def node_name(self): + """Name of the node from which the tensor value was dumped. + + Returns: + (`str`) name of the node watched by the debug op. + """ + + return self._node_name + + @property + def output_slot(self): + """Output slot index from which the tensor value was dumped. + + Returns: + (`int`) output slot index watched by the debug op. + """ + + return self._output_slot + + @property + def tensor_name(self): + """Name of the tensor watched by the debug op. + + Returns: + (`str`) `Tensor` name, in the form of `node_name`:`output_slot` + """ + + return _get_tensor_name(self.node_name, self.output_slot) + + @property + def watch_key(self): + """Watch key identities a debug watch on a tensor. + + Returns: + (`str`) A watch key, in the form of `tensor_name`:`debug_op`. + """ + + return _get_tensor_watch_key(self.node_name, self.output_slot, + self.debug_op) + + @property + def file_path(self): + """Path to the file which stores the value of the dumped tensor.""" + + return self._file_path + + @property + def dump_size_bytes(self): + """Size of the dump file. + + Unit: byte. + + Returns: + If the dump file exists, size of the dump file, in bytes. + If the dump file does not exist, None. + """ + + return self._dump_size_bytes + + +class WatchKeyDoesNotExistInDebugDumpDirError(ValueError): + pass + + +class DebugDumpDir: + """Data set from a debug-dump directory on filesystem. + + An instance of `DebugDumpDir` contains all `DebugTensorDatum` instances + in a tfdbg dump root directory. + """ + + def __init__(self, dump_root, partition_graphs=None, validate=True): + """`DebugDumpDir` constructor. + + Args: + dump_root: (`str`) path to the dump root directory. + partition_graphs: A repeated field of GraphDefs representing the + partition graphs executed by the TensorFlow runtime. + validate: (`bool`) whether the dump files are to be validated against the + partition graphs. + + Raises: + IOError: If dump_root does not exist as a directory. + ValueError: If more than one core metadata file is found under the dump + root directory. + """ + + if not gfile.IsDirectory(dump_root): + raise IOError("Dump root directory %s does not exist" % dump_root) + + self._core_metadata = [] + + # Find the list of devices. + self._dump_root = dump_root + + self._load_core_metadata() + self._load_fetches_info() + self._load_feeds_info() + self._load_all_device_dumps(partition_graphs, validate) + + self._python_graph = None + + def _load_all_device_dumps(self, partition_graphs, validate): + """Load the dump data for all devices.""" + device_dirs = _glob(os.path.join( + self._dump_root, METADATA_FILE_PREFIX + DEVICE_TAG + "*")) + + self._device_names = [] + self._t0s = {} + self._dump_tensor_data = {} + self._dump_graph_file_paths = {} + self._debug_watches = {} + self._watch_key_to_devices = {} + self._watch_key_to_datum = {} + self._watch_key_to_rel_time = {} + self._watch_key_to_dump_size_bytes = {} + for device_dir in device_dirs: + device_name = device_path_to_device_name(device_dir) + self._device_names.append(device_name) + self._load_device_dumps(device_name, device_dir) + self._load_partition_graphs(partition_graphs, validate) + self._calculate_t0() + + for device_name in self._device_names: + self._create_tensor_watch_maps(device_name) + + def _load_device_dumps(self, device_name, device_root): + """Load `DebugTensorDatum` instances from the dump root of a given device. + + Populates a map {device_name: a list of `DebugTensorDatum`}, where the list + is sorted by ascending timestamp. + + This sorting order reflects the order in which the TensorFlow executor + processed the nodes of the graph. It is (one of many possible) topological + sort of the nodes. This is useful for displaying tensors in the debugger + frontend as well as for the use case in which the user wants to find a + "culprit tensor", i.e., the first tensor in the graph that exhibits certain + problematic properties, i.e., all zero values, or bad numerical values such + as nan and inf. + + In addition, creates a map from node name to debug watches. In this Map, + the key is the watched node name; the value is a dictionary. + Of this dictionary, the key is the watched_output_slot. + + This method attempts to load the debug watches from the tensor dump files + first, before loading the full set of debug watches from the partition + graphs as done later. This is necessary because sometimes the partition + graphs may not be available, e.g., when the run errors out. + + Args: + device_name: (`str`) name of the device. + device_root: (`str`) dump root directory of the given device. + + Raises: + ValueError: If GraphDef for the device is not available. + """ + + self._dump_tensor_data[device_name] = [] + self._debug_watches[device_name] = collections.defaultdict( + lambda: collections.defaultdict(set)) + + for root, _, files in gfile.Walk(device_root): + for f in files: + if _is_graph_file(f): + self._dump_graph_file_paths[device_name] = os.path.join(root, f) + else: + datum = self._dump_file_name_to_datum(root, f) + self._dump_tensor_data[device_name].append(datum) + self._debug_watches[device_name][datum.node_name][ + datum.output_slot].add(datum.debug_op) + + self._dump_tensor_data[device_name] = sorted( + self._dump_tensor_data[device_name], + key=lambda x: x.extended_timestamp) + + if self._dump_tensor_data[device_name]: + self._t0s[device_name] = self._dump_tensor_data[device_name][0].timestamp + else: + self._t0s[device_name] = None + + def _calculate_t0(self): + """Calculate the first timestamp across all devices.""" + t0s = [t0 for t0 in self._t0s.values() if t0 is not None] + self._t0 = min(t0s) if t0s else None + + def _load_core_metadata(self): + core_metadata_files = _glob(os.path.join( + self._dump_root, METADATA_FILE_PREFIX + CORE_METADATA_TAG + "*")) + for core_metadata_file in core_metadata_files: + with gfile.Open(core_metadata_file, "rb") as f: + event = event_pb2.Event() + event.ParseFromString(f.read()) + self._core_metadata.append( + extract_core_metadata_from_event_proto(event)) + + def _load_fetches_info(self): + fetches_info_files = _glob(os.path.join( + self._dump_root, METADATA_FILE_PREFIX + FETCHES_INFO_FILE_TAG + "*")) + self._run_fetches_info = [] + for fetches_info_file in fetches_info_files: + self._run_fetches_info.append( + _load_log_message_from_event_file(fetches_info_file)) + + def _load_feeds_info(self): + feeds_info_files = _glob(os.path.join( + self._dump_root, METADATA_FILE_PREFIX + FEED_KEYS_INFO_FILE_TAG + "*")) + self._run_feed_keys_info = [] + for feeds_info_file in feeds_info_files: + self._run_feed_keys_info.append( + _load_log_message_from_event_file(feeds_info_file)) + + def _dump_file_name_to_datum(self, dir_name, file_name): + """Obtain a DebugTensorDatum from the directory and file name. + + Args: + dir_name: (`str`) Name of the directory in which the dump file resides. + file_name: (`str`) Base name of the dump file. + + Returns: + (`DebugTensorDatum`) The `DebugTensorDatum` loaded from the dump file. + """ + + # Calculate the relative path of the dump file with respect to the root. + debug_dump_rel_path = os.path.join( + os.path.relpath(dir_name, self._dump_root), file_name) + return DebugTensorDatum(self._dump_root, debug_dump_rel_path) + + def _create_tensor_watch_maps(self, device_name): + """Create maps from tensor watch keys to datum and to timestamps. + + Create a map from watch key (tensor name + debug op) to `DebugTensorDatum` + item. Also make a map from watch key to relative timestamp. + "relative" means (absolute timestamp - t0). + + Args: + device_name: (str) name of the device. + """ + + self._watch_key_to_datum[device_name] = {} + self._watch_key_to_rel_time[device_name] = {} + self._watch_key_to_dump_size_bytes[device_name] = {} + for datum in self._dump_tensor_data[device_name]: + if datum.watch_key not in self._watch_key_to_devices: + self._watch_key_to_devices[datum.watch_key] = {device_name} + else: + self._watch_key_to_devices[datum.watch_key].add(device_name) + + if datum.watch_key not in self._watch_key_to_datum[device_name]: + self._watch_key_to_datum[device_name][datum.watch_key] = [datum] + self._watch_key_to_rel_time[device_name][datum.watch_key] = [ + datum.timestamp - self._t0] + self._watch_key_to_dump_size_bytes[device_name][datum.watch_key] = [ + datum.dump_size_bytes] + else: + self._watch_key_to_datum[device_name][datum.watch_key].append(datum) + self._watch_key_to_rel_time[device_name][datum.watch_key].append( + datum.timestamp - self._t0) + self._watch_key_to_dump_size_bytes[device_name][datum.watch_key].append( + datum.dump_size_bytes) + + def set_python_graph(self, python_graph): + """Provide Python `Graph` object to the wrapper. + + Unlike the partition graphs, which are protobuf `GraphDef` objects, `Graph` + is a Python object and carries additional information such as the traceback + of the construction of the nodes in the graph. + + Args: + python_graph: (ops.Graph) The Python Graph object. + """ + + self._python_graph = python_graph + self._node_traceback = {} + if self._python_graph: + for op in self._python_graph.get_operations(): + self._node_traceback[op.name] = tuple(map(tuple, op.traceback)) + + @property + def python_graph(self): + """Get the Python graph. + + Returns: + If the Python graph has been set, returns a `tf.Graph` object. Otherwise, + returns None. + """ + + return self._python_graph + + @property + def core_metadata(self): + """Metadata about the `Session.run()` call from the core runtime. + + Of the three counters available in the return value, `global_step` is + supplied by the caller of the debugged `Session.run()`, while + `session_run_index` and `executor_step_index` are determined by the state + of the core runtime, automatically. For the same fetch list, feed keys and + debug tensor watch options, the same executor will be used and + `executor_step_index` should increase by one at a time. However, runs with + different fetch lists, feed keys and debug_tensor watch options that all + share the same `Session` object can lead to gaps in `session_run_index`. + + Returns: + If core metadata are loaded, a `namedtuple` with the fields: + `global_step`: A global step count supplied by the caller of + `Session.run()`. It is optional to the caller. If the caller did not + supply this parameter, its value will be -1. + `session_run_index`: A sorted index for Run() calls to the underlying + TensorFlow `Session` object. + `executor_step_index`: A counter for invocations of a given runtime + executor. The same executor is re-used for the same fetched tensors, + target nodes, input feed keys and debug tensor watch options. + `input_names`: Names of the input (feed) Tensors. + `output_names`: Names of the output (fetched) Tensors. + `target_nodes`: Names of the target nodes. + If the core metadata have not been loaded, `None`. + If more than one core metadata files exist, return a list of the + `nametuple` described above. + """ + + output = self._core_metadata + return output[0] if len(output) == 1 else output + + @property + def dumped_tensor_data(self): + """Retrieve dumped tensor data.""" + if len(self.devices()) == 1: + return self._dump_tensor_data[self.devices()[0]] + else: + all_devices_data = self._dump_tensor_data.values() + data = [] + for device_data in all_devices_data: + data.extend(device_data) + return sorted(data, key=lambda x: x.extended_timestamp) + + @property + def t0(self): + """Absolute timestamp of the first dumped tensor across all devices. + + Returns: + (`int`) absolute timestamp of the first dumped tensor, in microseconds. + """ + return self._t0 + + @property + def size(self): + """Total number of dumped tensors in the dump root directory. + + Returns: + (`int`) The total number of dumped tensors in the dump root directory. + """ + return sum(len(self._dump_tensor_data[device_name]) + for device_name in self._dump_tensor_data) + + def _load_partition_graphs(self, client_partition_graphs, validate): + """Load and process partition graphs. + + Load the graphs; parse the input and control input structure; obtain the + device and op type of each node; remove the Copy and debug ops inserted + by the debugger. The gathered information can be used to validate the + tensor dumps. + + Args: + client_partition_graphs: A repeated field of GraphDefs representing the + partition graphs executed by the TensorFlow runtime, from the Python + client. These partition graphs are used only if partition graphs + cannot be loaded from the dump directory on the file system. + validate: (`bool`) Whether the dump files are to be validated against the + partition graphs. + + Raises: + ValueError: If the partition GraphDef of one or more devices fail to be + loaded. + """ + self._debug_graphs = {} + self._node_devices = {} + + partition_graphs_and_device_names = [] + for device_name in self._device_names: + partition_graph = None + if device_name in self._dump_graph_file_paths: + partition_graph = _load_graph_def_from_event_file( + self._dump_graph_file_paths[device_name]) + else: + logging.warn( + "Failed to load partition graphs for device %s from disk. " + "As a fallback, the client graphs will be used. This " + "may cause mismatches in device names." % device_name) + partition_graph = self._find_partition_graph(client_partition_graphs, + device_name) + + if partition_graph: + partition_graphs_and_device_names.append((partition_graph, + device_name)) + + for partition_graph, maybe_device_name in partition_graphs_and_device_names: + debug_graph = debug_graphs.DebugGraph(partition_graph, + device_name=maybe_device_name) + self._debug_graphs[debug_graph.device_name] = debug_graph + self._collect_node_devices(debug_graph) + + if validate and debug_graph.device_name in self._dump_tensor_data: + self._validate_dump_with_graphs(debug_graph.device_name) + + def _find_partition_graph(self, partition_graphs, device_name): + if partition_graphs is None: + return None + else: + for graph_def in partition_graphs: + for node_def in graph_def.node: + if node_def.device == device_name: + return graph_def + return None + + def _collect_node_devices(self, debug_graph): + for node_name in debug_graph.node_devices: + if node_name in self._node_devices: + self._node_devices[node_name] = self._node_devices[node_name].union( + debug_graph.node_devices[node_name]) + else: + self._node_devices[node_name] = debug_graph.node_devices[node_name] + + def _validate_dump_with_graphs(self, device_name): + """Validate the dumped tensor data against the partition graphs. + + Only the watched nodes are validated by this method, because tfdbg allows + clients to watch only a subset of the nodes. + + Args: + device_name: (`str`) device name. + + Raises: + LookupError: If the partition graphs have not been loaded yet. + ValueError: If dumps contain node names not found in partition graph. + Or if the temporal order of the dump's timestamps violate the + input relations on the partition graphs. + """ + if not self._debug_graphs: + raise LookupError( + "No partition graphs loaded for device %s" % device_name) + debug_graph = self._debug_graphs[device_name] + + # Verify that the node names in the dump data are all present in the + # partition graphs. + for datum in self._dump_tensor_data[device_name]: + if datum.node_name not in debug_graph.node_inputs: + raise ValueError("Node name '%s' is not found in partition graphs of " + "device %s." % (datum.node_name, device_name)) + + pending_inputs = {} + for node in debug_graph.node_inputs: + pending_inputs[node] = [] + inputs = debug_graph.node_inputs[node] + for inp in inputs: + inp_node = debug_graphs.get_node_name(inp) + inp_output_slot = debug_graphs.get_output_slot(inp) + # Inputs from Enter and NextIteration nodes are not validated because + # DebugNodeInserter::InsertNodes() in the debugger core skips creating + # control edges from debug ops watching these types of nodes. + if (inp_node in self._debug_watches[device_name] and + inp_output_slot in self._debug_watches[device_name][inp_node] and + debug_graph.node_op_types.get(inp) not in ( + "Enter", "NextIteration") and + (inp_node, inp_output_slot) not in pending_inputs[node]): + pending_inputs[node].append((inp_node, inp_output_slot)) + + for i, datum in enumerate(self._dump_tensor_data[device_name]): + node = datum.node_name + slot = datum.output_slot + # In some cases (e.g., system clocks with insufficient precision), + # the upstream and downstream tensors may have identical timestamps, the + # following check examines this possibility and avoids raising an error if + # that is the case. + if not self._satisfied_at_timestamp( + device_name, pending_inputs[node], datum.timestamp, start_i=i + 1): + raise ValueError("Causality violated in timing relations of debug " + "dumps: %s (%d): " + "these input(s) are not satisfied: %s" % + (node, datum.timestamp, repr(pending_inputs[node]))) + + recipients = debug_graph.node_recipients[node] + for recipient in recipients: + recipient_pending_inputs = pending_inputs[recipient] + if (node, slot) in recipient_pending_inputs: + if self.node_op_type(recipient) == "Merge": + # If this is a Merge op, we automatically clear the list because + # a Merge node only requires one of its two inputs. + del recipient_pending_inputs[:] + else: + del recipient_pending_inputs[ + recipient_pending_inputs.index((node, slot))] + + def _satisfied_at_timestamp(self, device_name, pending, timestamp, start_i=0): + """Determine whether pending inputs are satisfied at given timestamp. + + Note: This method mutates the input argument "pending". + + Args: + device_name: (str) device name. + pending: A list of 2-tuple (node_name, output_slot): the dependencies to + check. + timestamp: (int) the timestamp in question. + start_i: (int) the index in self._dump_tensor_data to start searching for + the timestamp. + + Returns: + (bool) Whether all the dependencies in pending are satisfied at the + timestamp. If pending is empty to begin with, return True. + """ + if not pending: + return True + + for datum in self._dump_tensor_data[device_name][start_i:]: + if datum.timestamp > timestamp: + break + if (datum.timestamp == timestamp and + (datum.node_name, datum.output_slot) in pending): + pending.remove((datum.node_name, datum.output_slot)) + if not pending: + return True + + return not pending + + def loaded_partition_graphs(self): + """Test whether partition graphs have been loaded.""" + return bool(self._debug_graphs) + + def partition_graphs(self): + """Get the partition graphs. + + Returns: + Partition graphs as a list of GraphDef. + + Raises: + LookupError: If no partition graphs have been loaded. + """ + if not self._debug_graphs: + raise LookupError("No partition graphs have been loaded.") + return [self._debug_graphs[key].debug_graph_def + for key in self._debug_graphs] + + def reconstructed_non_debug_partition_graphs(self): + """Reconstruct partition graphs with the debugger-inserted ops stripped. + + The reconstructed partition graphs are identical to the original (i.e., + non-debugger-decorated) partition graphs except in the following respects: + 1) The exact names of the runtime-inserted internal nodes may differ. + These include _Send, _Recv, _HostSend, _HostRecv, _Retval ops. + 2) As a consequence of 1, the nodes that receive input directly from such + send- and recv-type ops will have different input names. + 3) The parallel_iteration attribute of while-loop Enter ops are set to 1. + + Returns: + A dict mapping device names (`str`s) to reconstructed + `tf.compat.v1.GraphDef`s. + """ + non_debug_graphs = {} + for key in self._debug_graphs: + non_debug_graphs[key] = self._debug_graphs[key].non_debug_graph_def + return non_debug_graphs + + @property + def run_fetches_info(self): + """Get a str representation of the fetches used in the Session.run() call. + + Returns: + If the information is available from one `Session.run` call, a `str` + obtained from `repr(fetches)`. + If the information is available from multiple `Session.run` calls, a + `list` of `str` from `repr(fetches)`. + If the information is not available, `None`. + """ + + output = self._run_fetches_info + return output[0] if len(output) == 1 else output + + @property + def run_feed_keys_info(self): + """Get a str representation of the feed_dict used in the Session.run() call. + + Returns: + If the information is available from one `Session.run` call, a `str` + obtained from `repr(feed_dict)`. + If the information is available from multiple `Session.run` calls, a + `list` of `str` obtained from `repr(feed_dict)`. + If the information is not available, `None`. + """ + + output = self._run_feed_keys_info + return output[0] if len(output) == 1 else output + + def _infer_device_name(self, device_name, node_name): + """Infer the device name given node name. + + If device_name is provided (i.e., not None), it'll be simply returned right + away. + + Args: + device_name: (str or None) name of the device. If None, will try to infer + the device name by looking at the available nodes. + node_name: (str) name of the node. + + Returns: + (str) Inferred name of the device, if available. + + Raises: + ValueError: If the node name does not exist on any of the available + devices or if there are multiple devices that contain the node with + the given name. + """ + if device_name is None: + if node_name in self._node_devices: + if len(self._node_devices[node_name]) == 1: + return list(self._node_devices[node_name])[0] + else: + raise ValueError( + "There are multiple (%d) devices with nodes named '%s' but " + "device_name is not specified." % + (len(self._node_devices[node_name]), node_name)) + else: + raise ValueError("None of the %d device(s) has a node named '%s'." % + (len(self._device_names), node_name)) + else: + return device_name + + def nodes(self, device_name=None): + """Get a list of all nodes from the partition graphs. + + Args: + device_name: (`str`) name of device. If None, all nodes from all available + devices will be included. + + Returns: + All nodes' names, as a list of str. + + Raises: + LookupError: If no partition graphs have been loaded. + ValueError: If specified node name does not exist. + """ + if not self._debug_graphs: + raise LookupError("No partition graphs have been loaded.") + if device_name is None: + nodes = [] + for device_name in self._debug_graphs: + nodes.extend(self._debug_graphs[device_name].node_inputs.keys()) + return nodes + else: + if device_name not in self._debug_graphs: + raise ValueError("Invalid device name: %s" % device_name) + return self._debug_graphs[device_name].node_inputs.keys() + + def node_attributes(self, node_name, device_name=None): + """Get the attributes of a node. + + Args: + node_name: Name of the node in question. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + Attributes of the node. + + Raises: + LookupError: If no partition graphs have been loaded. + """ + if not self._debug_graphs: + raise LookupError("No partition graphs have been loaded.") + + device_name = self._infer_device_name(device_name, node_name) + return self._debug_graphs[device_name].node_attributes[node_name] + + def node_inputs(self, node_name, is_control=False, device_name=None): + """Get the inputs of given node according to partition graphs. + + Args: + node_name: Name of the node. + is_control: (`bool`) Whether control inputs, rather than non-control + inputs, are to be returned. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + (`list` of `str`) inputs to the node, as a list of node names. + + Raises: + LookupError: If node inputs and control inputs have not been loaded + from partition graphs yet. + """ + if not self._debug_graphs: + raise LookupError( + "Node inputs are not loaded from partition graphs yet.") + + device_name = self._infer_device_name(device_name, node_name) + if is_control: + return self._debug_graphs[device_name].node_ctrl_inputs[node_name] + else: + return self._debug_graphs[device_name].node_inputs[node_name] + + def transitive_inputs(self, + node_name, + include_control=True, + include_reversed_ref=False, + device_name=None,): + """Get the transitive inputs of given node according to partition graphs. + + Args: + node_name: Name of the node. + include_control: Include control inputs (True by default). + include_reversed_ref: Whether a ref input, say from A to B, is to be also + considered as an input from B to A. The rationale is that ref inputs + generally let the recipient (e.g., B in this case) mutate the value of + the source (e.g., A in this case). So the reverse direction of the ref + edge reflects the direction of information flow. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + (`list` of `str`) all transitive inputs to the node, as a list of node + names. + + Raises: + LookupError: If node inputs and control inputs have not been loaded + from partition graphs yet. + """ + if not self._debug_graphs: + raise LookupError( + "Node inputs are not loaded from partition graphs yet.") + + device_name = self._infer_device_name(device_name, node_name) + + input_lists = [self._debug_graphs[device_name].node_inputs] + if include_control: + input_lists.append(self._debug_graphs[device_name].node_ctrl_inputs) + if include_reversed_ref: + input_lists.append( + self._debug_graphs[device_name].node_reversed_ref_inputs) + tracer = debug_graphs.DFSGraphTracer( + input_lists, + skip_node_names=self._get_merge_node_names(device_name)) + tracer.trace(node_name) + return tracer.inputs() + + def _get_merge_node_names(self, device_name): + """Lazily get a list of Merge nodes on a given device.""" + if device_name not in self._device_names: + raise ValueError("Invalid device name: %s" % device_name) + + if not hasattr(self, "_merge_node_names"): + self._merge_node_names = {} + if device_name not in self._merge_node_names: + debug_graph = self._debug_graphs[device_name] + self._merge_node_names[device_name] = [ + node for node in debug_graph.node_op_types + if debug_graph.node_op_types[node] == "Merge"] + return self._merge_node_names[device_name] + + def find_some_path(self, + src_node_name, + dst_node_name, + include_control=True, + include_reversed_ref=False, + device_name=None): + """Find a path between a source node and a destination node. + + Limitation: the source and destination are required to be on the same + device, i.e., this method does not yet take into account Send/Recv nodes + across devices. + + TODO(cais): Make this method work across device edges by tracing Send/Recv + nodes. + + Args: + src_node_name: (`str`) name of the source node or name of an output tensor + of the node. + dst_node_name: (`str`) name of the destination node or name of an output + tensor of the node. + include_control: (`bool`) whrther control edges are considered in the + graph tracing. + include_reversed_ref: Whether a ref input, say from A to B, is to be also + considered as an input from B to A. The rationale is that ref inputs + generally let the recipient (e.g., B in this case) mutate the value of + the source (e.g., A in this case). So the reverse direction of the ref + edge reflects the direction of information flow. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + A path from the src_node_name to dst_node_name, as a `list` of `str`, if + it exists. The list includes src_node_name as the first item and + dst_node_name as the last. + If such a path does not exist, `None`. + + Raises: + ValueError: If the source and destination nodes are not on the same + device. + """ + src_device_name = self._infer_device_name(device_name, src_node_name) + dst_device_name = self._infer_device_name(device_name, dst_node_name) + + if src_device_name != dst_device_name: + raise ValueError( + "Source (%s) and destination (%s) are not on the same device: " + "%s vs. %s" % (src_node_name, dst_node_name, src_device_name, + dst_device_name)) + + input_lists = [self._debug_graphs[dst_device_name].node_inputs] + debug_graph = self._debug_graphs[dst_device_name] + if include_control: + input_lists.append(debug_graph.node_ctrl_inputs) + if include_reversed_ref: + input_lists.append(debug_graph.node_reversed_ref_inputs) + tracer = debug_graphs.DFSGraphTracer( + input_lists, + skip_node_names=self._get_merge_node_names(dst_device_name), + destination_node_name=src_node_name) + # Here the value of destination_node_name is src_node_name, because we + # are tracing the graph from output to its inputs (i.e., going backwards + # on the graph). + + try: + tracer.trace(dst_node_name) + except debug_graphs.GraphTracingReachedDestination: + # Prune nodes not on the path. + inputs = [dst_node_name] + tracer.inputs() + depth_list = [0] + tracer.depth_list() + + path = [] + curr_depth = depth_list[-1] + for inp, depth in zip(reversed(inputs), reversed(depth_list)): + if depth == curr_depth: + path.append(inp) + curr_depth -= 1 + return path + + def node_recipients(self, node_name, is_control=False, device_name=None): + """Get recipient of the given node's output according to partition graphs. + + Args: + node_name: (`str`) name of the node. + is_control: (`bool`) whether control outputs, rather than non-control + outputs, are to be returned. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + (`list` of `str`) all inputs to the node, as a list of node names. + + Raises: + LookupError: If node inputs and control inputs have not been loaded + from partition graphs yet. + """ + + if not self._debug_graphs: + raise LookupError( + "Node recipients are not loaded from partition graphs yet.") + + device_name = self._infer_device_name(device_name, node_name) + debug_graph = self._debug_graphs[device_name] + if is_control: + return debug_graph.node_ctrl_recipients[node_name] + else: + return debug_graph.node_recipients[node_name] + + def devices(self): + """Get the list of device names. + + Returns: + (`list` of `str`) names of the devices. + """ + return self._device_names + + def node_exists(self, node_name, device_name=None): + """Test if a node exists in the partition graphs. + + Args: + node_name: (`str`) name of the node to be checked. + device_name: optional device name. If None, will search for the node + on all available devices. Otherwise, search for the node only on + the given device. + + Returns: + A boolean indicating whether the node exists. + + Raises: + LookupError: If no partition graphs have been loaded yet. + ValueError: If device_name is specified but cannot be found. + """ + if not self._debug_graphs: + raise LookupError( + "Nodes have not been loaded from partition graphs yet.") + + if (device_name is not None) and device_name not in self._debug_graphs: + raise ValueError( + "The specified device_name '%s' cannot be found." % device_name) + + for _, debug_graph in self._debug_graphs.items(): + if node_name in debug_graph.node_inputs: + return True + return False + + def node_device(self, node_name): + """Get the names of the devices that has nodes of the specified name. + + Args: + node_name: (`str`) name of the node. + + Returns: + (`str` or `list` of `str`) name of the device(s) on which the node of the + given name is found. Returns a `str` if there is only one such device, + otherwise return a `list` of `str`. + + Raises: + LookupError: If node inputs and control inputs have not been loaded + from partition graphs yet. + ValueError: If the node does not exist in partition graphs. + """ + if not self._debug_graphs: + raise LookupError( + "Node devices are not loaded from partition graphs yet.") + + if node_name not in self._node_devices: + raise ValueError("Node '%s' does not exist in partition graphs." % + node_name) + + output = list(self._node_devices[node_name]) + return output[0] if len(output) == 1 else output + + def node_op_type(self, node_name, device_name=None): + """Get the op type of given node. + + Args: + node_name: (`str`) name of the node. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + (`str`) op type of the node. + + Raises: + LookupError: If node op types have not been loaded + from partition graphs yet. + """ + if not self._debug_graphs: + raise LookupError( + "Node op types are not loaded from partition graphs yet.") + + device_name = self._infer_device_name(device_name, node_name) + return self._debug_graphs[device_name].node_op_types[node_name] + + def debug_watch_keys(self, node_name, device_name=None): + """Get all tensor watch keys of given node according to partition graphs. + + Args: + node_name: (`str`) name of the node. + device_name: (`str`) name of the device. If there is only one device or if + node_name exists on only one device, this argument is optional. + + Returns: + (`list` of `str`) all debug tensor watch keys. Returns an empty list if + the node name does not correspond to any debug watch keys. + + Raises: + `LookupError`: If debug watch information has not been loaded from + partition graphs yet. + """ + + try: + device_name = self._infer_device_name(device_name, node_name) + except ValueError: + return [] + + if node_name not in self._debug_watches[device_name]: + return [] + + watch_keys = [] + for watched_slot in self._debug_watches[device_name][node_name]: + debug_ops = self._debug_watches[device_name][node_name][watched_slot] + for debug_op in debug_ops: + watch_keys.append( + _get_tensor_watch_key(node_name, watched_slot, debug_op)) + + return watch_keys + + def watch_key_to_data(self, debug_watch_key, device_name=None): + """Get all `DebugTensorDatum` instances corresponding to a debug watch key. + + Args: + debug_watch_key: (`str`) debug watch key. + device_name: (`str`) name of the device. If there is only one device or if + the specified debug_watch_key exists on only one device, this argument + is optional. + + Returns: + A list of `DebugTensorDatum` instances that correspond to the debug watch + key. If the watch key does not exist, returns an empty list. + + Raises: + ValueError: If there are multiple devices that have the debug_watch_key, + but device_name is not specified. + """ + if device_name is None: + matching_device_names = [ + name for name in self._watch_key_to_datum + if debug_watch_key in self._watch_key_to_datum[name]] + if not matching_device_names: + return [] + elif len(matching_device_names) == 1: + device_name = matching_device_names[0] + else: + raise ValueError( + "The debug watch key '%s' exists on multiple (%d) devices, but " + "device name is not specified." % + (debug_watch_key, len(matching_device_names))) + elif device_name not in self._debug_key_to_datum: + raise ValueError( + "There is no device named '%s' consisting of debug watch keys." % + device_name) + + return self._watch_key_to_datum[device_name].get(debug_watch_key, []) + + def find(self, + predicate, + first_n=0, + device_name=None, + exclude_node_names=None): + """Find dumped tensor data by a certain predicate. + + Args: + predicate: A callable that takes two input arguments: + + ```python + def predicate(debug_tensor_datum, tensor): + # returns a bool + ``` + + where `debug_tensor_datum` is an instance of `DebugTensorDatum`, which + carries the metadata, such as the `Tensor`'s node name, output slot + timestamp, debug op name, etc.; and `tensor` is the dumped tensor value + as a `numpy.ndarray`. + first_n: (`int`) return only the first n `DebugTensotDatum` instances (in + time order) for which the predicate returns True. To return all the + `DebugTensotDatum` instances, let first_n be <= 0. + device_name: optional device name. + exclude_node_names: Optional regular expression to exclude nodes with + names matching the regular expression. + + Returns: + A list of all `DebugTensorDatum` objects in this `DebugDumpDir` object + for which predicate returns True, sorted in ascending order of the + timestamp. + """ + if exclude_node_names: + exclude_node_names = re.compile(exclude_node_names) + + matched_data = [] + for device in (self._dump_tensor_data if device_name is None + else (self._dump_tensor_data[device_name],)): + for datum in self._dump_tensor_data[device]: + if exclude_node_names and exclude_node_names.match(datum.node_name): + continue + + if predicate(datum, datum.get_tensor()): + matched_data.append(datum) + + if first_n > 0 and len(matched_data) >= first_n: + return matched_data + + return matched_data + + def get_tensor_file_paths(self, + node_name, + output_slot, + debug_op, + device_name=None): + """Get the file paths from a debug-dumped tensor. + + Args: + node_name: (`str`) name of the node that the tensor is produced by. + output_slot: (`int`) output slot index of tensor. + debug_op: (`str`) name of the debug op. + device_name: (`str`) name of the device. If there is only one device or if + the specified debug_watch_key exists on only one device, this argument + is optional. + + Returns: + List of file path(s) loaded. This is a list because each debugged tensor + may be dumped multiple times. + + Raises: + WatchKeyDoesNotExistInDebugDumpDirError: If the tensor does not exist in + the debug-dump data. + """ + + device_name = self._infer_device_name(device_name, node_name) + watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op) + if watch_key not in self._watch_key_to_datum[device_name]: + raise WatchKeyDoesNotExistInDebugDumpDirError( + "Watch key \"%s\" does not exist in the debug dump of device %s" % + (watch_key, device_name)) + + return [datum.file_path for datum in + self._watch_key_to_datum[device_name][watch_key]] + + def get_tensors(self, node_name, output_slot, debug_op, device_name=None): + """Get the tensor value from for a debug-dumped tensor. + + The tensor may be dumped multiple times in the dump root directory, so a + list of tensors (`numpy.ndarray`) is returned. + + Args: + node_name: (`str`) name of the node that the tensor is produced by. + output_slot: (`int`) output slot index of tensor. + debug_op: (`str`) name of the debug op. + device_name: (`str`) name of the device. If there is only one device or if + the specified debug_watch_key exists on only one device, this argument + is optional. + + Returns: + List of tensors (`numpy.ndarray`) loaded from the debug-dump file(s). + + Raises: + WatchKeyDoesNotExistInDebugDumpDirError: If the tensor does not exist in + the debug-dump data. + """ + + watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op) + try: + device_name = self._infer_device_name(device_name, node_name) + return [datum.get_tensor() for datum in + self._watch_key_to_datum[device_name][watch_key]] + except (ValueError, KeyError): + raise WatchKeyDoesNotExistInDebugDumpDirError( + "Watch key \"%s\" does not exist in the debug dump of device %s" % + (watch_key, device_name)) + + def get_rel_timestamps(self, + node_name, + output_slot, + debug_op, + device_name=None): + """Get the relative timestamp from for a debug-dumped tensor. + + Relative timestamp means (absolute timestamp - `t0`), where `t0` is the + absolute timestamp of the first dumped tensor in the dump root. The tensor + may be dumped multiple times in the dump root directory, so a list of + relative timestamps (`numpy.ndarray`) is returned. + + Args: + node_name: (`str`) name of the node that the tensor is produced by. + output_slot: (`int`) output slot index of tensor. + debug_op: (`str`) name of the debug op. + device_name: (`str`) name of the device. If there is only one device or if + the specified debug_watch_key exists on only one device, this argument + is optional. + + Returns: + (`list` of `int`) list of relative timestamps. + + Raises: + WatchKeyDoesNotExistInDebugDumpDirError: If the tensor watch key does not + exist in the debug dump data. + """ + + device_name = self._infer_device_name(device_name, node_name) + watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op) + if watch_key not in self._watch_key_to_datum[device_name]: + raise WatchKeyDoesNotExistInDebugDumpDirError( + "Watch key \"%s\" does not exist in the debug dump" % watch_key) + + # TODO(cais): Figure out whether this should be relative to the global t0. + return self._watch_key_to_rel_time[device_name][watch_key] + + def get_dump_sizes_bytes(self, + node_name, + output_slot, + debug_op, + device_name=None): + """Get the sizes of the dump files for a debug-dumped tensor. + + Unit of the file size: byte. + + Args: + node_name: (`str`) name of the node that the tensor is produced by. + output_slot: (`int`) output slot index of tensor. + debug_op: (`str`) name of the debug op. + device_name: (`str`) name of the device. If there is only one device or if + the specified debug_watch_key exists on only one device, this argument + is optional. + + Returns: + (`list` of `int`): list of dump file sizes in bytes. + + Raises: + WatchKeyDoesNotExistInDebugDumpDirError: If the tensor watch key does not + exist in the debug dump data. + """ + + device_name = self._infer_device_name(device_name, node_name) + watch_key = _get_tensor_watch_key(node_name, output_slot, debug_op) + if watch_key not in self._watch_key_to_datum[device_name]: + raise WatchKeyDoesNotExistInDebugDumpDirError( + "Watch key \"%s\" does not exist in the debug dump of device %s" % + (watch_key, device_name)) + + return self._watch_key_to_dump_size_bytes[device_name][watch_key] + + def node_traceback(self, element_name): + """Try to retrieve the Python traceback of node's construction. + + Args: + element_name: (`str`) Name of a graph element (node or tensor). + + Returns: + (list) The traceback list object as returned by the `extract_trace` + method of Python's traceback module. + + Raises: + LookupError: If Python graph is not available for traceback lookup. + KeyError: If the node cannot be found in the Python graph loaded. + """ + + if self._python_graph is None: + raise LookupError("Python graph is not available for traceback lookup") + + node_name = debug_graphs.get_node_name(element_name) + if node_name not in self._node_traceback: + raise KeyError("Cannot find node \"%s\" in Python graph" % node_name) + + return self._node_traceback[node_name] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_monitors.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_monitors.py new file mode 100644 index 0000000000000000000000000000000000000000..53ba03cddc7232d9548b876dae237c6b59d66fdc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_monitors.py @@ -0,0 +1,307 @@ +# 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. +# ============================================================================== +"""Monitors for Debug Events in the tfdbg2 format. + +Monitors get access to graph-building- and execution-related data +objects as the DebugDataReader (see `debug_events_reader.py`) reads the +data in a continuous fashion, via a set of callbacks. This mechanism enables +hooking custom logic into the DebugEvent reading stream without the need for +any polling or iterating over the entire data held by DebugDataReader. + +This module includes the following built-in hooks: + - InfNanMonitor: Monitors infinity and nan values in top-level execution and + intra-graph execution events. + +When a monitor (subtype of `BaseMonitor`) is constructed with a DebugDataReader +as the first argument of the constructor call, the monitor is automatically +registered with the DebugDataReader. For example: + +```py +debug_data_reader = debug_events_reader.DebugDataReader(dump_dir) +inf_nan_monitor = debug_events_monitors.InfNanMonitor(debug_data_reader) + +debug_data_reader.update() +# `inf_nan_monitor`'s on_* methods will get called as the execution-related +# and other types of data are read by `debug_data_reader`. +``` +""" +import numpy as np + +from tensorflow.core.protobuf import debug_event_pb2 + + +class BaseMonitor(object): + """Base class for debug event data monitors.""" + + def __init__(self, debug_events_reader): + self._debug_data_reader = debug_events_reader + debug_events_reader._add_monitor(self) # pylint:disable=protected-access + + def on_execution(self, execution_index, execution): + """Monitor method for top-level execution events. + + Return values (if any) are ignored by the associated DebugDataReader. + + Args: + execution_index: The index of the top-level execution event, as an int. + execution: An Execution data object, for a top-level op or function + execution event. + """ + + def on_graph_execution_trace(self, + graph_execution_trace_index, + graph_execution_trace): + """Monitor method for intra-graph execution events. + + Return values (if any) are ignored by the associated DebugDataReader. + + Args: + graph_execution_trace_index: The index of the intra-graph execution + event, as an int. + graph_execution_trace: A GraphExecutionTrace data object, for an + intra-graph tensor event. + """ + + # TODO(cais): Add more monitor methods such as on_graph_op_creation(). + + +class InfNanAlert(object): + """Alert for Infinity and NaN values.""" + + def __init__(self, + wall_time, + op_type, + output_slot, + size=None, + num_neg_inf=None, + num_pos_inf=None, + num_nan=None, + execution_index=None, + graph_execution_trace_index=None): + self._wall_time = wall_time + self._op_type = op_type + self._output_slot = output_slot + self._size = size + self._num_neg_inf = num_neg_inf + self._num_pos_inf = num_pos_inf + self._num_nan = num_nan + self._execution_index = execution_index + self._graph_execution_trace_index = graph_execution_trace_index + + @property + def wall_time(self): + return self._wall_time + + @property + def op_type(self): + return self._op_type + + @property + def output_slot(self): + return self._output_slot + + @property + def size(self): + return self._size + + @property + def num_neg_inf(self): + return self._num_neg_inf + + @property + def num_pos_inf(self): + return self._num_pos_inf + + @property + def num_nan(self): + return self._num_nan + + @property + def execution_index(self): + return self._execution_index + + @property + def graph_execution_trace_index(self): + return self._graph_execution_trace_index + + +class InfNanMonitor(BaseMonitor): + """Monitor for Infinity and NaN in tensor values.""" + + def __init__(self, debug_events_reader, limit=0): + super(InfNanMonitor, self).__init__(debug_events_reader) + self._limit = limit # Track only the first _ alert events, for efficiency. + self._alerts = [] + + def _check_full_tensor_value(self, + tensor_value, + wall_time, + op_type, + output_slot, + execution_index=None, + graph_execution_trace_index=None): + """Check a full tensor value. + + Appends to the list of alerts if any inf or nan is found in the full tensor + value. + + Args: + tensor_value: The full tensor value as a `np.ndarray`. + wall_time: Wall timestamp for the execution event that generated the + tensor value. + op_type: Op type executed. + output_slot: The output slot of the op. + execution_index: Index to the top-level execution event. + graph_execution_trace_index: Index to the intra-graph execution trace + (if applicable.) + """ + size = np.size(tensor_value) + if not size or not np.issubdtype(tensor_value.dtype, np.floating): + return + is_inf = np.isinf(tensor_value) + num_neg_inf = np.count_nonzero( + np.logical_and(is_inf, np.less(tensor_value, 0.0))) + num_pos_inf = np.count_nonzero( + np.logical_and(is_inf, np.greater(tensor_value, 0.0))) + num_nan = np.count_nonzero(np.isnan(tensor_value)) + if num_neg_inf or num_pos_inf or num_nan: + self._alerts.append(InfNanAlert( + wall_time, + op_type, + output_slot, + size=size, + num_neg_inf=num_neg_inf, + num_pos_inf=num_pos_inf, + num_nan=num_nan, + execution_index=execution_index, + graph_execution_trace_index=graph_execution_trace_index)) + + def _check_debug_tensor_value(self, + tensor_debug_mode, + debug_tensor_value, + wall_time, + op_type, + output_slot, + execution_index=None, + graph_execution_trace_index=None): + """Check for bad numerical values based on debug summary of tensor value. + + If tensor_debug_mode is one in which debug_tensor_value does not carry + information about the presence or count of inf / nan values (e.g., SHAPE), + this method is a no-op. + + When infs and/or nans are found, `InfNanAlert` objects are created and + appended to `self._alerts`. + + Args: + tensor_debug_mode: TensorDebugMode proto enum. + debug_tensor_value: Debug tensor value as a list of numbers. + wall_time: Wall timestamp for the tensor event. + op_type: Type of the op that generated the tensor (e.g., "Conv2D"). + output_slot: Output slot index of the tensor for the op. + execution_index: Top-level execution index. + graph_execution_trace_index: Intra-graph execution index. + """ + # FULL_TENSOR mode is handled by a separate code path. + assert tensor_debug_mode != debug_event_pb2.TensorDebugMode.FULL_TENSOR + if not debug_tensor_value: + return + if tensor_debug_mode == debug_event_pb2.TensorDebugMode.CURT_HEALTH: + _, any_nan_inf = debug_tensor_value + if any_nan_inf: + self._alerts.append(InfNanAlert( + wall_time, + op_type, + output_slot, + execution_index=execution_index, + graph_execution_trace_index=graph_execution_trace_index)) + elif tensor_debug_mode == debug_event_pb2.TensorDebugMode.CONCISE_HEALTH: + _, size, num_neg_inf, num_pos_inf, num_nan = debug_tensor_value + if num_neg_inf or num_pos_inf or num_nan: + self._alerts.append(InfNanAlert( + wall_time, + op_type, + output_slot, + size=size, + num_neg_inf=num_neg_inf, + num_pos_inf=num_pos_inf, + num_nan=num_nan, + execution_index=execution_index, + graph_execution_trace_index=graph_execution_trace_index)) + elif tensor_debug_mode == debug_event_pb2.TensorDebugMode.FULL_HEALTH: + (_, _, _, _, size, num_neg_inf, num_pos_inf, num_nan, + _, _, _) = debug_tensor_value + if num_neg_inf or num_pos_inf or num_nan: + self._alerts.append(InfNanAlert( + wall_time, + op_type, + output_slot, + size=size, + num_neg_inf=num_neg_inf, + num_pos_inf=num_pos_inf, + num_nan=num_nan, + execution_index=execution_index, + graph_execution_trace_index=graph_execution_trace_index)) + + def on_execution(self, + execution_index, + execution): + if self._limit > 0 and len(self._alerts) >= self._limit: + return + if (execution.tensor_debug_mode == + debug_event_pb2.TensorDebugMode.FULL_TENSOR): + tensor_values = self._debug_data_reader.execution_to_tensor_values( + execution) + for output_slot, tensor_value in enumerate(tensor_values): + self._check_full_tensor_value( + tensor_value, execution.wall_time, execution.op_type, output_slot, + execution_index=execution_index) + elif execution.debug_tensor_values: + for output_slot, debug_tensor_value in enumerate( + execution.debug_tensor_values): + self._check_debug_tensor_value( + execution.tensor_debug_mode, + debug_tensor_value, + execution.wall_time, + execution.op_type, + output_slot, + execution_index=execution_index) + + def on_graph_execution_trace(self, + graph_execution_trace_index, + graph_execution_trace): + """Monitor method for GraphExecutionTrace data object.""" + if self._limit > 0 and len(self._alerts) >= self._limit: + return + if (graph_execution_trace.tensor_debug_mode == + debug_event_pb2.TensorDebugMode.FULL_TENSOR): + tensor_value = ( + self._debug_data_reader.graph_execution_trace_to_tensor_value( + graph_execution_trace)) + self._check_full_tensor_value( + tensor_value, graph_execution_trace.wall_time, + graph_execution_trace.op_type, graph_execution_trace.output_slot, + graph_execution_trace_index=graph_execution_trace_index) + elif graph_execution_trace.debug_tensor_value: + self._check_debug_tensor_value( + graph_execution_trace.tensor_debug_mode, + graph_execution_trace.debug_tensor_value, + graph_execution_trace.wall_time, + graph_execution_trace.op_type, + graph_execution_trace.output_slot, + graph_execution_trace_index=graph_execution_trace_index) + + def alerts(self): + return self._alerts diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_reader.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..706823b799b14a5b6aab98775ccbf04f45f97f49 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_reader.py @@ -0,0 +1,1355 @@ +# 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. +# ============================================================================== +"""Reader class for tfdbg v2 debug events.""" + +import collections +import os +import threading + +from tensorflow.core.protobuf import debug_event_pb2 +from tensorflow.python.framework import errors +from tensorflow.python.framework import tensor_util +from tensorflow.python.lib.io import file_io +from tensorflow.python.lib.io import tf_record +from tensorflow.python.util import compat + + +DebugEventWithOffset = collections.namedtuple( + "DebugEventWithOffset", "debug_event offset") + + +class DebugEventsReader: + """Reader class for a tfdbg v2 DebugEvents directory.""" + + # Number of digests after which a read lock is released and re-acquired during + # serial reading of digests for SourceFiles, Execution, and + # GraphExecutionTrace. This allows us to avoid releasing and re-acquiring the + # lock too often (i.e., after each digest) and to minimize performance + # penalty. + _READER_RELEASE_PER = 100 + + _METADATA_SUFFIX = ".metadata" + _SOURCE_FILE_SUFFIX = ".source_files" + _STACK_FRAMES_SUFFIX = ".stack_frames" + _GRAPHS_SUFFIX = ".graphs" + _EXECUTION_SUFFIX = ".execution" + _GRAPH_EXECUTION_TRACES_SUFFIX = ".graph_execution_traces" + + def __init__(self, dump_root): + if not file_io.is_directory(dump_root): + raise ValueError("Specified dump_root is not a directory: %s" % dump_root) + self._dump_root = dump_root + self._metadata_paths = self._load_metadata_files() + + prefixes = [ + metadata_path[:-len(self._METADATA_SUFFIX)] + for metadata_path in self._metadata_paths + ] + prefix = prefixes[0] # This is the prefix of the main file set. + self._source_files_path = compat.as_bytes(prefix + self._SOURCE_FILE_SUFFIX) + self._stack_frames_path = compat.as_bytes(prefix + + self._STACK_FRAMES_SUFFIX) + self._graphs_path = compat.as_bytes(prefix + self._GRAPHS_SUFFIX) + self._execution_path = compat.as_bytes(prefix + self._EXECUTION_SUFFIX) + # There can be multiple .graph_execution_trace files each belonging + # to a file set generated on an individual host, in the case of + # a distributed TensorFlow job. + # This is different from the other debug event files in the file set. + self._graph_execution_traces_paths = [ + compat.as_bytes(prefix + self._GRAPH_EXECUTION_TRACES_SUFFIX) + for prefix in prefixes + ] + self._readers = dict() # A map from file path to reader. + # A map from file path to current reading offset. + self._reader_offsets = dict() + # Lock for reader creation. + self._readers_lock = threading.Lock() + # Locks for read operation on individual readers. + self._reader_read_locks = dict() + + self._offsets = dict() + + def _load_metadata_files(self): + """Load and parse metadata files in the dump root. + + Check that all metadata files have a common tfdbg_run_id, and raise + a ValueError if their tfdbg_run_ids differ. + + Returns: + A list of metadata file paths in ascending order of their starting + wall_time timestamp. + """ + + metadata_paths = file_io.get_matching_files( + os.path.join(self._dump_root, "*%s" % self._METADATA_SUFFIX)) + if not metadata_paths: + raise ValueError("Cannot find any tfdbg metadata file in directory: %s" % + self._dump_root) + wall_times = [] + run_ids = [] + tensorflow_versions = [] + file_versions = [] + for metadata_path in metadata_paths: + reader = tf_record.tf_record_random_reader(metadata_path) + try: + record = reader.read(0)[0] + debug_event = debug_event_pb2.DebugEvent.FromString(record) + wall_times.append(debug_event.wall_time) + run_ids.append(debug_event.debug_metadata.tfdbg_run_id) + tensorflow_versions.append( + debug_event.debug_metadata.tensorflow_version) + file_versions.append(debug_event.debug_metadata.file_version) + finally: + reader.close() + self._starting_wall_time = wall_times[0] + self._tfdbg_run_id = run_ids[0] + self._tensorflow_version = tensorflow_versions[0] + self._file_version = file_versions[0] + if len(metadata_paths) == 1: + # Fast path for a common case (only one DebugEvent file set.) + return metadata_paths + + num_no_id = len([run_id for run_id in run_ids if not run_id]) + if num_no_id: + paths_without_run_id = [ + metadata_path + for metadata_path, run_id in zip(metadata_paths, run_ids) + if not run_id + ] + raise ValueError( + "Found %d tfdbg metadata files and %d of them do not " + "have tfdbg run ids. The metadata files without run ids are: %s" % + (len(run_ids), num_no_id, paths_without_run_id)) + elif len(set(run_ids)) != 1: + raise ValueError( + "Unexpected: Found multiple (%d) tfdbg2 runs in directory %s" % + (len(set(run_ids)), self._dump_root)) + # Return the metadata files in ascending order of their timestamps. + paths_and_timestamps = sorted( + zip(metadata_paths, wall_times), key=lambda t: t[1]) + self._starting_wall_time = paths_and_timestamps[0][1] + return [path[0] for path in paths_and_timestamps] + + def starting_wall_time(self): + """Get the starting timestamp of the instrumented TensorFlow program. + + When there are multiple hosts (i.e., multiple tfdbg file sets), the earliest + timestamp among the file sets is returned. It is assumed to be the job that + starts first (e.g., the coordinator). + + Returns: + Starting timestamp in seconds since the epoch, as a float. + """ + return self._starting_wall_time + + def tfdbg_run_id(self): + """Get the run ID of the instrumented TensorFlow program.""" + return self._tfdbg_run_id + + def tensorflow_version(self): + """Get the version string of TensorFlow that the debugged program ran on.""" + return self._tensorflow_version + + def tfdbg_file_version(self): + """Get the tfdbg file format version.""" + return self._file_version + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + del exception_type, exception_value, traceback # Unused + self.close() + + def _generic_iterator(self, file_path): + """A helper method that makes an iterator given a debug-events file path. + + Repeated calls to this method create iterators that remember the last + successful reading position (offset) for each given `file_path`. So the + iterators are meant for incremental reading of the file. + + Args: + file_path: Path to the file to create the iterator for. + + Yields: + A tuple of (offset, debug_event_proto) on each `next()` call. + """ + yield_count = 0 + reader = self._get_reader(file_path) + read_lock = self._reader_read_locks[file_path] + read_lock.acquire() + try: + while True: + current_offset = self._reader_offsets[file_path] + try: + record, self._reader_offsets[file_path] = reader.read(current_offset) + except (errors.DataLossError, IndexError): + # We ignore partial read exceptions, because a record may be + # truncated. The PyRandomRecordReader throws an `IndexError` when + # offset goes out of bound. + break + yield DebugEventWithOffset( + debug_event=debug_event_pb2.DebugEvent.FromString(record), + offset=current_offset) + yield_count += 1 + # The read lock must be periodically released to allow for concurrent + # random reads. But we do so at a number of reads, instead of after + # every single read, in order to minimize the performance penalty. + if yield_count % self._READER_RELEASE_PER == 0: + read_lock.release() + read_lock.acquire() + finally: + read_lock.release() + + def _get_reader(self, file_path): + """Get a random-access reader for TFRecords file at file_path.""" + file_path = compat.as_bytes(file_path) + # The following code uses the double-checked locking pattern to optimize + # the common case (where the reader is already initialized). + if file_path not in self._readers: # 1st check, without lock. + with self._readers_lock: + if file_path not in self._readers: # 2nd check, with lock. + self._readers[file_path] = tf_record.tf_record_random_reader( + file_path) + self._reader_read_locks[file_path] = threading.Lock() + self._reader_offsets[file_path] = 0 + return self._readers[file_path] + + def source_files_iterator(self): + return self._generic_iterator(self._source_files_path) + + def stack_frames_iterator(self): + return self._generic_iterator(self._stack_frames_path) + + def graphs_iterator(self): + return self._generic_iterator(self._graphs_path) + + def read_source_files_event(self, offset): + """Read a DebugEvent proto at given offset from the .source_files file.""" + with self._reader_read_locks[self._source_files_path]: + proto_string = self._get_reader(self._source_files_path).read(offset)[0] + return debug_event_pb2.DebugEvent.FromString(proto_string) + + def read_graphs_event(self, offset): + """Read a DebugEvent proto at a given offset from the .graphs file. + + Args: + offset: Offset to read the DebugEvent proto from. + + Returns: + A DebugEventProto. + + Raises: + `errors.DataLossError` if offset is at a wrong location. + `IndexError` if offset is out of range of the file. + """ + return debug_event_pb2.DebugEvent.FromString( + self._get_reader(self._graphs_path).read(offset)[0]) + + def execution_iterator(self): + return self._generic_iterator(self._execution_path) + + def read_execution_event(self, offset): + """Read a DebugEvent proto at a given offset from the .execution file. + + Args: + offset: Offset to read the DebugEvent proto from. + + Returns: + A DebugEventProto. + + Raises: + `errors.DataLossError` if offset is at a wrong location. + `IndexError` if offset is out of range of the file. + """ + with self._reader_read_locks[self._execution_path]: + proto_string = self._get_reader(self._execution_path).read(offset)[0] + return debug_event_pb2.DebugEvent.FromString(proto_string) + + def graph_execution_traces_iterators(self): + return [ + self._generic_iterator(path) + for path in self._graph_execution_traces_paths + ] + + def read_graph_execution_traces_event(self, locator): + """Read DebugEvent at given offset from given .graph_execution_traces file. + + Args: + locator: A (file_index, offset) tuple that locates the DebugEvent + containing the graph execution trace. + + Returns: + A DebugEventProto. + + Raises: + `errors.DataLossError` if offset is at a wrong location. + `IndexError` if offset is out of range of the file. + """ + file_index, offset = locator + graph_execution_traces_path = self._graph_execution_traces_paths[file_index] + with self._reader_read_locks[graph_execution_traces_path]: + proto_string = self._get_reader(graph_execution_traces_path).read( + offset)[0] + return debug_event_pb2.DebugEvent.FromString(proto_string) + + def close(self): + with self._readers_lock: + file_paths = list(self._readers.keys()) + for file_path in file_paths: + self._readers[file_path].close() + del self._readers[file_path] + + +class BaseDigest: + """Base class for digest. + + Properties: + wall_time: A timestamp for the digest as a `float` (unit: s). + locator: A datum that allows tracng the digest to its original + location. It can be either of the two: + 1. Bytes offset from the beginning of the file as a single integer, + for the case of all digests of the same kind coming from the same + file. + 2. A tuple of a file index and a byte offset. This applies to case + in which the same type of debugger data may come from multiple files, + e.g., graph execution traces. + """ + + def __init__(self, wall_time, locator): + self._wall_time = wall_time + self._locator = locator + + @property + def wall_time(self): + return self._wall_time + + @property + def locator(self): + return self._locator + + def to_json(self): + return {"wall_time": self.wall_time} + + +class ExecutionDigest(BaseDigest): + """Light-weight digest summarizing top-level execution event. + + Use `DebugDataReader.read_execution(execution_digest)` to load the more + detailed data object concerning the execution event (`Execution`). + + Properties: + op_type: Type name of the executed op. In the case of the eager execution of + an individual op, it is the name of the op (e.g., "MatMul"). + In the case of the execution of a tf.function (FuncGraph), this is the + internally-generated name of the function (e.g., + "__inference_my_func_123"). + output_tensor_device_ids: IDs of the devices on which the output tensors of + the execution reside. For no-output execution, this is `None`. + """ + + def __init__(self, + wall_time, + locator, + op_type, + output_tensor_device_ids=None): + super().__init__(wall_time, locator) + self._op_type = op_type + self._output_tensor_device_ids = _tuple_or_none(output_tensor_device_ids) + + @property + def op_type(self): + return self._op_type + + @property + def output_tensor_device_ids(self): + return self._output_tensor_device_ids + + def to_json(self): + output = super().to_json() + output.update({ + "op_type": self.op_type, + "output_tensor_device_ids": self.output_tensor_device_ids, + }) + return output + + +def _tuple_or_none(data): + return tuple(data) if data else None + + +class Execution(ExecutionDigest): + """Detailed data relating to a top-level execution event. + + The execution is of an individual op or a tf.function, which may have any + number of output tensors. + + Properties (beyond the base class `ExecutionDigest`): + host_name: Name of the host on which the execution happened. + stack_frame_ids: Reference IDs for stack frames, ordered from bottommost to + topmost. Use `DebugDataReader.read_execution_stack_trace()` to load the + detailed stack frames (filepath, lineno and function name). + tensor_debug_mode: TensorDebugMode enum value, as an `int`. + graph_id: ID of the executed FuncGraph (applicable only the execution of a + tf.function). `None` for the eager execution of an individual op. + input_tensor_ids: IDs of the input (eager) tensor(s) for this execution, if + any. If the eager execution has no input tensor, this is `None`. Else, + this is a `tuple` of `int`s. + output_tensor_ids: IDs of the output (eager) tensor(s) from this execution, + if any. If the eager execution produces no output tensor, this is `None`. + Else, this is a `tuple` of `int`s. + debug_tensor_values: Values of the debug tensor(s), applicable only to + non-FULL_TENSOR tensor debug mode. A tuple of list of numbers. Each + element of the tuple corresponds to an output tensor of the execution. + See documentation of the various TensorDebugModes for the semantics of the + numbers. If the eager execution produces no output tensor, this is + `None`. Else, this is a `tuple` of `list`s. + """ + + def __init__(self, + execution_digest, + host_name, + stack_frame_ids, + tensor_debug_mode, + graph_id=None, + input_tensor_ids=None, + output_tensor_ids=None, + debug_tensor_values=None): + super().__init__( + execution_digest.wall_time, + execution_digest.locator, + execution_digest.op_type, + output_tensor_device_ids=execution_digest.output_tensor_device_ids) + self._host_name = host_name + self._stack_frame_ids = tuple(stack_frame_ids) + self._tensor_debug_mode = tensor_debug_mode + self._graph_id = graph_id + self._input_tensor_ids = _tuple_or_none(input_tensor_ids) + self._output_tensor_ids = _tuple_or_none(output_tensor_ids) + self._debug_tensor_values = _tuple_or_none(debug_tensor_values) + + @property + def host_name(self): + return self._host_name + + @property + def stack_frame_ids(self): + return self._stack_frame_ids + + @property + def tensor_debug_mode(self): + return self._tensor_debug_mode + + @property + def graph_id(self): + return self._graph_id + + @property + def input_tensor_ids(self): + return self._input_tensor_ids + + @property + def num_outputs(self): + return len(self._output_tensor_ids) if self._output_tensor_ids else 0 + + @property + def output_tensor_ids(self): + return self._output_tensor_ids + + @property + def debug_tensor_values(self): + return self._debug_tensor_values + + def to_json(self): + output = super().to_json() + output.update({ + "host_name": self.host_name, + "stack_frame_ids": self.stack_frame_ids, + "tensor_debug_mode": self.tensor_debug_mode, + "graph_id": self.graph_id, + "input_tensor_ids": self.input_tensor_ids, + "output_tensor_ids": self.output_tensor_ids, + "debug_tensor_values": self.debug_tensor_values, + }) + return output + + +class DebuggedGraph: + """Data object representing debugging information about a tf.Graph. + + Includes `FuncGraph`s. + + Properties: + name: Name of the graph (if any). May be `None` for non-function graphs. + graph_id: Debugger-generated ID for the graph. + inner_graph_ids: A list of the debugger-generated IDs for the graphs + enclosed by this graph. + outer_graph_id: If this graph is nested within an outer graph, ID of the + outer graph. If this is an outermost graph, `None`. + """ + + def __init__(self, + name, + graph_id, + outer_graph_id=None): + self._name = name + self._graph_id = graph_id + self._outer_graph_id = outer_graph_id + self._inner_graph_ids = [] + # A dictionary from op name to GraphOpCreationDigest. + self._op_by_name = dict() + # A dictionary mapping op to immediate downstream consumers. + self._op_consumers = collections.defaultdict(list) + + def add_inner_graph_id(self, inner_graph_id): + """Add the debugger-generated ID of a graph nested within this graph. + + Args: + inner_graph_id: The debugger-generated ID of the nested inner graph. + """ + assert isinstance(inner_graph_id, str) + self._inner_graph_ids.append(inner_graph_id) + + def add_op(self, graph_op_creation_digest): + """Add an op creation data object. + + Args: + graph_op_creation_digest: A GraphOpCreationDigest data object describing + the creation of an op inside this graph. + """ + if graph_op_creation_digest.op_name in self._op_by_name: + raise ValueError( + "Duplicate op name: %s (op type: %s)" % + (graph_op_creation_digest.op_name, graph_op_creation_digest.op_type)) + self._op_by_name[ + graph_op_creation_digest.op_name] = graph_op_creation_digest + + def add_op_consumer(self, src_op_name, src_slot, dst_op_name, dst_slot): + """Add a consuming op for this op. + + Args: + src_op_name: Name of the op of which the output tensor is being consumed. + src_slot: 0-based output slot of the op being consumed. + dst_op_name: Name of the consuming op (e.g., "Conv2D_3/BiasAdd") + dst_slot: 0-based input slot of the consuming op that receives the tensor + from this op. + """ + self._op_consumers[src_op_name].append((src_slot, dst_op_name, dst_slot)) + + @property + def name(self): + return self._name + + @property + def graph_id(self): + return self._graph_id + + @property + def outer_graph_id(self): + return self._outer_graph_id + + @property + def inner_graph_ids(self): + return self._inner_graph_ids + + def get_tensor_id(self, op_name, output_slot): + """Get the ID of a symbolic tensor in this graph.""" + return self._op_by_name[op_name].output_tensor_ids[output_slot] + + def get_op_creation_digest(self, op_name): + """Get the GraphOpCreationDigest for a op in the graph.""" + return self._op_by_name[op_name] + + def get_op_consumers(self, src_op_name): + """Get all the downstream consumers of this op. + + Only data (non-control) edges are tracked. + + Args: + src_op_name: Name of the op providing the tensor being consumed. + + Returns: + A list of (src_slot, dst_op_name, dst_slot) tuples. In each item of + the list: + src_slot: 0-based output slot of the op of which the output tensor + is being consumed. + dst_op_name: Name of the consuming op (e.g., "Conv2D_3/BiasAdd") + dst_slot: 0-based input slot of the consuming op that receives + the tensor from this op. + """ + return self._op_consumers[src_op_name] + + def to_json(self): + return { + "name": self.name, + "graph_id": self.graph_id, + "outer_graph_id": self._outer_graph_id, + "inner_graph_ids": self._inner_graph_ids, + } + + +class DebuggedDevice: + """Debugger data regarding a device involved in the debugged program. + + Properties: + device_name: Name of the device, as a str. + device_id: An integer ID for the device, unique for each device within + the scope of the debugged TensorFlow program. + """ + + def __init__(self, + device_name, + device_id): + self._device_name = device_name + self._device_id = device_id + + @property + def device_name(self): + return self._device_name + + @property + def device_id(self): + return self._device_id + + def to_json(self): + return { + "device_name": self._device_name, + "device_id": self._device_id, + } + + +class GraphOpCreationDigest(BaseDigest): + """Data object describing the creation of an op inside a graph. + + For size efficiency, this digest object does not contain any stack frames or + any references to them. To obtain the stack frames, use + `DataReader.read_graph_op_creation_stack_trace()`. + + Properties (beyond the base class): + graph_id: Debugger-generated ID of the immediately-enclosing graph. + op_type: Type name of the op (e.g., "MatMul"). + op_name: Name of the op (e.g., "dense_1/MatMul"). + output_tensor_ids: Debugger-generated IDs for the output(s) of the op. + If the op produces no output tensor, this is `None`. Else, this is a + `tuple` of `int`s. + input_names: Names of the input tensors to the op. + device_name: The name of the device that the op is placed on (if available). + host_name: Name of the host on which the op is created. + stack_frame_ids: IDs of the frames of the stack trace at which the op + is created. + """ + + def __init__(self, + wall_time, + locator, + graph_id, + op_type, + op_name, + output_tensor_ids, + host_name, + stack_frame_ids, + input_names=None, + device_name=None): + super().__init__(wall_time, locator) + self._graph_id = graph_id + self._op_type = op_type + self._op_name = op_name + self._output_tensor_ids = _tuple_or_none(output_tensor_ids) + self._host_name = host_name + self._stack_frame_ids = stack_frame_ids + self._input_names = _tuple_or_none(input_names) + self._device_name = device_name + + @property + def graph_id(self): + return self._graph_id + + @property + def op_type(self): + return self._op_type + + @property + def op_name(self): + return self._op_name + + @property + def output_tensor_ids(self): + return self._output_tensor_ids + + @property + def num_outputs(self): + return len(self._output_tensor_ids) if self.output_tensor_ids else 0 + + @property + def input_names(self): + return self._input_names + + @property + def device_name(self): + return self._device_name + + @property + def host_name(self): + return self._host_name + + @property + def stack_frame_ids(self): + return self._stack_frame_ids + + def to_json(self): + output = super().to_json() + output.update({ + "graph_id": self.graph_id, + "op_type": self.op_type, + "op_name": self.op_name, + "output_tensor_ids": self.output_tensor_ids, + "host_name": self.host_name, + "stack_frame_ids": self.stack_frame_ids, + "input_names": self.input_names, + "device_name": self.device_name, + }) + return output + + +class GraphExecutionTraceDigest(BaseDigest): + """Light-weight summary of a intra-graph tensor execution event. + + Use `DebugDataReader.read_graph_execution_trace()` on this object to read more + detailed data (`GraphExecutionTrace`). + + Properties (beyond the base class): + op_type: Type name of the executed op (e.g., "Conv2D"). + op_name: Name of the op (e.g., "conv_2d_3/Conv2D"). + output_slot: Output slot index of the tensor. + graph_id: The debugger-generated ID of the innermost (immediately-enclosing) + graph. + """ + + def __init__(self, wall_time, locator, op_type, op_name, output_slot, + graph_id): + super().__init__(wall_time, locator) + self._op_type = op_type + self._op_name = op_name + self._output_slot = output_slot + self._graph_id = graph_id + + @property + def op_type(self): + return self._op_type + + @property + def op_name(self): + return self._op_name + + @property + def output_slot(self): + return self._output_slot + + @property + def graph_id(self): + return self._graph_id + + def to_json(self): + output = super().to_json() + output.update({ + "op_type": self.op_type, + "op_name": self.op_name, + "output_slot": self.output_slot, + "graph_id": self.graph_id, + }) + return output + + +class GraphExecutionTrace(GraphExecutionTraceDigest): + """Detailed data object describing an intra-graph tensor execution. + + Attributes (in addition to GraphExecutionTraceDigest): + graph_ids: The debugger-generated IDs of the graphs that enclose the + executed op (tensor), ordered from the outermost to the innermost. + graph_id: The debugger-generated ID of the innermost (immediately-enclosing) + graph. + tensor_debug_mode: TensorDebugMode enum value. + debug_tensor_value: Debug tensor values (only for non-FULL_TENSOR + tensor_debug_mode). A list of numbers. See the documentation of the + TensorDebugModes for the semantics of the numbers. + device_name: Device on which the tensor resides (if available) + """ + + def __init__(self, + graph_execution_trace_digest, + graph_ids, + tensor_debug_mode, + debug_tensor_value=None, + device_name=None): + super().__init__(graph_execution_trace_digest.wall_time, + graph_execution_trace_digest.locator, + graph_execution_trace_digest.op_type, + graph_execution_trace_digest.op_name, + graph_execution_trace_digest.output_slot, + graph_execution_trace_digest.graph_id) + self._graph_ids = tuple(graph_ids) + self._tensor_debug_mode = tensor_debug_mode + self._debug_tensor_value = debug_tensor_value + self._device_name = device_name + + @property + def graph_ids(self): + return self._graph_ids + + @property + def graph_id(self): + return self._graph_ids[-1] + + @property + def tensor_debug_mode(self): + return self._tensor_debug_mode + + @property + def debug_tensor_value(self): + return _tuple_or_none(self._debug_tensor_value) + + @property + def device_name(self): + return self._device_name + + def to_json(self): + output = super().to_json() + output.update({ + "graph_ids": self.graph_ids, + "tensor_debug_mode": self.tensor_debug_mode, + "debug_tensor_value": self.debug_tensor_value, + "device_name": self.device_name, + }) + return output + + +def _parse_tensor_value(tensor_proto, return_list=False): + """Helper method for reading a tensor value from a tensor proto. + + The rationale for the distinction between `True` and `False value of + `return_list` is as follows: + - `return_list=True` is used for TensorDebugMode values other than + FULL_TENSOR, e.g., CONCISE_HEALTH, SHAPE and FULL_HEATLH. Under + those modes, the value is guaranteed (by contract) to be a 1D float64 + tensor. + - `return_list=False` is used for the FULL_HEALTH TensorDebugMode + specifically. Instead, we use `numpy.ndarray` to maximally preserve + the shape, dtype and value information regarding the underlying tensor + value. Under that mode, we don't use a python list to represent the + tensor value because that can lead to loss of information (e.g., both + float16 and float32 dtypes get mapped to Python floats). + + Args: + tensor_proto: The TensorProto instance from which the tensor value will be + loaded. + return_list: Whether the return value will be a nested Python list that + comes out from `numpy.ndarray.tolist()`. + + Returns: + If parsing is successful, the tensor value as a `numpy.ndarray` or the + nested Python list converted from it. + If parsing fails, `None`. + """ + try: + ndarray = tensor_util.MakeNdarray(tensor_proto) + return ndarray.tolist() if return_list else ndarray + except TypeError: + # Depending on tensor_debug_mode, certain dtype of tensors don't + # have logged debug tensor values. + return None + + +def _execution_digest_from_debug_event_proto(debug_event, locator): + """Convert a DebugEvent proto into an ExecutionDigest data object.""" + return ExecutionDigest( + debug_event.wall_time, + locator, + debug_event.execution.op_type, + output_tensor_device_ids=(debug_event.execution.output_tensor_device_ids + or None)) + + +def _execution_from_debug_event_proto(debug_event, locator): + """Convert a DebugEvent proto into an Execution data object.""" + execution_proto = debug_event.execution + + debug_tensor_values = None + if (execution_proto.tensor_debug_mode == + debug_event_pb2.TensorDebugMode.FULL_TENSOR): + pass # TODO(cais): Build tensor store. + elif (execution_proto.tensor_debug_mode != + debug_event_pb2.TensorDebugMode.NO_TENSOR): + debug_tensor_values = [] + for tensor_proto in execution_proto.tensor_protos: + # TODO(cais): Refactor into a helper method. + debug_tensor_values.append( + _parse_tensor_value(tensor_proto, return_list=True)) + return Execution( + _execution_digest_from_debug_event_proto(debug_event, locator), + execution_proto.code_location.host_name, + tuple(execution_proto.code_location.stack_frame_ids), + execution_proto.tensor_debug_mode, + graph_id=execution_proto.graph_id, + input_tensor_ids=tuple(execution_proto.input_tensor_ids), + output_tensor_ids=tuple(execution_proto.output_tensor_ids), + debug_tensor_values=_tuple_or_none(debug_tensor_values)) + + +class DebugDataReader: + """A reader that reads structured debugging data in the tfdbg v2 format. + + The set of data read by an object of this class concerns the execution history + of a tfdbg2-instrumented TensorFlow program. + + Note: + - An object of this class incrementally reads data from files that belong to + the tfdbg v2 DebugEvent file set. Calling `update()` triggers the reading + from the last-successful reading positions in the files. + - This object can be used as a context manager. Its `__exit__()` call + closes the file readers cleanly. + """ + + def __init__(self, dump_root): + self._reader = DebugEventsReader(dump_root) + + # TODO(cais): Implement pagination for memory constraints. + self._execution_digests = [] + + # Mapping (host_name, file_path) tuple to offset in the .source_files file. + self._host_name_file_path_to_offset = collections.OrderedDict() + # A dict mapping id to (host_name, file_path, lineno, func) tuple. + self._stack_frame_by_id = dict() + # Stores unprocessed stack frame IDs. This is necessary to handle the + # case in which reading of the .stack_frames file gets ahead of the reading + # of the .source_files file. + self._unprocessed_stack_frames = dict() + # A dict mapping id to DebuggedDevice objects. + self._device_by_id = dict() + # A dict mapping id to DebuggedGraph objects. + self._graph_by_id = dict() + self._graph_op_digests = [] + # TODO(cais): Implement pagination for memory constraints. + self._graph_execution_trace_digests = [] + + self._monitors = [] + + def _add_monitor(self, monitor): + self._monitors.append(monitor) + + def _load_source_files(self): + """Incrementally read the .source_files DebugEvent file.""" + source_files_iter = self._reader.source_files_iterator() + for debug_event, offset in source_files_iter: + source_file = debug_event.source_file + self._host_name_file_path_to_offset[ + (source_file.host_name, source_file.file_path)] = offset + + def _load_stack_frames(self): + """Incrementally read the .stack_frames file. + + This must be called after _load_source_files(). + It assumes that the following contract is honored by the writer of the tfdbg + v2 data file set: + - Before a stack frame is written to the .stack_frames file, the + corresponding source file information must have been written to the + .source_files file first. + """ + stack_frames_iter = self._reader.stack_frames_iterator() + for debug_event, _ in stack_frames_iter: + stack_frame_with_id = debug_event.stack_frame_with_id + file_line_col = stack_frame_with_id.file_line_col + self._unprocessed_stack_frames[stack_frame_with_id.id] = file_line_col + # We do the processing in a separate stage, because the reading in the + # .source_files file may sometimes get ahead of the .source_files file. + unprocessed_stack_frame_ids = tuple(self._unprocessed_stack_frames.keys()) + for stack_frame_id in unprocessed_stack_frame_ids: + file_line_col = self._unprocessed_stack_frames[stack_frame_id] + if len(self._host_name_file_path_to_offset) > file_line_col.file_index: + host_name, file_path = list(self._host_name_file_path_to_offset.keys())[ + file_line_col.file_index] + self._stack_frame_by_id[stack_frame_id] = ( + host_name, file_path, file_line_col.line, file_line_col.func) + del self._unprocessed_stack_frames[stack_frame_id] + + def _load_graphs(self): + """Incrementally read the .graphs file. + + Compiles the DebuggedGraph and GraphOpCreation data. + """ + graphs_iter = self._reader.graphs_iterator() + for debug_event, offset in graphs_iter: + if debug_event.graph_op_creation.ByteSize(): + op_creation_proto = debug_event.graph_op_creation + op_digest = GraphOpCreationDigest( + debug_event.wall_time, + offset, + op_creation_proto.graph_id, + op_creation_proto.op_type, + op_creation_proto.op_name, + tuple(op_creation_proto.output_tensor_ids), + op_creation_proto.code_location.host_name, + tuple(op_creation_proto.code_location.stack_frame_ids), + input_names=tuple(op_creation_proto.input_names)) + self._graph_op_digests.append(op_digest) + debugged_graph = self._graph_by_id[op_creation_proto.graph_id] + debugged_graph.add_op(op_digest) + for dst_slot, input_name in enumerate(op_creation_proto.input_names): + src_op_name, src_slot = input_name.split(":") + debugged_graph.add_op_consumer(src_op_name, int(src_slot), + op_creation_proto.op_name, dst_slot) + + elif debug_event.debugged_graph.ByteSize(): + graph_proto = debug_event.debugged_graph + graph = DebuggedGraph( + graph_proto.graph_name or None, + graph_proto.graph_id, + outer_graph_id=graph_proto.outer_context_id or None) + self._graph_by_id[graph_proto.graph_id] = graph + if graph_proto.outer_context_id: + self._graph_by_id[ + graph_proto.outer_context_id].add_inner_graph_id(graph.graph_id) + elif debug_event.debugged_device.ByteSize(): + device_proto = debug_event.debugged_device + self._device_by_id[device_proto.device_id] = DebuggedDevice( + device_proto.device_name, device_proto.device_id) + + def _load_graph_execution_traces(self): + """Incrementally load the .graph_execution_traces file.""" + for i, traces_iter in enumerate( + self._reader.graph_execution_traces_iterators()): + for debug_event, offset in traces_iter: + self._graph_execution_trace_digests.append( + self._graph_execution_trace_digest_from_debug_event_proto( + debug_event, (i, offset))) + if self._monitors: + graph_execution_trace = ( + self._graph_execution_trace_from_debug_event_proto( + debug_event, (i, offset))) + for monitor in self._monitors: + monitor.on_graph_execution_trace( + len(self._graph_execution_trace_digests) - 1, + graph_execution_trace) + + def _graph_execution_trace_digest_from_debug_event_proto( + self, debug_event, locator): + trace_proto = debug_event.graph_execution_trace + op_name = trace_proto.op_name + op_type = self._lookup_op_type(trace_proto.tfdbg_context_id, op_name) + return GraphExecutionTraceDigest( + debug_event.wall_time, locator, op_type, op_name, + trace_proto.output_slot, + debug_event.graph_execution_trace.tfdbg_context_id) + + def _graph_execution_trace_from_debug_event_proto(self, debug_event, locator): + """Convert a DebugEvent proto into a GraphExecutionTrace data object.""" + trace_proto = debug_event.graph_execution_trace + graph_ids = [trace_proto.tfdbg_context_id] + # Walk up the chain of outer contexts (graphs), so as to include all of + # their IDs + while True: + graph = self.graph_by_id(graph_ids[0]) + if graph.outer_graph_id: + graph_ids.insert(0, graph.outer_graph_id) + else: + break + + if (trace_proto.tensor_debug_mode == + debug_event_pb2.TensorDebugMode.FULL_TENSOR): + debug_tensor_value = None + else: + debug_tensor_value = _parse_tensor_value( + trace_proto.tensor_proto, return_list=True) + return GraphExecutionTrace( + self._graph_execution_trace_digest_from_debug_event_proto( + debug_event, locator), + graph_ids=graph_ids, + tensor_debug_mode=trace_proto.tensor_debug_mode, + debug_tensor_value=debug_tensor_value, + device_name=trace_proto.device_name or None) + + def _lookup_op_type(self, graph_id, op_name): + """Lookup the type of an op by name and the immediately enclosing graph. + + Args: + graph_id: Debugger-generated ID of the immediately-enclosing graph. + op_name: Name of the op. + + Returns: + Op type as a str. + """ + return self._graph_by_id[graph_id].get_op_creation_digest(op_name).op_type + + def _load_execution(self): + """Incrementally read the .execution file.""" + execution_iter = self._reader.execution_iterator() + for debug_event, offset in execution_iter: + self._execution_digests.append( + _execution_digest_from_debug_event_proto(debug_event, offset)) + if self._monitors: + execution = _execution_from_debug_event_proto(debug_event, offset) + for monitor in self._monitors: + monitor.on_execution(len(self._execution_digests) - 1, execution) + + def update(self): + """Perform incremental read of the file set.""" + self._load_source_files() + self._load_stack_frames() + self._load_graphs() + self._load_graph_execution_traces() + self._load_execution() + + def source_file_list(self): + """Get a list of source files known to the debugger data reader. + + Returns: + A tuple of `(host_name, file_path)` tuples. + """ + return tuple(self._host_name_file_path_to_offset.keys()) + + def source_lines(self, host_name, file_path): + """Read the line-by-line content of a source file. + + Args: + host_name: Host name on which the source file is located. + file_path: File path at which the source file is located. + + Returns: + Lines of the source file as a `list` of `str`s. + """ + offset = self._host_name_file_path_to_offset[(host_name, file_path)] + return list(self._reader.read_source_files_event(offset).source_file.lines) + + def starting_wall_time(self): + """Wall timestamp for when the debugged TensorFlow program started. + + Returns: + Stating wall time as seconds since the epoch, as a `float`. + """ + return self._reader.starting_wall_time() + + def tensorflow_version(self): + """TensorFlow version used in the debugged TensorFlow program. + + Note: this is not necessarily the same as the version of TensorFlow used to + load the DebugEvent file set. + + Returns: + TensorFlow version used by the debugged program, as a `str`. + """ + return self._reader.tensorflow_version() + + def tfdbg_run_id(self): + """Get the debugger run ID of the debugged TensorFlow program.""" + return self._reader.tfdbg_run_id() + + def outermost_graphs(self): + """Get the number of outer most graphs read so far.""" + return [graph for graph in self._graph_by_id.values() + if not graph.outer_graph_id] + + def graph_by_id(self, graph_id): + """Get a DebuggedGraph object by its ID.""" + return self._graph_by_id[graph_id] + + def device_name_by_id(self, device_id): + """Get the name of a device by the debugger-generated ID of the device.""" + return self._device_by_id[device_id].device_name + + def device_name_map(self): + """Get a map mapping device IDs to device names.""" + return {device_id: self._device_by_id[device_id].device_name + for device_id in self._device_by_id} + + def graph_op_digests(self, op_type=None): + """Get the list of the digests for graph-op creation so far. + + Args: + op_type: Optional op type to filter the creation events with. + + Returns: + A list of `GraphOpCreationDigest` objects. + """ + if op_type is not None: + return [digest for digest in self._graph_op_digests + if digest.op_type == op_type] + else: + return self._graph_op_digests + + def graph_execution_traces(self, digest=False, begin=None, end=None): + """Get all the intra-graph execution tensor traces read so far. + + Args: + digest: Whether the results will be returned in the more light-weight + digest form. + begin: Optional beginning index for the requested traces or their digests. + Python-style negative indices are supported. + end: Optional ending index for the requested traces or their digests. + Python-style negative indices are supported. + + Returns: + If `digest`: a `list` of `GraphExecutionTraceDigest` objects. + Else: a `list` of `GraphExecutionTrace` objects. + """ + digests = self._graph_execution_trace_digests + if begin is not None or end is not None: + begin = begin or 0 + end = end or len(digests) + digests = digests[begin:end] + if digest: + return digests + else: + return [self.read_graph_execution_trace(digest) for digest in digests] + + def num_graph_execution_traces(self): + """Get the number of graph execution traces read so far.""" + return len(self._graph_execution_trace_digests) + + def executions(self, digest=False, begin=None, end=None): + """Get `Execution`s or `ExecutionDigest`s this reader has read so far. + + Args: + digest: Whether the results are returned in a digest form, i.e., + `ExecutionDigest` format, instead of the more detailed `Execution` + format. + begin: Optional beginning index for the requested execution data objects + or their digests. Python-style negative indices are supported. + end: Optional ending index for the requested execution data objects or + their digests. Python-style negative indices are supported. + + Returns: + If `digest`: a `list` of `ExecutionDigest` objects. + Else: a `list` of `Execution` objects. + """ + digests = self._execution_digests + if begin is not None or end is not None: + begin = begin or 0 + end = end or len(digests) + digests = digests[begin:end] + if digest: + return digests + else: + # TODO(cais): Optimizer performance removing repeated file open/close. + return [self.read_execution(digest) for digest in digests] + + def num_executions(self): + """Get the number of execution events read so far.""" + return len(self._execution_digests) + + def read_execution(self, execution_digest): + """Read a detailed Execution object.""" + debug_event = self._reader.read_execution_event(execution_digest.locator) + return _execution_from_debug_event_proto(debug_event, + execution_digest.locator) + + def read_graph_execution_trace(self, graph_execution_trace_digest): + """Read the detailed graph execution trace. + + Args: + graph_execution_trace_digest: A `GraphExecutionTraceDigest` object. + + Returns: + The corresponding `GraphExecutionTrace` object. + """ + debug_event = self._reader.read_graph_execution_traces_event( + graph_execution_trace_digest.locator) + return self._graph_execution_trace_from_debug_event_proto( + debug_event, graph_execution_trace_digest.locator) + + def read_execution_stack_trace(self, execution): + """Read the stack trace of a given Execution object. + + Args: + execution: The Execution object of interest. + + Returns: + 1. The host name. + 2. The stack trace, as a list of (file_path, lineno, func) tuples. + """ + host_name = self._stack_frame_by_id[execution.stack_frame_ids[0]][0] + return (host_name, [ + self._stack_frame_by_id[frame_id][1:] + for frame_id in execution.stack_frame_ids]) + + def read_graph_op_creation_stack_trace(self, graph_op_creation_digest): + """Read the stack trace of a given graph op creation object. + + Args: + graph_op_creation_digest: The GraphOpCreationDigest object of interest. + + Returns: + A tuple consisting of: + 1. The host name. + 2. The stack trace, as a list of (file_path, lineno, func) tuples. + """ + return graph_op_creation_digest.host_name, [ + self._stack_frame_by_id[frame_id][1:] + for frame_id in graph_op_creation_digest.stack_frame_ids + ] + + # TODO(cais): Add graph_execution_digests() with an ExecutionDigest + # as a kwarg, to establish the association between top-level and intra-graph + # execution events. + + def execution_to_tensor_values(self, execution): + """Read the full tensor values from an Execution or ExecutionDigest. + + Args: + execution: An `ExecutionDigest` or `ExecutionDigest` object. + + Returns: + A list of numpy arrays representing the output tensor values of the + execution event. + """ + debug_event = self._reader.read_execution_event(execution.locator) + return [_parse_tensor_value(tensor_proto) + for tensor_proto in debug_event.execution.tensor_protos] + + def graph_execution_trace_to_tensor_value(self, trace): + """Read full tensor values from an Execution or ExecutionDigest. + + Args: + trace: An `GraphExecutionTraceDigest` or `GraphExecutionTrace` object. + + Returns: + A numpy array representing the output tensor value of the intra-graph + tensor execution event. + """ + debug_event = self._reader.read_graph_execution_traces_event(trace.locator) + return _parse_tensor_value(debug_event.graph_execution_trace.tensor_proto) + + def symbolic_tensor_id(self, graph_id, op_name, output_slot): + """Get the ID of a symbolic tensor. + + Args: + graph_id: The ID of the immediately-enclosing graph. + op_name: Name of the op. + output_slot: Output slot as an int. + + Returns: + The ID of the symbolic tensor as an int. + """ + return self._graph_by_id[graph_id].get_tensor_id(op_name, output_slot) + + def graph_execution_trace_to_tensor_id(self, trace): + """Get symbolic tensor ID from a GraphExecutoinTraceDigest object.""" + return self.symbolic_tensor_id( + trace.graph_id, trace.op_name, trace.output_slot) + + def __enter__(self): + return self + + def __exit__(self, exception_type, exception_value, traceback): + del exception_type, exception_value, traceback # Unused + self._reader.close() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_writer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..3373b78498f43e8631a6cd8df6f74cfacb406b1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_events_writer.py @@ -0,0 +1,158 @@ +# 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. +# ============================================================================== +"""Writer class for `DebugEvent` protos in tfdbg v2.""" + +import time + +from tensorflow.core.protobuf import debug_event_pb2 +from tensorflow.python.client import _pywrap_debug_events_writer + +# Default size of each circular buffer (unit: number of DebugEvent protos). +DEFAULT_CIRCULAR_BUFFER_SIZE = 1000 + + +class DebugEventsWriter(object): + """A writer for TF debugging events. Used by tfdbg v2.""" + + def __init__(self, + dump_root, + tfdbg_run_id, + circular_buffer_size=DEFAULT_CIRCULAR_BUFFER_SIZE): + """Construct a DebugEventsWriter object. + + NOTE: Given the same `dump_root`, all objects from this constructor + will point to the same underlying set of writers. In other words, they + will write to the same set of debug events files in the `dump_root` + folder. + + Args: + dump_root: The root directory for dumping debug data. If `dump_root` does + not exist as a directory, it will be created. + tfdbg_run_id: Debugger Run ID. + circular_buffer_size: Size of the circular buffer for each of the two + execution-related debug events files: with the following suffixes: - + .execution - .graph_execution_traces If <= 0, the circular-buffer + behavior will be abolished in the constructed object. + """ + if not dump_root: + raise ValueError("Empty or None dump root") + self._dump_root = dump_root + self._tfdbg_run_id = tfdbg_run_id + _pywrap_debug_events_writer.Init(self._dump_root, self._tfdbg_run_id, + circular_buffer_size) + + def WriteSourceFile(self, source_file): + """Write a SourceFile proto with the writer. + + Args: + source_file: A SourceFile proto, describing the content of a source file + involved in the execution of the debugged TensorFlow program. + """ + # TODO(cais): Explore performance optimization that avoids memcpy. + debug_event = debug_event_pb2.DebugEvent(source_file=source_file) + self._EnsureTimestampAdded(debug_event) + _pywrap_debug_events_writer.WriteSourceFile(self._dump_root, debug_event) + + def WriteStackFrameWithId(self, stack_frame_with_id): + """Write a StackFrameWithId proto with the writer. + + Args: + stack_frame_with_id: A StackFrameWithId proto, describing the content a + stack frame involved in the execution of the debugged TensorFlow + program. + """ + debug_event = debug_event_pb2.DebugEvent( + stack_frame_with_id=stack_frame_with_id) + self._EnsureTimestampAdded(debug_event) + _pywrap_debug_events_writer.WriteStackFrameWithId(self._dump_root, + debug_event) + + def WriteGraphOpCreation(self, graph_op_creation): + """Write a GraphOpCreation proto with the writer. + + Args: + graph_op_creation: A GraphOpCreation proto, describing the details of the + creation of an op inside a TensorFlow Graph. + """ + debug_event = debug_event_pb2.DebugEvent( + graph_op_creation=graph_op_creation) + self._EnsureTimestampAdded(debug_event) + _pywrap_debug_events_writer.WriteGraphOpCreation(self._dump_root, + debug_event) + + def WriteDebuggedGraph(self, debugged_graph): + """Write a DebuggedGraph proto with the writer. + + Args: + debugged_graph: A DebuggedGraph proto, describing the details of a + TensorFlow Graph that has completed its construction. + """ + debug_event = debug_event_pb2.DebugEvent(debugged_graph=debugged_graph) + self._EnsureTimestampAdded(debug_event) + _pywrap_debug_events_writer.WriteDebuggedGraph(self._dump_root, debug_event) + + def WriteExecution(self, execution): + """Write a Execution proto with the writer. + + Args: + execution: An Execution proto, describing a TensorFlow op or graph + execution event. + """ + debug_event = debug_event_pb2.DebugEvent(execution=execution) + self._EnsureTimestampAdded(debug_event) + _pywrap_debug_events_writer.WriteExecution(self._dump_root, debug_event) + + def WriteGraphExecutionTrace(self, graph_execution_trace): + """Write a GraphExecutionTrace proto with the writer. + + Args: + graph_execution_trace: A GraphExecutionTrace proto, concerning the value + of an intermediate tensor or a list of intermediate tensors that are + computed during the graph's execution. + """ + debug_event = debug_event_pb2.DebugEvent( + graph_execution_trace=graph_execution_trace) + self._EnsureTimestampAdded(debug_event) + _pywrap_debug_events_writer.WriteGraphExecutionTrace( + self._dump_root, debug_event) + + def RegisterDeviceAndGetId(self, device_name): + return _pywrap_debug_events_writer.RegisterDeviceAndGetId( + self._dump_root, device_name) + + def FlushNonExecutionFiles(self): + """Flush the non-execution debug event files.""" + _pywrap_debug_events_writer.FlushNonExecutionFiles(self._dump_root) + + def FlushExecutionFiles(self): + """Flush the execution debug event files. + + Causes the current content of the cyclic buffers to be written to + the .execution and .graph_execution_traces debug events files. + Also clears those cyclic buffers. + """ + _pywrap_debug_events_writer.FlushExecutionFiles(self._dump_root) + + def Close(self): + """Close the writer.""" + _pywrap_debug_events_writer.Close(self._dump_root) + + @property + def dump_root(self): + return self._dump_root + + def _EnsureTimestampAdded(self, debug_event): + if debug_event.wall_time == 0: + debug_event.wall_time = time.time() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_gradients.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..529264b2c5525f669f8f52d9312d605110810840 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_gradients.py @@ -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. +# ============================================================================== +"""TensorFlow Debugger: Tools for debugging gradients.""" + +import re +import uuid + +from tensorflow.python.debug.lib import debug_data +from tensorflow.python.debug.lib import debug_graphs +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import variables + +_GRADIENT_DEBUG_TAG = "gradient_debug_" + +_gradient_debuggers = {} + + +def _tensor_to_grad_debug_op_name(tensor, grad_debugger_uuid): + op_name, slot = debug_graphs.parse_node_or_tensor_name(tensor.name) + return "%s_%d/%s%s" % (op_name, slot, _GRADIENT_DEBUG_TAG, grad_debugger_uuid) + + +def _parse_grad_debug_op_name(op_name): + """Parse the name of a debug gradient op. + + Args: + op_name: the name of the debug gradient op. + + Returns: + 1) The UUID of the GradientsDebugger that created the debug gradient op. + 2) Name of the original tensor whose gradient is debugged by the debug + gradient op. + """ + name_items = op_name.split("/") + assert len(name_items) > 1 + assert name_items[-1].startswith(_GRADIENT_DEBUG_TAG) + + grad_debugger_uuid = name_items[-1][len(_GRADIENT_DEBUG_TAG):] + if "_" in grad_debugger_uuid: + grad_debugger_uuid = grad_debugger_uuid[:grad_debugger_uuid.index("_")] + orig_tensor_slot = int(name_items[-2][name_items[-2].rfind("_") + 1:]) + orig_base_op_name = name_items[-2][:name_items[-2].rfind("_")] + orig_tensor_name = ("/".join(name_items[:-2] + [orig_base_op_name]) + + ":%d" % orig_tensor_slot) + + return grad_debugger_uuid, orig_tensor_name + + +class GradientsDebugger: + """Gradients Debugger. + + Allows retrieval of gradient tensors created by TensorFlow's automatic + differentiation algorithm, i.e., `tf.gradients` and optimizer classes that + use it. + """ + # TODO(cais): Add examples code in the doc string? + + def __init__(self, y_tensor=None): + """Constructor of GradientsDebugger. + + Args: + y_tensor: optional: the `tf.Tensor` to be differentiated, i.e., the tensor + on the numerator of the differentiation. + """ + + self._uuid = uuid.uuid4().hex + _gradient_debuggers[self._uuid] = self + + # A dict mapping x-tensor names to gradient tensor. x-tensor refers to the + # independent tf.Tensor, i.e., the tensor on the denominator of the + # differentiation. + self._gradient_tensors = {} + self._y_tensor = y_tensor + + self._graph = None + if y_tensor: + self._graph = y_tensor.graph + + self._is_active_context = False + + @property + def y_tensor(self): + return self._y_tensor + + @property + def graph(self): + return self._graph + + def __enter__(self): + self._is_active_context = True + + def __exit__(self, unused_type, unused_value, unused_traceback): + self._is_active_context = False + + def identify_gradient(self, input_tensor): + """Create a debug identity tensor that registers and forwards gradients. + + The side effect of this method is that when gradient tensor(s) are created + with respect to the any paths that include the `input_tensor`, the gradient + tensor(s) with respect to `input_tensor` will be registered with this + this `GradientsDebugger` instance and can later be retrieved, with the + methods `gradient_tensor` and `gradient_tensors`. + + Example: + + ```python + x = tf.Variable(1.0) + y = tf.add(x, x) + + grad_debugger = tf_debug.GradientsDebugger() + debug_y = grad_debugger.identify_gradient(y) + z = tf.square(debug_y) + + # Create a train op under the grad_debugger context. + with grad_debugger: + train_op = tf.compat.v1.train.GradientDescentOptimizer(z) + + # Now we can reflect through grad_debugger to get the gradient tensor + # with respect to y. + y_grad = grad_debugger.gradient_tensor(y) + ``` + + Args: + input_tensor: the input `tf.Tensor` object whose related gradient tensors + are to be registered with this `GradientsDebugger` instance when they + are created, e.g., during `tf.gradients` calls or the construction + of optimization (training) op that uses `tf.gradients`. + + Returns: + A forwarded identity of `input_tensor`, as a `tf.Tensor`. + + Raises: + ValueError: If an op with name that duplicates the gradient-debugging op + already exists in the graph (highly unlikely). + """ + # TODO(cais): Allow overriding gradient. + # TODO(cais): Implement value_stack. + grad_debug_op_name = _tensor_to_grad_debug_op_name(input_tensor, self._uuid) + # pylint: disable=protected-access + identity_op = ( + gen_array_ops.debug_gradient_ref_identity + if input_tensor.dtype._is_ref_dtype else + gen_array_ops.debug_gradient_identity) + # pylint: enable=protected-access + debug_grad_identity = identity_op(input_tensor, name=grad_debug_op_name) + assert debug_grad_identity.dtype == input_tensor.dtype + if debug_grad_identity.op.name != grad_debug_op_name: + raise ValueError( + "The graph already contains an op named %s" % grad_debug_op_name) + return debug_grad_identity + + def watch_gradients_by_tensors(self, graph, tensors): + """Watch gradient tensors by x-tensor(s). + + The side effect of this method is that when gradient tensor(s) are created + with respect to the any paths that include the `x_tensor`s, the gradient + tensor(s) with respect to the tensor will be registered with this + this `GradientsDebugger` instance and can later be retrieved, with the + methods `gradient_tensor` and `gradient_tensors`. + + Unlike the method `identify_gradient`, this method is used to retrieve + gradient tensors after the construction of the forward subgraph has + completed (but before the construction of the backward subgraph). + + This method is the same as `watch_gradients_by_x_tensor_names` except that + the tensors are specified by the Python `tf.Tensor` or `tf.Variable` + objects, instead by name patterns. + + Example: + + ```python + x = tf.Variable(1.0) + y = tf.add(x, x, name="y") + z = tf.square(debug_y) + + # Create a train op under the grad_debugger context. + grad_debugger = tf_debug.GradientsDebugger() + with grad_debugger.watch_gradients_by_tensors(y): + train_op = tf.compat.v1.train.GradientDescentOptimizer(z) + + # Now we can reflect through grad_debugger to get the gradient tensor + # with respect to y. + y_grad = grad_debugger.gradient_tensor(y) + # or + y_grad = grad_debugger.gradient_tensor("y:0") + ``` + + Args: + graph: the `tf.Graph` to watch the gradients on. + tensors: a `tf.Tensor` or `tf.Variable` object, or a list of such objects. + + Returns: + The GradientsDebugger instance itself. + """ + + if not isinstance(tensors, list): + tensors = [tensors] + + tensor_name_regex = [] + for tensor in tensors: + tensor_name_regex.append(re.escape(tensor.name) + "$") + tensor_name_regex = "(" + "|".join(tensor_name_regex) + ")" + return self.watch_gradients_by_tensor_names(graph, tensor_name_regex) + + def watch_gradients_by_tensor_names(self, graph, tensor_name_regex): + """Watch gradient tensors by name(s) of the x-tensor(s). + + The side effect of this method is that when gradient tensor(s) are created + with respect to the x-tensors, the gradient tensor(s) will be registered + with this `GradientsDebugger` instance and can later be retrieved. + + Unlike the `identify_gradient` method, this method is used after the + construction of the forward graph has completed. Unlike the + `watch_gradients_by_tensor` method, this method does not use handles to the + tensors of interest; it uses their names. + + This method is the same as `watch_gradients_by_tensors` except that the + x-tensors are specified by name patterns, instead of `tf.Tensor` or + `tf.Variable` objects. + + Example: + + ```python + x = tf.Variable(1.0, name="x") + y = tf.add(x, x, name="y") + z = tf.square(debug_y) + + # Create a train op under the grad_debugger context. + grad_debugger = tf_debug.GradientsDebugger() + with grad_debugger.watch_gradients_by_tensor_names(r"(x|y):0$"): + train_op = tf.compat.v1.train.GradientDescentOptimizer(z) + + # Now we can reflect through grad_debugger to get the gradient tensor + # with respect to x and y. + x_grad = grad_debugger.gradient_tensor("x:0") + y_grad = grad_debugger.gradient_tensor("y:0") + ``` + + Args: + graph: the `tf.Graph` to watch the gradients on. + tensor_name_regex: the regular-expression pattern of the name(s) of the + x-tensor(s) to watch. x-tensor refers to the tensors on the denominator + of the differentiation. + + Returns: + The GradientsDebugger instance itself. + """ + tensor_name_pattern = re.compile(tensor_name_regex) + with graph.as_default(): + for op in graph.get_operations(): + for output in op.outputs: + if tensor_name_pattern.match(output.name): + debug_op = self.identify_gradient(output) + + # Make a copy of output.consumers() since we'll modify the consumers + # TODO(skyewm): this is unnecessary once the C API is enabled + for consumer in list(output.consumers()): + if consumer == debug_op.op: + continue + + # Locate the slot index of the original input. + for i, consumer_input in enumerate(consumer.inputs): + if consumer_input == output: + consumer._update_input(i, debug_op) # pylint: disable=protected-access + return self + + def _check_same_graph(self, tensor): + if self._graph is None: + self._graph = tensor.graph + elif self._graph != tensor.graph: + raise ValueError( + "The graph of the value (%s) is not the same as the graph %s" % + (tensor.graph, self._graph)) + + def register_gradient_tensor(self, + x_tensor_name, + gradient_tensor): + """Register the gradient tensor for an x-tensor. + + Args: + x_tensor_name: (`str`) the name of the independent `tf.Tensor`, i.e., + the tensor on the denominator of the differentiation. + gradient_tensor: the gradient `tf.Tensor`. + """ + if len(_gradient_debuggers) == 1 or self._is_active_context: + self._check_same_graph(gradient_tensor) + self._gradient_tensors[x_tensor_name] = gradient_tensor + + def gradient_tensor(self, x_tensor): + """Get the gradient tensor of an x-tensor. + + Args: + x_tensor: (`tf.Tensor`, `tf.Variable` or `str`) The x-tensor object or its + name. x-tensor refers to the independent `tf.Tensor`, i.e., the tensor + on the denominator of the differentiation. + + Returns: + If found, the gradient tensor. + + Raises: + TypeError: If `x_tensor` is not a `tf.Tensor`, `tf.Variable` or `str`. + LookupError: If the `x_tensor` has not been registered with a gradient + tensor. + """ + x_tensor_name = self._get_tensor_name(x_tensor) + if x_tensor_name not in self._gradient_tensors: + raise LookupError( + "This GradientsDebugger has not received any gradient tensor for " + "x-tensor %s" % x_tensor_name) + return self._gradient_tensors[x_tensor_name] + + def gradient_tensors(self): + """Get the gradient tensors that this object is aware of. + + Returns: + A dict mapping x-tensor names to gradient tensor objects. x-tensor refers + to the tensors on the denominator of the differentation. + """ + return self._gradient_tensors + + def _get_tensor_name(self, tensor): + if isinstance(tensor, (tensor_lib.Tensor, variables.Variable)): + return tensor.name + elif isinstance(tensor, str): + return tensor + else: + raise TypeError( + "x_tensor must be a str or tf.Tensor or tf.Variable, " + "but instead has type %s" % type(tensor)) + + +def clear_gradient_debuggers(): + """Clear all globally registered gradient debuggers.""" + _gradient_debuggers.clear() + + +@ops.RegisterGradient("DebugGradientIdentity") +def _identify_gradient_grad(op, dy): + """Gradient function for the DebugIdentity op.""" + # TODO(cais): Allow overriding gradient. + grad_debugger_uuid, orig_tensor_name = _parse_grad_debug_op_name(op.name) + grad_debugger = _gradient_debuggers[grad_debugger_uuid] + grad_debugger.register_gradient_tensor(orig_tensor_name, dy) + return dy + + +@ops.RegisterGradient("DebugGradientRefIdentity") +def _identify_gradient_grad_ref(op, dy): + """Gradient function for the DebugIdentity op.""" + return _identify_gradient_grad(op, dy) + + +def gradient_values_from_dump(grad_debugger, x_tensor, dump): + """Find gradient values from a `DebugDumpDir` object. + + Args: + grad_debugger: the `tf_debug.GradientsDebugger` instance to be used. + x_tensor: (`tf.Tensor`, `tf.Variable` or `str`) The x-tensor object or its + name. x-tensor refers to the independent `tf.Tensor`, i.e., the tensor + on the denominator of the differentiation. + dump: A `tfdbg.DebugDumpDir` object. + + Returns: + If this `GradientsDebugger` instance has the gradient tensor of `x_tensor` + registered: a list of `numpy.ndarray` representing the value of the + gradient tensor from `dump`. The list could be empty, if the gradient + tensor is not executed in the `tf.Session.run()` call that generated + the `dump`. The list could also contain multiple values of the gradient + tensor, e.g., if gradient tensor is computed repeatedly in a + `tf.while_loop` during the run that generated the `dump`. + + Raises: + LookupError: If this `GradientsDebugger` instance does not have the + gradient tensor of `x_tensor` registered. + ValueError: If this `GradientsDebugger` has a `tf.Graph` object that + does not match the `tf.Graph` object of the `dump`. + TypeError: If `x_tensor` is not a `tf.Tensor`, `tf.Variable` or `str`. + """ + # TODO(cais): Use this method in LocalCLIDebugWrapperSession to present the + # gradient tensors to the TFDBG CLI. + + # If possible, verify that the Python graph of the dump and that of this + # GradientsDebugger match. + if (dump.python_graph and grad_debugger.graph and + dump.python_graph != grad_debugger.graph): + raise ValueError( + "This GradientsDebugger instance has a graph (%s) that differs from " + "the graph of the DebugDumpDir object (%s)." % + (grad_debugger.graph, dump.python_graph)) + + gradient_tensor = grad_debugger.gradient_tensor(x_tensor) + node_name, output_slot = debug_graphs.parse_node_or_tensor_name( + gradient_tensor.name) + + try: + return dump.get_tensors(node_name, output_slot, "DebugIdentity") + except debug_data.WatchKeyDoesNotExistInDebugDumpDirError: + return [] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_graphs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_graphs.py new file mode 100644 index 0000000000000000000000000000000000000000..f49ad8f301c5296e2d710c3fea4d9b3df2b9fbb2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_graphs.py @@ -0,0 +1,499 @@ +# 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 and methods for processing debugger-decorated graphs.""" +from tensorflow.core.framework import graph_pb2 +from tensorflow.python.framework import op_def_registry +from tensorflow.python.platform import tf_logging as logging + + +def parse_node_or_tensor_name(name): + """Get the node name from a string that can be node or tensor name. + + Args: + name: An input node name (e.g., "node_a") or tensor name (e.g., + "node_a:0"), as a str. + + Returns: + 1) The node name, as a str. If the input name is a tensor name, i.e., + consists of a colon, the final colon and the following output slot + will be stripped. + 2) If the input name is a tensor name, the output slot, as an int. If + the input name is not a tensor name, None. + """ + + if ":" in name and not name.endswith(":"): + node_name = name[:name.rfind(":")] + output_slot = int(name[name.rfind(":") + 1:]) + + return node_name, output_slot + else: + return name, None + + +def get_node_name(element_name): + node_name, _ = parse_node_or_tensor_name(element_name) + return node_name + + +def get_output_slot(element_name): + """Get the output slot number from the name of a graph element. + + If element_name is a node name without output slot at the end, 0 will be + assumed. + + Args: + element_name: (`str`) name of the graph element in question. + + Returns: + (`int`) output slot number. + """ + _, output_slot = parse_node_or_tensor_name(element_name) + return output_slot if output_slot is not None else 0 + + +def is_copy_node(node_name): + """Determine whether a node name is that of a debug Copy node. + + Such nodes are inserted by TensorFlow core upon request in + RunOptions.debug_options.debug_tensor_watch_opts. + + Args: + node_name: Name of the node. + + Returns: + A bool indicating whether the input argument is the name of a debug Copy + node. + """ + return node_name.startswith("__copy_") + + +def is_debug_node(node_name): + """Determine whether a node name is that of a debug node. + + Such nodes are inserted by TensorFlow core upon request in + RunOptions.debug_options.debug_tensor_watch_opts. + + Args: + node_name: Name of the node. + + Returns: + A bool indicating whether the input argument is the name of a debug node. + """ + return node_name.startswith("__dbg_") + + +def parse_debug_node_name(node_name): + """Parse the name of a debug node. + + Args: + node_name: Name of the debug node. + + Returns: + 1. Name of the watched node, as a str. + 2. Output slot index of the watched tensor, as an int. + 3. Index of the debug node, as an int. + 4. Name of the debug op, as a str, e.g, "DebugIdentity". + + Raises: + ValueError: If the input node name is not a valid debug node name. + """ + prefix = "__dbg_" + + name = node_name + if not name.startswith(prefix): + raise ValueError("Invalid prefix in debug node name: '%s'" % node_name) + + name = name[len(prefix):] + + if name.count("_") < 2: + raise ValueError("Invalid debug node name: '%s'" % node_name) + + debug_op = name[name.rindex("_") + 1:] + name = name[:name.rindex("_")] + + debug_op_index = int(name[name.rindex("_") + 1:]) + name = name[:name.rindex("_")] + + if name.count(":") != 1: + raise ValueError("Invalid tensor name in debug node name: '%s'" % node_name) + + watched_node_name = name[:name.index(":")] + watched_output_slot = int(name[name.index(":") + 1:]) + + return watched_node_name, watched_output_slot, debug_op_index, debug_op + + +class GraphTracingReachedDestination(Exception): + pass + + +class DFSGraphTracer(object): + """Graph input tracer using depth-first search.""" + + def __init__(self, + input_lists, + skip_node_names=None, + destination_node_name=None): + """Constructor of _DFSGraphTracer. + + Args: + input_lists: A list of dicts. Each dict is an adjacency (input) map from + the recipient node name as the key and the list of input node names + as the value. + skip_node_names: Optional: a list of node names to skip tracing. + destination_node_name: Optional: destination node name. If not `None`, it + should be the name of a destination not as a str and the graph tracing + will raise GraphTracingReachedDestination as soon as the node has been + reached. + + Raises: + GraphTracingReachedDestination: if stop_at_node_name is not None and + the specified node is reached. + """ + + self._input_lists = input_lists + self._skip_node_names = skip_node_names + + self._inputs = [] + self._visited_nodes = [] + self._depth_count = 0 + self._depth_list = [] + + self._destination_node_name = destination_node_name + + def trace(self, graph_element_name): + """Trace inputs. + + Args: + graph_element_name: Name of the node or an output tensor of the node, as a + str. + + Raises: + GraphTracingReachedDestination: if destination_node_name of this tracer + object is not None and the specified node is reached. + """ + self._depth_count += 1 + + node_name = get_node_name(graph_element_name) + if node_name == self._destination_node_name: + raise GraphTracingReachedDestination() + + if node_name in self._skip_node_names: + return + if node_name in self._visited_nodes: + return + + self._visited_nodes.append(node_name) + + for input_list in self._input_lists: + if node_name not in input_list: + continue + for inp in input_list[node_name]: + if get_node_name(inp) in self._visited_nodes: + continue + self._inputs.append(inp) + self._depth_list.append(self._depth_count) + self.trace(inp) + + self._depth_count -= 1 + + def inputs(self): + return self._inputs + + def depth_list(self): + return self._depth_list + + +def _infer_device_name(graph_def): + """Infer device name from a partition GraphDef.""" + device_name = None + for node in graph_def.node: + if node.device: + device_name = node.device + break + if device_name is None: + logging.warn( + "Failed to infer device name from partition GraphDef: none of the " + "nodes of the GraphDef has a non-empty device name.") + return device_name + + +class DebugGraph(object): + """Represents a debugger-decorated graph.""" + + def __init__(self, debug_graph_def, device_name=None): + self._debug_graph_def = debug_graph_def + self._non_debug_graph_def = None + + self._node_attributes = {} + self._node_inputs = {} + self._node_reversed_ref_inputs = {} + self._node_ctrl_inputs = {} + self._node_recipients = {} + self._node_ctrl_recipients = {} + self._node_devices = {} + self._node_op_types = {} + self._copy_send_nodes = [] + self._ref_args = {} + + self._device_name = device_name + if not self._device_name: + self._device_name = _infer_device_name(debug_graph_def) + + for node in debug_graph_def.node: + self._process_debug_graph_node(node) + + self._prune_non_control_edges_of_debug_ops() + self._prune_control_edges_of_debug_ops() + self._prune_nodes_from_input_and_recipient_maps(self._get_copy_nodes()) + + self._populate_recipient_maps() + + def _process_debug_graph_node(self, node): + """Process a node from the debug GraphDef. + + Args: + node: (NodeDef) A partition-graph node to be processed. + + Raises: + ValueError: If duplicate node names are encountered. + """ + if is_debug_node(node.name): + # This is a debug node. Parse the node name and retrieve the + # information about debug watches on tensors. But do not include + # the node in the graph. + return + + if node.name in self._node_inputs: + raise ValueError("Duplicate node name on device %s: '%s'" % + (self._device_name, node.name)) + + self._node_attributes[node.name] = node.attr + + self._node_inputs[node.name] = [] + self._node_ctrl_inputs[node.name] = [] + self._node_recipients[node.name] = [] + self._node_ctrl_recipients[node.name] = [] + + if node.name not in self._node_devices: + self._node_devices[node.name] = set() + self._node_devices[node.name].add( + node.device if node.device else self._device_name) + self._node_op_types[node.name] = node.op + self._ref_args[node.name] = self._get_ref_args(node) + + for inp in node.input: + if is_copy_node(inp) and (node.op == "_Send" or node.op == "_Retval"): + self._copy_send_nodes.append(node.name) + + if inp.startswith("^"): + cinp = inp[1:] + self._node_ctrl_inputs[node.name].append(cinp) + else: + self._node_inputs[node.name].append(inp) + + def _get_ref_args(self, node): + """Determine whether an input of an op is ref-type. + + Args: + node: A `NodeDef`. + + Returns: + A list of the arg names (as strs) that are ref-type. + """ + op_def = op_def_registry.get(node.op) + if op_def is None: + return [] + + ref_args = [] + for i, output_arg in enumerate(op_def.output_arg): + if output_arg.is_ref: + arg_name = node.name if i == 0 else ("%s:%d" % (node.name, i)) + ref_args.append(arg_name) + return ref_args + + def _get_copy_nodes(self): + """Find all Copy nodes in the loaded graph.""" + copy_nodes = [] + for node in self._node_inputs: + if is_copy_node(node): + copy_nodes.append(node) + return copy_nodes + + def _prune_non_control_edges_of_debug_ops(self): + """Prune (non-control) edges related to debug ops. + + Prune the Copy ops and associated _Send ops inserted by the debugger out + from the non-control inputs and output recipients map. Replace the inputs + and recipients with original ones. + """ + for node in self._node_inputs: + inputs = self._node_inputs[node] + + for i, inp in enumerate(inputs): + if is_copy_node(inp): + # Find the input to the Copy node, which should be the original + # input to the node. + orig_inp = self._node_inputs[inp][0] + inputs[i] = orig_inp + + def _prune_control_edges_of_debug_ops(self): + """Prune control edges related to the debug ops.""" + for node in self._node_ctrl_inputs: + ctrl_inputs = self._node_ctrl_inputs[node] + debug_op_inputs = [] + for ctrl_inp in ctrl_inputs: + if is_debug_node(ctrl_inp): + debug_op_inputs.append(ctrl_inp) + for debug_op_inp in debug_op_inputs: + ctrl_inputs.remove(debug_op_inp) + + def _populate_recipient_maps(self): + """Populate the map from node name to recipient(s) of its output(s). + + This method also populates the input map based on reversed ref edges. + """ + for node in self._node_inputs: + inputs = self._node_inputs[node] + for inp in inputs: + inp = get_node_name(inp) + if inp not in self._node_recipients: + self._node_recipients[inp] = [] + self._node_recipients[inp].append(node) + + if inp in self._ref_args: + if inp not in self._node_reversed_ref_inputs: + self._node_reversed_ref_inputs[inp] = [] + self._node_reversed_ref_inputs[inp].append(node) + + for node in self._node_ctrl_inputs: + ctrl_inputs = self._node_ctrl_inputs[node] + for ctrl_inp in ctrl_inputs: + if ctrl_inp in self._copy_send_nodes: + continue + + if ctrl_inp not in self._node_ctrl_recipients: + self._node_ctrl_recipients[ctrl_inp] = [] + self._node_ctrl_recipients[ctrl_inp].append(node) + + def _prune_nodes_from_input_and_recipient_maps(self, nodes_to_prune): + """Prune nodes out of input and recipient maps. + + Args: + nodes_to_prune: (`list` of `str`) Names of the nodes to be pruned. + """ + for node in nodes_to_prune: + del self._node_inputs[node] + del self._node_ctrl_inputs[node] + del self._node_recipients[node] + del self._node_ctrl_recipients[node] + + def _reconstruct_non_debug_graph_def(self): + """Reconstruct non-debug GraphDef. + + Non-debug GraphDef means the original GraphDef without the Copy* and Debug + nodes inserted by the debugger. + """ + if self._non_debug_graph_def: + return + + self._non_debug_graph_def = graph_pb2.GraphDef() + for node in self._debug_graph_def.node: + if is_copy_node(node.name) or is_debug_node(node.name): + continue + + new_node = self._non_debug_graph_def.node.add() + new_node.CopyFrom(node) + + # Redo the list of inputs, because in _debug_graph_def, the list can + # consist of Copy* and Debug* nodes inserted by the debugger. Those will + # be replaced with the original inputs here. + del new_node.input[:] + for inp in self._node_inputs[node.name]: + new_node.input.append(inp) + for ctrl_inp in self._node_ctrl_inputs[node.name]: + new_node.input.append("^" + ctrl_inp) + + @property + def device_name(self): + return self._device_name + + @property + def debug_graph_def(self): + """The debugger-decorated GraphDef.""" + return self._debug_graph_def + + @property + def non_debug_graph_def(self): + """The GraphDef without the Copy* and Debug* nodes added by the debugger.""" + self._reconstruct_non_debug_graph_def() + return self._non_debug_graph_def + + @property + def node_devices(self): + return self._node_devices + + @property + def node_op_types(self): + return self._node_op_types + + @property + def node_attributes(self): + return self._node_attributes + + @property + def node_inputs(self): + return self._node_inputs + + @property + def node_ctrl_inputs(self): + return self._node_ctrl_inputs + + @property + def node_reversed_ref_inputs(self): + return self._node_reversed_ref_inputs + + @property + def node_recipients(self): + return self._node_recipients + + @property + def node_ctrl_recipients(self): + return self._node_ctrl_recipients + + +def reconstruct_non_debug_graph_def(debug_graph_def): + """Reconstruct original (non-debugger-decorated) partition GraphDef. + + This method strips the input `tf.compat.v1.GraphDef` of the Copy* and + Debug*-type nodes inserted by the debugger. + + The reconstructed partition graph is identical to the original (i.e., + non-debugger-decorated) partition graph except in the following respects: + 1) The exact names of the runtime-inserted internal nodes may differ. + These include _Send, _Recv, _HostSend, _HostRecv, _Retval ops. + 2) As a consequence of 1, the nodes that receive input directly from such + send- and recv-type ops will have different input names. + 3) The parallel_iteration attribute of while-loop Enter ops are set to 1. + + Args: + debug_graph_def: The debugger-decorated `tf.compat.v1.GraphDef`, with the + debugger-inserted Copy* and Debug* nodes. + + Returns: + The reconstructed `tf.compat.v1.GraphDef` stripped of the debugger-inserted + nodes. + """ + return DebugGraph(debug_graph_def).non_debug_graph_def diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_service_pb2_grpc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_service_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..290a23017a270f049c5b7958d3133fa64c07787b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_service_pb2_grpc.py @@ -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. +# ============================================================================== +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +# +# Do not use pylint on generated code. +# pylint: disable=missing-docstring,g-short-docstring-punctuation,g-no-space-after-docstring-summary,invalid-name,line-too-long,unused-argument,g-doc-args +import grpc + +from tensorflow.core.debug import debug_service_pb2 as tensorflow_dot_core_dot_debug_dot_debug__service__pb2 +from tensorflow.core.protobuf import debug_pb2 as tensorflow_dot_core_dot_protobuf_dot_debug__pb2 +from tensorflow.core.util import event_pb2 as tensorflow_dot_core_dot_util_dot_event__pb2 + + +class EventListenerStub(object): + """EventListener: Receives Event protos, e.g., from debugged TensorFlow + runtime(s). + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.SendEvents = channel.stream_stream( + '/tensorflow.EventListener/SendEvents', + request_serializer=tensorflow_dot_core_dot_util_dot_event__pb2.Event.SerializeToString, + response_deserializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.EventReply.FromString, + ) + self.SendTracebacks = channel.unary_unary( + '/tensorflow.EventListener/SendTracebacks', + request_serializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.CallTraceback.SerializeToString, + response_deserializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.EventReply.FromString, + ) + self.SendSourceFiles = channel.unary_unary( + '/tensorflow.EventListener/SendSourceFiles', + request_serializer=tensorflow_dot_core_dot_protobuf_dot_debug__pb2.DebuggedSourceFiles.SerializeToString, + response_deserializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.EventReply.FromString, + ) + + +class EventListenerServicer(object): + """EventListener: Receives Event protos, e.g., from debugged TensorFlow + runtime(s). + """ + + def SendEvents(self, request_iterator, context): + """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. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SendTracebacks(self, request, context): + """Send the tracebacks of ops in a Python graph definition. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SendSourceFiles(self, request, context): + """Send a collection of source code files being debugged. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_EventListenerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'SendEvents': grpc.stream_stream_rpc_method_handler( + servicer.SendEvents, + request_deserializer=tensorflow_dot_core_dot_util_dot_event__pb2.Event.FromString, + response_serializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.EventReply.SerializeToString, + ), + 'SendTracebacks': grpc.unary_unary_rpc_method_handler( + servicer.SendTracebacks, + request_deserializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.CallTraceback.FromString, + response_serializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.EventReply.SerializeToString, + ), + 'SendSourceFiles': grpc.unary_unary_rpc_method_handler( + servicer.SendSourceFiles, + request_deserializer=tensorflow_dot_core_dot_protobuf_dot_debug__pb2.DebuggedSourceFiles.FromString, + response_serializer=tensorflow_dot_core_dot_debug_dot_debug__service__pb2.EventReply.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'tensorflow.EventListener', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..277c1403c553b4816b2871c19d7425eaf85b5ba5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/debug_utils.py @@ -0,0 +1,286 @@ +# 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. +# ============================================================================== +"""TensorFlow Debugger (tfdbg) Utilities.""" + +import re + + + +def add_debug_tensor_watch(run_options, + node_name, + output_slot=0, + debug_ops="DebugIdentity", + debug_urls=None, + tolerate_debug_op_creation_failures=False, + global_step=-1): + """Add watch on a `Tensor` to `RunOptions`. + + N.B.: + 1. Under certain circumstances, the `Tensor` may not get actually watched + (e.g., if the node of the `Tensor` is constant-folded during runtime). + 2. For debugging purposes, the `parallel_iteration` attribute of all + `tf.while_loop`s in the graph are set to 1 to prevent any node from + being executed multiple times concurrently. This change does not affect + subsequent non-debugged runs of the same `tf.while_loop`s. + + Args: + run_options: An instance of `config_pb2.RunOptions` to be modified. + node_name: (`str`) name of the node to watch. + output_slot: (`int`) output slot index of the tensor from the watched node. + debug_ops: (`str` or `list` of `str`) name(s) of the debug op(s). Can be a + `list` of `str` or a single `str`. The latter case is equivalent to a + `list` of `str` with only one element. + For debug op types with customizable attributes, each debug op string can + optionally contain a list of attribute names, in the syntax of: + debug_op_name(attr_name_1=attr_value_1;attr_name_2=attr_value_2;...) + debug_urls: (`str` or `list` of `str`) URL(s) to send debug values to, + e.g., `file:///tmp/tfdbg_dump_1`, `grpc://localhost:12345`. + tolerate_debug_op_creation_failures: (`bool`) Whether to tolerate debug op + creation failures by not throwing exceptions. + global_step: (`int`) Optional global_step count for this debug tensor + watch. + """ + + watch_opts = run_options.debug_options.debug_tensor_watch_opts + run_options.debug_options.global_step = global_step + + watch = watch_opts.add() + watch.tolerate_debug_op_creation_failures = ( + tolerate_debug_op_creation_failures) + watch.node_name = node_name + watch.output_slot = output_slot + + if isinstance(debug_ops, str): + debug_ops = [debug_ops] + + watch.debug_ops.extend(debug_ops) + + if debug_urls: + if isinstance(debug_urls, str): + debug_urls = [debug_urls] + + watch.debug_urls.extend(debug_urls) + + +def watch_graph(run_options, + graph, + debug_ops="DebugIdentity", + debug_urls=None, + node_name_regex_allowlist=None, + op_type_regex_allowlist=None, + tensor_dtype_regex_allowlist=None, + tolerate_debug_op_creation_failures=False, + global_step=-1, + reset_disk_byte_usage=False): + """Add debug watches to `RunOptions` for a TensorFlow graph. + + To watch all `Tensor`s on the graph, let both `node_name_regex_allowlist` + and `op_type_regex_allowlist` be the default (`None`). + + N.B.: + 1. Under certain circumstances, the `Tensor` may not get actually watched + (e.g., if the node of the `Tensor` is constant-folded during runtime). + 2. For debugging purposes, the `parallel_iteration` attribute of all + `tf.while_loop`s in the graph are set to 1 to prevent any node from + being executed multiple times concurrently. This change does not affect + subsequent non-debugged runs of the same `tf.while_loop`s. + + + Args: + run_options: An instance of `config_pb2.RunOptions` to be modified. + graph: An instance of `ops.Graph`. + debug_ops: (`str` or `list` of `str`) name(s) of the debug op(s) to use. + debug_urls: URLs to send debug values to. Can be a list of strings, + a single string, or None. The case of a single string is equivalent to + a list consisting of a single string, e.g., `file:///tmp/tfdbg_dump_1`, + `grpc://localhost:12345`. + For debug op types with customizable attributes, each debug op name string + can optionally contain a list of attribute names, in the syntax of: + debug_op_name(attr_name_1=attr_value_1;attr_name_2=attr_value_2;...) + node_name_regex_allowlist: Regular-expression allowlist for node_name, + e.g., `"(weight_[0-9]+|bias_.*)"` + op_type_regex_allowlist: Regular-expression allowlist for the op type of + nodes, e.g., `"(Variable|Add)"`. + If both `node_name_regex_allowlist` and `op_type_regex_allowlist` + are set, the two filtering operations will occur in a logical `AND` + relation. In other words, a node will be included if and only if it + hits both allowlists. + tensor_dtype_regex_allowlist: Regular-expression allowlist for Tensor + data type, e.g., `"^int.*"`. + This allowlist operates in logical `AND` relations to the two allowlists + above. + tolerate_debug_op_creation_failures: (`bool`) whether debug op creation + failures (e.g., due to dtype incompatibility) are to be tolerated by not + throwing exceptions. + global_step: (`int`) Optional global_step count for this debug tensor + watch. + reset_disk_byte_usage: (`bool`) whether to reset the tracked disk byte + usage to zero (default: `False`). + """ + if not debug_ops: + raise ValueError("debug_ops must not be empty or None.") + if not debug_urls: + raise ValueError("debug_urls must not be empty or None.") + + if isinstance(debug_ops, str): + debug_ops = [debug_ops] + + node_name_pattern = ( + re.compile(node_name_regex_allowlist) + if node_name_regex_allowlist else None) + op_type_pattern = ( + re.compile(op_type_regex_allowlist) if op_type_regex_allowlist else None) + tensor_dtype_pattern = ( + re.compile(tensor_dtype_regex_allowlist) + if tensor_dtype_regex_allowlist else None) + + ops = graph.get_operations() + for op in ops: + # Skip nodes without any output tensors. + if not op.outputs: + continue + + node_name = op.name + op_type = op.type + + if node_name_pattern and not node_name_pattern.match(node_name): + continue + if op_type_pattern and not op_type_pattern.match(op_type): + continue + + for slot in range(len(op.outputs)): + if (tensor_dtype_pattern and + not tensor_dtype_pattern.match(op.outputs[slot].dtype.name)): + continue + + add_debug_tensor_watch( + run_options, + node_name, + output_slot=slot, + debug_ops=debug_ops, + debug_urls=debug_urls, + tolerate_debug_op_creation_failures=( + tolerate_debug_op_creation_failures), + global_step=global_step) + + # If no filter for node or tensor is used, will add a wildcard node name, so + # that all nodes, including the ones created internally by TensorFlow itself + # (e.g., by Grappler), can be watched during debugging. + use_node_name_wildcard = (not node_name_pattern and + not op_type_pattern and + not tensor_dtype_pattern) + if use_node_name_wildcard: + add_debug_tensor_watch( + run_options, + "*", + output_slot=-1, + debug_ops=debug_ops, + debug_urls=debug_urls, + tolerate_debug_op_creation_failures=tolerate_debug_op_creation_failures, + global_step=global_step) + + run_options.debug_options.reset_disk_byte_usage = reset_disk_byte_usage + + +def watch_graph_with_denylists(run_options, + graph, + debug_ops="DebugIdentity", + debug_urls=None, + node_name_regex_denylist=None, + op_type_regex_denylist=None, + tensor_dtype_regex_denylist=None, + tolerate_debug_op_creation_failures=False, + global_step=-1, + reset_disk_byte_usage=False): + """Add debug tensor watches, denylisting nodes and op types. + + This is similar to `watch_graph()`, but the node names and op types are + denylisted, instead of allowlisted. + + N.B.: + 1. Under certain circumstances, the `Tensor` may not get actually watched + (e.g., if the node of the `Tensor` is constant-folded during runtime). + 2. For debugging purposes, the `parallel_iteration` attribute of all + `tf.while_loop`s in the graph are set to 1 to prevent any node from + being executed multiple times concurrently. This change does not affect + subsequent non-debugged runs of the same `tf.while_loop`s. + + Args: + run_options: An instance of `config_pb2.RunOptions` to be modified. + graph: An instance of `ops.Graph`. + debug_ops: (`str` or `list` of `str`) name(s) of the debug op(s) to use. See + the documentation of `watch_graph` for more details. + debug_urls: URL(s) to send debug values to, e.g., + `file:///tmp/tfdbg_dump_1`, `grpc://localhost:12345`. + node_name_regex_denylist: Regular-expression denylist for node_name. This + should be a string, e.g., `"(weight_[0-9]+|bias_.*)"`. + op_type_regex_denylist: Regular-expression denylist for the op type of + nodes, e.g., `"(Variable|Add)"`. If both node_name_regex_denylist and + op_type_regex_denylist are set, the two filtering operations will occur in + a logical `OR` relation. In other words, a node will be excluded if it + hits either of the two denylists; a node will be included if and only if + it hits neither of the denylists. + tensor_dtype_regex_denylist: Regular-expression denylist for Tensor data + type, e.g., `"^int.*"`. This denylist operates in logical `OR` relations + to the two allowlists above. + tolerate_debug_op_creation_failures: (`bool`) whether debug op creation + failures (e.g., due to dtype incompatibility) are to be tolerated by not + throwing exceptions. + global_step: (`int`) Optional global_step count for this debug tensor watch. + reset_disk_byte_usage: (`bool`) whether to reset the tracked disk byte + usage to zero (default: `False`). + """ + + if isinstance(debug_ops, str): + debug_ops = [debug_ops] + + node_name_pattern = ( + re.compile(node_name_regex_denylist) + if node_name_regex_denylist else None) + op_type_pattern = ( + re.compile(op_type_regex_denylist) if op_type_regex_denylist else None) + tensor_dtype_pattern = ( + re.compile(tensor_dtype_regex_denylist) + if tensor_dtype_regex_denylist else None) + + ops = graph.get_operations() + for op in ops: + # Skip nodes without any output tensors. + if not op.outputs: + continue + + node_name = op.name + op_type = op.type + + if node_name_pattern and node_name_pattern.match(node_name): + continue + if op_type_pattern and op_type_pattern.match(op_type): + continue + + for slot in range(len(op.outputs)): + if (tensor_dtype_pattern and + tensor_dtype_pattern.match(op.outputs[slot].dtype.name)): + continue + + add_debug_tensor_watch( + run_options, + node_name, + output_slot=slot, + debug_ops=debug_ops, + debug_urls=debug_urls, + tolerate_debug_op_creation_failures=( + tolerate_debug_op_creation_failures), + global_step=global_step) + run_options.debug_options.reset_disk_byte_usage = reset_disk_byte_usage diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/dumping_callback.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/dumping_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..8abfc242c91f3ede624c9c7a1252d3e2f0653ae2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/dumping_callback.py @@ -0,0 +1,886 @@ +# 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. +# ============================================================================== +"""Dumping op callbacks: Enables dump-based features in tfdbg v2.""" + +import atexit +import os +import re +import socket +import threading +import uuid + +from tensorflow.core.framework import graph_debug_info_pb2 +from tensorflow.core.framework import tensor_pb2 +from tensorflow.core.protobuf import debug_event_pb2 +from tensorflow.python.debug.lib import debug_events_writer +from tensorflow.python.debug.lib import op_callbacks_common +from tensorflow.python.debug.lib import source_utils +from tensorflow.python.eager import function as function_lib +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_debug_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_stack +from tensorflow.python.util.tf_export import tf_export + +_state = threading.local() +DEFAULT_TENSOR_DEBUG_MODE = "NO_TENSOR" + +# pylint:disable=protected-access +_FUNCTION_PREFIXES = ( + compat.as_bytes(function_lib._FORWARD_PREFIX), + compat.as_bytes(function_lib._BACKWARD_PREFIX), + compat.as_bytes(function_lib._INFERENCE_PREFIX)) +# pylint:enable=protected-access + + +def is_op_type_function(op_type): + return compat.as_bytes(op_type).startswith(_FUNCTION_PREFIXES) + + +@ops.RegisterGradient("DebugIdentityV2") +def _debug_identity_v2_grad(op, dy): + """Gradient function for the DebugIdentityV2 op.""" + del op # Unused + return dy + + +def _get_tfdbg_run_id(): + return str(uuid.uuid4())[:8] + + +def _get_id(): + """Get a short unique ID.""" + return str(uuid.uuid4()) + + +def _concrete_tensor_to_proto(tensor): + return tensor_util.make_tensor_proto(tensor.numpy()) + + +class _DumpingCallback(object): + """An object holding the states surrounding the dumping callback.""" + + def __init__(self, + dump_root, + tensor_debug_mode, + circular_buffer_size, + op_regex, + tensor_dtypes): + self._dump_root = dump_root + self._tfdbg_run_id = _get_tfdbg_run_id() + self._tensor_debug_mode = tensor_debug_mode + self._circular_buffer_size = circular_buffer_size + self._op_regex = op_regex + self._tensor_dtypes = tensor_dtypes + + self._hostname = socket.gethostname() + # A list of source-file paths. + self._source_file_paths = [] + # A map from stack frame (FileLineCol) to unique ID. + self._stack_frame_to_id = dict() + # Mapping op context to unique ID. + self._context_to_id = dict() + self._function_to_graph_id = dict() + self._op_type_to_context_id = dict() + # Keeps track of counter for symbolic tensors output by in-graph ops. + # It is used to make unique names for debugger-generated tensors. + self._symbolic_tensor_counter = 0 + # A map from the names of debugger-generated Identity and DebugIdentityV2 + # tensors to the names of the original insrumented graph tensors. This is + # applicable to v1 graph mode only. + self._tensor_aliases = dict() + self._source_file_paths_lock = threading.Lock() + self._stack_frame_to_id_lock = threading.Lock() + self._context_lock = threading.Lock() + self._symbolic_tensor_counter_lock = threading.Lock() + # A dict mapping Placeholder tensors to their instrumenting debug tensors. + # Used only under V1 graph mode, where we can't rely on auto control + # dependency to execute the debug tensors and hence need to attach the debug + # tensors as control dependencies of the ops that consume the Placeholder. + self._placeholder_to_debug_tensor = ( + object_identity.ObjectIdentityDictionary()) + self._writer = None + + def function_callback(self, function): + """A callback to be called on creation of ConcreteFunctions.""" + graph_id = self._get_context_id(function.graph) + with self._context_lock: + # NOTE(cais): We currently store the function (ConcreteFunction) + # as keys of this dict, because weakrefs to them sometimes become + # unreferenceable by the time the op callback is called. This approach + # may cause memory leaks due to the holding of the functions. If that's + # the case, calling `tf.debugging.disable_dump_debug_info()` should + # cause GC of this object and this dict. + self._function_to_graph_id[function] = graph_id + + @property + def dump_root(self): + return self._dump_root + + @dump_root.setter + def dump_root(self, dump_root): + if self._dump_root != dump_root: + self._dump_root = dump_root + self._writer = None + + @property + def tfdbg_run_id(self): + return self._tfdbg_run_id + + @property + def tensor_debug_mode(self): + return self._tensor_debug_mode + + @property + def circular_buffer_size(self): + return self._circular_buffer_size + + def get_writer(self): + """Get the debug events writer for the currently configured dump root.""" + if not self._writer: + self._writer = debug_events_writer.DebugEventsWriter( + self._dump_root, + self._tfdbg_run_id, + circular_buffer_size=self._circular_buffer_size) + return self._writer + + def _get_context_id(self, context): + """Get a unique ID for an op-construction context (e.g., a graph). + + If the graph has been encountered before, reuse the same unique ID. + When encountering a new context (graph), this methods writes a DebugEvent + proto with the debugged_graph field to the proper DebugEvent file. + + Args: + context: A context to get the unique ID for. Must be hashable. E.g., a + Graph object. + + Returns: + A unique ID for the context. + """ + # Use the double-checked lock pattern to optimize the common case. + if context in self._context_to_id: # 1st check, without lock. + return self._context_to_id[context] + graph_is_new = False + with self._context_lock: + if context not in self._context_to_id: # 2nd check, with lock. + graph_is_new = True + context_id = _get_id() + self._context_to_id[context] = context_id + if graph_is_new: + self.get_writer().WriteDebuggedGraph(debug_event_pb2.DebuggedGraph( + graph_id=context_id, + graph_name=getattr(context, "name", None), + outer_context_id=self._get_outer_context_id(context))) + return self._context_to_id[context] + + def _get_outer_context_id(self, graph): + """Get the ID of the immediate outer context of the input graph. + + Args: + graph: The graph (context) in question. + + Returns: + If an outer context exists, the immediate outer context name as a string. + If such as outer context does not exist (i.e., `graph` is itself + outermost), `None`. + """ + if hasattr(graph, "outer_graph") and graph.outer_graph: + return self._get_context_id(graph.outer_graph) + else: + return None + + def _write_source_file_content(self, file_path): + """Send the content of a source file via debug-events writer. + + Args: + file_path: Path to the source file. + + Returns: + An int index for the file. + """ + if file_path in self._source_file_paths: + return self._source_file_paths.index(file_path) + with self._source_file_paths_lock: + if file_path not in self._source_file_paths: + lines = None + if source_utils.is_extension_uncompiled_python_source(file_path): + try: + lines, _ = source_utils.load_source(file_path) + except IOError as e: + logging.warn( + "Failed to read source code from path: %s. Reason: %s", + file_path, e) + writer = self.get_writer() + writer.WriteSourceFile(debug_event_pb2.SourceFile( + file_path=file_path, host_name=self._hostname, lines=lines)) + self._source_file_paths.append(file_path) + return self._source_file_paths.index(file_path) + + def _process_stack_frames(self): + """Process stack frames. + + Send the content of source-files, on a best-effort basis. + + Returns: + A list of stack frame IDs. + """ + stack_frames = tf_stack.extract_stack() + stack_frame_ids = [] + writer = None + for file_path, lineno, func, _ in stack_frames: + abs_path = os.path.abspath(file_path) + if (abs_path, lineno, func) in self._stack_frame_to_id: + stack_frame_ids.append( + self._stack_frame_to_id[(abs_path, lineno, func)]) + continue + with self._stack_frame_to_id_lock: + if (abs_path, lineno, func) not in self._stack_frame_to_id: + stack_frame_id = _get_id() + self._stack_frame_to_id[(abs_path, lineno, func)] = stack_frame_id + file_index = self._write_source_file_content(abs_path) + file_line_col = graph_debug_info_pb2.GraphDebugInfo.FileLineCol( + file_index=file_index, line=lineno, func=func) + stack_frame_with_id = debug_event_pb2.StackFrameWithId( + id=stack_frame_id, file_line_col=file_line_col) + writer = self.get_writer() + writer.WriteStackFrameWithId(stack_frame_with_id) + stack_frame_ids.append( + self._stack_frame_to_id[(abs_path, lineno, func)]) + + code_location = debug_event_pb2.CodeLocation( + host_name=self._hostname, stack_frame_ids=stack_frame_ids) + return code_location + + def _process_v1_graph_mode_tensor(self, + op_type, + tensor, + debug_tensor, + tensor_debug_mode): + """For V1 graph mode, determine what tensor to output from callback. + + Args: + op_type: Type of the op that outputs the original symbolic tensor. + tensor: The original output symbolic tensor. + debug_tensor: The debugger-instrumented tensor. + tensor_debug_mode: Debug mode used, a tfdbg TensorDebugMode enum. + + Returns: + A symbolic tensor to be returned by the dumping op_callback. + """ + # Placeholders need special treatment under V1 graph mode. The + # callback can't simply override the Placeholder tensor to a debug tensor, + # as that would cause the Placeholder op to lack a value. + if op_type in ("Placeholder", "PlaceholderWithDefault"): + self._placeholder_to_debug_tensor[tensor] = debug_tensor + return tensor + else: + # TODO(cais): Evaluate performance optimization options. For the + # `NO_TENSOR` debug mode, an alternative is to add `debug_tensor` as a + # control dependency of `tensor.op` without an additional identity op. + if (tensor_debug_mode == debug_event_pb2.TensorDebugMode.FULL_TENSOR and + op_type != "Const"): + # NOTE(b/153716279): Under v1 graph mode, overriding the output tensor + # of Const ops can lead to downstream errors related to shapes. We opt + # to use an identity op to avoid this issue at the cost of slightly + # larger graph size. + self._tensor_aliases[debug_tensor.name] = tensor.name + return debug_tensor + else: + with self._symbolic_tensor_counter_lock: + identity_name = "tfdbg_identity_%d" % self._symbolic_tensor_counter + identity = array_ops.identity(tensor, name=identity_name) + identity.op._add_control_input( # pylint: disable=protected-access + debug_tensor.op) + self._tensor_aliases[identity.name] = tensor.name + return identity + + def _instrument_symbolic_tensors(self, + tensors, + op_type, + op_name, + tfdbg_context_id, + tensor_ids): + """Add debugging instrumentation for symbolic (i.e., non-eager) tensors. + + The detailed fashion in which the tensors are instrumented is determined + by the tensor_debug_mode configured for the currently enabled dumping + callback. + + Args: + tensors: A tuple of Tensors to instrument. It is assumed that their + ordering corresponds to the ordering of output tensors of an original + op. Output slot indices (0-based) will be generated based on the + ordering. + op_type: Type name of the op that emits the Tensors (e.g., "MatMul"). + op_name: Name of the op that emits the Tensors (e.g., "dense_1/MatMul"). + tfdbg_context_id: A unique ID for the context that the op belongs to + (e.g., a graph). + tensor_ids: A list of unique ID numbers for the tensors, for tfdbg's + internal use. + + Returns: + Non-eager Tensors that override the `tensors` as the output of the op + that originally generated `tensors`. In some cases (e.g., non-V1 graph + mode), this may be `None`, as the instrumentation can simply rely on + automatic control dependencies (see `auto_control_deps.py`) instead of + tensor overriding. + """ + tensor_debug_mode = self._tensor_debug_mode + debug_urls = ["file://%s" % self._dump_root] + is_v1_graph_mode = not ops.executing_eagerly_outside_functions() + instrumented_tensors = [] if is_v1_graph_mode else None + for output_slot, tensor in enumerate(tensors): + with self._symbolic_tensor_counter_lock: + debug_identity_name = ("DebugIdentityV2_%d" % + self._symbolic_tensor_counter) + debug_identity_op_kwargs = { + "tfdbg_context_id": tfdbg_context_id, + "op_name": op_name, + "output_slot": output_slot, + "tensor_debug_mode": self._tensor_debug_mode, + "debug_urls": debug_urls, + "name": debug_identity_name, + "circular_buffer_size": self._circular_buffer_size, + "tfdbg_run_id": self._tfdbg_run_id, + } + if tensor_debug_mode == debug_event_pb2.TensorDebugMode.NO_TENSOR: + if (not self._should_dump_tensor(op_type, tensor.dtype) or + not tensor.dtype.is_numpy_compatible): + if is_v1_graph_mode: + instrumented_tensors.append(tensor) + continue + if is_v1_graph_mode and not tensor.dtype.is_numpy_compatible: + # Avoid instrumenting Placeholder under is_v1_graph_mode. Doing that + # would cause runtime complaint about Placeholders not being fed. + instrumented_tensors.append(tensor) + continue + # Except in V1 graph mode + control flow, debug_identity_v2 triggers + # auto control dependency because it's a stateful op. + debug_tensor = gen_debug_ops.debug_identity_v2( + # Use an empty (shape=[0]) float32 tensor for the NO_TENSOR mode + # as a low-overhead placeholder, since no actual tensor value is + # traced. + constant_op.constant([], dtype=dtypes.float32), + **debug_identity_op_kwargs) + if is_v1_graph_mode: + instrumented_tensors.append(self._process_v1_graph_mode_tensor( + op_type, tensor, debug_tensor, tensor_debug_mode)) + elif tensor_debug_mode in (debug_event_pb2.TensorDebugMode.CURT_HEALTH, + debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, + debug_event_pb2.TensorDebugMode.FULL_HEALTH, + debug_event_pb2.TensorDebugMode.SHAPE): + dtype = tensor.dtype + dtype_is_dumpable = ( + tensor_debug_mode in ( + debug_event_pb2.TensorDebugMode.CURT_HEALTH, + debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, + debug_event_pb2.TensorDebugMode.FULL_HEALTH) and + dtype.is_floating or + tensor_debug_mode == debug_event_pb2.TensorDebugMode.SHAPE and + (dtype.is_floating or dtype.is_integer or dtype.is_bool)) + if (not self._should_dump_tensor(op_type, tensor.dtype) or + not dtype_is_dumpable): + if is_v1_graph_mode: + instrumented_tensors.append(tensor) + continue + debug_tensor = gen_debug_ops.debug_identity_v2( + gen_debug_ops.debug_numeric_summary_v2( + tensor, + tensor_id=tensor_ids[output_slot], + tensor_debug_mode=self._tensor_debug_mode, + output_dtype=dtypes.float64), **debug_identity_op_kwargs) + if is_v1_graph_mode: + instrumented_tensors.append(self._process_v1_graph_mode_tensor( + op_type, tensor, debug_tensor, tensor_debug_mode)) + elif tensor_debug_mode == debug_event_pb2.TensorDebugMode.FULL_TENSOR: + if (not self._should_dump_tensor(op_type, tensor.dtype) or + not tensor.dtype.is_numpy_compatible): + # Instrumenting DT_VARIANT and DT_RESOURCE type tensors under + # V1 graph mode is known to have issues. TODO(cais): Investigate. + if is_v1_graph_mode: + instrumented_tensors.append(tensor) + continue + debug_tensor = gen_debug_ops.debug_identity_v2( + tensor, **debug_identity_op_kwargs) + if is_v1_graph_mode: + instrumented_tensors.append(self._process_v1_graph_mode_tensor( + op_type, tensor, debug_tensor, tensor_debug_mode)) + else: + raise NotImplementedError( + "Symbolic tensor instrumentation is not implemented for debug mode " + "%s" % self._tensor_debug_mode) + return instrumented_tensors + + def _dump_eager_tensors(self, + tensors, + op_type, + input_tensor_ids, + output_tensor_device_ids, + graph_id=None): + """Dump the value of eager tensors. + + The destination of the dumping is determined by the dump_root of the + currently enabled dumping callback. The tensors may be transformed prior to + dumping (e.g., reduced as summary statistics such as minimum, maximum and + arithmetic mean). The details of this transformation (if any) depends on + the tensor_debug_mode of the currently enabled dumping callback. + + Args: + tensors: The EagerTensors whose values are to be dumped, with or without + value transform. + op_type: Type of the op that generates the tensors, as a string. + input_tensor_ids: IDs of the input EagerTensors to the op. + output_tensor_device_ids: Debugged-generated IDs for the devices on which + the output tensors are allocated, as a `list` of `int`s. Must match + `tensors` in length. + graph_id: ID of the executed graph, applicable only to eager execution of + a FuncGraph. + + Returns: + A tfdbg Execution protocol buffer. + """ + tensor_debug_mode = self._tensor_debug_mode + output_tensor_ids = [ + t._id for t in tensors] # pylint:disable=protected-access + assert len(tensors) == len(output_tensor_device_ids) + if tensor_debug_mode == debug_event_pb2.TensorDebugMode.NO_TENSOR: + return debug_event_pb2.Execution( + op_type=op_type, + graph_id=graph_id, + num_outputs=len(tensors), + input_tensor_ids=input_tensor_ids, + output_tensor_ids=output_tensor_ids, + output_tensor_device_ids=output_tensor_device_ids, + tensor_debug_mode=tensor_debug_mode, + code_location=self._process_stack_frames()) + elif tensor_debug_mode in (debug_event_pb2.TensorDebugMode.CURT_HEALTH, + debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, + debug_event_pb2.TensorDebugMode.FULL_HEALTH, + debug_event_pb2.TensorDebugMode.SHAPE, + debug_event_pb2.TensorDebugMode.FULL_TENSOR): + execution_proto = debug_event_pb2.Execution( + op_type=op_type, + num_outputs=len(tensors), + graph_id=graph_id, + input_tensor_ids=input_tensor_ids, + output_tensor_ids=output_tensor_ids, + output_tensor_device_ids=output_tensor_device_ids, + tensor_debug_mode=tensor_debug_mode, + code_location=self._process_stack_frames()) + for tensor in tensors: + if (self._should_dump_tensor(op_type, tensor.dtype) and + tensor.dtype.is_numpy_compatible): + if tensor_debug_mode in ( + debug_event_pb2.TensorDebugMode.CURT_HEALTH, + debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, + debug_event_pb2.TensorDebugMode.FULL_HEALTH): + if tensor.dtype.is_floating: + tensor_proto = _concrete_tensor_to_proto( + gen_debug_ops.debug_numeric_summary_v2( + tensor, + tensor_debug_mode=tensor_debug_mode, + output_dtype=dtypes.float64)) + else: + # A placeholder for non-floating-type output tensors. + tensor_proto = tensor_pb2.TensorProto() + elif tensor_debug_mode == debug_event_pb2.TensorDebugMode.SHAPE: + if (tensor.dtype.is_floating or tensor.dtype.is_integer or + tensor.dtype.is_bool): + tensor_proto = _concrete_tensor_to_proto( + gen_debug_ops.debug_numeric_summary_v2( + tensor, + tensor_debug_mode=tensor_debug_mode, + output_dtype=dtypes.float64)) + else: + # A placeholder for non-floating-type output tensors. + tensor_proto = tensor_pb2.TensorProto() + elif tensor_debug_mode == debug_event_pb2.TensorDebugMode.FULL_TENSOR: + tensor_proto = _concrete_tensor_to_proto(tensor) + if tensor_proto: + execution_proto.tensor_protos.append(tensor_proto) + return execution_proto + else: + raise NotImplementedError( + "Tensor instrumentation is not implemented for debug mode %s yet " % + self._tensor_debug_mode) + + def callback(self, + op_type, + inputs, + attrs, + outputs, + op_name=None, + graph=None): + """Op callback for tracing (dumping) a TF program's execution.""" + del attrs # Unused + + writer = self.get_writer() + if graph: + is_v1_graph_mode = not ops.executing_eagerly_outside_functions() + context_id = self._get_context_id(graph) # Innermost context ID. + output_tensor_ids = self._get_symbolic_tensor_ids(len(outputs)) + if op_type in ("Const", "Placeholder", "PlaceholderWithDefault"): + # In some cases, the op name of a Const or Placeholder op in a graph + # can be duplicate (e.g., `None` or "resource"). + # When this happens, we use the output tensor name to infer + # the non-duplicated tensor name. + op_name = outputs[0].name.split(":")[0] + if is_v1_graph_mode: + for input_tensor in inputs: + if input_tensor in self._placeholder_to_debug_tensor and outputs: + outputs[0].op._add_control_input( # pylint: disable=protected-access + self._placeholder_to_debug_tensor[input_tensor].op) + graph_op_creation = debug_event_pb2.GraphOpCreation( + op_type=op_type, + op_name=op_name, + graph_name=graph.name if hasattr(graph, "name") else None, + graph_id=context_id, + input_names=[ + self._lookup_tensor_name(input_tensor) for input_tensor in inputs + ], + num_outputs=len(outputs), + output_tensor_ids=output_tensor_ids, + code_location=self._process_stack_frames()) + writer.WriteGraphOpCreation(graph_op_creation) + if outputs and compat.as_bytes( + op_type) not in op_callbacks_common.OP_CALLBACK_SKIP_OPS: + return self._instrument_symbolic_tensors( + outputs, op_type, op_name, context_id, output_tensor_ids) + else: + op_type_bytes = compat.as_bytes(op_type) + if op_type_bytes == b"DebugNumericSummaryV2": + # TODO(b/140334369): Remove this special casing logic once op_callback. + # automatically prevents infinite recursion in eager mode. + return None + if op_type_bytes in op_callbacks_common.OP_CALLBACK_SKIP_OPS: + return None + context_id = self._func_graph_id_from_func_name(op_type) + input_ids = [t._id for t in inputs] # pylint:disable=protected-access + output_tensor_device_ids = [writer.RegisterDeviceAndGetId(output.device) + for output in outputs] if outputs else [] + writer.WriteExecution(self._dump_eager_tensors( + outputs, op_type, input_ids, output_tensor_device_ids, + graph_id=context_id)) + + def _lookup_tensor_name(self, tensor): + """Look up the name of a graph tensor. + + This method maps the name of a debugger-generated Identity or + DebugIdentityV2 tensor to the name of the original instrumented tensor, + if `tensor` is such a debugger-created tensor. + Otherwise, it returns the name of `tensor` as is. + + Args: + tensor: The graph tensor to look up the name for. + + Returns: + Name of the original instrumented tensor as known to the debugger. + """ + return self._tensor_aliases.get(tensor.name, tensor.name) + + def _func_graph_id_from_func_name(self, op_type): + """Attempt to get the ID of a FuncGraph based on an op type name. + + Also caches the ID for faster access later. + + Args: + op_type: Op type string, which may be the name of a function. + + Returns: + If the op_type name does not fit the pattern of a function name (e.g., + one that starts with "__inference_"), `None` is returned immediately. + Else, if the FuncGraph is found, ID of the underlying FuncGraph is + returned as a string. + Else, `None` is returned. + """ + op_type = compat.as_bytes(op_type) + if is_op_type_function(op_type): + # op_type for eagerly-executed FuncGraphs have the prefixed and suffixed + # form such as "__inference_my_function_13579", wherein the middle part + # "my_function" is the name of the Python function from which the + # FuncGraph is compiled. Due to the suffix, the op_type is unique for + # - duplicate Python function names + # - multiple compilation of the same Python function + if op_type in self._op_type_to_context_id: + return self._op_type_to_context_id[op_type] + with self._context_lock: + for function in self._function_to_graph_id: + if function.name == op_type: + graph_id = self._function_to_graph_id[function] + self._op_type_to_context_id[op_type] = graph_id + return graph_id + return None + else: + return None + + def _get_symbolic_tensor_ids(self, num_tensors): + tensor_ids = [] + if num_tensors: + with self._symbolic_tensor_counter_lock: + for _ in range(num_tensors): + self._symbolic_tensor_counter += 1 + tensor_ids.append(self._symbolic_tensor_counter) + return tensor_ids + + def _should_dump_tensor(self, op_type, dtype): + """Determine if the given tensor's value will be dumped. + + The determination is made given the configurations such as `op_regex`, + `tensor_dtypes`. + + Args: + op_type: Name of the op's type, as a string (e.g., "MatMul"). + dtype: The dtype of the tensor, as a `dtypes.DType` object. + + Returns: + A bool indicating whether the tensor's value will be dumped. + """ + should_dump = True + if self._op_regex: + should_dump = (should_dump and + re.match(self._op_regex, op_type)) + if self._tensor_dtypes: + if isinstance(self._tensor_dtypes, (list, tuple)): + should_dump = (should_dump and + any(dtype == dtype_item for dtype_item + in self._tensor_dtypes)) + else: # A callable that takes a DType argument and return a boolean. + should_dump = should_dump and self._tensor_dtypes(dtype) + return should_dump + + +@tf_export("debugging.experimental.enable_dump_debug_info") +def enable_dump_debug_info(dump_root, + tensor_debug_mode=DEFAULT_TENSOR_DEBUG_MODE, + circular_buffer_size=1000, + op_regex=None, + tensor_dtypes=None): + """Enable dumping debugging information from a TensorFlow program. + + The debugging information is dumped to a directory on the file system + specified as `dump_root`. + + The dumped debugging information can be ingested by debugger UIs. + + The files in the dump directory contain the following information: + - TensorFlow Function construction (e.g., compilation of Python functions + decorated with @tf.function), the op types, names (if available), context, + the input and output tensors, and the associated stack traces. + - Execution of TensorFlow operations (ops) and Functions and their stack + traces, op types, names (if available) and contexts. In addition, + depending on the value of the `tensor_debug_mode` argument (see Args + section below), the value(s) of the output tensors or more concise + summaries of the tensor values will be dumped. + - A snapshot of Python source files involved in the execution of the + TensorFlow program. + + Once enabled, the dumping can be disabled with the corresponding + `disable_dump_debug_info()` method under the same Python namespace. + Calling this method more than once with the same `dump_root` is idempotent. + Calling this method more than once with different `tensor_debug_mode`s + leads to a `ValueError`. + Calling this method more than once with different `circular_buffer_size`s + leads to a `ValueError`. + Calling this method with a different `dump_root` abolishes the + previously-enabled `dump_root`. + + Usage example: + + ```py + tf.debugging.experimental.enable_dump_debug_info('/tmp/my-tfdbg-dumps') + + # Code to build, train and run your TensorFlow model... + ``` + + NOTE: If your code is running on TPUs, be sure to call + `tf.config.set_soft_device_placement(True)` before calling + `tf.debugging.experimental.enable_dump_debug_info()` as this API uses + automatic outside compilation on TPUs. For example: + + ```py + tf.config.set_soft_device_placement(True) + tf.debugging.experimental.enable_dump_debug_info( + logdir, tensor_debug_mode="FULL_HEALTH") + + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + strategy = tf.distribute.TPUStrategy(resolver) + with strategy.scope(): + # ... + ``` + + Args: + dump_root: The directory path where the dumping information will be written. + tensor_debug_mode: Debug mode for tensor values, as a string. + The currently supported options are: + - "NO_TENSOR": (Default) Only traces the output tensors of all executed + ops (including those executed eagerly at the Python level or as a part + of a TensorFlow graph) and functions, while not extracting any + information from the values of the tensors. + - "CURT_HEALTH": For each floating-dtype tensor (e.g., tensors of dtypes + such as `float32`, `float64` and `bfloat16`), extracts a binary bit + indicating whether it contains any -infinity, +infinity or NaN. + - "CONCISE_HEALTH": For each floating-dtype tensor, extract total + element count, and counts of -infinity, +infinity and NaN elements. + - "FULL_HEALTH": For each floating-dtype tensor, extracts the dtype, + rank (number of dimensions), total element count, and counts of + -infinity, +infinity and NaN elements. + - "SHAPE": For each tensor (regardless of dtype), extracts its dtype, + rank, total element count and shape. + circular_buffer_size: Size of the circular buffers for execution events. + These circular buffers are designed to reduce the overhead of debugging + dumping. They hold the most recent debug events concerning eager execution + of ops and `tf.function`s and traces of tensor values computed inside + `tf.function`s. They are written to the file system only when the proper + flushing method is called (see description of return values below). + Expected to be an integer. If <= 0, the circular-buffer behavior will be + disabled, i.e., the execution debug events will be written to the file + writers in the same way as non-execution events such as op creations and + source-file snapshots. + op_regex: Dump data from only the tensors from op types that matches to the + regular expression (through Python's `re.match()`). + "Op type" refers to the names of the TensorFlow operations (e.g., + "MatMul", "LogSoftmax"), which may repeat in a TensorFlow + function. It does *not* refer to the names of nodes (e.g., + "dense/MatMul", "dense_1/MatMul_1") which are unique within a function. + - Example 1: Dump tensor data from only MatMul and Relu ops + `op_regex="^(MatMul|Relu)$"`. + - Example 2: Dump tensors from all ops *except* Relu: + `op_regex="(?!^Relu$)"`. + This filter operates in a logical AND relation with `tensor_dtypes`. + tensor_dtypes: Dump data from only the tensors of which the specified + dtypes. This optional argument can be in any of the following format: + - a list or tuple of `DType` objects or strings that can be converted + to `DType` objects via `tf.as_dtype()`. Examples: + - `tensor_dtype=[tf.float32, tf.float64]`, + - `tensor_dtype=["float32", "float64"]`, + - `tensor_dtypes=(tf.int32, tf.bool)`, + - `tensor_dtypes=("int32", "bool")` + - a callable that takes a single `DType` argument and returns a Python + `boolean` indicating whether the dtype is to be included in the data + dumping. Examples: + - `tensor_dtype=lambda dtype: dtype.is_integer`. + This filter operates in a logical AND relation with `op_regex`. + Returns: + A DebugEventsWriter instance used by the dumping callback. The caller + may use its flushing methods, including `FlushNonExecutionFiles()` and + `FlushExecutionFiles()`. + """ + # TODO(cais): Revise the "UIs (currently under construction)" part of the doc + # string above. + # TODO(cais): Add Python code example to the doc string above. + global _state + + tensor_debug_mode_keys = debug_event_pb2.TensorDebugMode.keys() + if tensor_debug_mode not in tensor_debug_mode_keys: + raise ValueError( + "Invalid value in tensor_debug_mode ('%s'). Valid options are: %s" % + (tensor_debug_mode, tensor_debug_mode_keys)) + + tensor_debug_mode = debug_event_pb2.TensorDebugMode.Value(tensor_debug_mode) + if tensor_debug_mode not in (debug_event_pb2.TensorDebugMode.NO_TENSOR, + debug_event_pb2.TensorDebugMode.CURT_HEALTH, + debug_event_pb2.TensorDebugMode.CONCISE_HEALTH, + debug_event_pb2.TensorDebugMode.FULL_HEALTH, + debug_event_pb2.TensorDebugMode.SHAPE, + debug_event_pb2.TensorDebugMode.FULL_TENSOR): + raise NotImplementedError( + "tfdbg dumping: support for tensor debug mode %s is not " + "implemented yet" % + debug_event_pb2.TensorDebugMode.Name(tensor_debug_mode)) + + # Validate the types of tensor_dtypes. + if tensor_dtypes is not None: + if (not isinstance(tensor_dtypes, (list, tuple)) and + not callable(tensor_dtypes)): + raise ValueError( + "If specified, tensor_dtypes is expected to be a list, a tuple, or " + "a callable that takes a DType argument and returns a boolean, " + "but received %s" % (tensor_dtypes,)) + if isinstance(tensor_dtypes, (list, tuple)): + tensor_dtypes = [ + dtypes.as_dtype(dtype_item) for dtype_item in tensor_dtypes] + + if hasattr(_state, "dumping_callback"): + if _state.dumping_callback.circular_buffer_size != circular_buffer_size: + raise ValueError( + "There is already a dumping callback configured with a different " + "circular-buffer size (%d). Therefore the newly request " + "circular-buffer size (%d) will not be honored." % + (_state.dumping_callback.circular_buffer_size, circular_buffer_size)) + if _state.dumping_callback.tensor_debug_mode != tensor_debug_mode: + raise ValueError( + "There is already a dumping callback configured for dump root " + "%s with a different " + "tensor-debug mode (%s). Therefore the newly request " + "tensor-debug mode (%s) size will not be honored." % + (_state.dumping_callback.dump_root, + tensor_debug_mode_keys[_state.dumping_callback.tensor_debug_mode], + tensor_debug_mode_keys[tensor_debug_mode])) + else: + _state.dumping_callback = _DumpingCallback(dump_root, + tensor_debug_mode, + circular_buffer_size, + op_regex, + tensor_dtypes) + op_callbacks.add_op_callback(_state.dumping_callback.callback) + function_lib.CONCRETE_FUNCTION_CALLBACKS.append( + _state.dumping_callback.function_callback) + + if _state.dumping_callback.dump_root != dump_root: + _state.dumping_callback.dump_root = dump_root + + logging.info( + "Enabled dumping callback in thread %s " + "(dump root: %s, tensor debug mode: %s)", + threading.current_thread().name, + _state.dumping_callback.dump_root, + debug_event_pb2.TensorDebugMode.Name(tensor_debug_mode)) + + atexit.register(disable_dump_debug_info) + return _state.dumping_callback.get_writer() + + +@tf_export("debugging.experimental.disable_dump_debug_info") +def disable_dump_debug_info(): + """Disable the currently-enabled debugging dumping. + + If the `enable_dump_debug_info()` method under the same Python namespace + has been invoked before, calling this method disables it. If no call to + `enable_dump_debug_info()` has been made, calling this method is a no-op. + Calling this method more than once is idempotent. + """ + if hasattr(_state, "dumping_callback"): + dump_root = _state.dumping_callback.dump_root + tfdbg_run_id = _state.dumping_callback.tfdbg_run_id + debug_events_writer.DebugEventsWriter(dump_root, tfdbg_run_id).Close() + op_callbacks.remove_op_callback(_state.dumping_callback.callback) + if ( + _state.dumping_callback.function_callback + in function_lib.CONCRETE_FUNCTION_CALLBACKS + ): + function_lib.CONCRETE_FUNCTION_CALLBACKS.remove( + _state.dumping_callback.function_callback + ) + delattr(_state, "dumping_callback") + logging.info("Disabled dumping callback in thread %s (dump root: %s)", + threading.current_thread().name, dump_root) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/dumping_callback_test_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/dumping_callback_test_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..fd898ca427e5c4914a0ce0238ebcd5019aed6592 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/dumping_callback_test_lib.py @@ -0,0 +1,49 @@ +# Copyright 2019 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Shared library for testing tfdbg v2 dumping callback.""" + +import os +import shutil +import tempfile +import uuid + +from tensorflow.python.debug.lib import check_numerics_callback +from tensorflow.python.debug.lib import debug_events_reader +from tensorflow.python.debug.lib import dumping_callback +from tensorflow.python.framework import test_util +from tensorflow.python.framework import versions + + +class DumpingCallbackTestBase(test_util.TensorFlowTestCase): + """Base test-case class for tfdbg v2 callbacks.""" + + def setUp(self): + super(DumpingCallbackTestBase, self).setUp() + self.dump_root = tempfile.mkdtemp() + self.tfdbg_run_id = str(uuid.uuid4()) + + def tearDown(self): + if os.path.isdir(self.dump_root): + shutil.rmtree(self.dump_root, ignore_errors=True) + check_numerics_callback.disable_check_numerics() + dumping_callback.disable_dump_debug_info() + super(DumpingCallbackTestBase, self).tearDown() + + def _readAndCheckMetadataFile(self): + """Read and check the .metadata debug-events file.""" + with debug_events_reader.DebugEventsReader(self.dump_root) as reader: + self.assertTrue(reader.tfdbg_run_id()) + self.assertEqual(reader.tensorflow_version(), versions.__version__) + self.assertTrue(reader.tfdbg_file_version().startswith("debug.Event")) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_server.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ea1660e42a736f0e1bc33685ee61018ca504cf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_server.py @@ -0,0 +1,492 @@ +# 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. +# ============================================================================== +"""gRPC debug server in Python.""" +# pylint: disable=g-bad-import-order +import collections +import json +import queue +import threading +import time + +from concurrent import futures +import grpc + +from tensorflow.core.debug import debug_service_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.python.debug.lib import debug_graphs +from tensorflow.python.debug.lib import debug_service_pb2_grpc +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat + +DebugWatch = collections.namedtuple("DebugWatch", + ["node_name", "output_slot", "debug_op"]) + + +def _state_change(new_state, node_name, output_slot, debug_op): + state_change = debug_service_pb2.EventReply.DebugOpStateChange() + state_change.state = new_state + state_change.node_name = node_name + state_change.output_slot = output_slot + state_change.debug_op = debug_op + return state_change + + +class EventListenerBaseStreamHandler: + """Per-stream handler of EventListener gRPC streams.""" + + def __init__(self): + """Constructor of EventListenerBaseStreamHandler.""" + + def on_core_metadata_event(self, event): + """Callback for core metadata. + + Args: + event: The Event proto that carries a JSON string in its + `log_message.message` field. + + Returns: + `None` or an `EventReply` proto to be sent back to the client. If `None`, + an `EventReply` proto construct with the default no-arg constructor will + be sent back to the client. + """ + raise NotImplementedError( + "on_core_metadata_event() is not implemented in the base servicer " + "class") + + def on_graph_def(self, graph_def, device_name, wall_time): + """Callback for Event proto received through the gRPC stream. + + This Event proto carries a GraphDef, encoded as bytes, in its graph_def + field. + + Args: + graph_def: A GraphDef object. + device_name: Name of the device on which the graph was created. + wall_time: An epoch timestamp (in microseconds) for the graph. + + Returns: + `None` or an `EventReply` proto to be sent back to the client. If `None`, + an `EventReply` proto construct with the default no-arg constructor will + be sent back to the client. + """ + raise NotImplementedError( + "on_graph_def() is not implemented in the base servicer class") + + def on_value_event(self, event): + """Callback for Event proto received through the gRPC stream. + + This Event proto carries a Tensor in its summary.value[0] field. + + Args: + event: The Event proto from the stream to be processed. + """ + raise NotImplementedError( + "on_value_event() is not implemented in the base servicer class") + + +class EventListenerBaseServicer(debug_service_pb2_grpc.EventListenerServicer): + """Base Python class for gRPC debug server.""" + + def __init__(self, server_port, stream_handler_class): + """Constructor. + + Args: + server_port: (int) Port number to bind to. + stream_handler_class: A class of the base class + `EventListenerBaseStreamHandler` that will be used to constructor + stream handler objects during `SendEvents` calls. + """ + + self._server_port = server_port + self._stream_handler_class = stream_handler_class + + self._server_lock = threading.Lock() + self._server_started = False + self._stop_requested = False + + self._debug_ops_state_change_queue = queue.Queue() + self._gated_grpc_debug_watches = set() + self._breakpoints = set() + + def SendEvents(self, request_iterator, context): + """Implementation of the SendEvents service method. + + This method receives streams of Event protos from the client, and processes + them in ways specified in the on_event() callback. The stream is + bi-directional, but currently only the client-to-server stream (i.e., the + stream from the debug ops to the server) is used. + + Args: + request_iterator: The incoming stream of Event protos. + context: Server context. + + Raises: + ValueError: If there are more than one core metadata events. + + Yields: + An empty stream of responses. + """ + core_metadata_count = 0 + + # A map from GraphDef hash to a list of received chunks. + graph_def_chunks = {} + tensor_chunks = {} + + stream_handler = None + for event in request_iterator: + if not stream_handler: + stream_handler = self._stream_handler_class() + + if event.summary and event.summary.value: + # An Event proto carrying a tensor value. + maybe_tensor_event = self._process_tensor_event_in_chunks( + event, tensor_chunks) + if maybe_tensor_event: + event_reply = stream_handler.on_value_event(maybe_tensor_event) + if event_reply is not None: + yield self._process_debug_op_state_changes(event_reply) + else: + # Non-tensor-value Event. + if event.graph_def: + # GraphDef-carrying Event. + maybe_graph_def, maybe_device_name, maybe_wall_time = ( + self._process_encoded_graph_def_in_chunks( + event, graph_def_chunks)) + if maybe_graph_def: + reply = stream_handler.on_graph_def( + maybe_graph_def, maybe_device_name, maybe_wall_time) + yield self._process_debug_op_state_changes(reply) + elif event.log_message.message: + # Core metadata-carrying Event. + core_metadata_count += 1 + if core_metadata_count > 1: + raise ValueError( + "Expected one core metadata event; received multiple") + reply = stream_handler.on_core_metadata_event(event) + yield self._process_debug_op_state_changes(reply) + + def _process_debug_op_state_changes(self, event_reply=None): + """Dequeue and process all the queued debug-op state change protos. + + Include all the debug-op state change protos in a `EventReply` proto. + + Args: + event_reply: An `EventReply` to add the `DebugOpStateChange` protos to, + or `None`. + + Returns: + An `EventReply` proto with the dequeued `DebugOpStateChange` protos (if + any) added. + """ + if event_reply is None: + event_reply = debug_service_pb2.EventReply() + while not self._debug_ops_state_change_queue.empty(): + state_change = self._debug_ops_state_change_queue.get() + debug_node_key = (state_change.node_name, state_change.output_slot, + state_change.debug_op) + if (state_change.state == + debug_service_pb2.EventReply.DebugOpStateChange.READ_WRITE): + logging.info("Adding breakpoint %s:%d:%s", state_change.node_name, + state_change.output_slot, state_change.debug_op) + self._breakpoints.add(debug_node_key) + elif (state_change.state == + debug_service_pb2.EventReply.DebugOpStateChange.READ_ONLY): + logging.info("Adding watchpoint %s:%d:%s", state_change.node_name, + state_change.output_slot, state_change.debug_op) + if debug_node_key in self._breakpoints: + self._breakpoints.discard(debug_node_key) + elif (state_change.state == + debug_service_pb2.EventReply.DebugOpStateChange.DISABLED): + logging.info("Removing watchpoint or breakpoint: %s:%d:%s", + state_change.node_name, state_change.output_slot, + state_change.debug_op) + if debug_node_key in self._breakpoints: + self._breakpoints.discard(debug_node_key) + else: + logging.warn( + "Attempting to remove a non-existent debug node key: %s", + debug_node_key) + new_state_change = event_reply.debug_op_state_changes.add() + new_state_change.CopyFrom(state_change) + return event_reply + + def _process_tensor_event_in_chunks(self, event, tensor_chunks): + """Possibly reassemble event chunks. + + Due to gRPC's message size limit, a large tensor can be encapsulated in + multiple Event proto chunks to be sent through the debugger stream. This + method keeps track of the chunks that have arrived, reassemble all chunks + corresponding to a tensor when they have arrived and return the reassembled + Event proto. + + Args: + event: The single Event proto that has arrived. + tensor_chunks: A dict used to keep track of the Event protos that have + arrived but haven't been reassembled. + + Returns: + If all Event protos corresponding to a tensor have arrived, returns the + reassembled Event proto. Otherwise, return None. + """ + + value = event.summary.value[0] + debugger_plugin_metadata = json.loads( + compat.as_text(value.metadata.plugin_data.content)) + device_name = debugger_plugin_metadata["device"] + num_chunks = debugger_plugin_metadata["numChunks"] + chunk_index = debugger_plugin_metadata["chunkIndex"] + + if num_chunks <= 1: + return event + + debug_node_name = value.node_name + timestamp = int(event.wall_time) + tensor_key = "%s_%s_%d" % (device_name, debug_node_name, timestamp) + + if tensor_key not in tensor_chunks: + tensor_chunks[tensor_key] = [None] * num_chunks + + chunks = tensor_chunks[tensor_key] + if value.tensor.tensor_content: + chunks[chunk_index] = value.tensor + elif value.tensor.string_val: + chunks[chunk_index] = event + + if None not in chunks: + if value.tensor.tensor_content: + event.summary.value[0].tensor.tensor_content = b"".join( + chunk.tensor_content for chunk in chunks) + del tensor_chunks[tensor_key] + return event + elif value.tensor.string_val: + merged_event = chunks[0] + for chunk in chunks[1:]: + merged_event.summary.value[0].tensor.string_val.extend( + list(chunk.summary.value[0].tensor.string_val)) + return merged_event + + def _process_encoded_graph_def_in_chunks(self, + event, + graph_def_chunks): + """Process an Event proto containing a chunk of encoded GraphDef. + + Args: + event: the Event proto containing the chunk of encoded GraphDef. + graph_def_chunks: A dict mapping keys for GraphDefs (i.e., + ",,") to a list of chunks of + encoded GraphDefs. + + Returns: + If all chunks of the GraphDef have arrived, + return decoded GraphDef proto, device name, wall_time. + Otherwise, + return None, None, None. + """ + graph_def = graph_pb2.GraphDef() + index_bar_0 = event.graph_def.find(b"|") + index_bar_1 = event.graph_def.find(b"|", index_bar_0 + 1) + index_bar_2 = event.graph_def.find(b"|", index_bar_1 + 1) + graph_def_hash_device_timestamp = event.graph_def[:index_bar_0] + chunk_index = int(event.graph_def[index_bar_0 + 1 : index_bar_1]) + num_chunks = int(event.graph_def[index_bar_1 + 1 : index_bar_2]) + if graph_def_hash_device_timestamp not in graph_def_chunks: + graph_def_chunks[graph_def_hash_device_timestamp] = [None] * num_chunks + graph_def_chunks[graph_def_hash_device_timestamp][ + chunk_index] = event.graph_def[index_bar_2 + 1:] + if all(graph_def_chunks[graph_def_hash_device_timestamp]): + device_name = graph_def_hash_device_timestamp.split(b",")[1] + wall_time = int(graph_def_hash_device_timestamp.split(b",")[2]) + graph_def.ParseFromString( + b"".join(graph_def_chunks[graph_def_hash_device_timestamp])) + del graph_def_chunks[graph_def_hash_device_timestamp] + self._process_graph_def(graph_def) + return graph_def, device_name, wall_time + else: + return None, None, None + + def _process_graph_def(self, graph_def): + for node_def in graph_def.node: + if (debug_graphs.is_debug_node(node_def.name) and + node_def.attr["gated_grpc"].b): + node_name, output_slot, _, debug_op = ( + debug_graphs.parse_debug_node_name(node_def.name)) + self._gated_grpc_debug_watches.add( + DebugWatch(node_name, output_slot, debug_op)) + + def run_server(self, blocking=True): + """Start running the server. + + Args: + blocking: If `True`, block until `stop_server()` is invoked. + + Raises: + ValueError: If server stop has already been requested, or if the server + has already started running. + """ + self._server_lock.acquire() + try: + if self._stop_requested: + raise ValueError("Server has already stopped") + if self._server_started: + raise ValueError("Server has already started running") + + no_max_message_sizes = [("grpc.max_receive_message_length", -1), + ("grpc.max_send_message_length", -1)] + self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), + options=no_max_message_sizes) + debug_service_pb2_grpc.add_EventListenerServicer_to_server(self, + self.server) + self.server.add_insecure_port("[::]:%d" % self._server_port) + self.server.start() + self._server_started = True + finally: + self._server_lock.release() + + if blocking: + while not self._stop_requested: + time.sleep(1.0) + + def stop_server(self, grace=1.0): + """Request server stopping. + + Once stopped, server cannot be stopped or started again. This method is + non-blocking. Call `wait()` on the returned event to block until the server + has completely stopped. + + Args: + grace: Grace period in seconds to be used when calling `server.stop()`. + + Raises: + ValueError: If server stop has already been requested, or if the server + has not started running yet. + + Returns: + A threading.Event that will be set when the server has completely stopped. + """ + self._server_lock.acquire() + try: + if not self._server_started: + raise ValueError("Server has not started running") + if self._stop_requested: + raise ValueError("Server has already stopped") + + self._stop_requested = True + return self.server.stop(grace=grace) + finally: + self._server_lock.release() + + def request_watch(self, node_name, output_slot, debug_op, breakpoint=False): # pylint: disable=redefined-builtin + """Request enabling a debug tensor watchpoint or breakpoint. + + This will let the server send a EventReply to the client side + (i.e., the debugged TensorFlow runtime process) to request adding a watch + key (i.e., ::) to the list of enabled + watch keys. The list applies only to debug ops with the attribute + gated_grpc=True. + + To disable the watch, use `request_unwatch()`. + + Args: + node_name: (`str`) name of the node that the to-be-watched tensor belongs + to, e.g., "hidden/Weights". + output_slot: (`int`) output slot index of the tensor to watch. + debug_op: (`str`) name of the debug op to enable. This should not include + any attribute substrings. + breakpoint: (`bool`) Iff `True`, the debug op will block and wait until it + receives an `EventReply` response from the server. The `EventReply` + proto may carry a TensorProto that modifies the value of the debug op's + output tensor. + """ + self._debug_ops_state_change_queue.put( + _state_change( + debug_service_pb2.EventReply.DebugOpStateChange.READ_WRITE + if breakpoint + else debug_service_pb2.EventReply.DebugOpStateChange.READ_ONLY, + node_name, output_slot, debug_op)) + + def request_unwatch(self, node_name, output_slot, debug_op): + """Request disabling a debug tensor watchpoint or breakpoint. + + This is the opposite of `request_watch()`. + + Args: + node_name: (`str`) name of the node that the to-be-watched tensor belongs + to, e.g., "hidden/Weights". + output_slot: (`int`) output slot index of the tensor to watch. + debug_op: (`str`) name of the debug op to enable. This should not include + any attribute substrings. + """ + self._debug_ops_state_change_queue.put( + _state_change( + debug_service_pb2.EventReply.DebugOpStateChange.DISABLED, node_name, + output_slot, debug_op)) + + @property + def breakpoints(self): + """Get a set of the currently-activated breakpoints. + + Returns: + A `set` of 3-tuples: (node_name, output_slot, debug_op), e.g., + {("MatMul", 0, "DebugIdentity")}. + """ + return self._breakpoints + + def gated_grpc_debug_watches(self): + """Get the list of debug watches with attribute gated_grpc=True. + + Since the server receives `GraphDef` from the debugged runtime, it can only + return such debug watches that it has received so far. + + Returns: + A `list` of `DebugWatch` `namedtuples` representing the debug watches with + gated_grpc=True. Each `namedtuple` element has the attributes: + `node_name` as a `str`, + `output_slot` as an `int`, + `debug_op` as a `str`. + """ + return list(self._gated_grpc_debug_watches) + + def SendTracebacks(self, request, context): + """Base implementation of the handling of SendTracebacks calls. + + The base implementation does nothing with the incoming request. + Override in an implementation of the server if necessary. + + Args: + request: A `CallTraceback` proto, containing information about the + type (e.g., graph vs. eager execution) and source-code traceback of the + call and (any) associated `tf.Graph`s. + context: Server context. + + Returns: + A `EventReply` proto. + """ + return debug_service_pb2.EventReply() + + def SendSourceFiles(self, request, context): + """Base implementation of the handling of SendSourceFiles calls. + + The base implementation does nothing with the incoming request. + Override in an implementation of the server if necessary. + + Args: + request: A `DebuggedSourceFiles` proto, containing the path, content, size + and last-modified timestamp of source files. + context: Server context. + + Returns: + A `EventReply` proto. + """ + return debug_service_pb2.EventReply() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_test_server.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_test_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb8fbd6287fd34972c5d49b1a443fa3fc6d6631 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_debug_test_server.py @@ -0,0 +1,484 @@ +# 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. +# ============================================================================== +"""GRPC debug server for testing.""" +import collections +import errno +import functools +import hashlib +import json +import os +import re +import tempfile +import threading +import time + +import portpicker + +from tensorflow.core.debug import debug_service_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.client import session +from tensorflow.python.debug.lib import debug_data +from tensorflow.python.debug.lib import debug_utils +from tensorflow.python.debug.lib import grpc_debug_server +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import errors +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variables +from tensorflow.python.util import compat + + +def _get_dump_file_path(dump_root, device_name, debug_node_name): + """Get the file path of the dump file for a debug node. + + Args: + dump_root: (str) Root dump directory. + device_name: (str) Name of the device that the debug node resides on. + debug_node_name: (str) Name of the debug node, e.g., + cross_entropy/Log:0:DebugIdentity. + + Returns: + (str) Full path of the dump file. + """ + + dump_root = os.path.join( + dump_root, debug_data.device_name_to_device_path(device_name)) + if "/" in debug_node_name: + dump_dir = os.path.join(dump_root, os.path.dirname(debug_node_name)) + dump_file_name = re.sub(":", "_", os.path.basename(debug_node_name)) + else: + dump_dir = dump_root + dump_file_name = re.sub(":", "_", debug_node_name) + + now_microsec = int(round(time.time() * 1000 * 1000)) + dump_file_name += "_%d" % now_microsec + + return os.path.join(dump_dir, dump_file_name) + + +class EventListenerTestStreamHandler( + grpc_debug_server.EventListenerBaseStreamHandler): + """Implementation of EventListenerBaseStreamHandler that dumps to file.""" + + def __init__(self, dump_dir, event_listener_servicer): + super(EventListenerTestStreamHandler, self).__init__() + self._dump_dir = dump_dir + self._event_listener_servicer = event_listener_servicer + if self._dump_dir: + self._try_makedirs(self._dump_dir) + + self._grpc_path = None + self._cached_graph_defs = [] + self._cached_graph_def_device_names = [] + self._cached_graph_def_wall_times = [] + + def on_core_metadata_event(self, event): + self._event_listener_servicer.toggle_watch() + + core_metadata = json.loads(event.log_message.message) + + if not self._grpc_path: + grpc_path = core_metadata["grpc_path"] + if grpc_path: + if grpc_path.startswith("/"): + grpc_path = grpc_path[1:] + if self._dump_dir: + self._dump_dir = os.path.join(self._dump_dir, grpc_path) + + # Write cached graph defs to filesystem. + for graph_def, device_name, wall_time in zip( + self._cached_graph_defs, + self._cached_graph_def_device_names, + self._cached_graph_def_wall_times): + self._write_graph_def(graph_def, device_name, wall_time) + + if self._dump_dir: + self._write_core_metadata_event(event) + else: + self._event_listener_servicer.core_metadata_json_strings.append( + event.log_message.message) + + def on_graph_def(self, graph_def, device_name, wall_time): + """Implementation of the tensor value-carrying Event proto callback. + + Args: + graph_def: A GraphDef object. + device_name: Name of the device on which the graph was created. + wall_time: An epoch timestamp (in microseconds) for the graph. + """ + if self._dump_dir: + if self._grpc_path: + self._write_graph_def(graph_def, device_name, wall_time) + else: + self._cached_graph_defs.append(graph_def) + self._cached_graph_def_device_names.append(device_name) + self._cached_graph_def_wall_times.append(wall_time) + else: + self._event_listener_servicer.partition_graph_defs.append(graph_def) + + def on_value_event(self, event): + """Implementation of the tensor value-carrying Event proto callback. + + Writes the Event proto to the file system for testing. The path written to + follows the same pattern as the file:// debug URLs of tfdbg, i.e., the + name scope of the op becomes the directory structure under the dump root + directory. + + Args: + event: The Event proto carrying a tensor value. + + Returns: + If the debug node belongs to the set of currently activated breakpoints, + a `EventReply` proto will be returned. + """ + if self._dump_dir: + self._write_value_event(event) + else: + value = event.summary.value[0] + tensor_value = debug_data.load_tensor_from_event(event) + self._event_listener_servicer.debug_tensor_values[value.node_name].append( + tensor_value) + + items = event.summary.value[0].node_name.split(":") + node_name = items[0] + output_slot = int(items[1]) + debug_op = items[2] + if ((node_name, output_slot, debug_op) in + self._event_listener_servicer.breakpoints): + return debug_service_pb2.EventReply() + + def _try_makedirs(self, dir_path): + if not os.path.isdir(dir_path): + try: + os.makedirs(dir_path) + except OSError as error: + if error.errno != errno.EEXIST: + raise + + def _write_core_metadata_event(self, event): + core_metadata_path = os.path.join( + self._dump_dir, + debug_data.METADATA_FILE_PREFIX + debug_data.CORE_METADATA_TAG + + "_%d" % event.wall_time) + self._try_makedirs(self._dump_dir) + with open(core_metadata_path, "wb") as f: + f.write(event.SerializeToString()) + + def _write_graph_def(self, graph_def, device_name, wall_time): + encoded_graph_def = graph_def.SerializeToString() + graph_hash = int(hashlib.sha1(encoded_graph_def).hexdigest(), 16) + event = event_pb2.Event(graph_def=encoded_graph_def, wall_time=wall_time) + graph_file_path = os.path.join( + self._dump_dir, + debug_data.device_name_to_device_path(device_name), + debug_data.METADATA_FILE_PREFIX + debug_data.GRAPH_FILE_TAG + + debug_data.HASH_TAG + "%d_%d" % (graph_hash, wall_time)) + self._try_makedirs(os.path.dirname(graph_file_path)) + with open(graph_file_path, "wb") as f: + f.write(event.SerializeToString()) + + def _write_value_event(self, event): + value = event.summary.value[0] + + # Obtain the device name from the metadata. + summary_metadata = event.summary.value[0].metadata + if not summary_metadata.plugin_data: + raise ValueError("The value lacks plugin data.") + try: + content = json.loads(compat.as_text(summary_metadata.plugin_data.content)) + except ValueError as err: + raise ValueError("Could not parse content into JSON: %r, %r" % (content, + err)) + device_name = content["device"] + + dump_full_path = _get_dump_file_path( + self._dump_dir, device_name, value.node_name) + self._try_makedirs(os.path.dirname(dump_full_path)) + with open(dump_full_path, "wb") as f: + f.write(event.SerializeToString()) + + +class EventListenerTestServicer(grpc_debug_server.EventListenerBaseServicer): + """An implementation of EventListenerBaseServicer for testing.""" + + def __init__(self, server_port, dump_dir, toggle_watch_on_core_metadata=None): + """Constructor of EventListenerTestServicer. + + Args: + server_port: (int) The server port number. + dump_dir: (str) The root directory to which the data files will be + dumped. If empty or None, the received debug data will not be dumped + to the file system: they will be stored in memory instead. + toggle_watch_on_core_metadata: A list of + (node_name, output_slot, debug_op) tuples to toggle the + watchpoint status during the on_core_metadata calls (optional). + """ + self.core_metadata_json_strings = [] + self.partition_graph_defs = [] + self.debug_tensor_values = collections.defaultdict(list) + self._initialize_toggle_watch_state(toggle_watch_on_core_metadata) + + grpc_debug_server.EventListenerBaseServicer.__init__( + self, server_port, + functools.partial(EventListenerTestStreamHandler, dump_dir, self)) + + # Members for storing the graph ops traceback and source files. + self._call_types = [] + self._call_keys = [] + self._origin_stacks = [] + self._origin_id_to_strings = [] + self._graph_tracebacks = [] + self._graph_versions = [] + self._source_files = [] + + def _initialize_toggle_watch_state(self, toggle_watches): + self._toggle_watches = toggle_watches + self._toggle_watch_state = {} + if self._toggle_watches: + for watch_key in self._toggle_watches: + self._toggle_watch_state[watch_key] = False + + def toggle_watch(self): + for watch_key in self._toggle_watch_state: + node_name, output_slot, debug_op = watch_key + if self._toggle_watch_state[watch_key]: + self.request_unwatch(node_name, output_slot, debug_op) + else: + self.request_watch(node_name, output_slot, debug_op) + self._toggle_watch_state[watch_key] = ( + not self._toggle_watch_state[watch_key]) + + def clear_data(self): + self.core_metadata_json_strings = [] + self.partition_graph_defs = [] + self.debug_tensor_values = collections.defaultdict(list) + self._call_types = [] + self._call_keys = [] + self._origin_stacks = [] + self._origin_id_to_strings = [] + self._graph_tracebacks = [] + self._graph_versions = [] + self._source_files = [] + + def SendTracebacks(self, request, context): + self._call_types.append(request.call_type) + self._call_keys.append(request.call_key) + self._origin_stacks.append(request.origin_stack) + self._origin_id_to_strings.append(request.origin_id_to_string) + self._graph_tracebacks.append(request.graph_traceback) + self._graph_versions.append(request.graph_version) + return debug_service_pb2.EventReply() + + def SendSourceFiles(self, request, context): + self._source_files.append(request) + return debug_service_pb2.EventReply() + + def query_op_traceback(self, op_name): + """Query the traceback of an op. + + Args: + op_name: Name of the op to query. + + Returns: + The traceback of the op, as a list of 3-tuples: + (filename, lineno, function_name) + + Raises: + ValueError: If the op cannot be found in the tracebacks received by the + server so far. + """ + for op_log_proto in self._graph_tracebacks: + for log_entry in op_log_proto.log_entries: + if log_entry.name == op_name: + return self._code_def_to_traceback(log_entry.code_def, + op_log_proto.id_to_string) + raise ValueError( + "Op '%s' does not exist in the tracebacks received by the debug " + "server." % op_name) + + def query_origin_stack(self): + """Query the stack of the origin of the execution call. + + Returns: + A `list` of all tracebacks. Each item corresponds to an execution call, + i.e., a `SendTracebacks` request. Each item is a `list` of 3-tuples: + (filename, lineno, function_name). + """ + ret = [] + for stack, id_to_string in zip( + self._origin_stacks, self._origin_id_to_strings): + ret.append(self._code_def_to_traceback(stack, id_to_string)) + return ret + + def query_call_types(self): + return self._call_types + + def query_call_keys(self): + return self._call_keys + + def query_graph_versions(self): + return self._graph_versions + + def query_source_file_line(self, file_path, lineno): + """Query the content of a given line in a source file. + + Args: + file_path: Path to the source file. + lineno: Line number as an `int`. + + Returns: + Content of the line as a string. + + Raises: + ValueError: If no source file is found at the given file_path. + """ + if not self._source_files: + raise ValueError( + "This debug server has not received any source file contents yet.") + for source_files in self._source_files: + for source_file_proto in source_files.source_files: + if source_file_proto.file_path == file_path: + return source_file_proto.lines[lineno - 1] + raise ValueError( + "Source file at path %s has not been received by the debug server", + file_path) + + def _code_def_to_traceback(self, code_def, id_to_string): + return [(id_to_string[trace.file_id], + trace.lineno, + id_to_string[trace.function_id]) for trace in code_def.traces] + + +def start_server_on_separate_thread(dump_to_filesystem=True, + server_start_delay_sec=0.0, + poll_server=False, + blocking=True, + toggle_watch_on_core_metadata=None): + """Create a test gRPC debug server and run on a separate thread. + + Args: + dump_to_filesystem: (bool) whether the debug server will dump debug data + to the filesystem. + server_start_delay_sec: (float) amount of time (in sec) to delay the server + start up for. + poll_server: (bool) whether the server will be polled till success on + startup. + blocking: (bool) whether the server should be started in a blocking mode. + toggle_watch_on_core_metadata: A list of + (node_name, output_slot, debug_op) tuples to toggle the + watchpoint status during the on_core_metadata calls (optional). + + Returns: + server_port: (int) Port on which the server runs. + debug_server_url: (str) grpc:// URL to the server. + server_dump_dir: (str) The debug server's dump directory. + server_thread: The server Thread object. + server: The `EventListenerTestServicer` object. + + Raises: + ValueError: If polling the server process for ready state is not successful + within maximum polling count. + """ + server_port = portpicker.pick_unused_port() + debug_server_url = "grpc://localhost:%d" % server_port + + server_dump_dir = tempfile.mkdtemp() if dump_to_filesystem else None + server = EventListenerTestServicer( + server_port=server_port, + dump_dir=server_dump_dir, + toggle_watch_on_core_metadata=toggle_watch_on_core_metadata) + + def delay_then_run_server(): + time.sleep(server_start_delay_sec) + server.run_server(blocking=blocking) + + server_thread = threading.Thread(target=delay_then_run_server) + server_thread.start() + + if poll_server: + if not _poll_server_till_success( + 50, + 0.2, + debug_server_url, + server_dump_dir, + server, + gpu_memory_fraction=0.1): + raise ValueError( + "Failed to start test gRPC debug server at port %d" % server_port) + server.clear_data() + return server_port, debug_server_url, server_dump_dir, server_thread, server + + +def _poll_server_till_success(max_attempts, + sleep_per_poll_sec, + debug_server_url, + dump_dir, + server, + gpu_memory_fraction=1.0): + """Poll server until success or exceeding max polling count. + + Args: + max_attempts: (int) How many times to poll at maximum + sleep_per_poll_sec: (float) How many seconds to sleep for after each + unsuccessful poll. + debug_server_url: (str) gRPC URL to the debug server. + dump_dir: (str) Dump directory to look for files in. If None, will directly + check data from the server object. + server: The server object. + gpu_memory_fraction: (float) Fraction of GPU memory to be + allocated for the Session used in server polling. + + Returns: + (bool) Whether the polling succeeded within max_polls attempts. + """ + poll_count = 0 + + config = config_pb2.ConfigProto(gpu_options=config_pb2.GPUOptions( + per_process_gpu_memory_fraction=gpu_memory_fraction)) + with session.Session(config=config) as sess: + for poll_count in range(max_attempts): + server.clear_data() + print("Polling: poll_count = %d" % poll_count) + + x_init_name = "x_init_%d" % poll_count + x_init = constant_op.constant([42.0], shape=[1], name=x_init_name) + x = variables.Variable(x_init, name=x_init_name) + + run_options = config_pb2.RunOptions() + debug_utils.add_debug_tensor_watch( + run_options, x_init_name, 0, debug_urls=[debug_server_url]) + try: + sess.run(x.initializer, options=run_options) + except errors.FailedPreconditionError: + pass + + if dump_dir: + if os.path.isdir( + dump_dir) and debug_data.DebugDumpDir(dump_dir).size > 0: + file_io.delete_recursively(dump_dir) + print("Poll succeeded.") + return True + else: + print("Poll failed. Sleeping for %f s" % sleep_per_poll_sec) + time.sleep(sleep_per_poll_sec) + else: + if server.debug_tensor_values: + print("Poll succeeded.") + return True + else: + print("Poll failed. Sleeping for %f s" % sleep_per_poll_sec) + time.sleep(sleep_per_poll_sec) + + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_tensorflow_server.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_tensorflow_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cdced44482132c4e802dc8819f0b1471be0b5f77 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/grpc_tensorflow_server.py @@ -0,0 +1,157 @@ +# 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. +# ============================================================================== +"""Python-based TensorFlow GRPC server. + +Takes input arguments cluster_spec, job_name and task_id, and start a blocking +TensorFlow GRPC server. + +Usage: + grpc_tensorflow_server.py --cluster_spec=SPEC --job_name=NAME --task_id=ID + +Where: + SPEC is (,)* + JOB is |(;)* + NAME is a valid job name ([a-z][0-9a-z]*) + HOST is a hostname or IP address + PORT is a port number +""" + +import argparse +import sys + +from absl import app + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import tensorflow_server_pb2 +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import server_lib + + +def parse_cluster_spec(cluster_spec, cluster, verbose=False): + """Parse content of cluster_spec string and inject info into cluster protobuf. + + Args: + cluster_spec: cluster specification string, e.g., + "local|localhost:2222;localhost:2223" + cluster: cluster protobuf. + verbose: If verbose logging is requested. + + Raises: + ValueError: if the cluster_spec string is invalid. + """ + + job_strings = cluster_spec.split(",") + + if not cluster_spec: + raise ValueError("Empty cluster_spec string") + + for job_string in job_strings: + job_def = cluster.job.add() + + if job_string.count("|") != 1: + raise ValueError("Not exactly one instance of '|' in cluster_spec") + + job_name = job_string.split("|")[0] + + if not job_name: + raise ValueError("Empty job_name in cluster_spec") + + job_def.name = job_name + + if verbose: + logging.info("Added job named \"%s\"", job_name) + + job_tasks = job_string.split("|")[1].split(";") + for i in range(len(job_tasks)): + if not job_tasks[i]: + raise ValueError("Empty task string at position %d" % i) + + job_def.tasks[i] = job_tasks[i] + + if verbose: + logging.info(" Added task \"%s\" to job \"%s\"", + job_tasks[i], job_name) + + +def main(unused_args): + # Create Protobuf ServerDef + server_def = tensorflow_server_pb2.ServerDef(protocol="grpc") + + # Cluster info + parse_cluster_spec(FLAGS.cluster_spec, server_def.cluster, FLAGS.verbose) + + # Job name + if not FLAGS.job_name: + raise ValueError("Empty job_name") + server_def.job_name = FLAGS.job_name + + # Task index + if FLAGS.task_id < 0: + raise ValueError("Invalid task_id: %d" % FLAGS.task_id) + server_def.task_index = FLAGS.task_id + + config = config_pb2.ConfigProto(gpu_options=config_pb2.GPUOptions( + per_process_gpu_memory_fraction=FLAGS.gpu_memory_fraction)) + + # Create GRPC Server instance + server = server_lib.Server(server_def, config=config) + + # join() is blocking, unlike start() + server.join() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.register("type", "bool", lambda v: v.lower() == "true") + parser.add_argument( + "--cluster_spec", + type=str, + default="", + help="""\ + Cluster spec: SPEC. SPEC is (,)*," JOB is + |(;)*," NAME is a valid job name + ([a-z][0-9a-z]*)," HOST is a hostname or IP address," PORT is a + port number." E.g., local|localhost:2222;localhost:2223, + ps|ps0:2222;ps1:2222\ + """ + ) + parser.add_argument( + "--job_name", + type=str, + default="", + help="Job name: e.g., local" + ) + parser.add_argument( + "--task_id", + type=int, + default=0, + help="Task index, e.g., 0" + ) + parser.add_argument( + "--gpu_memory_fraction", + type=float, + default=1.0, + help="Fraction of GPU memory allocated",) + parser.add_argument( + "--verbose", + type="bool", + nargs="?", + const=True, + default=False, + help="Verbose mode" + ) + + FLAGS, unparsed = parser.parse_known_args() + app.run(main=main, argv=[sys.argv[0]] + unparsed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/op_callbacks_common.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/op_callbacks_common.py new file mode 100644 index 0000000000000000000000000000000000000000..948f86a86fbfa5982acb5912937a8399513d5602 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/op_callbacks_common.py @@ -0,0 +1,46 @@ +# 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 utilities and settings used by tfdbg v2's op callbacks.""" + +# The ops that are skipped by tfdbg v2's op callbacks. +# They belong to TensorFlow's control flow ops (e.g., "Enter", "StatelessIf") +# and ops that wrap nested tf.function calls. +OP_CALLBACK_SKIP_OPS = ( + # TODO(b/139668453): The following skipped ops are related to a limitation + # in the op callback. + b"Enter", + b"Exit", + b"Identity", + b"If", + b"LoopCond", + b"Merge", + b"NextIteration", + b"StatelessIf", + b"StatefulPartitionedCall", + b"Switch", + b"While", + # NOTE(b/154097452): On TPUs, debugger ops are colocated with RemoteCall + # ops. This exclusion prevents an error due to no OpKernel for those + # debugger ops. + b"RemoteCall", + # TPU-specific ops begin. + b"TPUReplicatedInput", + b"TPUReplicateMetadata", + b"TPUCompilationResult", + b"TPUReplicatedOutput", + b"ConfigureDistributedTPU", + # Other special ops used by TensorFlow internally. + b"DestroyResourceOp", +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/profiling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..b60068ab1a936079b4224d8cde3a079c5779879d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/profiling.py @@ -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. +# ============================================================================== +"""Data structures and algorithms for profiling information.""" + +import os + + +class ProfileDatum(object): + """Profile data point.""" + + def __init__(self, + device_name, + node_exec_stats, + file_path, + line_number, + func_name, + op_type): + """Constructor. + + Args: + device_name: (string) name of the device. + node_exec_stats: `NodeExecStats` proto. + file_path: path to the source file involved in creating the op. + line_number: line number in the file involved in creating the op. + func_name: name of the function that the line belongs to. + op_type: (string) Operation type. + """ + self.device_name = device_name + self.node_exec_stats = node_exec_stats + self.file_path = file_path + self.line_number = line_number + self.func_name = func_name + if self.file_path: + self.file_line_func = "%s:%d(%s)" % ( + os.path.basename(self.file_path), self.line_number, self.func_name) + else: + self.file_line_func = "" + self.op_type = op_type + self.start_time = self.node_exec_stats.all_start_micros + self.op_time = (self.node_exec_stats.op_end_rel_micros - + self.node_exec_stats.op_start_rel_micros) + + @property + def exec_time(self): + """Op execution time plus pre- and post-processing.""" + return self.node_exec_stats.all_end_rel_micros + + +class AggregateProfile(object): + """Profile summary data for aggregating a number of ProfileDatum.""" + + def __init__(self, profile_datum): + """Constructor. + + Args: + profile_datum: (`ProfileDatum`) an instance of `ProfileDatum` to + initialize this object with. + """ + + self.total_op_time = profile_datum.op_time + self.total_exec_time = profile_datum.exec_time + device_and_node = "%s:%s" % (profile_datum.device_name, + profile_datum.node_exec_stats.node_name) + self._node_to_exec_count = {device_and_node: 1} + + def add(self, profile_datum): + """Accumulate a new instance of ProfileDatum. + + Args: + profile_datum: (`ProfileDatum`) an instance of `ProfileDatum` to + accumulate to this object. + """ + + self.total_op_time += profile_datum.op_time + self.total_exec_time += profile_datum.exec_time + device_and_node = "%s:%s" % (profile_datum.device_name, + profile_datum.node_exec_stats.node_name) + + device_and_node = "%s:%s" % (profile_datum.device_name, + profile_datum.node_exec_stats.node_name) + if device_and_node in self._node_to_exec_count: + self._node_to_exec_count[device_and_node] += 1 + else: + self._node_to_exec_count[device_and_node] = 1 + + @property + def node_count(self): + return len(self._node_to_exec_count) + + @property + def node_exec_count(self): + return sum(self._node_to_exec_count.values()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/session_debug_testlib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/session_debug_testlib.py new file mode 100644 index 0000000000000000000000000000000000000000..20556a415859184c505be2faf3b55f02bc2eb32e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/session_debug_testlib.py @@ -0,0 +1,1566 @@ +# 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. +# ============================================================================== +"""Tests for debugger functionalities in tf.Session.""" +import collections +import functools +import glob +import os +import tempfile +import threading + +import numpy as np + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.client import session +from tensorflow.python.debug.lib import debug_data +from tensorflow.python.debug.lib import debug_graphs +from tensorflow.python.debug.lib import debug_utils +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.ops import rnn +from tensorflow.python.ops import rnn_cell_impl +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.ops import while_loop +import tensorflow.python.ops.tensor_array_grad # pylint: disable=unused-import +from tensorflow.python.platform import googletest +from tensorflow.python.platform import test +from tensorflow.python.training import gradient_descent + + +def no_rewrite_session_config(): + rewriter_config = rewriter_config_pb2.RewriterConfig( + disable_model_pruning=True, + arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF, + dependency_optimization=rewriter_config_pb2.RewriterConfig.OFF) + graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_config) + return config_pb2.ConfigProto(graph_options=graph_options) + + +class _RNNCellForTest(rnn_cell_impl.RNNCell): + """RNN cell for testing.""" + + def __init__(self, input_output_size, state_size): + self._input_output_size = input_output_size + self._state_size = state_size + self._w = variable_v1.VariableV1(1.0, dtype=dtypes.float32, name="w") + + @property + def output_size(self): + return self._input_output_size + + @property + def state_size(self): + return self._state_size + + def __call__(self, input_, state, scope=None): + return (math_ops.multiply(self._w, input_), state) + + +@test_util.run_v1_only("b/120545219") +class SessionDebugTestBase(test_util.TensorFlowTestCase): + """Base class for unit tests of tfdbg running with tf.Session.""" + + @classmethod + def setUpClass(cls): + if test.is_gpu_available(): + cls._expected_partition_graph_count = 2 + cls._expected_num_devices = 2 + gpu_name = test_util.gpu_device_name() + cls._main_device = "/job:localhost/replica:0/task:0" + gpu_name + else: + cls._expected_partition_graph_count = 1 + cls._expected_num_devices = 1 + cls._main_device = "/job:localhost/replica:0/task:0/device:CPU:0" + + @classmethod + def tearDownClass(cls): + pass + + def setUp(self): + self._dump_root = tempfile.mkdtemp() + + def tearDown(self): + ops.reset_default_graph() + + # Tear down temporary dump directory. + if os.path.isdir(self._dump_root): + file_io.delete_recursively(self._dump_root) + + def _debug_urls(self, run_number=None): + raise NotImplementedError( + "_debug_urls() method is not implemented in the base test class.") + + def _debug_dump_dir(self, run_number=None): + raise NotImplementedError( + "_debug_dump_dir() method is not implemented in the base test class.") + + def _debug_run_and_get_dump(self, + sess, + fetches, + feed_dict=None, + debug_ops="DebugIdentity", + tolerate_debug_op_creation_failures=False, + global_step=-1, + validate=True, + expected_partition_graph_count=None): + """Run fetches with debugging and obtain DebugDumpDir. + + Args: + sess: the tf.compat.v1.Session to be used. + fetches: fetches of the Session.run(). + feed_dict: feed dict for the Session.run(). + debug_ops: name(s) of the debug ops to be used. + tolerate_debug_op_creation_failures: whether to tolerate debug op + creation failures. + global_step: Optional global step. + validate: whether to validate dumped tensors against graph. + expected_partition_graph_count: optional count of partition graphs to + assert on. + + Returns: + 1. Return values of the Session.run(). + 2. The DebugDumpDir object from the debugged run(). + """ + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=debug_ops, + debug_urls=self._debug_urls(), + tolerate_debug_op_creation_failures=tolerate_debug_op_creation_failures, + global_step=global_step) + run_metadata = config_pb2.RunMetadata() + run_output = sess.run(fetches, + feed_dict=feed_dict, + options=run_options, + run_metadata=run_metadata) + + if expected_partition_graph_count is not None: + self.assertEqual(expected_partition_graph_count, + len(run_metadata.partition_graphs)) + return run_output, debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs, + validate=validate) + + def _generate_dump_from_simple_addition_graph(self): + with session.Session(config=no_rewrite_session_config()) as sess: + u_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]]) + v_init_val = np.array([[2.0], [-1.0]]) + + # Use node names with overlapping namespace (i.e., parent directory) to + # test concurrent, non-racing directory creation. + u_name = "u" + v_name = "v" + w_name = "w" + + u_init = constant_op.constant(u_init_val, shape=[2, 2]) + u = variable_v1.VariableV1(u_init, name=u_name) + v_init = constant_op.constant(v_init_val, shape=[2, 1]) + v = variable_v1.VariableV1(v_init, name=v_name) + + w = math_ops.matmul(u, v, name=w_name) + + u.initializer.run() + v.initializer.run() + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_urls = "file://%s" % self._dump_root + + # Add debug tensor watch for u. + debug_utils.add_debug_tensor_watch( + run_options, "%s/read" % u_name, 0, debug_urls=debug_urls) + # Add debug tensor watch for v. + debug_utils.add_debug_tensor_watch( + run_options, "%s/read" % v_name, 0, debug_urls=debug_urls) + + run_metadata = config_pb2.RunMetadata() + + # Invoke Session.run(). + sess.run(w, options=run_options, run_metadata=run_metadata) + + self.assertEqual(self._expected_partition_graph_count, + len(run_metadata.partition_graphs)) + + dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + simple_add_results = collections.namedtuple("SimpleAddResults", [ + "u_init_val", "v_init_val", "u", "v", "w", "u_name", "v_name", "w_name", + "dump" + ]) + return simple_add_results(u_init_val, v_init_val, u, v, w, u_name, v_name, + w_name, dump) + + def testCopyNodesHaveCorrectDebugOpsAndURLsAttributeValues(self): + with session.Session() as sess: + u = variable_v1.VariableV1(2.1, name="u") + v = variable_v1.VariableV1(20.0, name="v") + w = math_ops.multiply(u, v, name="w") + + sess.run(variables.global_variables_initializer()) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_urls = self._debug_urls() + debug_utils.add_debug_tensor_watch( + run_options, + "u", + 0, ["DebugNumericSummary(gated_grpc=True)", "DebugIdentity"], + debug_urls=debug_urls) + debug_utils.add_debug_tensor_watch( + run_options, "v", 0, ["DebugNumericSummary"], debug_urls=debug_urls) + + run_metadata = config_pb2.RunMetadata() + r = sess.run(w, options=run_options, run_metadata=run_metadata) + self.assertAllClose(42.0, r) + + u_copy_node_def = None + v_copy_node_def = None + for partition_graph in run_metadata.partition_graphs: + for node_def in partition_graph.node: + if debug_graphs.is_copy_node(node_def.name): + if node_def.name == "__copy_u_0": + u_copy_node_def = node_def + elif node_def.name == "__copy_v_0": + v_copy_node_def = node_def + + self.assertIsNotNone(u_copy_node_def) + debug_ops_spec = u_copy_node_def.attr["debug_ops_spec"].list.s + self.assertEqual(2, len(debug_ops_spec)) + self.assertEqual("DebugNumericSummary;%s;1" % debug_urls[0], + debug_ops_spec[0].decode("utf-8")) + self.assertEqual("DebugIdentity;%s;0" % debug_urls[0], + debug_ops_spec[1].decode("utf-8")) + + self.assertIsNotNone(v_copy_node_def) + debug_ops_spec = v_copy_node_def.attr["debug_ops_spec"].list.s + self.assertEqual(1, len(debug_ops_spec)) + self.assertEqual("DebugNumericSummary;%s;0" % debug_urls[0], + debug_ops_spec[0].decode("utf-8")) + + def testConcurrentDumpingToPathsWithOverlappingParentDirsWorks(self): + results = self._generate_dump_from_simple_addition_graph() + self.assertTrue(results.dump.loaded_partition_graphs()) + + # Since global_step is not explicitly specified, it should take its default + # value: -1. + self.assertEqual(-1, results.dump.core_metadata.global_step) + self.assertGreaterEqual(results.dump.core_metadata.session_run_index, 0) + self.assertGreaterEqual(results.dump.core_metadata.executor_step_index, 0) + self.assertEqual([], results.dump.core_metadata.input_names) + self.assertEqual([results.w.name], results.dump.core_metadata.output_names) + self.assertEqual([], results.dump.core_metadata.target_nodes) + + # Verify the dumped tensor values for u and v. + self.assertEqual(2, results.dump.size) + + self.assertAllClose([results.u_init_val], + results.dump.get_tensors("%s/read" % results.u_name, 0, + "DebugIdentity")) + self.assertAllClose([results.v_init_val], + results.dump.get_tensors("%s/read" % results.v_name, 0, + "DebugIdentity")) + + self.assertGreaterEqual( + results.dump.get_rel_timestamps("%s/read" % results.u_name, 0, + "DebugIdentity")[0], 0) + self.assertGreaterEqual( + results.dump.get_rel_timestamps("%s/read" % results.v_name, 0, + "DebugIdentity")[0], 0) + + self.assertGreater( + results.dump.get_dump_sizes_bytes("%s/read" % results.u_name, 0, + "DebugIdentity")[0], 0) + self.assertGreater( + results.dump.get_dump_sizes_bytes("%s/read" % results.v_name, 0, + "DebugIdentity")[0], 0) + + def testGetOpTypeWorks(self): + results = self._generate_dump_from_simple_addition_graph() + + self.assertEqual(results.u.op.type, + results.dump.node_op_type(results.u_name)) + self.assertIn(results.v.op.type, results.dump.node_op_type(results.v_name)) + self.assertIn(results.w.op.type, results.dump.node_op_type(results.w_name)) + + with self.assertRaisesRegexp( + ValueError, r"None of the .* device\(s\) has a node named "): + results.dump.node_op_type("foo_bar") + + def testDumpStringTensorsWorks(self): + with session.Session(config=no_rewrite_session_config()) as sess: + str1_init_val = np.array(b"abc") + str2_init_val = np.array(b"def") + + str1_init = constant_op.constant(str1_init_val) + str2_init = constant_op.constant(str2_init_val) + + str1_name = "str1" + str2_name = "str2" + str1 = variable_v1.VariableV1(str1_init, name=str1_name) + str2 = variable_v1.VariableV1(str2_init, name=str2_name) + # Concatenate str1 and str2 + str_concat = math_ops.add(str1, str2, name="str_concat") + + str1.initializer.run() + str2.initializer.run() + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_urls = self._debug_urls() + + # Add debug tensor watch for u. + debug_utils.add_debug_tensor_watch( + run_options, "%s/read" % str1_name, 0, debug_urls=debug_urls) + # Add debug tensor watch for v. + debug_utils.add_debug_tensor_watch( + run_options, "%s/read" % str2_name, 0, debug_urls=debug_urls) + + run_metadata = config_pb2.RunMetadata() + sess.run(str_concat, options=run_options, run_metadata=run_metadata) + + # String ops are located on CPU. + self.assertEqual(1, len(run_metadata.partition_graphs)) + + dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + self.assertIn(str1_name, dump.nodes()) + self.assertIn(str2_name, dump.nodes()) + + self.assertEqual(2, dump.size) + + self.assertEqual([str1_init_val], + dump.get_tensors("%s/read" % str1_name, 0, + "DebugIdentity")) + self.assertEqual([str2_init_val], + dump.get_tensors("%s/read" % str2_name, 0, + "DebugIdentity")) + + self.assertGreaterEqual( + dump.get_rel_timestamps("%s/read" % str1_name, 0, "DebugIdentity")[0], + 0) + self.assertGreaterEqual( + dump.get_rel_timestamps("%s/read" % str2_name, 0, "DebugIdentity")[0], + 0) + + self.assertGreater( + dump.get_dump_sizes_bytes("%s/read" % str1_name, 0, + "DebugIdentity")[0], 0) + self.assertGreater( + dump.get_dump_sizes_bytes("%s/read" % str2_name, 0, + "DebugIdentity")[0], 0) + + def testDumpUninitializedVariable(self): + op_namespace = "testDumpUninitializedVariable" + with session.Session() as sess: + u_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]]) + s_init_val = b"str1" + + u_name = "%s/u" % op_namespace + s_name = "%s/s" % op_namespace + + u_init = constant_op.constant(u_init_val, shape=[2, 2]) + u = variable_v1.VariableV1(u_init, name=u_name) + s_init = constant_op.constant(s_init_val) + s = variable_v1.VariableV1(s_init, name=s_name) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_urls = self._debug_urls() + + # Add debug tensor watch for u. + debug_utils.add_debug_tensor_watch( + run_options, u_name, 0, debug_urls=debug_urls) + debug_utils.add_debug_tensor_watch( + run_options, s_name, 0, debug_urls=debug_urls) + + run_metadata = config_pb2.RunMetadata() + + # Initialize u and s. + sess.run(variables.global_variables_initializer(), + options=run_options, + run_metadata=run_metadata) + + # Verify the dump file for the uninitialized value of u. + dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + self.assertEqual(2, dump.size) + self.assertEqual(self._expected_partition_graph_count, + len(run_metadata.partition_graphs)) + + # Verify that the variable is properly initialized by the run() call. + u_vals = dump.get_tensors(u_name, 0, "DebugIdentity") + s_vals = dump.get_tensors(s_name, 0, "DebugIdentity") + self.assertEqual(1, len(u_vals)) + self.assertIsInstance(u_vals[0], debug_data.InconvertibleTensorProto) + self.assertFalse(u_vals[0].initialized) + self.assertEqual(1, len(s_vals)) + self.assertIsInstance(s_vals[0], debug_data.InconvertibleTensorProto) + self.assertFalse(s_vals[0].initialized) + + # Call run() again, to check that u is initialized properly. + self.assertAllClose(u_init_val, sess.run(u)) + self.assertEqual(s_init_val, sess.run(s)) + + def testDebugWhileLoopGeneratesMultipleDumps(self): + with session.Session(config=no_rewrite_session_config()) as sess: + num_iter = 10 + + # "u" is the Variable being updated in the loop. + u_name = "testDumpToFileWhileLoop/u" + u_namespace = u_name.split("/")[0] + + u_init_val = np.array(11.0) + u_init = constant_op.constant(u_init_val) + u = variable_v1.VariableV1(u_init, name=u_name) + + # "v" is the increment. + v_name = "testDumpToFileWhileLoop/v" + v_namespace = v_name.split("/")[0] + + v_init_val = np.array(2.0) + v_init = constant_op.constant(v_init_val) + v = variable_v1.VariableV1(v_init, name=v_name) + + u.initializer.run() + v.initializer.run() + + i = constant_op.constant(0, name="testDumpToFileWhileLoop/i") + + def cond(i): + return math_ops.less(i, num_iter) + + def body(i): + new_u = state_ops.assign_add(u, v) + new_i = math_ops.add(i, 1) + op = control_flow_ops.group(new_u) + new_i = control_flow_ops.with_dependencies([op], new_i) + return [new_i] + + loop = while_loop.while_loop(cond, body, [i], parallel_iterations=10) + + # Create RunOptions for debug-watching tensors + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_urls = self._debug_urls() + + # Add debug tensor watch for u. + debug_utils.add_debug_tensor_watch( + run_options, u_name, 0, debug_urls=debug_urls) + # Add debug tensor watch for v. + debug_utils.add_debug_tensor_watch( + run_options, "%s/read" % v_name, 0, debug_urls=debug_urls) + # Add debug tensor watch for while/Identity. + debug_utils.add_debug_tensor_watch( + run_options, "while/Identity", 0, debug_urls=debug_urls) + # Add debug tensor watch for while/Add/y. + debug_utils.add_debug_tensor_watch( + run_options, "while/Add/y", 0, debug_urls=debug_urls) + + run_metadata = config_pb2.RunMetadata() + r = sess.run(loop, options=run_options, run_metadata=run_metadata) + + self.assertEqual(self._expected_partition_graph_count, + len(run_metadata.partition_graphs)) + + self.assertEqual(num_iter, r) + u_val_final = sess.run(u) + self.assertAllClose(u_init_val + num_iter * v_init_val, u_val_final) + + # Verify dump files + self.assertTrue(os.path.isdir(self._dump_root)) + + u_glob_out = glob.glob(os.path.join(self._dump_root, "*", u_namespace)) + v_glob_out = glob.glob(os.path.join( + self._dump_root, "*", v_namespace, "v")) + self.assertTrue(os.path.isdir(u_glob_out[0])) + self.assertTrue(os.path.isdir(v_glob_out[0])) + + dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + # Expected dumped tensors: u, v/read, 10 iterations of while/Identity, + # and 10 iterations of while/Add/y. + self.assertEqual(1 + 1 + num_iter + num_iter, dump.size) + + # Verify tensor values. + self.assertAllClose([u_init_val], + dump.get_tensors(u_name, 0, "DebugIdentity")) + self.assertAllClose([v_init_val], + dump.get_tensors("%s/read" % v_name, 0, + "DebugIdentity")) + + while_id_tensors = dump.get_tensors("while/Identity", 0, "DebugIdentity") + self.assertEqual(10, len(while_id_tensors)) + for k in range(len(while_id_tensors)): + self.assertAllClose(np.array(k), while_id_tensors[k]) + + # Verify ascending timestamps from the while loops. + while_id_rel_timestamps = dump.get_rel_timestamps("while/Identity", 0, + "DebugIdentity") + while_id_dump_sizes_bytes = dump.get_dump_sizes_bytes("while/Identity", 0, + "DebugIdentity") + self.assertEqual(10, len(while_id_rel_timestamps)) + prev_rel_time = 0 + prev_dump_size_bytes = while_id_dump_sizes_bytes[0] + for rel_time, dump_size_bytes in zip(while_id_rel_timestamps, + while_id_dump_sizes_bytes): + self.assertGreaterEqual(rel_time, prev_rel_time) + self.assertEqual(dump_size_bytes, prev_dump_size_bytes) + prev_rel_time = rel_time + prev_dump_size_bytes = dump_size_bytes + + # Test querying debug watch keys from node name. + watch_keys = dump.debug_watch_keys("while/Identity") + self.assertEqual(["while/Identity:0:DebugIdentity"], watch_keys) + + # Test querying debug datum instances from debug watch key. + self.assertEqual(10, len(dump.watch_key_to_data(watch_keys[0]))) + self.assertEqual([], dump.watch_key_to_data("foo")) + + def testDebugWhileLoopWatchingWholeGraphWorks(self): + with session.Session() as sess: + loop_body = lambda i: math_ops.add(i, 2) + loop_cond = lambda i: math_ops.less(i, 16) + + i = constant_op.constant(10, name="i") + loop = while_loop.while_loop(loop_cond, loop_body, [i]) + + loop_result, dump = self._debug_run_and_get_dump(sess, loop) + self.assertEqual(16, loop_result) + + self.assertEqual( + [[10]], dump.get_tensors("while/Enter", 0, "DebugIdentity")) + self.assertEqual( + [[12], [14], [16]], + dump.get_tensors("while/NextIteration", 0, "DebugIdentity")) + + def testDebugTrainingDynamicRNNWorks(self): + with session.Session() as sess: + input_size = 3 + state_size = 2 + time_steps = 4 + batch_size = 2 + + input_values = np.random.randn(time_steps, batch_size, input_size) + sequence_length = np.random.randint(0, time_steps, size=batch_size) + concat_inputs = array_ops.placeholder( + dtypes.float32, shape=(time_steps, batch_size, input_size)) + + outputs_dynamic, _ = rnn.dynamic_rnn( + _RNNCellForTest(input_size, state_size), + inputs=concat_inputs, + sequence_length=sequence_length, + time_major=True, + dtype=dtypes.float32) + toy_loss = math_ops.reduce_sum(outputs_dynamic * outputs_dynamic) + train_op = gradient_descent.GradientDescentOptimizer( + learning_rate=0.1).minimize(toy_loss, name="train_op") + + sess.run(variables.global_variables_initializer()) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph_with_denylists( + run_options, + sess.graph, + node_name_regex_denylist="(.*rnn/while/.*|.*TensorArray.*)", + debug_urls=self._debug_urls()) + # b/36870549: Nodes with these name patterns need to be excluded from + # tfdbg in order to prevent MSAN warnings of uninitialized Tensors + # under both file:// and grpc:// debug URL schemes. + + run_metadata = config_pb2.RunMetadata() + sess.run(train_op, feed_dict={concat_inputs: input_values}, + options=run_options, run_metadata=run_metadata) + + debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + def testDebugCondWatchingWholeGraphWorks(self): + with session.Session() as sess: + x = variable_v1.VariableV1(10.0, name="x") + y = variable_v1.VariableV1(20.0, name="y") + cond = tf_cond.cond( + x > y, lambda: math_ops.add(x, 1), lambda: math_ops.add(y, 1)) + + sess.run(variables.global_variables_initializer()) + + cond_result, dump = self._debug_run_and_get_dump(sess, cond) + self.assertEqual(21, cond_result) + + self.assertAllClose( + [21.0], dump.get_tensors("cond/Merge", 0, "DebugIdentity")) + + def testFindNodesWithBadTensorValues(self): + with session.Session() as sess: + u_name = "testFindNodesWithBadTensorValues/u" + v_name = "testFindNodesWithBadTensorValues/v" + w_name = "testFindNodesWithBadTensorValues/w" + x_name = "testFindNodesWithBadTensorValues/x" + y_name = "testFindNodesWithBadTensorValues/y" + z_name = "testFindNodesWithBadTensorValues/z" + + u_init = constant_op.constant([2.0, 4.0]) + u = variable_v1.VariableV1(u_init, name=u_name) + v_init = constant_op.constant([2.0, 1.0]) + v = variable_v1.VariableV1(v_init, name=v_name) + + # Expected output: [0.0, 3.0] + w = math_ops.subtract(u, v, name=w_name) + + # Expected output: [inf, 1.3333] + x = math_ops.div(u, w, name=x_name) + + # Expected output: [nan, 4.0] + y = math_ops.multiply(w, x, name=y_name) + + z = math_ops.multiply(y, y, name=z_name) + + u.initializer.run() + v.initializer.run() + + _, dump = self._debug_run_and_get_dump( + sess, z, + expected_partition_graph_count=self._expected_partition_graph_count) + + def has_bad_value(_, tensor): + return np.any(np.isnan(tensor)) or np.any(np.isinf(tensor)) + + # Find all "offending tensors". + bad_data = dump.find(has_bad_value) + + # Verify that the nodes with bad values are caught through running find + # on the debug dump. + self.assertLessEqual(3, len(bad_data)) + node_names = [datum.node_name for datum in bad_data] + self.assertIn(x_name, node_names) + self.assertIn(y_name, node_names) + self.assertIn(z_name, node_names) + + # Test first_n kwarg of find(): Find the first offending tensor. + first_bad_datum = dump.find(has_bad_value, first_n=1) + self.assertEqual(1, len(first_bad_datum)) + + def testFindInfOrNanWithOpNameExclusion(self): + with session.Session() as sess: + u_name = "testFindInfOrNanWithOpNameExclusion/u" + v_name = "testFindInfOrNanWithOpNameExclusion/v" + w_name = "testFindInfOrNanWithOpNameExclusion/w" + x_name = "testFindInfOrNanWithOpNameExclusion/x" + y_name = "testFindInfOrNanWithOpNameExclusion/y" + z_name = "testFindInfOrNanWithOpNameExclusion/z" + + u_init = constant_op.constant([2.0, 4.0]) + u = variable_v1.VariableV1(u_init, name=u_name) + v_init = constant_op.constant([2.0, 1.0]) + v = variable_v1.VariableV1(v_init, name=v_name) + + # Expected output: [0.0, 3.0] + w = math_ops.subtract(u, v, name=w_name) + + # Expected output: [inf, 1.3333] + x = math_ops.div(u, w, name=x_name) + + # Expected output: [nan, 4.0] + y = math_ops.multiply(w, x, name=y_name) + + z = math_ops.multiply(y, y, name=z_name) + + u.initializer.run() + v.initializer.run() + + _, dump = self._debug_run_and_get_dump( + sess, z, + expected_partition_graph_count=self._expected_partition_graph_count) + + # Find all "offending tensors". + bad_data = dump.find(debug_data.has_inf_or_nan, + exclude_node_names=".*/x$") + + # Verify that the nodes with bad values are caught through running find + # on the debug dump. + self.assertLessEqual(2, len(bad_data)) + # Assert that the node `x` should have been excluded. + node_names = [datum.node_name for datum in bad_data] + self.assertIn(y_name, node_names) + self.assertIn(z_name, node_names) + + first_bad_datum = dump.find( + debug_data.has_inf_or_nan, first_n=1, exclude_node_names=".*/x$") + self.assertEqual(1, len(first_bad_datum)) + + def _session_run_for_graph_structure_lookup(self): + with session.Session(config=no_rewrite_session_config()) as sess: + u_name = "testDumpGraphStructureLookup/u" + v_name = "testDumpGraphStructureLookup/v" + w_name = "testDumpGraphStructureLookup/w" + + u_init = constant_op.constant([2.0, 4.0]) + u = variable_v1.VariableV1(u_init, name=u_name) + v = math_ops.add(u, u, name=v_name) + w = math_ops.add(v, v, name=w_name) + + u.initializer.run() + + _, dump = self._debug_run_and_get_dump( + sess, w, + expected_partition_graph_count=self._expected_partition_graph_count) + + return u_name, v_name, w_name, dump + + def testGraphStructureLookupGivesDevicesAndNodesInfo(self): + u_name, _, _, dump = self._session_run_for_graph_structure_lookup() + + # Test num_devices(). + self.assertEqual(self._expected_num_devices, len(dump.devices())) + + # Test node_device(). + self.assertEqual(self._main_device, dump.node_device(u_name)) + + with self.assertRaisesRegexp(ValueError, + "does not exist in partition graphs"): + dump.node_device(u_name + "foo") + + # Test node_exists(). + self.assertTrue(dump.node_exists(u_name)) + self.assertTrue(dump.node_exists(u_name + "/read")) + self.assertFalse(dump.node_exists(u_name + "/read" + "/foo")) + + def testGraphStructureLookupGivesNodesAndAttributes(self): + u_name, _, _, dump = self._session_run_for_graph_structure_lookup() + + u_read_name = u_name + "/read" + + # Test node name list lookup of the DebugDumpDir object. + if test_util.gpu_device_name(): + node_names = dump.nodes( + device_name="/job:localhost/replica:0/task:0/device:GPU:0") + else: + node_names = dump.nodes() + self.assertTrue(u_name in node_names) + self.assertTrue(u_read_name in node_names) + + # Test querying node attributes. + u_attr = dump.node_attributes(u_name) + self.assertEqual(dtypes.float32, u_attr["dtype"].type) + self.assertEqual(1, len(u_attr["shape"].shape.dim)) + self.assertEqual(2, u_attr["shape"].shape.dim[0].size) + + with self.assertRaisesRegexp( + ValueError, r"None of the .* device\(s\) has a node named "): + dump.node_attributes("foo") + + def testGraphStructureLookupGivesDebugWatchKeys(self): + u_name, v_name, w_name, dump = ( + self._session_run_for_graph_structure_lookup()) + + # Test querying the debug watch keys with node names. + self.assertEqual(["%s:0:DebugIdentity" % u_name], + dump.debug_watch_keys(u_name)) + self.assertEqual(["%s:0:DebugIdentity" % v_name], + dump.debug_watch_keys(v_name)) + self.assertEqual(["%s:0:DebugIdentity" % w_name], + dump.debug_watch_keys(w_name)) + self.assertEqual([], dump.debug_watch_keys("foo")) + + # Test querying debug datum instances from debug watch. + u_data = dump.watch_key_to_data(dump.debug_watch_keys(u_name)[0]) + self.assertEqual(1, len(u_data)) + self.assertEqual(u_name, u_data[0].node_name) + self.assertEqual(0, u_data[0].output_slot) + self.assertEqual("DebugIdentity", u_data[0].debug_op) + self.assertGreaterEqual(u_data[0].timestamp, 0) + self.assertEqual([], dump.watch_key_to_data("foo")) + + def testGraphStructureLookupGivesNodeInputsAndRecipients(self): + u_name, v_name, w_name, dump = ( + self._session_run_for_graph_structure_lookup()) + + u_read_name = u_name + "/read" + + # Test the inputs lookup of the DebugDumpDir object. + self.assertEqual([], dump.node_inputs(u_name)) + self.assertEqual([u_name], dump.node_inputs(u_read_name)) + self.assertEqual([u_read_name] * 2, dump.node_inputs(v_name)) + self.assertEqual([v_name] * 2, dump.node_inputs(w_name)) + + self.assertEqual([], dump.node_inputs(u_name, is_control=True)) + self.assertEqual([], dump.node_inputs(u_read_name, is_control=True)) + self.assertEqual([], dump.node_inputs(v_name, is_control=True)) + self.assertEqual([], dump.node_inputs(w_name, is_control=True)) + + # Test the outputs recipient lookup of the DebugDumpDir object. + self.assertTrue(u_read_name in dump.node_recipients(u_name)) + self.assertEqual(2, dump.node_recipients(u_read_name).count(v_name)) + self.assertEqual(2, dump.node_recipients(v_name).count(w_name)) + + self.assertEqual([], dump.node_recipients(u_name, is_control=True)) + self.assertEqual([], dump.node_recipients(u_read_name, is_control=True)) + self.assertEqual([], dump.node_recipients(v_name, is_control=True)) + self.assertEqual([], dump.node_recipients(w_name, is_control=True)) + + # Test errors raised on invalid node names. + with self.assertRaisesRegexp( + ValueError, r"None of the .* device\(s\) has a node named "): + dump.node_inputs(u_name + "foo") + with self.assertRaisesRegexp( + ValueError, r"None of the .* device\(s\) has a node named "): + dump.node_recipients(u_name + "foo") + + # Test transitive_inputs(). + self.assertEqual([], dump.transitive_inputs(u_name)) + self.assertEqual([u_name], dump.transitive_inputs(u_read_name)) + self.assertEqual( + set([u_name, u_read_name]), set(dump.transitive_inputs(v_name))) + self.assertEqual( + set([u_name, u_read_name, v_name]), set(dump.transitive_inputs(w_name))) + + with self.assertRaisesRegexp( + ValueError, r"None of the .* device\(s\) has a node named "): + dump.transitive_inputs(u_name + "foo") + + def testGraphStructureLookupWithoutPartitionGraphsDoesNotErrorOut(self): + _, _, _, dump = self._session_run_for_graph_structure_lookup() + + # Now load the dump again, without the partition graphs, so we can check + # errors are not raised because the partition graphs are loaded from the + # dump directory. + dump = debug_data.DebugDumpDir(self._dump_root, validate=False) + self.assertTrue(dump.loaded_partition_graphs()) + + def testGraphPathFindingOnControlEdgesWorks(self): + with session.Session(config=no_rewrite_session_config()) as sess: + v1 = variable_v1.VariableV1(1.0, name="v1") + v2 = variable_v1.VariableV1(2.0, name="v2") + v3 = variable_v1.VariableV1(3.0, name="v3") + a = math_ops.add(v1, v2, name="a") + with ops.control_dependencies([a]): + c = math_ops.subtract(v3, v3, name="c") + + sess.run(variables.global_variables_initializer()) + _, dump = self._debug_run_and_get_dump(sess, c) + + self.assertEqual(["v1", "v1/read", "a", "c"], + dump.find_some_path("v1", "c")) + self.assertIsNone(dump.find_some_path("v1", "c", include_control=False)) + + def testGraphPathFindingReverseRefEdgeWorks(self): + with session.Session(config=no_rewrite_session_config()) as sess: + v = variable_v1.VariableV1(10.0, name="v") + delta = variable_v1.VariableV1(1.0, name="delta") + inc_v = state_ops.assign_add(v, delta, name="inc_v") + + sess.run(variables.global_variables_initializer()) + _, dump = self._debug_run_and_get_dump(sess, inc_v) + + self.assertEqual( + ["delta", "delta/read", "inc_v", "v"], + dump.find_some_path("delta", "v", include_reversed_ref=True)) + self.assertIsNone(dump.find_some_path("delta", "v")) + + def testCausalityCheckOnDumpsDetectsWrongTemporalOrder(self): + with session.Session(config=no_rewrite_session_config()) as sess: + u_name = "testDumpCausalityCheck/u" + v_name = "testDumpCausalityCheck/v" + w_name = "testDumpCausalityCheck/w" + + u_init = constant_op.constant([2.0, 4.0]) + u = variable_v1.VariableV1(u_init, name=u_name) + v = math_ops.add(u, u, name=v_name) + w = math_ops.add(v, v, name=w_name) + + u.initializer.run() + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=["DebugIdentity"], + debug_urls=self._debug_urls()) + + run_metadata = config_pb2.RunMetadata() + sess.run(w, options=run_options, run_metadata=run_metadata) + + self.assertEqual(self._expected_partition_graph_count, + len(run_metadata.partition_graphs)) + + # First, loading the original dump without supplying the + # partition_graphs should not cause a LookupError, validation occurs + # only with partition_graphs loaded. + debug_data.DebugDumpDir(self._dump_root) + + # Now, loading the original dump with partition graphs supplied should + # succeed. The validation should pass quietly. + dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + # Get the dump file names and compute their timestamps. + self.assertEqual( + 1, len(dump.get_tensor_file_paths(v_name, 0, "DebugIdentity"))) + v_file_path = dump.get_tensor_file_paths(v_name, 0, "DebugIdentity")[0] + + self.assertEqual( + 1, len(dump.get_tensor_file_paths(w_name, 0, "DebugIdentity"))) + w_file_path = dump.get_tensor_file_paths(w_name, 0, "DebugIdentity")[0] + + v_timestamp = int(v_file_path[v_file_path.rindex("_") + 1:]) + w_timestamp = int(w_file_path[w_file_path.rindex("_") + 1:]) + + # Swap and slightly shift the time stamps of the last two dumped tensors, + # to simulate "causality violation", which can happen if the dump + # directory contains incomplete data and/or mixes data from different + # Session.run() calls. + v_file_path_1 = v_file_path[:v_file_path.rindex( + "_")] + "_%d" % w_timestamp + w_file_path_1 = w_file_path[:w_file_path.rindex("_")] + "_%d" % ( + v_timestamp - 1) + + os.rename(v_file_path, v_file_path_1) + os.rename(w_file_path, w_file_path_1) + + # Load the dump directory again. Now a ValueError is expected to be + # raised due to the timestamp swap. + with self.assertRaisesRegexp(ValueError, "Causality violated"): + dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + # Loading the dump directory with kwarg "validate" set explicitly to + # False should get rid of the error. + dump = debug_data.DebugDumpDir( + self._dump_root, + partition_graphs=run_metadata.partition_graphs, + validate=False) + + # Next, set the two times stamps to be the same, which should be fine. + v_file_path_2 = v_file_path[:v_file_path.rindex( + "_")] + "_%d" % w_timestamp + w_file_path_2 = w_file_path[:w_file_path.rindex( + "_")] + "_%d" % w_timestamp + + os.rename(v_file_path_1, v_file_path_2) + os.rename(w_file_path_1, w_file_path_2) + + debug_data.DebugDumpDir( + self._dump_root, partition_graphs=run_metadata.partition_graphs) + + def testWatchingOnlyOneOfTwoOutputSlotsDoesNotLeadToCausalityFailure(self): + with session.Session() as sess: + x_name = "oneOfTwoSlots/x" + u_name = "oneOfTwoSlots/u" + v_name = "oneOfTwoSlots/v" + w_name = "oneOfTwoSlots/w" + y_name = "oneOfTwoSlots/y" + + x = variable_v1.VariableV1([1, 3, 3, 7], dtype=dtypes.int32, name=x_name) + sess.run(x.initializer) + + unique_x, indices, _ = array_ops.unique_with_counts(x, name=u_name) + + v = math_ops.add(unique_x, unique_x, name=v_name) + w = math_ops.add(indices, indices, name=w_name) + y = math_ops.add(w, w, name=y_name) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + # Watch only the first output slot of u, even though it has two output + # slots. + debug_utils.add_debug_tensor_watch( + run_options, u_name, 0, debug_urls=self._debug_urls()) + debug_utils.add_debug_tensor_watch( + run_options, w_name, 0, debug_urls=self._debug_urls()) + debug_utils.add_debug_tensor_watch( + run_options, y_name, 0, debug_urls=self._debug_urls()) + + run_metadata = config_pb2.RunMetadata() + sess.run([v, y], options=run_options, run_metadata=run_metadata) + + dump = debug_data.DebugDumpDir( + self._dump_root, + partition_graphs=run_metadata.partition_graphs, + validate=True) + + self.assertAllClose([1, 3, 7], + dump.get_tensors(u_name, 0, "DebugIdentity")[0]) + + def testOutputSlotWithoutOutgoingEdgeCanBeWatched(self): + """Test watching output slots not attached to any outgoing edges.""" + + with session.Session(config=no_rewrite_session_config()) as sess: + u_init_val = np.array([[5.0, 3.0], [-1.0, 0.0]]) + u = constant_op.constant(u_init_val, shape=[2, 2], name="u") + + # Create a control edge from a node with an output: From u to z. + # Node u will get executed only because of the control edge. The output + # tensor u:0 is not attached to any outgoing edge in the graph. This test + # checks that the debugger can watch such a tensor. + with ops.control_dependencies([u]): + z = control_flow_ops.no_op(name="z") + + _, dump = self._debug_run_and_get_dump(sess, z) + + # Assert that the DebugIdentity watch on u works properly. + self.assertEqual(1, len(dump.dumped_tensor_data)) + datum = dump.dumped_tensor_data[0] + self.assertEqual("u", datum.node_name) + self.assertEqual(0, datum.output_slot) + self.assertEqual("DebugIdentity", datum.debug_op) + self.assertAllClose([[5.0, 3.0], [-1.0, 0.0]], datum.get_tensor()) + + def testWatchingVariableUpdateOpsSeesUpdatedValues(self): + """Watch output slots on Variable-updating ops, with no emitted edges.""" + + with session.Session(config=no_rewrite_session_config()) as sess: + u_init = constant_op.constant(10.0) + u = variable_v1.VariableV1(u_init, name="gdo/u") + v_init = constant_op.constant(20.0) + v = variable_v1.VariableV1(v_init, name="gdo/v") + + w = math_ops.multiply(u, v, name="gdo/w") + # gdo stands for GradientDescentOptimizer. + + train_op = gradient_descent.GradientDescentOptimizer( + learning_rate=0.1).minimize( + w, name="gdo/train") + + u.initializer.run() + v.initializer.run() + + _, dump = self._debug_run_and_get_dump(sess, train_op) + + update_u_data = dump.watch_key_to_data( + "gdo/train/update_gdo/u/ApplyGradientDescent:0:DebugIdentity") + self.assertEqual(1, len(update_u_data)) + + # Gradient descent on u: w = u * v, so dw / du = v. + # Updated value of u should be: + # 10.0 - learning_rate * v = 10.0 - 0.1 * 20.0 = 8.0 + self.assertAllClose(8.0, update_u_data[0].get_tensor()) + + update_v_data = dump.watch_key_to_data( + "gdo/train/update_gdo/v/ApplyGradientDescent:0:DebugIdentity") + self.assertEqual(1, len(update_v_data)) + + # Gradient descent on u: w = u * v, so dw / dv = u. + # Updated value of u should be: + # 20.0 - learning_rate * u = 20.0 - 0.1 * 10.0 = 19.0 + self.assertAllClose(19.0, update_v_data[0].get_tensor()) + + # Verify that the Variables u and v are updated properly. + self.assertAllClose(8.0, sess.run(u)) + self.assertAllClose(19.0, sess.run(v)) + + def testAllowsWatchingUnconnectedOutputTensor(self): + """Watch an output slot not emitting any edges. + + (Not even control edges from the node.) + """ + + with session.Session() as sess: + x_init = constant_op.constant([2, 2, 3, 5, 5]) + x = variable_v1.VariableV1(x_init, name="unconnected/x") + + # The UniqueOp (tf.unique) has two output slots. Use only slot 0 in the + # graph. Let the debugger watch the unused slot 1. + unique_x, _ = array_ops.unique(x, name="unconnected/unique_x") + y = math_ops.add(unique_x, [0, 1, 2], name="unconnected/y") + + x.initializer.run() + + # Verify that only slot 0 of unique_x has recipients, while slot 1 of the + # same node does not have recipients. + unique_x_slot_0_recipients = [] + unique_x_slot_1_recipients = [] + for op in sess.graph.get_operations(): + for inp in op.inputs: + if inp.name == "unconnected/unique_x:0": + unique_x_slot_0_recipients.append(op.name) + elif inp.name == "unconnected/unique_x:1": + unique_x_slot_1_recipients.append(op.name) + + self.assertEqual(["unconnected/y"], unique_x_slot_0_recipients) + self.assertEqual([], unique_x_slot_1_recipients) + + y_result, dump = self._debug_run_and_get_dump(sess, y) + self.assertAllClose([2, 4, 7], y_result) + + # Assert that the connected slot (slot 0) is dumped properly. + unique_x_slot_0_dumps = dump.watch_key_to_data( + "unconnected/unique_x:0:DebugIdentity") + self.assertEqual(1, len(unique_x_slot_0_dumps)) + self.assertEqual("unconnected/unique_x", + unique_x_slot_0_dumps[0].node_name) + self.assertEqual(0, unique_x_slot_0_dumps[0].output_slot) + self.assertAllClose([2, 3, 5], unique_x_slot_0_dumps[0].get_tensor()) + + # Assert that the unconnected slot (slot 1) is dumped properly. + unique_x_slot_1_dumps = dump.watch_key_to_data( + "unconnected/unique_x:1:DebugIdentity") + self.assertEqual(1, len(unique_x_slot_1_dumps)) + self.assertEqual("unconnected/unique_x", + unique_x_slot_1_dumps[0].node_name) + self.assertEqual(1, unique_x_slot_1_dumps[0].output_slot) + self.assertAllClose([0, 0, 1, 2, 2], + unique_x_slot_1_dumps[0].get_tensor()) + + def testSuccessiveDebuggingRunsIncreasesCounters(self): + """Test repeated Session.run() calls with debugger increments counters.""" + + with session.Session() as sess: + ph = array_ops.placeholder(dtypes.float32, name="successive/ph") + x = array_ops.transpose(ph, name="mismatch/x") + y = array_ops.squeeze(ph, name="mismatch/y") + + _, dump1 = self._debug_run_and_get_dump( + sess, x, feed_dict={ph: np.array([[7.0, 8.0]])}, global_step=1) + self.assertEqual(1, dump1.core_metadata.global_step) + self.assertGreaterEqual(dump1.core_metadata.session_run_index, 0) + self.assertEqual(0, dump1.core_metadata.executor_step_index) + self.assertEqual([ph.name], dump1.core_metadata.input_names) + self.assertEqual([x.name], dump1.core_metadata.output_names) + self.assertEqual([], dump1.core_metadata.target_nodes) + file_io.delete_recursively(self._dump_root) + + # Calling run() with the same feed, same output and same debug watch + # options should increment both session_run_index and + # executor_step_index. + _, dump2 = self._debug_run_and_get_dump( + sess, x, feed_dict={ph: np.array([[7.0, 8.0]])}, global_step=2) + self.assertEqual(2, dump2.core_metadata.global_step) + self.assertEqual(dump1.core_metadata.session_run_index + 1, + dump2.core_metadata.session_run_index) + self.assertEqual(dump1.core_metadata.executor_step_index + 1, + dump2.core_metadata.executor_step_index) + self.assertEqual([ph.name], dump2.core_metadata.input_names) + self.assertEqual([x.name], dump2.core_metadata.output_names) + self.assertEqual([], dump2.core_metadata.target_nodes) + file_io.delete_recursively(self._dump_root) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, sess.graph, debug_urls=self._debug_urls(), global_step=3) + + # Calling run() with a different output should increment + # session_run_index, but not executor_step_index. + _, dump3 = self._debug_run_and_get_dump( + sess, y, feed_dict={ph: np.array([[7.0, 8.0]])}, global_step=3) + self.assertEqual(3, dump3.core_metadata.global_step) + self.assertEqual(dump2.core_metadata.session_run_index + 1, + dump3.core_metadata.session_run_index) + self.assertEqual(0, dump3.core_metadata.executor_step_index) + self.assertEqual([ph.name], dump3.core_metadata.input_names) + self.assertEqual([y.name], dump3.core_metadata.output_names) + self.assertEqual([], dump3.core_metadata.target_nodes) + + def testDebuggingDuringOpError(self): + """Test the debug tensor dumping when error occurs in graph runtime.""" + + with session.Session() as sess: + ph = array_ops.placeholder(dtypes.float32, name="mismatch/ph") + x = array_ops.transpose(ph, name="mismatch/x") + m = constant_op.constant( + np.array( + [[1.0, 2.0]], dtype=np.float32), name="mismatch/m") + y = math_ops.matmul(m, x, name="mismatch/y") + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=["DebugIdentity"], + debug_urls=self._debug_urls()) + + with self.assertRaises(errors.OpError): + sess.run(y, + options=run_options, + feed_dict={ph: np.array([[-3.0], [0.0]])}) + + dump = debug_data.DebugDumpDir(self._dump_root) + + self.assertGreaterEqual(dump.core_metadata.session_run_index, 0) + self.assertGreaterEqual(dump.core_metadata.executor_step_index, 0) + self.assertEqual([ph.name], dump.core_metadata.input_names) + self.assertEqual([y.name], dump.core_metadata.output_names) + self.assertEqual([], dump.core_metadata.target_nodes) + + # Despite the fact that the run() call errored out and partition_graphs + # are not available via run_metadata, the partition graphs should still + # have been loaded from the dump directory. + self.assertTrue(dump.loaded_partition_graphs()) + + m_dumps = dump.watch_key_to_data("mismatch/m:0:DebugIdentity") + self.assertEqual(1, len(m_dumps)) + self.assertAllClose(np.array([[1.0, 2.0]]), m_dumps[0].get_tensor()) + + x_dumps = dump.watch_key_to_data("mismatch/x:0:DebugIdentity") + self.assertEqual(1, len(x_dumps)) + self.assertAllClose(np.array([[-3.0, 0.0]]), x_dumps[0].get_tensor()) + + def testDebugNumericSummaryOnInitializedTensorGivesCorrectResult(self): + with session.Session(config=no_rewrite_session_config()) as sess: + a = variable_v1.VariableV1([ + np.nan, np.nan, 0.0, 0.0, 0.0, -1.0, -3.0, 3.0, 7.0, -np.inf, -np.inf, + np.inf, np.inf, np.inf, np.inf, np.inf, np.nan, np.nan + ], + dtype=np.float32, + name="numeric_summary/a") + b = variable_v1.VariableV1( + [0.0] * 18, dtype=np.float32, name="numeric_summary/b") + c = math_ops.add(a, b, name="numeric_summary/c") + + sess.run(variables.global_variables_initializer()) + + _, dump = self._debug_run_and_get_dump( + sess, c, debug_ops=["DebugNumericSummary"]) + self.assertTrue(dump.loaded_partition_graphs()) + + self.assertAllClose([[ + 1.0, 18.0, 4.0, 2.0, 2.0, 3.0, 2.0, 5.0, -3.0, 7.0, 0.85714286, + 8.97959184, 1.0, 1.0, 18.0 + ]], dump.get_tensors("numeric_summary/a/read", 0, "DebugNumericSummary")) + + def testDebugNumericSummaryOnUninitializedTensorGivesCorrectResult(self): + with session.Session() as sess: + a = variable_v1.VariableV1([42], + dtype=np.float32, + name="numeric_summary_uninit/a") + + _, dump = self._debug_run_and_get_dump( + sess, a.initializer, debug_ops=["DebugNumericSummary"]) + + self.assertTrue(dump.loaded_partition_graphs()) + + # DebugNumericSummary output should reflect the uninitialized state of + # the watched tensor. + numeric_summary = dump.get_tensors("numeric_summary_uninit/a", 0, + "DebugNumericSummary")[0] + self.assertAllClose([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + numeric_summary[0:8]) + # Check dtype (index 12), ndims (index 13) and dimension sizes (index + # 14+). + self.assertAllClose([1.0, 1.0, 1.0], numeric_summary[12:]) + self.assertTrue(np.isinf(numeric_summary[8])) + self.assertGreater(numeric_summary[8], 0.0) + self.assertTrue(np.isinf(numeric_summary[9])) + self.assertLess(numeric_summary[9], 0.0) + self.assertTrue(np.isnan(numeric_summary[10])) + self.assertTrue(np.isnan(numeric_summary[11])) + + def testDebugNumericSummaryFailureIsToleratedWhenOrdered(self): + with session.Session() as sess: + a = variable_v1.VariableV1("1", name="a") + b = variable_v1.VariableV1("3", name="b") + c = variable_v1.VariableV1("2", name="c") + + d = math_ops.add(a, b, name="d") + e = math_ops.add(d, c, name="e") + n = parsing_ops.string_to_number(e, name="n") + m = math_ops.add(n, n, name="m") + + sess.run(variables.global_variables_initializer()) + + # Using DebugNumericSummary on sess.run(m) with the default + # tolerate_debug_op_creation_failures=False should error out due to the + # presence of string-dtype Tensors in the graph. + run_metadata = config_pb2.RunMetadata() + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=["DebugNumericSummary"], + debug_urls=self._debug_urls()) + with self.assertRaises(errors.FailedPreconditionError): + sess.run(m, options=run_options, run_metadata=run_metadata) + + # Using tolerate_debug_op_creation_failures=True should get rid of the + # error. + m_result, dump = self._debug_run_and_get_dump( + sess, m, debug_ops=["DebugNumericSummary"], + tolerate_debug_op_creation_failures=True) + self.assertEqual(264, m_result) + + # The integer-dtype Tensors in the graph should have been dumped + # properly. + self.assertIn("n:0:DebugNumericSummary", dump.debug_watch_keys("n")) + self.assertIn("m:0:DebugNumericSummary", dump.debug_watch_keys("m")) + + def testDebugNumericSummaryInvalidAttributesStringAreCaught(self): + with session.Session(config=no_rewrite_session_config()) as sess: + a = variable_v1.VariableV1(10.0, name="a") + b = variable_v1.VariableV1(0.0, name="b") + c = variable_v1.VariableV1(0.0, name="c") + + x = math_ops.divide(a, b, name="x") + y = math_ops.multiply(x, c, name="y") + + sess.run(variables.global_variables_initializer()) + + run_metadata = config_pb2.RunMetadata() + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=["DebugNumericSummary(foo=1.0)"], + debug_urls=self._debug_urls()) + with self.assertRaisesRegexp( + errors.FailedPreconditionError, + r"1 attribute key\(s\) were not valid for debug node " + r"__dbg_.:0_0_DebugNumericSummary: foo"): + sess.run(y, options=run_options, run_metadata=run_metadata) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=["DebugNumericSummary(foo=1.0; bar=false)"], + debug_urls=self._debug_urls()) + with self.assertRaisesRegexp( + errors.FailedPreconditionError, + r"2 attribute key\(s\) were not valid for debug node " + r"__dbg_.:0_0_DebugNumericSummary:"): + sess.run(y, options=run_options, run_metadata=run_metadata) + + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, + sess.graph, + debug_ops=["DebugNumericSummary(foo=1.0; mute_if_healthy=true)"], + debug_urls=self._debug_urls()) + with self.assertRaisesRegexp( + errors.FailedPreconditionError, + r"1 attribute key\(s\) were not valid for debug node " + r"__dbg_.:0_0_DebugNumericSummary: foo"): + sess.run(y, options=run_options, run_metadata=run_metadata) + + def testDebugNumericSummaryMuteOnHealthyMutesOnlyHealthyTensorDumps(self): + with session.Session(config=no_rewrite_session_config()) as sess: + a = variable_v1.VariableV1(10.0, name="a") + b = variable_v1.VariableV1(0.0, name="b") + c = variable_v1.VariableV1(0.0, name="c") + + x = math_ops.divide(a, b, name="x") + y = math_ops.multiply(x, c, name="y") + + sess.run(variables.global_variables_initializer()) + + # Here, validate=False is necessary to avoid causality check error. + # TODO(cais): Maybe let DebugDumpDir constructor automatically ignore + # debug ops with mute_if_healthy=false attribute during validation. + _, dump = self._debug_run_and_get_dump( + sess, y, debug_ops=["DebugNumericSummary(mute_if_healthy=true)"], + validate=False) + + self.assertLessEqual(2, dump.size) + self.assertAllClose([[ + 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, np.inf, -np.inf, np.nan, + np.nan, 1.0, 0.0 + ]], dump.get_tensors("x", 0, "DebugNumericSummary")) + self.assertAllClose([[ + 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, np.inf, -np.inf, np.nan, + np.nan, 1.0, 0.0 + ]], dump.get_tensors("y", 0, "DebugNumericSummary")) + + # Another run with the default mute_if_healthy (false) value should + # dump all the tensors. + file_io.delete_recursively(self._dump_root) + _, dump = self._debug_run_and_get_dump( + sess, y, debug_ops=["DebugNumericSummary()"]) + self.assertLessEqual(8, dump.size) + + def testDebugNumericSummaryMuteOnHealthyAndCustomBoundsWork(self): + with session.Session() as sess: + a = variable_v1.VariableV1([10.0, 10.0], name="a") + b = variable_v1.VariableV1([10.0, 2.0], name="b") + + x = math_ops.add(a, b, name="x") # [20.0, 12.0] + y = math_ops.divide(x, b, name="y") # [2.0, 6.0] + + sess.run(variables.global_variables_initializer()) + + # Here, validate=False is necessary to avoid causality check error. + # TODO(cais): Maybe let DebugDumpDir constructor automatically ignore + # debug ops with mute_if_healthy=false attribute during validation. + _, dump = self._debug_run_and_get_dump( + sess, y, debug_ops=[ + "DebugNumericSummary(mute_if_healthy=true; upper_bound=11.0)"], + validate=False) + + self.assertEqual(1, dump.size) + self.assertAllClose([[ + 1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 12.0, 20.0, 16.0, 16.0, 1.0, + 1.0, 2.0]], dump.get_tensors("x", 0, "DebugNumericSummary")) + + def testDebugQueueOpsDoesNotoErrorOut(self): + with session.Session() as sess: + q = data_flow_ops.FIFOQueue(3, "float", name="fifo_queue") + q_init = q.enqueue_many(([101.0, 202.0, 303.0],), name="enqueue_many") + + _, dump = self._debug_run_and_get_dump(sess, q_init) + self.assertTrue(dump.loaded_partition_graphs()) + + fifo_queue_tensor = dump.get_tensors("fifo_queue", 0, "DebugIdentity")[0] + self.assertIsInstance(fifo_queue_tensor, + debug_data.InconvertibleTensorProto) + self.assertTrue(fifo_queue_tensor.initialized) + self.assertAllClose( + [101.0, 202.0, 303.0], + dump.get_tensors("enqueue_many/component_0", 0, "DebugIdentity")[0]) + + def testLookUpNodePythonTracebackWorks(self): + with session.Session() as sess: + u_init = constant_op.constant(10.0) + u = variable_v1.VariableV1(u_init, name="traceback/u") + v_init = constant_op.constant(20.0) + v = variable_v1.VariableV1(v_init, name="traceback/v") + + w = math_ops.multiply(u, v, name="traceback/w") + + sess.run(variables.global_variables_initializer()) + _, dump = self._debug_run_and_get_dump(sess, w) + + # Prior to setting the Python graph, attempts to do traceback lookup + # should lead to exceptions. + with self.assertRaisesRegexp( + LookupError, "Python graph is not available for traceback lookup"): + dump.node_traceback("traceback/w") + + dump.set_python_graph(sess.graph) + + # After setting the Python graph, attempts to look up nonexistent nodes + # should lead to exceptions. + with self.assertRaisesRegexp(KeyError, + r"Cannot find node \"foo\" in Python graph"): + dump.node_traceback("foo") + + # Lookup should work with node name input. + traceback = dump.node_traceback("traceback/w") + self.assertIsInstance(traceback, tuple) + self.assertGreater(len(traceback), 0) + for trace in traceback: + self.assertIsInstance(trace, tuple) + + # Lookup should also work with tensor name input. + traceback = dump.node_traceback("traceback/w:0") + self.assertIsInstance(traceback, tuple) + self.assertGreater(len(traceback), 0) + for trace in traceback: + self.assertIsInstance(trace, tuple) + + +class DebugConcurrentRunCallsTest(test_util.TensorFlowTestCase): + """Test for debugging concurrent Session.run() calls.""" + + def _get_concurrent_debug_urls(self): + """Abstract method to generate debug URLs for concurrent debugged runs.""" + raise NotImplementedError( + "_get_concurrent_debug_urls is not implemented in the base test class") + + def testDebugConcurrentVariableUpdates(self): + if test.is_gpu_available(): + self.skipTest("No testing concurrent runs on a single GPU.") + + with session.Session() as sess: + v = variable_v1.VariableV1(30.0, name="v") + constants = [] + for i in range(self._num_concurrent_runs): + constants.append(constant_op.constant(1.0, name="c%d" % i)) + incs = [ + state_ops.assign_add( + v, c, use_locking=True, name=("inc%d" % i)) + for (i, c) in enumerate(constants) + ] + sess.run(v.initializer) + + concurrent_debug_urls = self._get_concurrent_debug_urls() + + def inc_job(index): + run_options = config_pb2.RunOptions(output_partition_graphs=True) + debug_utils.watch_graph( + run_options, sess.graph, debug_urls=concurrent_debug_urls[index]) + for _ in range(100): + sess.run(incs[index], options=run_options) + + inc_threads = [] + for index in range(self._num_concurrent_runs): + inc_thread = threading.Thread(target=functools.partial(inc_job, index)) + inc_thread.start() + inc_threads.append(inc_thread) + for inc_thread in inc_threads: + inc_thread.join() + + self.assertAllClose(30.0 + 1.0 * self._num_concurrent_runs * 100, + sess.run(v)) + + all_session_run_indices = [] + for index in range(self._num_concurrent_runs): + dump = debug_data.DebugDumpDir(self._dump_roots[index]) + self.assertTrue(dump.loaded_partition_graphs()) + + v_data = dump.get_tensors("v", 0, "DebugIdentity") + self.assertEqual(100, len(v_data)) + + # Examine all the core metadata files + core_metadata_files = glob.glob( + os.path.join(self._dump_roots[index], "_tfdbg_core*")) + + timestamps = [] + session_run_indices = [] + executor_step_indices = [] + for core_metadata_file in core_metadata_files: + with open(core_metadata_file, "rb") as f: + event = event_pb2.Event() + event.ParseFromString(f.read()) + core_metadata = ( + debug_data.extract_core_metadata_from_event_proto(event)) + timestamps.append(event.wall_time) + session_run_indices.append(core_metadata.session_run_index) + executor_step_indices.append(core_metadata.executor_step_index) + + all_session_run_indices.extend(session_run_indices) + + # Assert that executor_step_index increases by one at a time. + executor_step_indices = zip(timestamps, executor_step_indices) + executor_step_indices = sorted( + executor_step_indices, key=lambda x: x[0]) + for i in range(len(executor_step_indices) - 1): + self.assertEquals(executor_step_indices[i][1] + 1, + executor_step_indices[i + 1][1]) + + # Assert that session_run_index increase monotonically. + session_run_indices = zip(timestamps, session_run_indices) + session_run_indices = sorted(session_run_indices, key=lambda x: x[0]) + for i in range(len(session_run_indices) - 1): + self.assertGreater(session_run_indices[i + 1][1], + session_run_indices[i][1]) + + # Assert that the session_run_indices from the concurrent run() calls are + # all unique. + self.assertEqual(len(all_session_run_indices), + len(set(all_session_run_indices))) + + +if __name__ == "__main__": + googletest.main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/source_remote.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/source_remote.py new file mode 100644 index 0000000000000000000000000000000000000000..cac32236069fab83f075396e62de4437ebe3e531 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/source_remote.py @@ -0,0 +1,210 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Communicating tracebacks and source code with debug server.""" + +import socket + +import grpc + +from tensorflow.core.debug import debug_service_pb2 +from tensorflow.core.protobuf import debug_pb2 +from tensorflow.python.debug.lib import common +from tensorflow.python.debug.lib import debug_service_pb2_grpc +from tensorflow.python.debug.lib import source_utils +from tensorflow.python.platform import gfile +from tensorflow.python.profiler import tfprof_logger + + +def _load_debugged_source_file(file_path, source_file_proto): + file_stat = gfile.Stat(file_path) + source_file_proto.host = socket.gethostname() + source_file_proto.file_path = file_path + source_file_proto.last_modified = file_stat.mtime_nsec + source_file_proto.bytes = file_stat.length + try: + with gfile.Open(file_path, "r") as f: + source_file_proto.lines.extend(f.read().splitlines()) + except IOError: + pass + + +def _string_to_id(string, string_to_id): + if string not in string_to_id: + string_to_id[string] = len(string_to_id) + return string_to_id[string] + + +def _format_origin_stack(origin_stack, call_traceback_proto): + """Format a traceback stack for a `CallTraceback` proto. + + Args: + origin_stack: The stack list as returned by `traceback.extract_stack()`. + call_traceback_proto: A `CallTraceback` proto whose fields are to be + populated. + """ + string_to_id = {} + string_to_id[None] = 0 + for frame in origin_stack: + file_path, lineno, func_name, line_text = frame + call_traceback_proto.origin_stack.traces.add( + file_id=_string_to_id(file_path, string_to_id), + lineno=lineno, + function_id=_string_to_id(func_name, string_to_id), + line_id=_string_to_id(line_text, string_to_id)) + + id_to_string = call_traceback_proto.origin_id_to_string + for key, value in string_to_id.items(): + id_to_string[value] = key if key is not None else "" + + +def _source_file_paths_outside_tensorflow_py_library(code_defs, id_to_string): + """Extract source file paths outside TensorFlow Python library. + + Args: + code_defs: An iterable of `CodeDef` protos, i.e., an iterable of stack + traces. + id_to_string: A proto map from integer ids to strings. + + Returns: + An iterable of source file paths outside the TensorFlow Python library. + """ + file_ids = set() + for code_def in code_defs: + for trace in code_def.traces: + file_ids.add(trace.file_id) + non_tf_files = (id_to_string[file_id] for file_id in file_ids) + non_tf_files = ( + f for f in non_tf_files + if not source_utils.guess_is_tensorflow_py_library(f) and gfile.Exists(f)) + return non_tf_files + + +def _send_call_tracebacks(destinations, + origin_stack, + is_eager_execution=False, + call_key=None, + graph=None, + send_source=True): + """Send the tracebacks of a TensorFlow execution call. + + To gRPC debug server(s). This applies to graph execution (`tf.Session.run()`) + calls and eager execution calls. + + If `send_source`, also sends the underlying source files outside the + TensorFlow library. + + Args: + destinations: gRPC destination addresses, a `str` or a `list` of `str`s, + e.g., "localhost:4242". If a `list`, gRPC requests containing the same + `CallTraceback` proto payload will be sent to all the destinations. + origin_stack: The traceback stack for the origin of the execution call. For + graph execution, this is the traceback of the `tf.Session.run()` + invocation. For eager execution, this is the traceback of the Python + line that executes the eager operation. + is_eager_execution: (`bool`) whether an eager execution call (i.e., not a + `tf.Session.run` or derived methods) is being sent. + call_key: The key of the execution call, as a string. For graph execution, + this is a string describing the feeds, fetches (and targets) names of the + `tf.Session.run` call. For eager execution, this is ignored. + graph: A Python `tf.Graph` object (i.e., *not* a `tf.compat.v1.GraphDef`), + which contains op tracebacks, if applicable. + send_source: Whether the source files involved in the op tracebacks but + outside the TensorFlow library are to be sent. + """ + if not isinstance(destinations, list): + destinations = [destinations] + # Strip grpc:// prefix, if any is present. + destinations = [ + dest[len(common.GRPC_URL_PREFIX):] + if dest.startswith(common.GRPC_URL_PREFIX) else dest + for dest in destinations] + + call_type = (debug_service_pb2.CallTraceback.EAGER_EXECUTION + if is_eager_execution + else debug_service_pb2.CallTraceback.GRAPH_EXECUTION) + graph_traceback = tfprof_logger.merge_default_with_oplog( + graph, add_trainable_var=False) if graph else None + call_traceback = debug_service_pb2.CallTraceback( + call_type=call_type, call_key=call_key, graph_traceback=graph_traceback, + graph_version=graph.version if graph else None) + + _format_origin_stack(origin_stack, call_traceback) + + if send_source: + source_file_paths = set() + source_file_paths.update(_source_file_paths_outside_tensorflow_py_library( + (log_entry.code_def for log_entry + in call_traceback.graph_traceback.log_entries), + call_traceback.graph_traceback.id_to_string)) + source_file_paths.update(_source_file_paths_outside_tensorflow_py_library( + [call_traceback.origin_stack], call_traceback.origin_id_to_string)) + + debugged_source_files = [] + for file_path in source_file_paths: + source_files = debug_pb2.DebuggedSourceFiles() + _load_debugged_source_file( + file_path, source_files.source_files.add()) + debugged_source_files.append(source_files) + + for destination in destinations: + no_max_message_sizes = [("grpc.max_receive_message_length", -1), + ("grpc.max_send_message_length", -1)] + channel = grpc.insecure_channel(destination, options=no_max_message_sizes) + stub = debug_service_pb2_grpc.EventListenerStub(channel) + stub.SendTracebacks(call_traceback) + if send_source: + for source_files in debugged_source_files: + stub.SendSourceFiles(source_files) + + +def send_graph_tracebacks(destinations, + run_key, + origin_stack, + graph, + send_source=True): + """Send the tracebacks of a graph execution call to debug server(s). + + Args: + destinations: gRPC destination addresses, a `str` or a `list` of `str`s, + e.g., "localhost:4242". If a `list`, gRPC requests containing the same + `CallTraceback` proto payload will be sent to all the destinations. + run_key: A string describing the feeds, fetches (and targets) names of the + `tf.Session.run` call. + origin_stack: The traceback of the `tf.Session.run()` invocation. + graph: A Python `tf.Graph` object (i.e., *not* a `tf.compat.v1.GraphDef`), + which contains op tracebacks. + send_source: Whether the source files involved in the op tracebacks but + outside the TensorFlow library are to be sent. + """ + _send_call_tracebacks( + destinations, origin_stack, is_eager_execution=False, call_key=run_key, + graph=graph, send_source=send_source) + + +def send_eager_tracebacks(destinations, + origin_stack, + send_source=True): + """Send the tracebacks of an eager execution call to debug server(s). + + Args: + destinations: gRPC destination addresses, a `str` or a `list` of `str`s, + e.g., "localhost:4242". If a `list`, gRPC requests containing the same + origin_stack: The traceback of the eager operation invocation. + send_source: Whether the source files involved in the op tracebacks but + outside the TensorFlow library are to be sent. + """ + _send_call_tracebacks( + destinations, origin_stack, is_eager_execution=True, + send_source=send_source) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/source_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/source_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8949101903ea4bd6157b51a94081f4785dda495a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/lib/source_utils.py @@ -0,0 +1,375 @@ +# 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 and functions that help to inspect Python source w.r.t. TF graphs.""" + +import collections +import os +import re +import zipfile + +from absl import app +import numpy as np + +from tensorflow.python.debug.lib import profiling + + +_TENSORFLOW_BASEDIR = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.normpath(os.path.abspath(__file__)))))) + +_ABSL_BASEDIR = os.path.dirname(app.__file__) + + +UNCOMPILED_SOURCE_SUFFIXES = (".py") +COMPILED_SOURCE_SUFFIXES = (".pyc", ".pyo") + + +def _norm_abs_path(file_path): + return os.path.normpath(os.path.abspath(file_path)) + + +def is_extension_uncompiled_python_source(file_path): + _, extension = os.path.splitext(file_path) + return extension.lower() in UNCOMPILED_SOURCE_SUFFIXES + + +def is_extension_compiled_python_source(file_path): + _, extension = os.path.splitext(file_path) + return extension.lower() in COMPILED_SOURCE_SUFFIXES + + +def _convert_watch_key_to_tensor_name(watch_key): + return watch_key[:watch_key.rfind(":")] + + +def guess_is_tensorflow_py_library(py_file_path): + """Guess whether a Python source file is a part of the tensorflow library. + + Special cases: + 1) Returns False for unit-test files in the library (*_test.py), + 2) Returns False for files under python/debug/examples. + + Args: + py_file_path: full path of the Python source file in question. + + Returns: + (`bool`) Whether the file is inferred to be a part of the tensorflow + library. + """ + if (not is_extension_uncompiled_python_source(py_file_path) and + not is_extension_compiled_python_source(py_file_path)): + return False + py_file_path = _norm_abs_path(py_file_path) + return ((py_file_path.startswith(_TENSORFLOW_BASEDIR) or + py_file_path.startswith(_ABSL_BASEDIR)) and + not py_file_path.endswith("_test.py") and + (os.path.normpath("tensorflow/python/debug/examples") not in + os.path.normpath(py_file_path))) + + +def load_source(source_file_path): + """Load the content of a Python source code file. + + This function covers the following case: + 1. source_file_path points to an existing Python (.py) file on the + file system. + 2. source_file_path is a path within a .par file (i.e., a zip-compressed, + self-contained Python executable). + + Args: + source_file_path: Path to the Python source file to read. + + Returns: + A length-2 tuple: + - Lines of the source file, as a `list` of `str`s. + - The width of the string needed to show the line number in the file. + This is calculated based on the number of lines in the source file. + + Raises: + IOError: if loading is unsuccessful. + """ + if os.path.isfile(source_file_path): + with open(source_file_path, "rb") as f: + source_text = f.read().decode("utf-8") + source_lines = source_text.split("\n") + else: + # One possible reason why the file doesn't exist is that it's a path + # inside a .par file. Try that possibility. + source_lines = _try_load_par_source(source_file_path) + if source_lines is None: + raise IOError( + "Source path neither exists nor can be loaded as a .par file: %s" % + source_file_path) + line_num_width = int(np.ceil(np.log10(len(source_lines)))) + 3 + return source_lines, line_num_width + + +def _try_load_par_source(source_file_path): + """Try loading the source code inside a .par file. + + A .par file is a zip-compressed, self-contained Python executable. + It contains the content of individual Python source files that can + be read only through extracting from the zip file. + + Args: + source_file_path: The full path to the file inside the .par file. This + path should include the path to the .par file itself, followed by the + intra-par path, e.g., + "/tmp/my_executable.par/org-tensorflow/tensorflow/python/foo/bar.py". + + Returns: + If successful, lines of the source file as a `list` of `str`s. + Else, `None`. + """ + prefix_path = source_file_path + while True: + prefix_path, basename = os.path.split(prefix_path) + if not basename: + break + suffix_path = os.path.normpath( + os.path.relpath(source_file_path, start=prefix_path)) + if prefix_path.endswith(".par") and os.path.isfile(prefix_path): + with zipfile.ZipFile(prefix_path) as z: + norm_names = [os.path.normpath(name) for name in z.namelist()] + if suffix_path in norm_names: + with z.open(z.namelist()[norm_names.index(suffix_path)]) as zf: + source_text = zf.read().decode("utf-8") + return source_text.split("\n") + + +def annotate_source(dump, + source_file_path, + do_dumped_tensors=False, + file_stack_top=False, + min_line=None, + max_line=None): + """Annotate a Python source file with a list of ops created at each line. + + (The annotation doesn't change the source file itself.) + + Args: + dump: (`DebugDumpDir`) A `DebugDumpDir` object of which the Python graph + has been loaded. + source_file_path: (`str`) Path to the source file being annotated. + do_dumped_tensors: (`str`) Whether dumped Tensors, instead of ops are to be + used to annotate the source file. + file_stack_top: (`bool`) Whether only the top stack trace in the + specified source file is to be annotated. + min_line: (`None` or `int`) The 1-based line to start annotate the source + file from (inclusive). + max_line: (`None` or `int`) The 1-based line number to end the annotation + at (exclusive). + + Returns: + A `dict` mapping 1-based line number to a list of op name(s) created at + that line, or tensor names if `do_dumped_tensors` is True. + + Raises: + ValueError: If the dump object does not have a Python graph set. + """ + + py_graph = dump.python_graph + if not py_graph: + raise ValueError("Cannot perform source annotation due to a lack of set " + "Python graph in the dump object") + + source_file_path = _norm_abs_path(source_file_path) + + line_to_op_names = {} + for op in py_graph.get_operations(): + for file_path, line_number, _, _ in reversed(dump.node_traceback(op.name)): + if (min_line is not None and line_number < min_line or + max_line is not None and line_number >= max_line): + continue + + if _norm_abs_path(file_path) != source_file_path: + continue + + if do_dumped_tensors: + watch_keys = dump.debug_watch_keys(op.name) + # Convert watch keys to unique Tensor names. + items_to_append = list( + set(map(_convert_watch_key_to_tensor_name, watch_keys))) + else: + items_to_append = [op.name] + + if line_number in line_to_op_names: + line_to_op_names[line_number].extend(items_to_append) + else: + line_to_op_names[line_number] = items_to_append + + if file_stack_top: + break + + return line_to_op_names + + +def list_source_files_against_dump(dump, + path_regex_allowlist=None, + node_name_regex_allowlist=None): + """Generate a list of source files with information regarding ops and tensors. + + Args: + dump: (`DebugDumpDir`) A `DebugDumpDir` object of which the Python graph + has been loaded. + path_regex_allowlist: A regular-expression filter for source file path. + node_name_regex_allowlist: A regular-expression filter for node names. + + Returns: + A list of tuples regarding the Python source files involved in constructing + the ops and tensors contained in `dump`. Each tuple is: + (source_file_path, is_tf_library, num_nodes, num_tensors, num_dumps, + first_line) + + is_tf_library: (`bool`) A guess of whether the file belongs to the + TensorFlow Python library. + num_nodes: How many nodes were created by lines of this source file. + These include nodes with dumps and those without. + num_tensors: How many Tensors were created by lines of this source file. + These include Tensors with dumps and those without. + num_dumps: How many debug Tensor dumps were from nodes (and Tensors) + that were created by this source file. + first_line: The first line number (1-based) that created any nodes or + Tensors in this source file. + + The list is sorted by ascending order of source_file_path. + + Raises: + ValueError: If the dump object does not have a Python graph set. + """ + + py_graph = dump.python_graph + if not py_graph: + raise ValueError("Cannot generate source list due to a lack of set " + "Python graph in the dump object") + + path_to_node_names = collections.defaultdict(set) + path_to_tensor_names = collections.defaultdict(set) + path_to_first_line = {} + tensor_name_to_num_dumps = {} + + path_regex = ( + re.compile(path_regex_allowlist) if path_regex_allowlist else None) + node_name_regex = ( + re.compile(node_name_regex_allowlist) + if node_name_regex_allowlist else None) + + to_skip_file_paths = set() + for op in py_graph.get_operations(): + if node_name_regex and not node_name_regex.match(op.name): + continue + + for file_path, line_number, _, _ in dump.node_traceback(op.name): + file_path = _norm_abs_path(file_path) + if (file_path in to_skip_file_paths or + path_regex and not path_regex.match(file_path) or + not os.path.isfile(file_path)): + to_skip_file_paths.add(file_path) + continue + + path_to_node_names[file_path].add(op.name) + if file_path in path_to_first_line: + if path_to_first_line[file_path] > line_number: + path_to_first_line[file_path] = line_number + else: + path_to_first_line[file_path] = line_number + + for output_tensor in op.outputs: + tensor_name = output_tensor.name + path_to_tensor_names[file_path].add(tensor_name) + + watch_keys = dump.debug_watch_keys(op.name) + for watch_key in watch_keys: + node_name, output_slot, debug_op = watch_key.split(":") + tensor_name = "%s:%s" % (node_name, output_slot) + if tensor_name not in tensor_name_to_num_dumps: + tensor_name_to_num_dumps[tensor_name] = len( + dump.get_tensors(node_name, int(output_slot), debug_op)) + + path_to_num_dumps = {} + for path in path_to_tensor_names: + path_to_num_dumps[path] = sum( + tensor_name_to_num_dumps.get(tensor_name, 0) + for tensor_name in path_to_tensor_names[path]) + + output = [] + for file_path in path_to_node_names: + output.append(( + file_path, + guess_is_tensorflow_py_library(file_path), + len(path_to_node_names.get(file_path, {})), + len(path_to_tensor_names.get(file_path, {})), + path_to_num_dumps.get(file_path, 0), + path_to_first_line[file_path])) + + return sorted(output, key=lambda x: x[0]) + + +def annotate_source_against_profile(profile_data, + source_file_path, + node_name_filter=None, + op_type_filter=None, + min_line=None, + max_line=None): + """Annotate a Python source file with profiling information at each line. + + (The annotation doesn't change the source file itself.) + + Args: + profile_data: (`list` of `ProfileDatum`) A list of `ProfileDatum`. + source_file_path: (`str`) Path to the source file being annotated. + node_name_filter: Regular expression to filter by node name. + op_type_filter: Regular expression to filter by op type. + min_line: (`None` or `int`) The 1-based line to start annotate the source + file from (inclusive). + max_line: (`None` or `int`) The 1-based line number to end the annotation + at (exclusive). + + Returns: + A `dict` mapping 1-based line number to a the namedtuple + `profiling.LineOrFuncProfileSummary`. + """ + + source_file_path = _norm_abs_path(source_file_path) + + node_name_regex = re.compile(node_name_filter) if node_name_filter else None + op_type_regex = re.compile(op_type_filter) if op_type_filter else None + + line_to_profile_summary = {} + for profile_datum in profile_data: + if not profile_datum.file_path: + continue + + if _norm_abs_path(profile_datum.file_path) != source_file_path: + continue + + if (min_line is not None and profile_datum.line_number < min_line or + max_line is not None and profile_datum.line_number >= max_line): + continue + + if (node_name_regex and + not node_name_regex.match(profile_datum.node_exec_stats.node_name)): + continue + + if op_type_regex and not op_type_regex.match(profile_datum.op_type): + continue + + if profile_datum.line_number not in line_to_profile_summary: + line_to_profile_summary[profile_datum.line_number] = ( + profiling.AggregateProfile(profile_datum)) + else: + line_to_profile_summary[profile_datum.line_number].add(profile_datum) + + return line_to_profile_summary diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/dumping_wrapper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/dumping_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..b2ed07dd1b70968106288359388af4457c25bd33 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/dumping_wrapper.py @@ -0,0 +1,124 @@ +# 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. +# ============================================================================== +"""Debugger wrapper session that dumps debug data to file:// URLs.""" +import os +import threading +import time + +from tensorflow.core.util import event_pb2 +from tensorflow.python.debug.lib import debug_data +from tensorflow.python.debug.wrappers import framework +from tensorflow.python.platform import gfile + + +class DumpingDebugWrapperSession(framework.NonInteractiveDebugWrapperSession): + """Debug Session wrapper that dumps debug data to filesystem.""" + + def __init__(self, + sess, + session_root, + watch_fn=None, + thread_name_filter=None, + pass_through_operrors=None): + """Constructor of DumpingDebugWrapperSession. + + Args: + sess: The TensorFlow `Session` object being wrapped. + session_root: (`str`) Path to the session root directory. Must be a + directory that does not exist or an empty directory. If the directory + does not exist, it will be created by the debugger core during debug + `tf.Session.run` + calls. + As the `run()` calls occur, subdirectories will be added to + `session_root`. The subdirectories' names has the following pattern: + run__ + E.g., run_1480734393835964_ad4c953a85444900ae79fc1b652fb324 + watch_fn: (`Callable`) A Callable that can be used to define per-run + debug ops and watched tensors. See the doc of + `NonInteractiveDebugWrapperSession.__init__()` for details. + thread_name_filter: Regular-expression white list for threads on which the + wrapper session will be active. See doc of `BaseDebugWrapperSession` for + more details. + pass_through_operrors: If true, all captured OpErrors will be + propagated. By default this captures all OpErrors. + + Raises: + ValueError: If `session_root` is an existing and non-empty directory or + if `session_root` is a file. + """ + framework.NonInteractiveDebugWrapperSession.__init__( + self, sess, watch_fn=watch_fn, thread_name_filter=thread_name_filter, + pass_through_operrors=pass_through_operrors) + + session_root = os.path.expanduser(session_root) + if gfile.Exists(session_root): + if not gfile.IsDirectory(session_root): + raise ValueError( + "session_root path points to a file: %s" % session_root) + elif gfile.ListDirectory(session_root): + raise ValueError( + "session_root path points to a non-empty directory: %s" % + session_root) + else: + gfile.MakeDirs(session_root) + self._session_root = session_root + + self._run_counter = 0 + self._run_counter_lock = threading.Lock() + + def prepare_run_debug_urls(self, fetches, feed_dict): + """Implementation of abstract method in superclass. + + See doc of `NonInteractiveDebugWrapperSession.prepare_run_debug_urls()` + for details. This implementation creates a run-specific subdirectory under + self._session_root and stores information regarding run `fetches` and + `feed_dict.keys()` in the subdirectory. + + Args: + fetches: Same as the `fetches` argument to `Session.run()` + feed_dict: Same as the `feed_dict` argument to `Session.run()` + + Returns: + debug_urls: (`str` or `list` of `str`) file:// debug URLs to be used in + this `Session.run()` call. + """ + + # Add a UUID to accommodate the possibility of concurrent run() calls. + self._run_counter_lock.acquire() + run_dir = os.path.join(self._session_root, "run_%d_%d" % + (int(time.time() * 1e6), self._run_counter)) + self._run_counter += 1 + self._run_counter_lock.release() + gfile.MkDir(run_dir) + + fetches_event = event_pb2.Event() + fetches_event.log_message.message = repr(fetches) + fetches_path = os.path.join( + run_dir, + debug_data.METADATA_FILE_PREFIX + debug_data.FETCHES_INFO_FILE_TAG) + with gfile.Open(os.path.join(fetches_path), "wb") as f: + f.write(fetches_event.SerializeToString()) + + feed_keys_event = event_pb2.Event() + feed_keys_event.log_message.message = (repr(feed_dict.keys()) if feed_dict + else repr(feed_dict)) + + feed_keys_path = os.path.join( + run_dir, + debug_data.METADATA_FILE_PREFIX + debug_data.FEED_KEYS_INFO_FILE_TAG) + with gfile.Open(os.path.join(feed_keys_path), "wb") as f: + f.write(feed_keys_event.SerializeToString()) + + return ["file://" + run_dir] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/framework.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/framework.py new file mode 100644 index 0000000000000000000000000000000000000000..be0d08ee3dcf6f3d97ca506e35b3c13be7b6602d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/framework.py @@ -0,0 +1,981 @@ +# 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. +# ============================================================================== +"""Framework of debug wrapper sessions. + +A debug wrapper session is a wrapper around a TensorFlow Python Session. +The wrapper preserves the Session interface, most importantly the run() method, +while providing abilities to: +a) Intercept a run() call to a wrapped session and insert debug tensor watches + according to externally-specified debug URLs. + +b) Release control to an external (i.e., non-Session) object before and after + the run() call, so that the external object can perform actions such as + launching a UI to let users inspect the intermediate tensors and partition + graphs from the run() call. + +c) (To be implemented in a future CL) Enter an instruction loop to let an + external object (e.g., remote client) launch run() and cont() calls + remotely. + +*** The lifetime of a debug wrapper session: *** + +1) The wrapper session is created by calling the constructor with a + wrapped (normal) session as the argument: + wrapper = FooDebugWrapperSession(sess) + wherein FooDebugWrapperSession is a concrete subclass implementing the + abstract BaseDebugWrapperSession class below. + +2) Near the end of the constructor call, the on_session_init() callback is + invoked, with a OnSessionInitRequest object as the argument. The object + carries the wrapped (normal) session object. + +3) The callback handles the request and returns a OnSessionInitResponse + object with an action field, directing the wrapper session what to do next. + +If the action field in the OnSessionInitResponse is PROCEED, the constructor +returns. Control is released back to the caller of the constructor, which can +invoke run() method of wrapper session with the same syntax as a non-wrapped +session, e.g.,: + wrapper.run(fetches, feed_dict=feeds, options=run_options) + +Below, A1 - A2 is the lifetime of a wrapper run() call if the action is +PROCEED: + +A1) Right at the start of each run() call, the on_run_start() callback is + invoked, with an OnRunStartRequest object carrying information such as + the fetches, the feed dict, the run options and run metadata used in + this run call, along with a count of how many run calls has occurred + on this wrapper session. The callback then returns an OnRunStartResponse + object, of which the action field directs what the wrapper session + actually will do of the run() call. + + If the action is DEBUG_RUN, a debugged (tensor-watched) run will ensue, + with the debug URLs supplied in the debug_urls field of the response. + These can be file:// or grpc:// URLs, for example. + + If the action is NON_DEBUG_RUN, a non-debug (normal) run will ensue. + +A2) Right before the run() returns, the on_run_end() callback is invoked, + with an OnRunEndRequest object as the argument, which carries information + including the actual action performed in the wrapper run() call and the + run_metadata from the run() call. + +However, if the action field in OnSessionInitResponse is +REMOTE_INSTR_LOOP, the constructor will automatically invoke an instruction loop +that gives the control to a remote caller. + +In the remote instruction loop, the following steps will happen: + +B1) Callback on_instr_start() is invoked. The callback will return an + OnInstrStartResponse object with an action field which can order one of + the following actions: + i) a run() call with fetches, feeds and debug_urls specified. + ii) exit the instruction loop. + +B2) The wrapper session carries out the action specified above. + +B3) If still in the instruction loop, the wrapper session invokes the + on_instr_end() callback. After the on_instr_end() callback returns, jump + back to B1. + +TODO(cais): Implemented the instruction loop in B1 - B3. + +""" + +import abc +import re +import threading + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session +from tensorflow.python.debug.lib import debug_utils +from tensorflow.python.framework import errors +from tensorflow.python.framework import stack +from tensorflow.python.platform import tf_logging +from tensorflow.python.training import monitored_session +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc + + +# Helper function. +def _check_type(obj, expected_types): + """Check if an object is of the expected type. + + Args: + obj: The object being checked. + expected_types: (`type` or an iterable of `type`s) The expected `type`(s) + of obj. + + Raises: + TypeError: If obj is not an instance of expected_type. + """ + if not isinstance(obj, expected_types): + raise TypeError("Expected type %s; got type %s" % + (expected_types, type(obj))) + + +class OnSessionInitRequest: + """Request to an on-session-init callback. + + This callback is invoked during the __init__ call to a debug-wrapper session. + """ + + def __init__(self, sess): + """Constructor. + + Args: + sess: A tensorflow Session object. + """ + + _check_type(sess, (session.BaseSession, monitored_session.MonitoredSession)) + self.session = sess + + +class OnSessionInitAction: + """Enum-like values for possible action to take on session init.""" + + # Proceed, without special actions, in the wrapper session initialization. + # What action the wrapper session performs next is determined by the caller + # of the wrapper session. E.g., it can call run(). + PROCEED = "proceed" + + # Instead of letting the caller of the wrapper session determine what actions + # the wrapper session will perform next, enter a loop to receive instructions + # from a remote client. + # For example, TensorBoard visual debugger can use this action so that it can + # launch session.run() calls remotely. + REMOTE_INSTR_LOOP = "remote_instr_loop" + + +class OnSessionInitResponse: + """Response from an on-session-init callback.""" + + def __init__(self, action): + """Constructor. + + Args: + action: (`OnSessionInitAction`) Debugger action to take on session init. + """ + _check_type(action, str) + self.action = action + + +class OnRunStartRequest: + """Request to an on-run-start callback. + + This callback is invoked during a run() call of the debug-wrapper + session, immediately after the run() call counter is incremented. + """ + + def __init__(self, fetches, feed_dict, run_options, run_metadata, + run_call_count, is_callable_runner=False): + """Constructor of `OnRunStartRequest`. + + Args: + fetches: Fetch targets of the run() call. + feed_dict: The feed dictionary to the run() call. + run_options: RunOptions input to the run() call. + run_metadata: RunMetadata input to the run() call. + The above four arguments are identical to the input arguments to the + run() method of a non-wrapped TensorFlow session. + run_call_count: 1-based count of how many run calls (including this one) + has been invoked. + is_callable_runner: (bool) whether a runner returned by + Session.make_callable is being run. + """ + self.fetches = fetches + self.feed_dict = feed_dict + self.run_options = run_options + self.run_metadata = run_metadata + self.run_call_count = run_call_count + self.is_callable_runner = is_callable_runner + + +class OnRunStartAction: + """Enum-like values for possible action to take on start of a run() call.""" + + # Run once with debug tensor-watching. + DEBUG_RUN = "debug_run" + + # Run once with profiler. + PROFILE_RUN = "profile_run" + + # Run without debug tensor-watching. + NON_DEBUG_RUN = "non_debug_run" + + + +class OnRunStartResponse: + """Request from an on-run-start callback. + + The caller of the callback can use this response object to specify what + action the debug-wrapper session actually takes on the run() call. + """ + + def __init__(self, + action, + debug_urls, + debug_ops="DebugIdentity", + node_name_regex_allowlist=None, + op_type_regex_allowlist=None, + tensor_dtype_regex_allowlist=None, + tolerate_debug_op_creation_failures=False): + """Constructor of `OnRunStartResponse`. + + Args: + action: (`OnRunStartAction`) the action actually taken by the wrapped + session for the run() call. + debug_urls: (`list` of `str`) debug_urls used in watching the tensors + during the run() call. + debug_ops: (`str` or `list` of `str`) Debug op(s) to be used by the + debugger. + node_name_regex_allowlist: Regular-expression allowlist for node + name. + op_type_regex_allowlist: Regular-expression allowlist for op type. + tensor_dtype_regex_allowlist: Regular-expression allowlist for tensor + dtype. + tolerate_debug_op_creation_failures: Whether debug op creation failures + are to be tolerated. + """ + + _check_type(action, str) + self.action = action + + _check_type(debug_urls, list) + self.debug_urls = debug_urls + + self.debug_ops = debug_ops + + self.node_name_regex_allowlist = node_name_regex_allowlist + self.op_type_regex_allowlist = op_type_regex_allowlist + self.tensor_dtype_regex_allowlist = tensor_dtype_regex_allowlist + self.tolerate_debug_op_creation_failures = ( + tolerate_debug_op_creation_failures) + + +class OnRunEndRequest: + """Request to an on-run-end callback. + + The callback is invoked immediately before the wrapped run() call ends. + """ + + def __init__(self, + performed_action, + run_metadata=None, + client_graph_def=None, + tf_error=None): + """Constructor for `OnRunEndRequest`. + + Args: + performed_action: (`OnRunStartAction`) Actually-performed action by the + debug-wrapper session. + run_metadata: run_metadata output from the run() call (if any). + client_graph_def: (GraphDef) GraphDef from the client side, i.e., from + the python front end of TensorFlow. Can be obtained with + session.graph.as_graph_def(). + tf_error: (errors.OpError subtypes) TensorFlow OpError that occurred + during the run (if any). + """ + + _check_type(performed_action, str) + self.performed_action = performed_action + + if run_metadata is not None: + _check_type(run_metadata, config_pb2.RunMetadata) + self.run_metadata = run_metadata + self.client_graph_def = client_graph_def + self.tf_error = tf_error + + +class OnRunEndResponse: + """Response from an on-run-end callback.""" + + def __init__(self): + + # Currently only a placeholder. + pass + + +class BaseDebugWrapperSession(session.SessionInterface, metaclass=abc.ABCMeta): + """Base class of debug-wrapper session classes. + + Concrete classes that inherit from this class need to implement the abstract + methods such as on_session_init, on_run_start and on_run_end. + """ + + def __init__(self, sess, thread_name_filter=None, + pass_through_operrors=False): + """Constructor of `BaseDebugWrapperSession`. + + Args: + sess: An (unwrapped) TensorFlow session instance. It should be a subtype + of `BaseSession` or `tf.MonitoredSession`. + thread_name_filter: Regular-expression filter (allowlist) for name(s) of + thread(s) on which the wrapper session will be active. This regular + expression is used in a start-anchored fashion on the thread name, i.e., + by applying the `match` method of the compiled pattern. The default + `None` means that the wrapper session will be active on all threads. + E.g., r"MainThread$", r"QueueRunnerThread.*". + pass_through_operrors: If True, all captured OpErrors will be + propagated. By default this captures all OpErrors. + + Raises: + ValueError: On invalid `OnSessionInitAction` value. + NotImplementedError: If a non-DirectSession sess object is received. + """ + + _check_type(sess, (session.BaseSession, monitored_session.MonitoredSession)) + + # The session being wrapped. + self._sess = sess + self._thread_name_filter_pattern = (re.compile(thread_name_filter) + if thread_name_filter else None) + # TODO(cais/kstevens): Unittest this pass through feature. + self._pass_through_operrors = pass_through_operrors + + # Keeps track of number of run calls that have been performed on this + # debug-wrapper session. The count can be used for purposes such as + # displaying the state of the Session in a UI and determining a run + # number-dependent debug URL. + self._run_call_count = 0 + + # Invoke on-session-init callback. + response = self.on_session_init(OnSessionInitRequest(self._sess)) + _check_type(response, OnSessionInitResponse) + + if response.action == OnSessionInitAction.PROCEED: + pass + elif response.action == OnSessionInitAction.REMOTE_INSTR_LOOP: + # TODO(cais): Implement REMOTE_INSTR_LOOP + raise NotImplementedError( + "OnSessionInitAction REMOTE_INSTR_LOOP has not been " + "implemented.") + else: + raise ValueError( + "Invalid OnSessionInitAction value: %s" % response.action) + + self._default_session_context_manager = None + + # A cache for callables created from CallableOptions. + self._cached_callables_from_options = {} + + @property + def graph(self): + return self._sess.graph + + @property + def graph_def(self): + return self._sess.graph_def + + @property + def sess_str(self): + return self._sess.sess_str + + @property + def session(self): + return self._sess + + def run(self, + fetches, + feed_dict=None, + options=None, + run_metadata=None, + callable_runner=None, + callable_runner_args=None, + callable_options=None): + """Wrapper around Session.run() that inserts tensor watch options. + + Args: + fetches: Same as the `fetches` arg to regular `Session.run()`. + feed_dict: Same as the `feed_dict` arg to regular `Session.run()`. + options: Same as the `options` arg to regular `Session.run()`. + run_metadata: Same as the `run_metadata` arg to regular `Session.run()`. + callable_runner: A `callable` returned by `Session.make_callable()`. + If not `None`, `fetches` and `feed_dict` must both be `None`. + Mutually exclusive with `callable_options`. + callable_runner_args: An optional list of arguments to `callable_runner` + or for `callable_options`. + callable_options: An instance of `config_pb2.CallableOptions`, to be + used with `Session._make_callable_from_options()`. Mutually exclusive + with `callable_runner`. + + Returns: + Simply forwards the output of the wrapped `Session.run()` call. + + Raises: + ValueError: On invalid `OnRunStartAction` value. Or if `callable_runner` + is not `None` and either or both of `fetches` and `feed_dict` is `None`. + """ + if callable_runner and callable_options: + raise ValueError( + "callable_runner and callable_options are mutually exclusive, but " + "are both specified in this call to BaseDebugWrapperSession.run().") + + if callable_runner and (fetches or feed_dict): + raise ValueError( + "callable_runner and fetches/feed_dict are mutually exclusive, " + "but are used simultaneously.") + elif callable_options and (fetches or feed_dict): + raise ValueError( + "callable_options and fetches/feed_dict are mutually exclusive, " + "but are used simultaneously.") + + self.increment_run_call_count() + + def is_empty(x): + """Check whether a possibly nested structure is empty.""" + if not nest.is_nested(x): + return False + if isinstance(x, collections_abc.Mapping): + return is_empty(list(x.values())) + for item in x: + if not is_empty(item): + return False + return True + + empty_fetches = is_empty(fetches) + if empty_fetches: + tf_logging.info( + "Due to empty fetches, tfdbg Session wrapper is letting a " + "Session.run pass through without any debugging actions.") + if self._is_disabled_thread() or empty_fetches: + if callable_runner: + return callable_runner(*callable_runner_args) + elif callable_options: + # pylint:disable=protected-access + return self._sess._make_callable_from_options( + callable_options)(*callable_runner_args) + # pylint:enable=protected-access + else: + return self._sess.run(fetches, + feed_dict=feed_dict, + options=options, + run_metadata=run_metadata) + + # Invoke on-run-start callback and obtain response. + run_start_resp = self.on_run_start( + OnRunStartRequest(fetches, feed_dict, options, run_metadata, + self._run_call_count, + is_callable_runner=bool(callable_runner))) + _check_type(run_start_resp, OnRunStartResponse) + + if run_start_resp.action == OnRunStartAction.DEBUG_RUN: + retvals, run_end_req = self._run_with_debugging( + run_start_resp, fetches, feed_dict, options, run_metadata, + callable_runner, callable_runner_args, callable_options) + elif run_start_resp.action == OnRunStartAction.PROFILE_RUN: + retvals, run_end_req = self._run_with_profiling( + run_start_resp, fetches, feed_dict, options, run_metadata, + callable_runner, callable_runner_args, callable_options) + elif run_start_resp.action == OnRunStartAction.NON_DEBUG_RUN: + # Invoke run() method of the wrapped session. + if callable_runner: + retvals = callable_runner(*callable_runner_args) + elif callable_options: + # pylint:disable=protected-access + callable_object = self._sess._make_callable_from_options( + callable_options) + # pylint:enable=protected-access + retvals = callable_object(*callable_runner_args) + else: + retvals = self._sess.run( + fetches, + feed_dict=feed_dict, + options=options, + run_metadata=run_metadata) + + # Prepare arg for the on-run-end callback. + run_end_req = OnRunEndRequest(run_start_resp.action) + else: + raise ValueError( + "Invalid OnRunStartAction value: %s" % run_start_resp.action) + + # Invoke on-run-end callback and obtain response. + run_end_resp = self.on_run_end(run_end_req) + _check_type(run_end_resp, OnRunEndResponse) + # Currently run_end_resp is only a placeholder. No action is taken on it. + + return retvals + + def _run_with_debugging(self, + run_start_resp, + fetches, + feed_dict, + options, + run_metadata, + callable_runner, + callable_runner_args, + callable_options): + """Perform a session.run() or callable with debugging.""" + # Decorate RunOption to fill in debugger tensor watch specifications. + decorated_run_options = None + if callable_options: + callable_options_id = id(callable_options) + if callable_options_id not in self._cached_callables_from_options: + # Make a copy of callable_options to avoid mutating it. + new_callable_options = config_pb2.CallableOptions() + new_callable_options.CopyFrom(callable_options) + decorated_run_options = new_callable_options.run_options + else: + decorated_run_options = options or config_pb2.RunOptions() + + run_metadata = run_metadata or config_pb2.RunMetadata() + + if decorated_run_options: + self._decorate_run_options_for_debug( + decorated_run_options, + run_start_resp.debug_urls, + debug_ops=run_start_resp.debug_ops, + node_name_regex_allowlist=(run_start_resp.node_name_regex_allowlist), + op_type_regex_allowlist=run_start_resp.op_type_regex_allowlist, + tensor_dtype_regex_allowlist=( + run_start_resp.tensor_dtype_regex_allowlist), + tolerate_debug_op_creation_failures=( + run_start_resp.tolerate_debug_op_creation_failures)) + + # Invoke the run() method of the wrapped Session. Catch any TensorFlow + # runtime errors. + tf_error = None + try: + if callable_runner: + retvals = callable_runner(*callable_runner_args, + options=decorated_run_options, + run_metadata=run_metadata) + elif callable_options: + # pylint:disable=protected-access + if callable_options_id in self._cached_callables_from_options: + callable_object = self._cached_callables_from_options[ + callable_options_id] + else: + callable_object = self._sess._make_callable_from_options( + new_callable_options) + self._cached_callables_from_options[ + callable_options_id] = callable_object + # pylint:enable=protected-access + retvals = callable_object( + *callable_runner_args, run_metadata=run_metadata) + else: + retvals = self._sess.run(fetches, + feed_dict=feed_dict, + options=decorated_run_options, + run_metadata=run_metadata) + except errors.OpError as op_error: + if self._pass_through_operrors: + raise op_error + tf_error = op_error + retvals = op_error + + return retvals, OnRunEndRequest( + run_start_resp.action, + run_metadata=run_metadata, + client_graph_def=self._sess.graph.as_graph_def(), + tf_error=tf_error) + + def _run_with_profiling(self, + run_start_resp, + fetches, + feed_dict, + options, + run_metadata, + callable_runner, + callable_runner_args, + callable_options): + """Perform a session.run() or callable with profiling.""" + # Decorate RunOption to fill in debugger tensor watch specifications. + decorated_run_options = None + if callable_options: + callable_options_id = id(callable_options) + if callable_options_id not in self._cached_callables_from_options: + # Make a copy of callable_options to avoid mutating it. + new_callable_options = config_pb2.CallableOptions() + new_callable_options.CopyFrom(callable_options) + decorated_run_options = new_callable_options.run_options + else: + decorated_run_options = options or config_pb2.RunOptions() + self._decorate_run_options_for_profile(decorated_run_options) + + run_metadata = run_metadata or config_pb2.RunMetadata() + if callable_runner: + retvals = callable_runner(*callable_runner_args, + options=decorated_run_options, + run_metadata=run_metadata) + elif callable_options: + # pylint:disable=protected-access + callable_object = self._sess._make_callable_from_options( + new_callable_options) + # pylint:enable=protected-access + retvals = callable_object( + *callable_runner_args, run_metadata=run_metadata) + else: + retvals = self._sess.run(fetches, + feed_dict=feed_dict, + options=decorated_run_options, + run_metadata=run_metadata) + return retvals, OnRunEndRequest( + run_start_resp.action, + run_metadata=run_metadata, + client_graph_def=self._sess.graph.as_graph_def()) + + def _is_disabled_thread(self): + thread_name = threading.current_thread().name or "" + return (self._thread_name_filter_pattern and + not self._thread_name_filter_pattern.match(thread_name)) + + def run_step_fn(self, step_fn): + return step_fn( + monitored_session.MonitoredSession.StepContext(self._sess, self.run)) + + def partial_run_setup(self, fetches, feeds=None): + """Sets up the feeds and fetches for partial runs in the session.""" + raise NotImplementedError( + "partial_run_setup is not implemented for debug-wrapper sessions.") + + def partial_run(self, handle, fetches, feed_dict=None): + raise NotImplementedError( + "partial_run is not implemented for debug-wrapper sessions.") + + def list_devices(self, *args, **kwargs): + return self._sess.list_devices(*args, **kwargs) + + def reset(self, *args, **kwargs): + return self._sess.reset(*args, **kwargs) + + def make_callable(self, + fetches, + feed_list=None, + accept_options=False): + runner = self._sess.make_callable( + fetches, feed_list=feed_list, accept_options=True) + def wrapped_runner(*runner_args, **kwargs): + return self.run(None, + feed_dict=None, + options=kwargs.get("options", None), + run_metadata=kwargs.get("run_metadata", None), + callable_runner=runner, + callable_runner_args=runner_args) + return wrapped_runner + + def _make_callable_from_options(self, callable_options): + def wrapped_runner(*feed_values, **kwargs): + return self.run(None, + run_metadata=kwargs.get("run_metadata", None), + callable_options=callable_options, + callable_runner_args=feed_values) + return wrapped_runner + + @property + def run_call_count(self): + return self._run_call_count + + def increment_run_call_count(self): + self._run_call_count += 1 + + def _is_disk_usage_reset_each_run(self): + """Indicates whether disk usage is reset after each Session.run. + + Subclasses that clean up the disk usage after every run should + override this protected method. + + Returns: + (`bool`) Whether the disk usage amount is reset to zero after + each Session.run. + """ + return False + + def _decorate_run_options_for_debug( + self, + run_options, + debug_urls, + debug_ops="DebugIdentity", + node_name_regex_allowlist=None, + op_type_regex_allowlist=None, + tensor_dtype_regex_allowlist=None, + tolerate_debug_op_creation_failures=False): + """Modify a RunOptions object for debug tensor watching. + + Specifies request for outputting partition graphs. Adds + debug_tensor_watch_opts with proper debug URLs. + + Args: + run_options: (RunOptions) the modified RunOptions object. + debug_urls: (list of str) debug URLs to be entered in run_options. + debug_tensor_watch_opts. + debug_ops: (str or list of str) debug op(s) to be used by the debugger. + node_name_regex_allowlist: Regular-expression allowlist for node + name. + op_type_regex_allowlist: Regular-expression allowlist for op type. + tensor_dtype_regex_allowlist: Regular-expression allowlist for tensor + dtype. + tolerate_debug_op_creation_failures: Whether debug op creation failures + are to be tolerated. + """ + + run_options.output_partition_graphs = True + debug_utils.watch_graph( + run_options, + self._sess.graph, + debug_urls=debug_urls, + debug_ops=debug_ops, + node_name_regex_allowlist=node_name_regex_allowlist, + op_type_regex_allowlist=op_type_regex_allowlist, + tensor_dtype_regex_allowlist=tensor_dtype_regex_allowlist, + tolerate_debug_op_creation_failures=tolerate_debug_op_creation_failures, + reset_disk_byte_usage=(self._run_call_count == 1 or + self._is_disk_usage_reset_each_run())) + + def _decorate_run_options_for_profile(self, run_options): + """Modify a RunOptions object for profiling TensorFlow graph execution. + + Args: + run_options: (RunOptions) the modified RunOptions object. + """ + + run_options.trace_level = config_pb2.RunOptions.FULL_TRACE + + @abc.abstractmethod + def on_session_init(self, request): + """Callback invoked during construction of the debug-wrapper session. + + This is a blocking callback. + The invocation happens right before the constructor ends. + + Args: + request: (`OnSessionInitRequest`) callback request carrying information + such as the session being wrapped. + + Returns: + An instance of `OnSessionInitResponse`. + """ + + @abc.abstractmethod + def on_run_start(self, request): + """Callback invoked on run() calls to the debug-wrapper session. + + This is a blocking callback. + The invocation happens after the wrapper's run() call is entered, + after an increment of run call counter. + + Args: + request: (`OnRunStartRequest`) callback request object carrying + information about the run call such as the fetches, feed dict, run + options, run metadata, and how many `run()` calls to this wrapper + session have occurred. + + Returns: + An instance of `OnRunStartResponse`, carrying information to + debug URLs used to watch the tensors. + """ + + @abc.abstractmethod + def on_run_end(self, request): + """Callback invoked on run() calls to the debug-wrapper session. + + This is a blocking callback. + The invocation happens right before the wrapper exits its run() call. + + Args: + request: (`OnRunEndRequest`) callback request object carrying information + such as the actual action performed by the session wrapper for the + run() call. + + Returns: + An instance of `OnRunStartResponse`. + """ + + def as_default(self): + return stack.default_session(self) + + def __enter__(self): + if self._default_session_context_manager is None: + self._default_session_context_manager = self.as_default() + return self._default_session_context_manager.__enter__() + + def __exit__(self, exec_type, exec_value, exec_tb): + self._default_session_context_manager.__exit__( + exec_type, exec_value, exec_tb) + + def __del__(self): + if hasattr(self._sess, "__del__"): + self._sess.__del__() + + def close(self): + self._sess.close() + + # TODO(cais): Add _node_name_regex_allowlist and + # _node_op_type_regex_allowlist. + + def should_stop(self): + if hasattr(self._sess, "should_stop"): + return self._sess.should_stop() + else: + raise ValueError( + "The wrapped session %r does not have a method called 'should_stop'. " + "Do you intend to wrap a tf.MonitoredSession instead?" % self._sess) + + +class WatchOptions: + """Type for return values of watch_fn.""" + + def __init__(self, + debug_ops=None, + node_name_regex_allowlist=None, + op_type_regex_allowlist=None, + tensor_dtype_regex_allowlist=None, + tolerate_debug_op_creation_failures=False): + """Constructor of WatchOptions: Debug watch options. + + Used as return values of `watch_fn`s. + + Args: + debug_ops: (`str` or `list of str`) Debug ops to be used. + node_name_regex_allowlist: Regular-expression allowlist for node_name, + e.g., `"(weight_[0-9]+|bias_.*)"` + op_type_regex_allowlist: Regular-expression allowlist for the op type of + nodes, e.g., `"(Variable|Add)"`. + If both `node_name_regex_allowlist` and `op_type_regex_allowlist` + are set, the two filtering operations will occur in a logical `AND` + relation. In other words, a node will be included if and only if it + hits both allowlists. + tensor_dtype_regex_allowlist: Regular-expression allowlist for Tensor + data type, e.g., `"^int.*"`. + This allowlist operates in logical `AND` relations to the two allowlists + above. + tolerate_debug_op_creation_failures: (`bool`) whether debug op creation + failures (e.g., due to dtype incompatibility) are to be tolerated by not + throwing exceptions. + """ + if debug_ops: + self.debug_ops = debug_ops + else: + self.debug_ops = ["DebugIdentity"] + self.node_name_regex_allowlist = node_name_regex_allowlist + self.op_type_regex_allowlist = op_type_regex_allowlist + self.tensor_dtype_regex_allowlist = tensor_dtype_regex_allowlist + self.tolerate_debug_op_creation_failures = ( + tolerate_debug_op_creation_failures) + + def __repr__(self): + return ("WatchOptions(debug_ops=%r, node_name_regex_allowlist=%r, " + "op_type_regex_allowlist=%r, tensor_dtype_regex_allowlist=%r, " + "tolerate_debug_op_creation_failures=%r)" % + (self.debug_ops, self.node_name_regex_allowlist, + self.op_type_regex_allowlist, self.tensor_dtype_regex_allowlist, + self.tolerate_debug_op_creation_failures)) + + +class NonInteractiveDebugWrapperSession(BaseDebugWrapperSession): + """Base class for non-interactive (i.e., non-CLI) debug wrapper sessions.""" + + def __init__(self, sess, watch_fn=None, thread_name_filter=None, + pass_through_operrors=False): + """Constructor of NonInteractiveDebugWrapperSession. + + Args: + sess: The TensorFlow `Session` object being wrapped. + watch_fn: (`Callable`) A Callable that maps the fetches and feeds of a + debugged `Session.run()` call to `WatchOptions.` + * Args: + * `fetches`: the fetches to the `Session.run()` call. + * `feeds`: the feeds to the `Session.run()` call. + + * Returns: + (`tf_debug.WatchOptions`) An object containing debug options including + the debug ops to use, the node names, op types and/or tensor data + types to watch, etc. See the documentation of `tf_debug.WatchOptions` + for more details. + thread_name_filter: Regular-expression white list for threads on which the + wrapper session will be active. See doc of `BaseDebugWrapperSession` for + more details. + pass_through_operrors: If true, all captured OpErrors will be + propagated. By default this captures all OpErrors. + Raises: + TypeError: If a non-None `watch_fn` is specified and it is not callable. + """ + + BaseDebugWrapperSession.__init__( + self, sess, thread_name_filter=thread_name_filter, + pass_through_operrors=pass_through_operrors) + + self._watch_fn = None + if watch_fn is not None: + if not callable(watch_fn): + raise TypeError("watch_fn is not callable") + self._watch_fn = watch_fn + + def on_session_init(self, request): + """See doc of BaseDebugWrapperSession.on_run_start.""" + + return OnSessionInitResponse(OnSessionInitAction.PROCEED) + + @abc.abstractmethod + def prepare_run_debug_urls(self, fetches, feed_dict): + """Abstract method to be implemented by concrete subclasses. + + This method prepares the run-specific debug URL(s). + + Args: + fetches: Same as the `fetches` argument to `Session.run()` + feed_dict: Same as the `feed_dict` argument to `Session.run()` + + Returns: + debug_urls: (`str` or `list` of `str`) Debug URLs to be used in + this `Session.run()` call. + """ + + def on_run_start(self, request): + """See doc of BaseDebugWrapperSession.on_run_start.""" + + debug_urls, watch_opts = self._prepare_run_watch_config( + request.fetches, request.feed_dict) + + return OnRunStartResponse( + OnRunStartAction.DEBUG_RUN, + debug_urls, + debug_ops=watch_opts.debug_ops, + node_name_regex_allowlist=watch_opts.node_name_regex_allowlist, + op_type_regex_allowlist=watch_opts.op_type_regex_allowlist, + tensor_dtype_regex_allowlist=watch_opts.tensor_dtype_regex_allowlist, + tolerate_debug_op_creation_failures=( + watch_opts.tolerate_debug_op_creation_failures)) + + def _prepare_run_watch_config(self, fetches, feed_dict): + """Get the debug_urls, and node/op allowlists for the current run() call. + + Args: + fetches: Same as the `fetches` argument to `Session.run()`. + feed_dict: Same as the `feed_dict argument` to `Session.run()`. + + Returns: + debug_urls: (str or list of str) Debug URLs for the current run() call. + Currently, the list consists of only one URL that is a file:// URL. + watch_options: (WatchOptions) The return value of a watch_fn, containing + options including debug_ops, and allowlists. + """ + + debug_urls = self.prepare_run_debug_urls(fetches, feed_dict) + if self._watch_fn is None: + watch_options = WatchOptions() + else: + watch_options = self._watch_fn(fetches, feed_dict) + if isinstance(watch_options, tuple): + # For legacy return type (tuples). + watch_options = WatchOptions(*watch_options) + + return debug_urls, watch_options + + def on_run_end(self, request): + """See doc of BaseDebugWrapperSession.on_run_end.""" + + return OnRunEndResponse() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/grpc_wrapper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/grpc_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6c9fde5ff06e6f7c2d307433b22220a2b701e2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/grpc_wrapper.py @@ -0,0 +1,213 @@ +# 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. +# ============================================================================== +"""Debugger wrapper session that sends debug data to file:// URLs.""" +import signal +import sys +import traceback + +from tensorflow.python.debug.lib import common +from tensorflow.python.debug.wrappers import framework + + +def publish_traceback(debug_server_urls, + graph, + feed_dict, + fetches, + old_graph_version): + """Publish traceback and source code if graph version is new. + + `graph.version` is compared with `old_graph_version`. If the former is higher + (i.e., newer), the graph traceback and the associated source code is sent to + the debug server at the specified gRPC URLs. + + Args: + debug_server_urls: A single gRPC debug server URL as a `str` or a `list` of + debug server URLs. + graph: A Python `tf.Graph` object. + feed_dict: Feed dictionary given to the `Session.run()` call. + fetches: Fetches from the `Session.run()` call. + old_graph_version: Old graph version to compare to. + + Returns: + If `graph.version > old_graph_version`, the new graph version as an `int`. + Else, the `old_graph_version` is returned. + """ + # TODO(cais): Consider moving this back to the top, after grpc becomes a + # pip dependency of tensorflow or tf_debug. + # pylint:disable=g-import-not-at-top + from tensorflow.python.debug.lib import source_remote + # pylint:enable=g-import-not-at-top + if graph.version > old_graph_version: + run_key = common.get_run_key(feed_dict, fetches) + source_remote.send_graph_tracebacks( + debug_server_urls, run_key, traceback.extract_stack(), graph, + send_source=True) + return graph.version + else: + return old_graph_version + + +class GrpcDebugWrapperSession(framework.NonInteractiveDebugWrapperSession): + """Debug Session wrapper that send debug data to gRPC stream(s).""" + + def __init__(self, + sess, + grpc_debug_server_addresses, + watch_fn=None, + thread_name_filter=None): + """Constructor of DumpingDebugWrapperSession. + + Args: + sess: The TensorFlow `Session` object being wrapped. + grpc_debug_server_addresses: (`str` or `list` of `str`) Single or a list + of the gRPC debug server addresses, in the format of + , with or without the "grpc://" prefix. For example: + "localhost:7000", + ["localhost:7000", "192.168.0.2:8000"] + watch_fn: (`Callable`) A Callable that can be used to define per-run + debug ops and watched tensors. See the doc of + `NonInteractiveDebugWrapperSession.__init__()` for details. + thread_name_filter: Regular-expression white list for threads on which the + wrapper session will be active. See doc of `BaseDebugWrapperSession` for + more details. + + Raises: + TypeError: If `grpc_debug_server_addresses` is not a `str` or a `list` + of `str`. + """ + framework.NonInteractiveDebugWrapperSession.__init__( + self, sess, watch_fn=watch_fn, thread_name_filter=thread_name_filter) + + if isinstance(grpc_debug_server_addresses, str): + self._grpc_debug_server_urls = [ + self._normalize_grpc_url(grpc_debug_server_addresses)] + elif isinstance(grpc_debug_server_addresses, list): + self._grpc_debug_server_urls = [] + for address in grpc_debug_server_addresses: + if not isinstance(address, str): + raise TypeError( + "Expected type str in list grpc_debug_server_addresses, " + "received type %s" % type(address)) + self._grpc_debug_server_urls.append(self._normalize_grpc_url(address)) + else: + raise TypeError( + "Expected type str or list in grpc_debug_server_addresses, " + "received type %s" % type(grpc_debug_server_addresses)) + + def prepare_run_debug_urls(self, fetches, feed_dict): + """Implementation of abstract method in superclass. + + See doc of `NonInteractiveDebugWrapperSession.prepare_run_debug_urls()` + for details. + + Args: + fetches: Same as the `fetches` argument to `Session.run()` + feed_dict: Same as the `feed_dict` argument to `Session.run()` + + Returns: + debug_urls: (`str` or `list` of `str`) file:// debug URLs to be used in + this `Session.run()` call. + """ + + return self._grpc_debug_server_urls + + def _normalize_grpc_url(self, address): + return (common.GRPC_URL_PREFIX + address + if not address.startswith(common.GRPC_URL_PREFIX) else address) + + +def _signal_handler(unused_signal, unused_frame): + while True: + response = input("\nSIGINT received. Quit program? (Y/n): ").strip() + if response in ("", "Y", "y"): + sys.exit(0) + elif response in ("N", "n"): + break + + +def register_signal_handler(): + try: + signal.signal(signal.SIGINT, _signal_handler) + except ValueError: + # This can happen if we are not in the MainThread. + pass + + +class TensorBoardDebugWrapperSession(GrpcDebugWrapperSession): + """A tfdbg Session wrapper that can be used with TensorBoard Debugger Plugin. + + This wrapper is the same as `GrpcDebugWrapperSession`, except that it uses a + predefined `watch_fn` that + 1) uses `DebugIdentity` debug ops with the `gated_grpc` attribute set to + `True` to allow the interactive enabling and disabling of tensor + breakpoints. + 2) watches all tensors in the graph. + This saves the need for the user to define a `watch_fn`. + """ + + def __init__(self, + sess, + grpc_debug_server_addresses, + thread_name_filter=None, + send_traceback_and_source_code=True): + """Constructor of TensorBoardDebugWrapperSession. + + Args: + sess: The `tf.compat.v1.Session` instance to be wrapped. + grpc_debug_server_addresses: gRPC address(es) of debug server(s), as a + `str` or a `list` of `str`s. E.g., "localhost:2333", + "grpc://localhost:2333", ["192.168.0.7:2333", "192.168.0.8:2333"]. + thread_name_filter: Optional filter for thread names. + send_traceback_and_source_code: Whether traceback of graph elements and + the source code are to be sent to the debug server(s). + """ + def _gated_grpc_watch_fn(fetches, feeds): + del fetches, feeds # Unused. + return framework.WatchOptions( + debug_ops=["DebugIdentity(gated_grpc=true)"]) + + super().__init__( + sess, + grpc_debug_server_addresses, + watch_fn=_gated_grpc_watch_fn, + thread_name_filter=thread_name_filter) + + self._send_traceback_and_source_code = send_traceback_and_source_code + # Keeps track of the latest version of Python graph object that has been + # sent to the debug servers. + self._sent_graph_version = -1 + + register_signal_handler() + + def run(self, + fetches, + feed_dict=None, + options=None, + run_metadata=None, + callable_runner=None, + callable_runner_args=None, + callable_options=None): + if self._send_traceback_and_source_code: + self._sent_graph_version = publish_traceback( + self._grpc_debug_server_urls, self.graph, feed_dict, fetches, + self._sent_graph_version) + return super().run( + fetches, + feed_dict=feed_dict, + options=options, + run_metadata=run_metadata, + callable_runner=callable_runner, + callable_runner_args=callable_runner_args, + callable_options=callable_options) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/hooks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c7515875f209c3014e593a20932477390ee63d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/hooks.py @@ -0,0 +1,341 @@ +# 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. +# ============================================================================== +"""tfdbg CLI as SessionRunHook.""" + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.debug.lib import debug_utils +from tensorflow.python.debug.wrappers import dumping_wrapper +from tensorflow.python.debug.wrappers import framework +from tensorflow.python.debug.wrappers import grpc_wrapper +from tensorflow.python.debug.wrappers import local_cli_wrapper +from tensorflow.python.training import session_run_hook + + +class LocalCLIDebugHook(session_run_hook.SessionRunHook): + """Command-line-interface debugger hook. + + Can be used as a hook for `tf.compat.v1.train.MonitoredSession`s and + `tf.estimator.Estimator`s. Provides a substitute for + `tfdbg.LocalCLIDebugWrapperSession` in cases where the session is not directly + available. + """ + + def __init__(self, + ui_type="readline", + dump_root=None, + thread_name_filter=None, + config_file_path=None): + """Create a local debugger command-line interface (CLI) hook. + + Args: + ui_type: (`str`) requested user-interface type. Currently supported: + (readline). + dump_root: (`str`) optional path to the dump root directory. Must be a + directory that does not exist or an empty directory. If the directory + does not exist, it will be created by the debugger core during debug + `run()` calls and removed afterwards. + thread_name_filter: Regular-expression white list for threads on which the + wrapper session will be active. See doc of `BaseDebugWrapperSession` for + more details. + config_file_path: Optional override to the default configuration file + path, which is at `${HOME}/.tfdbg_config`. + """ + + self._ui_type = ui_type + self._dump_root = dump_root + self._thread_name_filter = thread_name_filter + self._session_wrapper = None + self._pending_tensor_filters = {} + self._config_file_path = config_file_path + + def add_tensor_filter(self, filter_name, tensor_filter): + """Add a tensor filter. + + See doc of `LocalCLIDebugWrapperSession.add_tensor_filter()` for details. + Override default behavior to accommodate the possibility of this method + being + called prior to the initialization of the underlying + `LocalCLIDebugWrapperSession` object. + + Args: + filter_name: See doc of `LocalCLIDebugWrapperSession.add_tensor_filter()` + for details. + tensor_filter: See doc of + `LocalCLIDebugWrapperSession.add_tensor_filter()` for details. + """ + + if self._session_wrapper: + self._session_wrapper.add_tensor_filter(filter_name, tensor_filter) + else: + self._pending_tensor_filters[filter_name] = tensor_filter + + def begin(self): + pass + + def before_run(self, run_context): + if not self._session_wrapper: + self._session_wrapper = local_cli_wrapper.LocalCLIDebugWrapperSession( + run_context.session, + ui_type=self._ui_type, + dump_root=self._dump_root, + thread_name_filter=self._thread_name_filter, + config_file_path=self._config_file_path) + + # Actually register tensor filters registered prior to the construction + # of the underlying LocalCLIDebugWrapperSession object. + for filter_name in self._pending_tensor_filters: + self._session_wrapper.add_tensor_filter( + filter_name, self._pending_tensor_filters[filter_name]) + + # Increment run call counter. + self._session_wrapper.increment_run_call_count() + + # Adapt run_context to an instance of OnRunStartRequest for invoking + # superclass on_run_start(). + on_run_start_request = framework.OnRunStartRequest( + run_context.original_args.fetches, run_context.original_args.feed_dict, + None, None, self._session_wrapper.run_call_count) + + on_run_start_response = self._session_wrapper.on_run_start( + on_run_start_request) + self._performed_action = on_run_start_response.action + + run_args = session_run_hook.SessionRunArgs( + None, feed_dict=None, options=config_pb2.RunOptions()) + if self._performed_action == framework.OnRunStartAction.DEBUG_RUN: + # pylint: disable=protected-access + self._session_wrapper._decorate_run_options_for_debug( + run_args.options, + on_run_start_response.debug_urls, + debug_ops=on_run_start_response.debug_ops, + node_name_regex_allowlist=( + on_run_start_response.node_name_regex_allowlist), + op_type_regex_allowlist=( + on_run_start_response.op_type_regex_allowlist), + tensor_dtype_regex_allowlist=( + on_run_start_response.tensor_dtype_regex_allowlist), + tolerate_debug_op_creation_failures=( + on_run_start_response.tolerate_debug_op_creation_failures)) + # pylint: enable=protected-access + elif self._performed_action == framework.OnRunStartAction.PROFILE_RUN: + # pylint: disable=protected-access + self._session_wrapper._decorate_run_options_for_profile(run_args.options) + # pylint: enable=protected-access + + return run_args + + def after_run(self, run_context, run_values): + # Adapt run_context and run_values to OnRunEndRequest and invoke superclass + # on_run_end() + on_run_end_request = framework.OnRunEndRequest(self._performed_action, + run_values.run_metadata) + self._session_wrapper.on_run_end(on_run_end_request) + + +class DumpingDebugHook(session_run_hook.SessionRunHook): + """A debugger hook that dumps debug data to filesystem. + + Can be used as a hook for `tf.compat.v1.train.MonitoredSession`s and + `tf.estimator.Estimator`s. + """ + + def __init__(self, + session_root, + watch_fn=None, + thread_name_filter=None): + """Create a local debugger command-line interface (CLI) hook. + + Args: + session_root: See doc of + `dumping_wrapper.DumpingDebugWrapperSession.__init__`. + watch_fn: See doc of + `dumping_wrapper.DumpingDebugWrapperSession.__init__`. + thread_name_filter: Regular-expression white list for threads on which the + wrapper session will be active. See doc of `BaseDebugWrapperSession` for + more details. + """ + + self._session_root = session_root + self._watch_fn = watch_fn + self._thread_name_filter = thread_name_filter + self._session_wrapper = None + + def begin(self): + pass + + def before_run(self, run_context): + reset_disk_byte_usage = False + if not self._session_wrapper: + self._session_wrapper = dumping_wrapper.DumpingDebugWrapperSession( + run_context.session, + self._session_root, + watch_fn=self._watch_fn, + thread_name_filter=self._thread_name_filter) + reset_disk_byte_usage = True + + self._session_wrapper.increment_run_call_count() + + # pylint: disable=protected-access + debug_urls, watch_options = self._session_wrapper._prepare_run_watch_config( + run_context.original_args.fetches, run_context.original_args.feed_dict) + # pylint: enable=protected-access + run_options = config_pb2.RunOptions() + debug_utils.watch_graph( + run_options, + run_context.session.graph, + debug_urls=debug_urls, + debug_ops=watch_options.debug_ops, + node_name_regex_allowlist=watch_options.node_name_regex_allowlist, + op_type_regex_allowlist=watch_options.op_type_regex_allowlist, + tensor_dtype_regex_allowlist=watch_options.tensor_dtype_regex_allowlist, + tolerate_debug_op_creation_failures=( + watch_options.tolerate_debug_op_creation_failures), + reset_disk_byte_usage=reset_disk_byte_usage) + + run_args = session_run_hook.SessionRunArgs( + None, feed_dict=None, options=run_options) + return run_args + + def after_run(self, run_context, run_values): + pass + + +class GrpcDebugHook(session_run_hook.SessionRunHook): + """A hook that streams debugger-related events to any grpc_debug_server. + + For example, the debugger data server is a grpc_debug_server. The debugger + data server writes debugger-related events it receives via GRPC to logdir. + This enables debugging features in Tensorboard such as health pills. + + When the arguments of debug_utils.watch_graph changes, strongly consider + changing arguments here too so that features are available to tflearn users. + + Can be used as a hook for `tf.compat.v1.train.MonitoredSession`s and + `tf.estimator.Estimator`s. + """ + + def __init__(self, + grpc_debug_server_addresses, + watch_fn=None, + thread_name_filter=None): + """Constructs a GrpcDebugHook. + + Args: + grpc_debug_server_addresses: (`list` of `str`) A list of the gRPC debug + server addresses, in the format of , with or without the + "grpc://" prefix. For example: ["localhost:7000", "192.168.0.2:8000"] + watch_fn: A function that allows for customizing which ops to watch at + which specific steps. See doc of + `dumping_wrapper.DumpingDebugWrapperSession.__init__` for details. + thread_name_filter: Regular-expression white list for threads on which the + wrapper session will be active. See doc of `BaseDebugWrapperSession` for + more details. + """ + self._grpc_debug_wrapper_session = None + self._thread_name_filter = thread_name_filter + self._grpc_debug_server_addresses = ( + grpc_debug_server_addresses + if isinstance(grpc_debug_server_addresses, list) else + [grpc_debug_server_addresses]) + + self._watch_fn = watch_fn + + def before_run(self, run_context): + """Called right before a session is run. + + Args: + run_context: A session_run_hook.SessionRunContext. Encapsulates + information on the run. + + Returns: + A session_run_hook.SessionRunArgs object. + """ + + if not self._grpc_debug_wrapper_session: + self._grpc_debug_wrapper_session = grpc_wrapper.GrpcDebugWrapperSession( + run_context.session, + self._grpc_debug_server_addresses, + watch_fn=self._watch_fn, + thread_name_filter=self._thread_name_filter) + + fetches = run_context.original_args.fetches + feed_dict = run_context.original_args.feed_dict + watch_options = self._watch_fn(fetches, feed_dict) + run_options = config_pb2.RunOptions() + debug_utils.watch_graph( + run_options, + run_context.session.graph, + debug_urls=self._grpc_debug_wrapper_session.prepare_run_debug_urls( + fetches, feed_dict), + debug_ops=watch_options.debug_ops, + node_name_regex_allowlist=watch_options.node_name_regex_allowlist, + op_type_regex_allowlist=watch_options.op_type_regex_allowlist, + tensor_dtype_regex_allowlist=watch_options.tensor_dtype_regex_allowlist, + tolerate_debug_op_creation_failures=( + watch_options.tolerate_debug_op_creation_failures)) + + return session_run_hook.SessionRunArgs( + None, feed_dict=None, options=run_options) + + +class TensorBoardDebugHook(GrpcDebugHook): + """A tfdbg hook that can be used with TensorBoard Debugger Plugin. + + This hook is the same as `GrpcDebugHook`, except that it uses a predefined + `watch_fn` that + 1) uses `DebugIdentity` debug ops with the `gated_grpc` attribute set to + `True`, to allow the interactive enabling and disabling of tensor + breakpoints. + 2) watches all tensors in the graph. + This saves the need for the user to define a `watch_fn`. + """ + + def __init__(self, + grpc_debug_server_addresses, + thread_name_filter=None, + send_traceback_and_source_code=True): + """Constructor of TensorBoardDebugHook. + + Args: + grpc_debug_server_addresses: gRPC address(es) of debug server(s), as a + `str` or a `list` of `str`s. E.g., "localhost:2333", + "grpc://localhost:2333", ["192.168.0.7:2333", "192.168.0.8:2333"]. + thread_name_filter: Optional filter for thread names. + send_traceback_and_source_code: Whether traceback of graph elements and + the source code are to be sent to the debug server(s). + """ + + def _gated_grpc_watch_fn(fetches, feeds): + del fetches, feeds # Unused. + return framework.WatchOptions( + debug_ops=["DebugIdentity(gated_grpc=true)"]) + + super(TensorBoardDebugHook, self).__init__( + grpc_debug_server_addresses, + watch_fn=_gated_grpc_watch_fn, + thread_name_filter=thread_name_filter) + + self._grpc_debug_server_addresses = grpc_debug_server_addresses + self._send_traceback_and_source_code = send_traceback_and_source_code + self._sent_graph_version = -1 + grpc_wrapper.register_signal_handler() + + def before_run(self, run_context): + if self._send_traceback_and_source_code: + self._sent_graph_version = grpc_wrapper.publish_traceback( + self._grpc_debug_server_addresses, run_context.session.graph, + run_context.original_args.feed_dict, + run_context.original_args.fetches, self._sent_graph_version) + return super(TensorBoardDebugHook, self).before_run(run_context) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/local_cli_wrapper.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/local_cli_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..91a2beed8b2da4df8500830eb665b890bb069a20 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/debug/wrappers/local_cli_wrapper.py @@ -0,0 +1,636 @@ +# 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. +# ============================================================================== +"""Debugger Wrapper Session Consisting of a Local Curses-based CLI.""" +import argparse +import os +import sys +import tempfile + +from tensorflow.python.debug.cli import analyzer_cli +from tensorflow.python.debug.cli import cli_config +from tensorflow.python.debug.cli import cli_shared +from tensorflow.python.debug.cli import command_parser +from tensorflow.python.debug.cli import debugger_cli_common +from tensorflow.python.debug.cli import profile_analyzer_cli +from tensorflow.python.debug.cli import ui_factory +from tensorflow.python.debug.lib import common +from tensorflow.python.debug.lib import debug_data +from tensorflow.python.debug.wrappers import framework +from tensorflow.python.lib.io import file_io + + +_DUMP_ROOT_PREFIX = "tfdbg_" + + +# TODO(donglin) Remove use_random_config_path after b/137652456 is fixed. +class LocalCLIDebugWrapperSession(framework.BaseDebugWrapperSession): + """Concrete subclass of BaseDebugWrapperSession implementing a local CLI. + + This class has all the methods that a `session.Session` object has, in order + to support debugging with minimal code changes. Invoking its `run()` method + will launch the command-line interface (CLI) of tfdbg. + """ + + def __init__(self, + sess, + dump_root=None, + ui_type="readline", + thread_name_filter=None, + config_file_path=False): + """Constructor of LocalCLIDebugWrapperSession. + + Args: + sess: The TensorFlow `Session` object being wrapped. + dump_root: (`str`) optional path to the dump root directory. Must be a + directory that does not exist or an empty directory. If the directory + does not exist, it will be created by the debugger core during debug + `run()` calls and removed afterwards. If `None`, the debug dumps will + be at tfdbg_ under the system temp directory. + ui_type: (`str`) requested UI type. Currently supported: + (readline) + thread_name_filter: Regular-expression white list for thread name. See + the doc of `BaseDebugWrapperSession` for details. + config_file_path: Optional override to the default configuration file + path, which is at `${HOME}/.tfdbg_config`. + + Raises: + ValueError: If dump_root is an existing and non-empty directory or if + dump_root is a file. + """ + framework.BaseDebugWrapperSession.__init__( + self, sess, thread_name_filter=thread_name_filter) + + if not dump_root: + self._dump_root = tempfile.mkdtemp(prefix=_DUMP_ROOT_PREFIX) + else: + dump_root = os.path.expanduser(dump_root) + if os.path.isfile(dump_root): + raise ValueError("dump_root path points to a file: %s" % dump_root) + elif os.path.isdir(dump_root) and os.listdir(dump_root): + raise ValueError("dump_root path points to a non-empty directory: %s" % + dump_root) + + self._dump_root = dump_root + + self._initialize_argparsers() + + # Registered tensor filters. + self._tensor_filters = {} + # Register frequently-used filter(s). + self.add_tensor_filter("has_inf_or_nan", debug_data.has_inf_or_nan) + + # Below are the state variables of this wrapper object. + # _active_tensor_filter: what (if any) tensor filter is in effect. If such + # a filter is in effect, this object will call run() method of the + # underlying TensorFlow Session object until the filter passes. This is + # activated by the "-f" flag of the "run" command. + # _run_through_times: keeps track of how many times the wrapper needs to + # run through without stopping at the run-end CLI. It is activated by the + # "-t" option of the "run" command. + # _skip_debug: keeps track of whether the current run should be executed + # without debugging. It is activated by the "-n" option of the "run" + # command. + # + # _run_start_response: keeps track what OnRunStartResponse the wrapper + # should return at the next run-start callback. If this information is + # unavailable (i.e., is None), the run-start CLI will be launched to ask + # the user. This is the case, e.g., right before the first run starts. + self._active_tensor_filter = None + self._active_filter_exclude_node_names = None + self._active_tensor_filter_run_start_response = None + self._run_through_times = 1 + self._skip_debug = False + self._run_start_response = None + self._is_run_start = True + self._ui_type = ui_type + self._config = None + if config_file_path: + self._config = cli_config.CLIConfig(config_file_path=config_file_path) + + def _is_disk_usage_reset_each_run(self): + # The dumped tensors are all cleaned up after every Session.run + # in a command-line wrapper. + return True + + def _initialize_argparsers(self): + self._argparsers = {} + ap = argparse.ArgumentParser( + description="Run through, with or without debug tensor watching.", + usage=argparse.SUPPRESS) + ap.add_argument( + "-t", + "--times", + dest="times", + type=int, + default=1, + help="How many Session.run() calls to proceed with.") + ap.add_argument( + "-n", + "--no_debug", + dest="no_debug", + action="store_true", + help="Run through without debug tensor watching.") + ap.add_argument( + "-f", + "--till_filter_pass", + dest="till_filter_pass", + type=str, + default="", + help="Run until a tensor in the graph passes the specified filter.") + ap.add_argument( + "-fenn", + "--filter_exclude_node_names", + dest="filter_exclude_node_names", + type=str, + default="", + help="When applying the tensor filter, exclude node with names " + "matching the regular expression. Applicable only if --tensor_filter " + "or -f is used.") + ap.add_argument( + "--node_name_filter", + dest="node_name_filter", + type=str, + default="", + help="Regular-expression filter for node names to be watched in the " + "run, e.g., loss, reshape.*") + ap.add_argument( + "--op_type_filter", + dest="op_type_filter", + type=str, + default="", + help="Regular-expression filter for op type to be watched in the run, " + "e.g., (MatMul|Add), Variable.*") + ap.add_argument( + "--tensor_dtype_filter", + dest="tensor_dtype_filter", + type=str, + default="", + help="Regular-expression filter for tensor dtype to be watched in the " + "run, e.g., (float32|float64), int.*") + ap.add_argument( + "-p", + "--profile", + dest="profile", + action="store_true", + help="Run and profile TensorFlow graph execution.") + self._argparsers["run"] = ap + + ap = argparse.ArgumentParser( + description="Display information about this Session.run() call.", + usage=argparse.SUPPRESS) + self._argparsers["run_info"] = ap + + self._argparsers["print_feed"] = command_parser.get_print_tensor_argparser( + "Print the value of a feed in feed_dict.") + + def add_tensor_filter(self, filter_name, tensor_filter): + """Add a tensor filter. + + Args: + filter_name: (`str`) name of the filter. + tensor_filter: (`callable`) the filter callable. See the doc string of + `DebugDumpDir.find()` for more details about its signature. + """ + + self._tensor_filters[filter_name] = tensor_filter + + def on_session_init(self, request): + """Overrides on-session-init callback. + + Args: + request: An instance of `OnSessionInitRequest`. + + Returns: + An instance of `OnSessionInitResponse`. + """ + + return framework.OnSessionInitResponse( + framework.OnSessionInitAction.PROCEED) + + def on_run_start(self, request): + """Overrides on-run-start callback. + + Args: + request: An instance of `OnRunStartRequest`. + + Returns: + An instance of `OnRunStartResponse`. + """ + self._is_run_start = True + self._update_run_calls_state( + request.run_call_count, request.fetches, request.feed_dict, + is_callable_runner=request.is_callable_runner) + + if self._active_tensor_filter: + # If we are running until a filter passes, we just need to keep running + # with the previous `OnRunStartResponse`. + return self._active_tensor_filter_run_start_response + + self._exit_if_requested_by_user() + + if self._run_call_count > 1 and not self._skip_debug: + if self._run_through_times > 0: + # Just run through without debugging. + return framework.OnRunStartResponse( + framework.OnRunStartAction.NON_DEBUG_RUN, []) + elif self._run_through_times == 0: + # It is the run at which the run-end CLI will be launched: activate + # debugging. + return (self._run_start_response or + framework.OnRunStartResponse( + framework.OnRunStartAction.DEBUG_RUN, + self._get_run_debug_urls())) + + if self._run_start_response is None: + self._prep_cli_for_run_start() + + self._run_start_response = self._launch_cli() + if self._active_tensor_filter: + self._active_tensor_filter_run_start_response = self._run_start_response + if self._run_through_times > 1: + self._run_through_times -= 1 + + self._exit_if_requested_by_user() + return self._run_start_response + + def _exit_if_requested_by_user(self): + if self._run_start_response == debugger_cli_common.EXPLICIT_USER_EXIT: + # Explicit user "exit" command leads to sys.exit(1). + print( + "Note: user exited from debugger CLI: Calling sys.exit(1).", + file=sys.stderr) + sys.exit(1) + + def _prep_cli_for_run_start(self): + """Prepare (but not launch) the CLI for run-start.""" + self._run_cli = ui_factory.get_ui(self._ui_type, config=self._config) + + help_intro = debugger_cli_common.RichTextLines([]) + if self._run_call_count == 1: + # Show logo at the onset of the first run. + help_intro.extend(cli_shared.get_tfdbg_logo()) + help_intro.extend(debugger_cli_common.get_tensorflow_version_lines()) + help_intro.extend(debugger_cli_common.RichTextLines("Upcoming run:")) + help_intro.extend(self._run_info) + + self._run_cli.set_help_intro(help_intro) + + # Create initial screen output detailing the run. + self._title = "run-start: " + self._run_description + self._init_command = "run_info" + self._title_color = "blue_on_white" + + def on_run_end(self, request): + """Overrides on-run-end callback. + + Actions taken: + 1) Load the debug dump. + 2) Bring up the Analyzer CLI. + + Args: + request: An instance of OnSessionInitRequest. + + Returns: + An instance of OnSessionInitResponse. + """ + + self._is_run_start = False + if request.performed_action == framework.OnRunStartAction.DEBUG_RUN: + partition_graphs = None + if request.run_metadata and request.run_metadata.partition_graphs: + partition_graphs = request.run_metadata.partition_graphs + elif request.client_graph_def: + partition_graphs = [request.client_graph_def] + + if request.tf_error and not os.path.isdir(self._dump_root): + # It is possible that the dump root may not exist due to errors that + # have occurred prior to graph execution (e.g., invalid device + # assignments), in which case we will just raise the exception as the + # unwrapped Session does. + raise request.tf_error + + debug_dump = debug_data.DebugDumpDir( + self._dump_root, partition_graphs=partition_graphs) + debug_dump.set_python_graph(self._sess.graph) + + passed_filter = None + passed_filter_exclude_node_names = None + if self._active_tensor_filter: + if not debug_dump.find( + self._tensor_filters[self._active_tensor_filter], first_n=1, + exclude_node_names=self._active_filter_exclude_node_names): + # No dumped tensor passes the filter in this run. Clean up the dump + # directory and move on. + self._remove_dump_root() + return framework.OnRunEndResponse() + else: + # Some dumped tensor(s) from this run passed the filter. + passed_filter = self._active_tensor_filter + passed_filter_exclude_node_names = ( + self._active_filter_exclude_node_names) + self._active_tensor_filter = None + self._active_filter_exclude_node_names = None + + self._prep_debug_cli_for_run_end( + debug_dump, request.tf_error, passed_filter, + passed_filter_exclude_node_names) + + self._run_start_response = self._launch_cli() + + # Clean up the dump generated by this run. + self._remove_dump_root() + elif request.performed_action == framework.OnRunStartAction.PROFILE_RUN: + self._prep_profile_cli_for_run_end(self._sess.graph, request.run_metadata) + self._run_start_response = self._launch_cli() + else: + # No debug information to show following a non-debug run() call. + self._run_start_response = None + + # Return placeholder response that currently holds no additional + # information. + return framework.OnRunEndResponse() + + def _remove_dump_root(self): + if os.path.isdir(self._dump_root): + file_io.delete_recursively(self._dump_root) + + def _prep_debug_cli_for_run_end(self, + debug_dump, + tf_error, + passed_filter, + passed_filter_exclude_node_names): + """Prepare (but not launch) CLI for run-end, with debug dump from the run. + + Args: + debug_dump: (debug_data.DebugDumpDir) The debug dump directory from this + run. + tf_error: (None or OpError) OpError that happened during the run() call + (if any). + passed_filter: (None or str) Name of the tensor filter that just passed + and caused the preparation of this run-end CLI (if any). + passed_filter_exclude_node_names: (None or str) Regular expression used + with the tensor filter to exclude ops with names matching the regular + expression. + """ + + if tf_error: + help_intro = cli_shared.get_error_intro(tf_error) + + self._init_command = "help" + self._title_color = "red_on_white" + else: + help_intro = None + self._init_command = "lt" + + self._title_color = "black_on_white" + if passed_filter is not None: + # Some dumped tensor(s) from this run passed the filter. + self._init_command = "lt -f %s" % passed_filter + if passed_filter_exclude_node_names: + self._init_command += (" --filter_exclude_node_names %s" % + passed_filter_exclude_node_names) + self._title_color = "red_on_white" + + self._run_cli = analyzer_cli.create_analyzer_ui( + debug_dump, + self._tensor_filters, + ui_type=self._ui_type, + on_ui_exit=self._remove_dump_root, + config=self._config) + + # Get names of all dumped tensors. + dumped_tensor_names = [] + for datum in debug_dump.dumped_tensor_data: + dumped_tensor_names.append("%s:%d" % + (datum.node_name, datum.output_slot)) + + # Tab completions for command "print_tensors". + self._run_cli.register_tab_comp_context(["print_tensor", "pt"], + dumped_tensor_names) + + # Tab completion for commands "node_info", "list_inputs" and + # "list_outputs". The list comprehension is used below because nodes() + # output can be unicodes and they need to be converted to strs. + self._run_cli.register_tab_comp_context( + ["node_info", "ni", "list_inputs", "li", "list_outputs", "lo"], + [str(node_name) for node_name in debug_dump.nodes()]) + # TODO(cais): Reduce API surface area for aliases vis-a-vis tab + # completion contexts and registered command handlers. + + self._title = "run-end: " + self._run_description + + if help_intro: + self._run_cli.set_help_intro(help_intro) + + def _prep_profile_cli_for_run_end(self, py_graph, run_metadata): + self._init_command = "lp" + self._run_cli = profile_analyzer_cli.create_profiler_ui( + py_graph, run_metadata, ui_type=self._ui_type, + config=self._run_cli.config) + self._title = "run-end (profiler mode): " + self._run_description + + def _launch_cli(self): + """Launch the interactive command-line interface. + + Returns: + The OnRunStartResponse specified by the user using the "run" command. + """ + + self._register_this_run_info(self._run_cli) + response = self._run_cli.run_ui( + init_command=self._init_command, + title=self._title, + title_color=self._title_color) + + return response + + def _run_info_handler(self, args, screen_info=None): + output = debugger_cli_common.RichTextLines([]) + + if self._run_call_count == 1: + output.extend(cli_shared.get_tfdbg_logo()) + output.extend(debugger_cli_common.get_tensorflow_version_lines()) + output.extend(self._run_info) + + if (not self._is_run_start and + debugger_cli_common.MAIN_MENU_KEY in output.annotations): + menu = output.annotations[debugger_cli_common.MAIN_MENU_KEY] + if "list_tensors" not in menu.captions(): + menu.insert( + 0, debugger_cli_common.MenuItem("list_tensors", "list_tensors")) + + return output + + def _print_feed_handler(self, args, screen_info=None): + np_printoptions = cli_shared.numpy_printoptions_from_screen_info( + screen_info) + + if not self._feed_dict: + return cli_shared.error( + "The feed_dict of the current run is None or empty.") + + parsed = self._argparsers["print_feed"].parse_args(args) + tensor_name, tensor_slicing = ( + command_parser.parse_tensor_name_with_slicing(parsed.tensor_name)) + + feed_key = None + feed_value = None + for key in self._feed_dict: + key_name = common.get_graph_element_name(key) + if key_name == tensor_name: + feed_key = key_name + feed_value = self._feed_dict[key] + break + + if feed_key is None: + return cli_shared.error( + "The feed_dict of the current run does not contain the key %s" % + tensor_name) + else: + return cli_shared.format_tensor( + feed_value, + feed_key + " (feed)", + np_printoptions, + print_all=parsed.print_all, + tensor_slicing=tensor_slicing, + highlight_options=cli_shared.parse_ranges_highlight(parsed.ranges), + include_numeric_summary=parsed.numeric_summary) + + def _run_handler(self, args, screen_info=None): + """Command handler for "run" command during on-run-start.""" + + del screen_info # Currently unused. + + parsed = self._argparsers["run"].parse_args(args) + parsed.node_name_filter = parsed.node_name_filter or None + parsed.op_type_filter = parsed.op_type_filter or None + parsed.tensor_dtype_filter = parsed.tensor_dtype_filter or None + + if parsed.filter_exclude_node_names and not parsed.till_filter_pass: + raise ValueError( + "The --filter_exclude_node_names (or -feon) flag is valid only if " + "the --till_filter_pass (or -f) flag is used.") + + if parsed.profile: + raise debugger_cli_common.CommandLineExit( + exit_token=framework.OnRunStartResponse( + framework.OnRunStartAction.PROFILE_RUN, [])) + + self._skip_debug = parsed.no_debug + self._run_through_times = parsed.times + + if parsed.times > 1 or parsed.no_debug: + # If requested -t times > 1, the very next run will be a non-debug run. + action = framework.OnRunStartAction.NON_DEBUG_RUN + debug_urls = [] + else: + action = framework.OnRunStartAction.DEBUG_RUN + debug_urls = self._get_run_debug_urls() + run_start_response = framework.OnRunStartResponse( + action, + debug_urls, + node_name_regex_allowlist=parsed.node_name_filter, + op_type_regex_allowlist=parsed.op_type_filter, + tensor_dtype_regex_allowlist=parsed.tensor_dtype_filter) + + if parsed.till_filter_pass: + # For the run-till-filter-pass (run -f) mode, use the DEBUG_RUN + # option to access the intermediate tensors, and set the corresponding + # state flag of the class itself to True. + if parsed.till_filter_pass in self._tensor_filters: + action = framework.OnRunStartAction.DEBUG_RUN + self._active_tensor_filter = parsed.till_filter_pass + self._active_filter_exclude_node_names = ( + parsed.filter_exclude_node_names) + self._active_tensor_filter_run_start_response = run_start_response + else: + # Handle invalid filter name. + return debugger_cli_common.RichTextLines( + ["ERROR: tensor filter \"%s\" does not exist." % + parsed.till_filter_pass]) + + # Raise CommandLineExit exception to cause the CLI to exit. + raise debugger_cli_common.CommandLineExit(exit_token=run_start_response) + + def _register_this_run_info(self, curses_cli): + curses_cli.register_command_handler( + "run", + self._run_handler, + self._argparsers["run"].format_help(), + prefix_aliases=["r"]) + curses_cli.register_command_handler( + "run_info", + self._run_info_handler, + self._argparsers["run_info"].format_help(), + prefix_aliases=["ri"]) + curses_cli.register_command_handler( + "print_feed", + self._print_feed_handler, + self._argparsers["print_feed"].format_help(), + prefix_aliases=["pf"]) + + if self._tensor_filters: + # Register tab completion for the filter names. + curses_cli.register_tab_comp_context(["run", "r"], + list(self._tensor_filters.keys())) + if self._feed_dict and hasattr(self._feed_dict, "keys"): + # Register tab completion for feed_dict keys. + feed_keys = [common.get_graph_element_name(key) + for key in self._feed_dict.keys()] + curses_cli.register_tab_comp_context(["print_feed", "pf"], feed_keys) + + def _get_run_debug_urls(self): + """Get the debug_urls value for the current run() call. + + Returns: + debug_urls: (list of str) Debug URLs for the current run() call. + Currently, the list consists of only one URL that is a file:// URL. + """ + + return ["file://" + self._dump_root] + + def _update_run_calls_state(self, + run_call_count, + fetches, + feed_dict, + is_callable_runner=False): + """Update the internal state with regard to run() call history. + + Args: + run_call_count: (int) Number of run() calls that have occurred. + fetches: a node/tensor or a list of node/tensor that are the fetches of + the run() call. This is the same as the fetches argument to the run() + call. + feed_dict: None of a dict. This is the feed_dict argument to the run() + call. + is_callable_runner: (bool) whether a runner returned by + Session.make_callable is being run. + """ + + self._run_call_count = run_call_count + self._feed_dict = feed_dict + self._run_description = cli_shared.get_run_short_description( + run_call_count, + fetches, + feed_dict, + is_callable_runner=is_callable_runner) + self._run_through_times -= 1 + + self._run_info = cli_shared.get_run_start_intro( + run_call_count, + fetches, + feed_dict, + self._tensor_filters, + is_callable_runner=is_callable_runner) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..86dc16cfd36492b8c56f6382c713bce7a2994a19 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/__init__.py @@ -0,0 +1,191 @@ +# 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. +# ============================================================================== +"""Library for running a computation across multiple devices. + +The intent of this library is that you can write an algorithm in a stylized way +and it will be usable with a variety of different `tf.distribute.Strategy` +implementations. Each descendant will implement a different strategy for +distributing the algorithm across multiple devices/machines. Furthermore, these +changes can be hidden inside the specific layers and other library classes that +need special treatment to run in a distributed setting, so that most users' +model definition code can run unchanged. The `tf.distribute.Strategy` API works +the same way with eager and graph execution. + +*Guides* + +* [TensorFlow v2.x](https://www.tensorflow.org/guide/distributed_training) +* [TensorFlow +v1.x](https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/distribute_strategy.ipynb) + +*Tutorials* + +* [Distributed Training +Tutorials](https://www.tensorflow.org/tutorials/distribute/) + + The tutorials cover how to use `tf.distribute.Strategy` to do distributed + training with native Keras APIs, custom training loops, + and Estimator APIs. They also cover how to save/load model when using + `tf.distribute.Strategy`. + +*Glossary* + +* _Data parallelism_ is where we run multiple copies of the model + on different slices of the input data. This is in contrast to + _model parallelism_ where we divide up a single copy of a model + across multiple devices. + Note: we only support data parallelism for now, but + hope to add support for model parallelism in the future. +* A _device_ is a CPU or accelerator (e.g. GPUs, TPUs) on some machine that + TensorFlow can run operations on (see e.g. `tf.device`). You may have multiple + devices on a single machine, or be connected to devices on multiple + machines. Devices used to run computations are called _worker devices_. + Devices used to store variables are _parameter devices_. For some strategies, + such as `tf.distribute.MirroredStrategy`, the worker and parameter devices + will be the same (see mirrored variables below). For others they will be + different. For example, `tf.distribute.experimental.CentralStorageStrategy` + puts the variables on a single device (which may be a worker device or may be + the CPU), and `tf.distribute.experimental.ParameterServerStrategy` puts the + variables on separate machines called _parameter servers_ (see below). +* A _replica_ is one copy of the model, running on one slice of the + input data. Right now each replica is executed on its own + worker device, but once we add support for model parallelism + a replica may span multiple worker devices. +* A _host_ is the CPU device on a machine with worker devices, typically + used for running input pipelines. +* A _worker_ is defined to be the physical machine(s) containing the physical + devices (e.g. GPUs, TPUs) on which the replicated computation is executed. A + worker may contain one or more replicas, but contains at least one + replica. Typically one worker will correspond to one machine, but in the case + of very large models with model parallelism, one worker may span multiple + machines. We typically run one input pipeline per worker, feeding all the + replicas on that worker. +* _Synchronous_, or more commonly _sync_, training is where the updates from + each replica are aggregated together before updating the model variables. This + is in contrast to _asynchronous_, or _async_ training, where each replica + updates the model variables independently. You may also have replicas + partitioned into groups which are in sync within each group but async between + groups. +* _Parameter servers_: These are machines that hold a single copy of + parameters/variables, used by some strategies (right now just + `tf.distribute.experimental.ParameterServerStrategy`). All replicas that want + to operate on a variable retrieve it at the beginning of a step and send an + update to be applied at the end of the step. These can in principle support + either sync or async training, but right now we only have support for async + training with parameter servers. Compare to + `tf.distribute.experimental.CentralStorageStrategy`, which puts all variables + on a single device on the same machine (and does sync training), and + `tf.distribute.MirroredStrategy`, which mirrors variables to multiple devices + (see below). + +* _Replica context_ vs. _Cross-replica context_ vs _Update context_ + + A _replica context_ applies + when you execute the computation function that was called with `strategy.run`. + Conceptually, you're in replica context when executing the computation + function that is being replicated. + + An _update context_ is entered in a `tf.distribute.StrategyExtended.update` + call. + + An _cross-replica context_ is entered when you enter a `strategy.scope`. This + is useful for calling `tf.distribute.Strategy` methods which operate across + the replicas (like `reduce_to()`). By default you start in a _replica context_ + (the "default single _replica context_") and then some methods can switch you + back and forth. + +* _Distributed value_: Distributed value is represented by the base class + `tf.distribute.DistributedValues`. `tf.distribute.DistributedValues` is useful + to represent values on multiple devices, and it contains a map from replica id + to values. Two representative types of `tf.distribute.DistributedValues` + are `tf.types.experimental.PerReplica` and `tf.types.experimental.Mirrored` + values. + + `PerReplica` values exist on the worker devices, with a different value for + each replica. They are produced by iterating through a distributed dataset + returned by `tf.distribute.Strategy.experimental_distribute_dataset` and + `tf.distribute.Strategy.distribute_datasets_from_function`. They are also the + typical result returned by `tf.distribute.Strategy.run`. + + `Mirrored` values are like `PerReplica` values, except we know that the value + on all replicas are the same. `Mirrored` values are kept synchronized by the + distribution strategy in use, while `PerReplica` values are left + unsynchronized. `Mirrored` values typically represent model weights. We can + safely read a `Mirrored` value in a cross-replica context by using the value + on any replica, while PerReplica values can only be read within a replica + context. + +* _Unwrapping_ and _merging_: Consider calling a function `fn` on multiple + replicas, like `strategy.run(fn, args=[w])` with an + argument `w` that is a `tf.distribute.DistributedValues`. This means `w` will + have a map taking replica id `0` to `w0`, replica id `1` to `w1`, etc. + `strategy.run()` unwraps `w` before calling `fn`, so it calls `fn(w0)` on + device `d0`, `fn(w1)` on device `d1`, etc. It then merges the return + values from `fn()`, which leads to one common object if the returned values + are the same object from every replica, or a `DistributedValues` object + otherwise. + +* _Reductions_ and _all-reduce_: A _reduction_ is a method of aggregating + multiple values into one value, like "sum" or "mean". If a strategy is doing + sync training, we will perform a reduction on the gradients to a parameter + from all replicas before applying the update. _All-reduce_ is an algorithm for + performing a reduction on values from multiple devices and making the result + available on all of those devices. + +* _Mirrored variables_: These are variables that are created on multiple + devices, where we keep the variables in sync by applying the same + updates to every copy. Mirrored variables are created with + `tf.Variable(...synchronization=tf.VariableSynchronization.ON_WRITE...)`. + Normally they are only used in synchronous training. + +* _SyncOnRead variables_ + + _SyncOnRead variables_ are created by + `tf.Variable(...synchronization=tf.VariableSynchronization.ON_READ...)`, and + they are created on multiple devices. In replica context, each + component variable on the local replica can perform reads and writes without + synchronization with each other. When the + _SyncOnRead variable_ is read in cross-replica context, the values from + component variables are aggregated and returned. + + _SyncOnRead variables_ bring a lot of custom configuration difficulty to the + underlying logic, so we do not encourage users to instantiate and use + _SyncOnRead variable_ on their own. We have mainly used _SyncOnRead + variables_ for use cases such as batch norm and metrics. For performance + reasons, we often don't need to keep these statistics in sync every step and + they can be accumulated on each replica independently. The only time we want + to sync them is reporting or checkpointing, which typically happens in + cross-replica context. _SyncOnRead variables_ are also often used by advanced + users who want to control when variable values are aggregated. For example, + users sometimes want to maintain gradients independently on each replica for a + couple of steps without aggregation. + +* _Distribute-aware layers_ + + Layers are generally called in a replica context, except when defining a + Keras functional model. `tf.distribute.in_cross_replica_context` will let you + determine which case you are in. If in a replica context, + the `tf.distribute.get_replica_context` function will return the default + replica context outside a strategy scope, `None` within a strategy scope, and + a `tf.distribute.ReplicaContext` object inside a strategy scope and within a + `tf.distribute.Strategy.run` function. The `ReplicaContext` object has an + `all_reduce` method for aggregating across all replicas. + + +Note that we provide a default version of `tf.distribute.Strategy` that is +used when no other strategy is in scope, that provides the same API with +reasonable default behavior. + +API docstring: tensorflow.distribute +""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/central_storage_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/central_storage_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..72515173904ab78421b8e0ba12a26858ee610c48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/central_storage_strategy.py @@ -0,0 +1,226 @@ +# 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. +# ============================================================================== +"""Class implementing a single machine parameter server strategy.""" + +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import parameter_server_strategy +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('distribute.experimental.CentralStorageStrategy', v1=[]) +class CentralStorageStrategy(distribute_lib.Strategy): + """A one-machine strategy that puts all variables on a single device. + + Variables are assigned to local CPU or the only GPU. If there is more + than one GPU, compute operations (other than variable update operations) + will be replicated across all GPUs. + + For Example: + ``` + strategy = tf.distribute.experimental.CentralStorageStrategy() + # Create a dataset + ds = tf.data.Dataset.range(5).batch(2) + # Distribute that dataset + dist_dataset = strategy.experimental_distribute_dataset(ds) + + with strategy.scope(): + @tf.function + def train_step(val): + return val + 1 + + # Iterate over the distributed dataset + for x in dist_dataset: + # process dataset elements + strategy.run(train_step, args=(x,)) + ``` + """ + + def __init__(self, compute_devices=None, parameter_device=None): + extended = parameter_server_strategy.ParameterServerStrategyExtended( + self, + compute_devices=compute_devices, + parameter_device=parameter_device) + """Initializes the strategy with optional device strings. + + Args: + compute_devices: an optional list of strings for device to replicate models + on. If this is not provided, all local GPUs will be used; if there is no + GPU, local CPU will be used. + parameter_device: an optional device string for which device to put + variables on. The default one is CPU or GPU if there is only one. + """ + super(CentralStorageStrategy, self).__init__(extended) + distribute_lib.distribution_strategy_gauge.get_cell('V2').set( + 'CentralStorageStrategy') + + @classmethod + def _from_num_gpus(cls, num_gpus): + return cls(device_util.local_devices_from_num_gpus(num_gpus)) + + def experimental_distribute_dataset(self, dataset, options=None): # pylint: disable=useless-super-delegation + """Distributes a tf.data.Dataset instance provided via dataset. + + The returned dataset is a wrapped strategy dataset which creates a + multidevice iterator under the hood. It prefetches the input data to the + specified devices on the worker. The returned distributed dataset can be + iterated over similar to how regular datasets can. + + NOTE: Currently, the user cannot add any more transformations to a + distributed dataset. + + For Example: + ``` + strategy = tf.distribute.CentralStorageStrategy() # with 1 CPU and 1 GPU + dataset = tf.data.Dataset.range(10).batch(2) + dist_dataset = strategy.experimental_distribute_dataset(dataset) + for x in dist_dataset: + print(x) # Prints PerReplica values [0, 1], [2, 3],... + + ``` + Args: + dataset: `tf.data.Dataset` to be prefetched to device. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + + Returns: + A "distributed `Dataset`" that the caller can iterate over. + """ + if (options and options.experimental_replication_moden == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + 'InputReplicationMode.PER_REPLICA ' + 'is only supported in ' + '`experimental_distribute_datasets_from_function`.' + ) + return super(CentralStorageStrategy, self).experimental_distribute_dataset( + dataset, options) + + def experimental_local_results(self, value): # pylint: disable=useless-super-delegation + """Returns the list of all local per-replica values contained in `value`. + + In `CentralStorageStrategy` there is a single worker so the value returned + will be all the values on that worker. + + Args: + value: A value returned by `run()`, `extended.call_for_each_replica()`, + or a variable created in `scope`. + + Returns: + A tuple of values contained in `value`. If `value` represents a single + value, this returns `(value,).` + """ + return super(CentralStorageStrategy, self).experimental_local_results(value) + + def run(self, fn, args=(), kwargs=None, options=None): # pylint: disable=useless-super-delegation + """Run `fn` on each replica, with the given arguments. + + In `CentralStorageStrategy`, `fn` is called on each of the compute + replicas, with the provided "per replica" arguments specific to that device. + + Args: + fn: The function to run. The output must be a `tf.nest` of `Tensor`s. + args: (Optional) Positional arguments to `fn`. + kwargs: (Optional) Keyword arguments to `fn`. + options: (Optional) An instance of `tf.distribute.RunOptions` specifying + the options to run `fn`. + + Returns: + Return value from running `fn`. + """ + return super(CentralStorageStrategy, self).run(fn, args, kwargs, options) + + def reduce(self, reduce_op, value, axis): # pylint: disable=useless-super-delegation + """Reduce `value` across replicas. + + Given a per-replica value returned by `run`, say a + per-example loss, the batch will be divided across all the replicas. This + function allows you to aggregate across replicas and optionally also across + batch elements. For example, if you have a global batch size of 8 and 2 + replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and + `[4, 5, 6, 7]` will be on replica 1. By default, `reduce` will just + aggregate across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful + when each replica is computing a scalar or some other value that doesn't + have a "batch" dimension (like a gradient). More often you will want to + aggregate across the global batch, which you can get by specifying the batch + dimension as the `axis`, typically `axis=0`. In this case it would return a + scalar `0+1+2+3+4+5+6+7`. + + If there is a last partial batch, you will need to specify an axis so + that the resulting shape is consistent across replicas. So if the last + batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you + would get a shape mismatch unless you specify `axis=0`. If you specify + `tf.distribute.ReduceOp.MEAN`, using `axis=0` will use the correct + denominator of 6. Contrast this with computing `reduce_mean` to get a + scalar value on each replica and this function to average those means, + which will weigh some values `1/8` and others `1/4`. + + For Example: + ``` + strategy = tf.distribute.experimental.CentralStorageStrategy( + compute_devices=['CPU:0', 'GPU:0'], parameter_device='CPU:0') + ds = tf.data.Dataset.range(10) + # Distribute that dataset + dist_dataset = strategy.experimental_distribute_dataset(ds) + + with strategy.scope(): + @tf.function + def train_step(val): + # pass through + return val + + # Iterate over the distributed dataset + for x in dist_dataset: + result = strategy.run(train_step, args=(x,)) + + result = strategy.reduce(tf.distribute.ReduceOp.SUM, result, + axis=None).numpy() + # result: array([ 4, 6, 8, 10]) + + result = strategy.reduce(tf.distribute.ReduceOp.SUM, result, axis=0).numpy() + # result: 28 + ``` + + Args: + reduce_op: A `tf.distribute.ReduceOp` value specifying how values should + be combined. + value: A "per replica" value, e.g. returned by `run` to + be combined into a single tensor. + axis: Specifies the dimension to reduce along within each + replica's tensor. Should typically be set to the batch dimension, or + `None` to only reduce across replicas (e.g. if the tensor has no batch + dimension). + + Returns: + A `Tensor`. + """ + return super(CentralStorageStrategy, self).reduce(reduce_op, value, axis) + + +@tf_export(v1=['distribute.experimental.CentralStorageStrategy']) # pylint: disable=missing-docstring +class CentralStorageStrategyV1(distribute_lib.StrategyV1): + + __doc__ = CentralStorageStrategy.__doc__ + + def __init__(self, compute_devices=None, parameter_device=None): + super(CentralStorageStrategyV1, self).__init__( + parameter_server_strategy.ParameterServerStrategyExtended( + self, + compute_devices=compute_devices, + parameter_device=parameter_device)) + distribute_lib.distribution_strategy_gauge.get_cell('V1').set( + 'CentralStorageStrategy') + + __init__.__doc__ = CentralStorageStrategy.__init__.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..35903dc7b254f7273efa212346e3adcf0012bb3d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/__init__.py @@ -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. +# ============================================================================== +"""Library imports for ClusterResolvers. + + This library contains all implementations of ClusterResolvers. + ClusterResolvers are a way of specifying cluster information for distributed + execution. Built on top of existing `ClusterSpec` framework, ClusterResolvers + are a way for TensorFlow to communicate with various cluster management + systems (e.g. GCE, AWS, etc...). +""" + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import SimpleClusterResolver +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import UnionClusterResolver +from tensorflow.python.distribute.cluster_resolver.gce_cluster_resolver import GCEClusterResolver +from tensorflow.python.distribute.cluster_resolver.kubernetes_cluster_resolver import KubernetesClusterResolver +from tensorflow.python.distribute.cluster_resolver.slurm_cluster_resolver import SlurmClusterResolver +from tensorflow.python.distribute.cluster_resolver.tfconfig_cluster_resolver import TFConfigClusterResolver +from tensorflow.python.distribute.cluster_resolver.tpu_cluster_resolver import TPUClusterResolver diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9ef493ec31566a4a07b9373e66f127d7538b1a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/cluster_resolver.py @@ -0,0 +1,624 @@ +# 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. +# ============================================================================== +"""Cluster Resolvers are used for dynamic cluster IP/hostname resolution.""" + +import abc + +import collections + +import six + +from tensorflow.python.client import session +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import ops +from tensorflow.python.training.server_lib import ClusterSpec +from tensorflow.python.util.tf_export import tf_export + + +def format_master_url(master, rpc_layer=None): + if rpc_layer: + return '%s://%s' % (rpc_layer, master) + else: + return master + + +def get_accelerator_devices(master, config_proto): + """Returns accelerator devices given a master and a configuration.""" + if context.executing_eagerly(): + logical_devices = config.list_logical_devices() + devices = [] + for d in logical_devices: + if d.device_type == 'CPU' or d.device_type == 'XLA_CPU': # Filter CPUs + continue + devices.append(session._DeviceAttributes(d.name, d.device_type, 0, 0)) # pylint: disable=protected-access + return devices + else: + with ops.Graph().as_default(): + with session.Session(master, config=config_proto) as s: + devices = s.list_devices() + return devices + + +@tf_export('distribute.cluster_resolver.ClusterResolver') +@six.add_metaclass(abc.ABCMeta) +class ClusterResolver(object): + """Abstract class for all implementations of ClusterResolvers. + + This defines the skeleton for all implementations of ClusterResolvers. + ClusterResolvers are a way for TensorFlow to communicate with various cluster + management systems (e.g. GCE, AWS, etc...) and gives TensorFlow necessary + information to set up distributed training. + + By letting TensorFlow communicate with these systems, we will be able to + automatically discover and resolve IP addresses for various TensorFlow + workers. This will eventually allow us to automatically recover from + underlying machine failures and scale TensorFlow worker clusters up and down. + + Note to Implementors of `tf.distribute.cluster_resolver.ClusterResolver` + subclass: In addition to these abstract methods, when task_type, task_id, and + rpc_layer attributes are applicable, you should also implement them either as + properties with getters or setters, or directly set the attributes + `self._task_type`, `self._task_id`, or `self._rpc_layer` so the base class' + getters and setters are used. See + `tf.distribute.cluster_resolver.SimpleClusterResolver.__init__` for an + example. + + In general, multi-client tf.distribute strategies such as + `tf.distribute.experimental.MultiWorkerMirroredStrategy` require task_type and + task_id properties to be available in the `ClusterResolver` they are using. On + the other hand, these concepts are not applicable in single-client strategies, + such as `tf.distribute.experimental.TPUStrategy`, because the program is only + expected to be run on one task, so there should not be a need to have code + branches according to task type and task id. + + - task_type is the name of the server's current named job (e.g. 'worker', + 'ps' in a distributed parameterized training job). + - task_id is the ordinal index of the server within the task type. + - rpc_layer is the protocol used by TensorFlow to communicate with other + TensorFlow servers in a distributed environment. + """ + + @abc.abstractmethod + def cluster_spec(self): + """Retrieve the current state of the cluster and return a `tf.train.ClusterSpec`. + + Returns: + A `tf.train.ClusterSpec` representing the state of the cluster at the + moment this function is called. + + Implementors of this function must take care in ensuring that the + ClusterSpec returned is up-to-date at the time of calling this function. + This usually means retrieving the information from the underlying cluster + management system every time this function is invoked and reconstructing + a cluster_spec, rather than attempting to cache anything. + """ + raise NotImplementedError() + + @abc.abstractmethod + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Retrieves the name or URL of the session master. + + Note: this is only useful for TensorFlow 1.x. + + Args: + task_type: (Optional) The type of the TensorFlow task of the master. + task_id: (Optional) The index of the TensorFlow task of the master. + rpc_layer: (Optional) The RPC protocol for the given cluster. + + Returns: + The name or URL of the session master. + + Implementors of this function must take care in ensuring that the master + returned is up-to-date at the time to calling this function. This usually + means retrieving the master every time this function is invoked. + """ + raise NotImplementedError() + + def num_accelerators(self, + task_type=None, + task_id=None, + config_proto=None): + """Returns the number of accelerator cores per worker. + + This returns the number of accelerator cores (such as GPUs and TPUs) + available per worker. + + Optionally, we allow callers to specify the task_type, and task_id, for + if they want to target a specific TensorFlow task to query + the number of accelerators. This is to support heterogenous environments, + where the number of accelerators cores per host is different. + + Args: + task_type: (Optional) The type of the TensorFlow task of the machine we + want to query. + task_id: (Optional) The index of the TensorFlow task of the machine we + want to query. + config_proto: (Optional) Configuration for starting a new session to + query how many accelerator cores it has. + + Returns: + A map of accelerator types to number of cores. + """ + master = self.master(task_type, task_id) + # TODO(b/126786766): in eager mode, we should check whether + # `tf.config.experimental_connect_to_cluster` is called or not. + devices = get_accelerator_devices(master, config_proto) + mapping = collections.defaultdict(int) + for device in devices: + if task_type is not None and task_id is not None: + job_path = '/job:%s' % task_type + task_path = '/task:%s' % task_id + if job_path not in device.name or task_path not in device.name: + continue + mapping[device.device_type] += 1 + return mapping + + @property + def environment(self): + """Returns the current environment which TensorFlow is running in. + + There are two possible return values, "google" (when TensorFlow is running + in a Google-internal environment) or an empty string (when TensorFlow is + running elsewhere). + + If you are implementing a ClusterResolver that works in both the Google + environment and the open-source world (for instance, a TPU ClusterResolver + or similar), you will have to return the appropriate string depending on the + environment, which you will have to detect. + + Otherwise, if you are implementing a ClusterResolver that will only work + in open-source TensorFlow, you do not need to implement this property. + """ + return '' + + @property + def task_type(self): + """Returns the task type this `ClusterResolver` indicates. + + In TensorFlow distributed environment, each job may have an applicable + task type. Valid task types in TensorFlow include + 'chief': a worker that is designated with more responsibility, + 'worker': a regular worker for training/evaluation, + 'ps': a parameter server, or + 'evaluator': an evaluator that evaluates the checkpoints for metrics. + + See [Multi-worker configuration]( + https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras#multi-worker_configuration) + for more information about 'chief' and 'worker' task type, which are most + commonly used. + + Having access to such information is useful when user needs to run specific + code according to task types. For example, + + ```python + cluster_spec = tf.train.ClusterSpec({ + "ps": ["localhost:2222", "localhost:2223"], + "worker": ["localhost:2224", "localhost:2225", "localhost:2226"] + }) + + # SimpleClusterResolver is used here for illustration; other cluster + # resolvers may be used for other source of task type/id. + simple_resolver = SimpleClusterResolver(cluster_spec, task_type="worker", + task_id=1) + + ... + + if cluster_resolver.task_type == 'worker': + # Perform something that's only applicable on workers. This block + # will run on this particular instance since we've specified this task to + # be a worker in above cluster resolver. + elif cluster_resolver.task_type == 'ps': + # Perform something that's only applicable on parameter servers. This + # block will not run on this particular instance. + ``` + + Returns `None` if such information is not available or is not applicable + in the current distributed environment, such as training with + `tf.distribute.experimental.TPUStrategy`. + + For more information, please see + `tf.distribute.cluster_resolver.ClusterResolver`'s class doc. + """ + return getattr(self, '_task_type', None) + + @property + def task_id(self): + """Returns the task id this `ClusterResolver` indicates. + + In TensorFlow distributed environment, each job may have an applicable + task id, which is the index of the instance within its task type. This is + useful when user needs to run specific code according to task index. For + example, + + ```python + cluster_spec = tf.train.ClusterSpec({ + "ps": ["localhost:2222", "localhost:2223"], + "worker": ["localhost:2224", "localhost:2225", "localhost:2226"] + }) + + # SimpleClusterResolver is used here for illustration; other cluster + # resolvers may be used for other source of task type/id. + simple_resolver = SimpleClusterResolver(cluster_spec, task_type="worker", + task_id=0) + + ... + + if cluster_resolver.task_type == 'worker' and cluster_resolver.task_id == 0: + # Perform something that's only applicable on 'worker' type, id 0. This + # block will run on this particular instance since we've specified this + # task to be a 'worker', id 0 in above cluster resolver. + else: + # Perform something that's only applicable on other ids. This block will + # not run on this particular instance. + ``` + + Returns `None` if such information is not available or is not applicable + in the current distributed environment, such as training with + `tf.distribute.cluster_resolver.TPUClusterResolver`. + + For more information, please see + `tf.distribute.cluster_resolver.ClusterResolver`'s class docstring. + """ + return getattr(self, '_task_id', None) + + @task_type.setter + def task_type(self, task_type): + """Setter of `task_type` property. See `task_type` property doc.""" + self._task_type = task_type + + @task_id.setter + def task_id(self, task_id): + """Setter of `task_id` property. See `task_type` property doc.""" + self._task_id = task_id + + +@tf_export('distribute.cluster_resolver.SimpleClusterResolver') +class SimpleClusterResolver(ClusterResolver): + """Simple implementation of ClusterResolver that accepts all attributes. + + Please see the base class for documentation of arguments of its constructor. + + It is useful if you want to specify some or all attributes. + + Usage example with `tf.distribute.Strategy`: + + ```Python + cluster = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222", + "worker1.example.com:2222"]}) + + # On worker 0 + cluster_resolver = SimpleClusterResolver(cluster, task_type="worker", + task_id=0, + num_accelerators={"GPU": 8}, + rpc_layer="grpc") + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=cluster_resolver) + + # On worker 1 + cluster_resolver = SimpleClusterResolver(cluster, task_type="worker", + task_id=1, + num_accelerators={"GPU": 8}, + rpc_layer="grpc") + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=cluster_resolver) + ``` + """ + + def __init__(self, cluster_spec, master='', task_type=None, task_id=None, + environment='', num_accelerators=None, + rpc_layer=None): + """Creates a SimpleClusterResolver from a ClusterSpec.""" + super(SimpleClusterResolver, self).__init__() + + self._task_type = task_type + self._task_id = task_id + self._environment = environment + + self._num_accelerators = num_accelerators + self._rpc_layer = rpc_layer + + if not isinstance(cluster_spec, ClusterSpec): + raise TypeError('cluster_spec must be a `tf.train.ClusterSpec`.') + self._cluster_spec = cluster_spec + + if not isinstance(master, str): + raise TypeError('master must be a string.') + self._master = master + + def cluster_spec(self): + """Returns the ClusterSpec passed into the constructor.""" + return self._cluster_spec + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Returns the master address to use when creating a session. + + Note: this is only useful for TensorFlow 1.x. + + Args: + task_type: (Optional) The type of the TensorFlow task of the master. + task_id: (Optional) The index of the TensorFlow task of the master. + rpc_layer: (Optional) The RPC used by distributed TensorFlow. + + Returns: + The name or URL of the session master. + + If a task_type and task_id is given, this will override the `master` + string passed into the initialization function. + """ + if task_type is not None and task_id is not None: + master = self.cluster_spec().task_address(task_type, task_id) + else: + master = self._master + + return format_master_url(master, rpc_layer=rpc_layer or self._rpc_layer) + + @property + def task_type(self): + return self._task_type + + @property + def task_id(self): + return self._task_id + + @task_type.setter + def task_type(self, task_type): + self._task_type = task_type + + @task_id.setter + def task_id(self, task_id): + self._task_id = task_id + + @property + def environment(self): + return self._environment + + def num_accelerators(self, + task_type=None, + task_id=None, + config_proto=None): + """Returns the number of accelerator cores per worker. + + The SimpleClusterResolver does not do automatic detection of accelerators, + and thus all arguments are unused and we simply return the value provided + in the constructor. + + Args: + task_type: Unused. + task_id: Unused. + config_proto: Unused. + """ + # Unused + del task_type, task_id, config_proto + if self._num_accelerators is None: + return {} + return self._num_accelerators + + @property + def rpc_layer(self): + return self._rpc_layer + + @rpc_layer.setter + def rpc_layer(self, rpc_layer): + self._rpc_layer = rpc_layer + + +@tf_export('distribute.cluster_resolver.UnionResolver') +class UnionClusterResolver(ClusterResolver): + """Performs a union on underlying ClusterResolvers. + + This class performs a union given two or more existing ClusterResolvers. It + merges the underlying ClusterResolvers, and returns one unified ClusterSpec + when cluster_spec is called. The details of the merge function is + documented in the cluster_spec function. + + For additional ClusterResolver properties such as task type, task index, + rpc layer, environment, etc..., we will return the value from the first + ClusterResolver in the union. + + An example to combine two cluster resolvers: + + ```Python + cluster_0 = tf.train.ClusterSpec({"worker": ["worker0.example.com:2222", + "worker1.example.com:2222"]}) + cluster_resolver_0 = SimpleClusterResolver(cluster, task_type="worker", + task_id=0, + rpc_layer="grpc") + + cluster_1 = tf.train.ClusterSpec({"ps": ["ps0.example.com:2222", + "ps1.example.com:2222"]}) + cluster_resolver_1 = SimpleClusterResolver(cluster, task_type="ps", + task_id=0, + rpc_layer="grpc") + + # Its task type would be "worker". + cluster_resolver = UnionClusterResolver(cluster_resolver_0, + cluster_resolver_1) + ``` + + An example to override the number of GPUs in a TFConfigClusterResolver + instance: + + ```Python + tf_config = TFConfigClusterResolver() + gpu_override = SimpleClusterResolver(tf_config.cluster_spec(), + num_accelerators={"GPU": 1}) + cluster_resolver = UnionResolver(gpu_override, tf_config) + ``` + """ + + def __init__(self, *args, **kwargs): + """Initializes a UnionClusterResolver with other ClusterResolvers. + + Args: + *args: `ClusterResolver` objects to be unionized. + **kwargs: + rpc_layer - (Optional) Override value for the RPC layer used by + TensorFlow. + task_type - (Optional) Override value for the current task type. + task_id - (Optional) Override value for the current task index. + + Raises: + TypeError: If any argument is not a subclass of `ClusterResolvers`. + ValueError: If there are no arguments passed. + """ + super(UnionClusterResolver, self).__init__() + + self._rpc_layer = kwargs.pop('rpc_layer', None) + self._task_type = kwargs.pop('task_type', None) + self._task_id = kwargs.pop('task_id', None) + + if kwargs: + raise ValueError('Unexpected kwargs provided {!r}'.format(kwargs)) + + if not args: + raise ValueError('At least one ClusterResolver is required.') + + for cluster_resolver in args: + if not isinstance(cluster_resolver, ClusterResolver): + raise TypeError('All arguments must be a sub-class of ' + '`ClusterResolver.`') + self._cluster_resolvers = args + + def cluster_spec(self): + """Returns a union of all the ClusterSpecs from the ClusterResolvers. + + Returns: + A ClusterSpec containing host information merged from all the underlying + ClusterResolvers. + + Raises: + KeyError: If there are conflicting keys detected when merging two or + more dictionaries, this exception is raised. + + Note: If there are multiple ClusterResolvers exposing ClusterSpecs with the + same job name, we will merge the list/dict of workers. + + If *all* underlying ClusterSpecs expose the set of workers as lists, we will + concatenate the lists of workers, starting with the list of workers from + the first ClusterResolver passed into the constructor. + + If *any* of the ClusterSpecs expose the set of workers as a dict, we will + treat all the sets of workers as dicts (even if they are returned as lists) + and will only merge them into a dict if there is no conflicting keys. If + there is a conflicting key, we will raise a `KeyError`. + """ + + merged_cluster = {} + + # We figure out whether it is all lists for a particular job, or whether + # there are dicts inside. + for cluster_resolver in self._cluster_resolvers: + cluster_spec = cluster_resolver.cluster_spec() + cluster_dict = cluster_spec.as_dict() + + for job_name, tasks in cluster_dict.items(): + if job_name in merged_cluster: + # If we see a dict, then we write a dict out regardless. + if isinstance(tasks, dict): + merged_cluster[job_name] = {} + else: + # We take whichever type is present. + if isinstance(tasks, list): + merged_cluster[job_name] = [] + else: + merged_cluster[job_name] = {} + + # We then do the merge as appropriate in merged_cluster[job]. + for cluster_resolver in self._cluster_resolvers: + cluster_spec = cluster_resolver.cluster_spec() + cluster_dict = cluster_spec.as_dict() + + for job_name, tasks in cluster_dict.items(): + if isinstance(merged_cluster[job_name], list): + # We all have lists, we can just concatenate and be done. + merged_cluster[job_name].extend(tasks) + else: + if isinstance(tasks, list): + # We convert to a dictionary if the type is a list. + task_dict = dict(zip(range(0, len(tasks)), tasks)) + else: + # We can simply make a copy (for update) and be done. + task_dict = tasks.copy() + + # We detect if there are duplicates, and raise an error if so. + task_keys = set(task_dict) + merged_keys = set(merged_cluster[job_name].keys()) + intersected_keys = task_keys.intersection(merged_keys) + if intersected_keys: + raise KeyError('Duplicate keys detected when merging two ' + 'ClusterSpecs: %s' % repr(intersected_keys)) + + # We do the merge after all the processing. + merged_cluster[job_name].update(task_dict) + + return ClusterSpec(merged_cluster) + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Returns the master address to use when creating a session. + + This usually returns the master from the first ClusterResolver passed in, + but you can override this by specifying the task_type and task_id. + + Note: this is only useful for TensorFlow 1.x. + + Args: + task_type: (Optional) The type of the TensorFlow task of the master. + task_id: (Optional) The index of the TensorFlow task of the master. + rpc_layer: (Optional) The RPC protocol for the given cluster. + + Returns: + The name or URL of the session master. + """ + if task_type is not None and task_id is not None: + master = self.cluster_spec().task_address(task_type, task_id) + return format_master_url(master, rpc_layer or self._rpc_layer) + + return self._cluster_resolvers[0].master(rpc_layer=rpc_layer) + + @property + def task_type(self): + return self._task_type or self._cluster_resolvers[0].task_type + + @property + def task_id(self): + return self._task_id or self._cluster_resolvers[0].task_id + + @task_type.setter + def task_type(self, task_type): + self._task_type = task_type + + @task_id.setter + def task_id(self, task_id): + self._task_id = task_id + + @property + def environment(self): + return self._cluster_resolvers[0].environment + + def num_accelerators(self, + task_type=None, + task_id=None, + config_proto=None): + return self._cluster_resolvers[0].num_accelerators( + task_type, task_id, config_proto) + + @property + def rpc_layer(self): + return self._rpc_layer or self._cluster_resolvers[0].rpc_layer + + @rpc_layer.setter + def rpc_layer(self, rpc_layer): + self._rpc_layer = rpc_layer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/gce_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/gce_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..054eeedb81b1cc8a5b83ba6a1c2f4c3ba0e60c87 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/gce_cluster_resolver.py @@ -0,0 +1,207 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Implementation of ClusterResolvers for GCE instance groups.""" + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.training.server_lib import ClusterSpec +from tensorflow.python.util.tf_export import tf_export + + +_GOOGLE_API_CLIENT_INSTALLED = True +try: + from googleapiclient import discovery # pylint: disable=g-import-not-at-top + from oauth2client.client import GoogleCredentials # pylint: disable=g-import-not-at-top +except ImportError: + _GOOGLE_API_CLIENT_INSTALLED = False + + +@tf_export('distribute.cluster_resolver.GCEClusterResolver') +class GCEClusterResolver(ClusterResolver): + """ClusterResolver for Google Compute Engine. + + This is an implementation of cluster resolvers for the Google Compute Engine + instance group platform. By specifying a project, zone, and instance group, + this will retrieve the IP address of all the instances within the instance + group and return a ClusterResolver object suitable for use for distributed + TensorFlow. + + Note: this cluster resolver cannot retrieve `task_type`, `task_id` or + `rpc_layer`. To use it with some distribution strategies like + `tf.distribute.experimental.MultiWorkerMirroredStrategy`, you will need to + specify `task_type` and `task_id` in the constructor. + + Usage example with tf.distribute.Strategy: + + ```Python + # On worker 0 + cluster_resolver = GCEClusterResolver("my-project", "us-west1", + "my-instance-group", + task_type="worker", task_id=0) + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=cluster_resolver) + + # On worker 1 + cluster_resolver = GCEClusterResolver("my-project", "us-west1", + "my-instance-group", + task_type="worker", task_id=1) + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=cluster_resolver) + ``` + """ + + def __init__(self, + project, + zone, + instance_group, + port, + task_type='worker', + task_id=0, + rpc_layer='grpc', + credentials='default', + service=None): + """Creates a new GCEClusterResolver object. + + This takes in a few parameters and creates a GCEClusterResolver project. It + will then use these parameters to query the GCE API for the IP addresses of + each instance in the instance group. + + Args: + project: Name of the GCE project. + zone: Zone of the GCE instance group. + instance_group: Name of the GCE instance group. + port: Port of the listening TensorFlow server (default: 8470) + task_type: Name of the TensorFlow job this GCE instance group of VM + instances belong to. + task_id: The task index for this particular VM, within the GCE + instance group. In particular, every single instance should be assigned + a unique ordinal index within an instance group manually so that they + can be distinguished from each other. + rpc_layer: The RPC layer TensorFlow should use to communicate across + instances. + credentials: GCE Credentials. If nothing is specified, this defaults to + GoogleCredentials.get_application_default(). + service: The GCE API object returned by the googleapiclient.discovery + function. (Default: discovery.build('compute', 'v1')). If you specify a + custom service object, then the credentials parameter will be ignored. + + Raises: + ImportError: If the googleapiclient is not installed. + """ + self._project = project + self._zone = zone + self._instance_group = instance_group + self._task_type = task_type + self._task_id = task_id + self._rpc_layer = rpc_layer + self._port = port + self._credentials = credentials + + if credentials == 'default': + if _GOOGLE_API_CLIENT_INSTALLED: + self._credentials = GoogleCredentials.get_application_default() + + if service is None: + if not _GOOGLE_API_CLIENT_INSTALLED: + raise ImportError('googleapiclient must be installed before using the ' + 'GCE cluster resolver') + self._service = discovery.build( + 'compute', 'v1', + credentials=self._credentials) + else: + self._service = service + + def cluster_spec(self): + """Returns a ClusterSpec object based on the latest instance group info. + + This returns a ClusterSpec object for use based on information from the + specified instance group. We will retrieve the information from the GCE APIs + every time this method is called. + + Returns: + A ClusterSpec containing host information retrieved from GCE. + """ + request_body = {'instanceState': 'RUNNING'} + request = self._service.instanceGroups().listInstances( + project=self._project, + zone=self._zone, + instanceGroups=self._instance_group, + body=request_body, + orderBy='name') + + worker_list = [] + + while request is not None: + response = request.execute() + + items = response['items'] + for instance in items: + instance_name = instance['instance'].split('/')[-1] + + instance_request = self._service.instances().get( + project=self._project, + zone=self._zone, + instance=instance_name) + + if instance_request is not None: + instance_details = instance_request.execute() + ip_address = instance_details['networkInterfaces'][0]['networkIP'] + instance_url = '%s:%s' % (ip_address, self._port) + worker_list.append(instance_url) + + request = self._service.instanceGroups().listInstances_next( + previous_request=request, + previous_response=response) + + worker_list.sort() + return ClusterSpec({self._task_type: worker_list}) + + def master(self, task_type=None, task_id=None, rpc_layer=None): + task_type = task_type if task_type is not None else self._task_type + task_id = task_id if task_id is not None else self._task_id + + if task_type is not None and task_id is not None: + master = self.cluster_spec().task_address(task_type, task_id) + if rpc_layer or self._rpc_layer: + return '%s://%s' % (rpc_layer or self._rpc_layer, master) + else: + return master + + return '' + + @property + def task_type(self): + return self._task_type + + @property + def task_id(self): + return self._task_id + + @task_type.setter + def task_type(self, task_type): + raise RuntimeError( + 'You cannot reset the task_type of the GCEClusterResolver after it has ' + 'been created.') + + @task_id.setter + def task_id(self, task_id): + self._task_id = task_id + + @property + def rpc_layer(self): + return self._rpc_layer + + @rpc_layer.setter + def rpc_layer(self, rpc_layer): + self._rpc_layer = rpc_layer diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/kubernetes_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/kubernetes_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..f74089ed0415b6fbf9bbd5f2d3dbfd98ea07d4ee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/kubernetes_cluster_resolver.py @@ -0,0 +1,181 @@ +# 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. +# ============================================================================== +"""Implementation of Cluster Resolvers for Kubernetes.""" + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import format_master_url +from tensorflow.python.training import server_lib +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('distribute.cluster_resolver.KubernetesClusterResolver') +class KubernetesClusterResolver(ClusterResolver): + """ClusterResolver for Kubernetes. + + This is an implementation of cluster resolvers for Kubernetes. When given the + the Kubernetes namespace and label selector for pods, we will retrieve the + pod IP addresses of all running pods matching the selector, and return a + ClusterSpec based on that information. + + Note: it cannot retrieve `task_type`, `task_id` or `rpc_layer`. To use it + with some distribution strategies like + `tf.distribute.experimental.MultiWorkerMirroredStrategy`, you will need to + specify `task_type` and `task_id` by setting these attributes. + + Usage example with tf.distribute.Strategy: + + ```Python + # On worker 0 + cluster_resolver = KubernetesClusterResolver( + {"worker": ["job-name=worker-cluster-a", "job-name=worker-cluster-b"]}) + cluster_resolver.task_type = "worker" + cluster_resolver.task_id = 0 + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=cluster_resolver) + + # On worker 1 + cluster_resolver = KubernetesClusterResolver( + {"worker": ["job-name=worker-cluster-a", "job-name=worker-cluster-b"]}) + cluster_resolver.task_type = "worker" + cluster_resolver.task_id = 1 + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=cluster_resolver) + ``` + """ + + def __init__(self, + job_to_label_mapping=None, + tf_server_port=8470, + rpc_layer='grpc', + override_client=None): + """Initializes a new KubernetesClusterResolver. + + This initializes a new Kubernetes ClusterResolver. The ClusterResolver + will attempt to talk to the Kubernetes master to retrieve all the instances + of pods matching a label selector. + + Args: + job_to_label_mapping: A mapping of TensorFlow jobs to label selectors. + This allows users to specify many TensorFlow jobs in one Cluster + Resolver, and each job can have pods belong with different label + selectors. For example, a sample mapping might be + ``` + {'worker': ['job-name=worker-cluster-a', 'job-name=worker-cluster-b'], + 'ps': ['job-name=ps-1', 'job-name=ps-2']} + ``` + tf_server_port: The port the TensorFlow server is listening on. + rpc_layer: (Optional) The RPC layer TensorFlow should use to communicate + between tasks in Kubernetes. Defaults to 'grpc'. + override_client: The Kubernetes client (usually automatically retrieved + using `from kubernetes import client as k8sclient`). If you pass this + in, you are responsible for setting Kubernetes credentials manually. + + Raises: + ImportError: If the Kubernetes Python client is not installed and no + `override_client` is passed in. + RuntimeError: If autoresolve_task is not a boolean or a callable. + """ + try: + from kubernetes import config as k8sconfig # pylint: disable=g-import-not-at-top + + k8sconfig.load_kube_config() + except ImportError: + if not override_client: + raise ImportError('The Kubernetes Python client must be installed ' + 'before using the Kubernetes Cluster Resolver. ' + 'To install the Kubernetes Python client, run ' + '`pip install kubernetes` on your command line.') + + if not job_to_label_mapping: + job_to_label_mapping = {'worker': ['job-name=tensorflow']} + + self._job_to_label_mapping = job_to_label_mapping + self._tf_server_port = tf_server_port + self._override_client = override_client + + self.task_type = None + self.task_id = None + self.rpc_layer = rpc_layer + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Returns the master address to use when creating a session. + + You must have set the task_type and task_id object properties before + calling this function, or pass in the `task_type` and `task_id` + parameters when using this function. If you do both, the function parameters + will override the object properties. + + Note: this is only useful for TensorFlow 1.x. + + Args: + task_type: (Optional) The type of the TensorFlow task of the master. + task_id: (Optional) The index of the TensorFlow task of the master. + rpc_layer: (Optional) The RPC protocol for the given cluster. + + Returns: + The name or URL of the session master. + """ + task_type = task_type if task_type is not None else self.task_type + task_id = task_id if task_id is not None else self.task_id + + if task_type is not None and task_id is not None: + return format_master_url( + self.cluster_spec().task_address(task_type, task_id), + rpc_layer or self.rpc_layer) + + return '' + + def cluster_spec(self): + """Returns a ClusterSpec object based on the latest info from Kubernetes. + + We retrieve the information from the Kubernetes master every time this + method is called. + + Returns: + A ClusterSpec containing host information returned from Kubernetes. + + Raises: + RuntimeError: If any of the pods returned by the master is not in the + `Running` phase. + """ + if self._override_client: + client = self._override_client + else: + from kubernetes import config as k8sconfig # pylint: disable=g-import-not-at-top + from kubernetes import client as k8sclient # pylint: disable=g-import-not-at-top + + k8sconfig.load_kube_config() + client = k8sclient.CoreV1Api() + + cluster_map = {} + + for tf_job in self._job_to_label_mapping: + all_pods = [] + for selector in self._job_to_label_mapping[tf_job]: + ret = client.list_pod_for_all_namespaces(label_selector=selector) + selected_pods = [] + + # Sort the list by the name to make sure it doesn't change call to call. + for pod in sorted(ret.items, key=lambda x: x.metadata.name): + if pod.status.phase == 'Running': + selected_pods.append( + '%s:%s' % (pod.status.host_ip, self._tf_server_port)) + else: + raise RuntimeError('Pod "%s" is not running; phase: "%s"' % + (pod.metadata.name, pod.status.phase)) + all_pods.extend(selected_pods) + cluster_map[tf_job] = all_pods + + return server_lib.ClusterSpec(cluster_map) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/sagemaker_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/sagemaker_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..c287a53ddb24e9a74a177604902f9679c1b9ea1b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/sagemaker_cluster_resolver.py @@ -0,0 +1,204 @@ +# 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. +# ============================================================================== +"""Implementation of Cluster Resolvers for SageMaker Environment.""" + +import json +import os + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.training.server_lib import ClusterSpec + +# List of envs +# https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md +# Only support Multi-Worker Mirrored Strategy + +_SESSION_MASTER_KEY = 'session_master' +_RPC_LAYER_KEY = 'rpc_layer' +_TASK_KEY = 'task' +_CLUSTER_KEY = 'cluster' +_WORKER_KEY = 'worker' +_INDEX_KEY = 'index' +_TYPE_KEY = 'type' + +_SM_CURRENT_HOST = 'SM_CURRENT_HOST' +_SM_HOSTS = 'SM_HOSTS' + + +def format_master_url(master, rpc_layer=None): + if rpc_layer: + return '%s://%s' % (rpc_layer, master) + else: + return master + + +def _load_tf_config(port): + # Create a tf_config from SM Variables + assert all([x in os.environ for x in [_SM_CURRENT_HOST, _SM_HOSTS] + ]), 'Not a SageMaker Environment' + hosts = sorted(json.loads( + os.environ[_SM_HOSTS])) if os.environ[_SM_HOSTS] != '' else [] + current_host = os.environ[_SM_CURRENT_HOST] + + if current_host not in hosts: + return {} + + host_index = hosts.index(current_host) + # Assign ports + hosts = ['%s:%s' % (host, port) for host in hosts] + + tf_config = { + _CLUSTER_KEY: { + _WORKER_KEY: hosts + }, + _TASK_KEY: { + _TYPE_KEY: _WORKER_KEY, + _INDEX_KEY: host_index + } + } + return tf_config + + +def _get_value_in_tfconfig(key, port, default=None): + tf_config = _load_tf_config(port) + return tf_config[key] if key in tf_config else default + + +class SageMakerClusterResolver(ClusterResolver): + """Implementation of a ClusterResolver which reads the Sagemaker EnvVars. This is an implementation of cluster resolvers when running in a SageMaker environment to set information about the cluster. + + The cluster spec returned will be initialized from the SageMaker + environment variables. + Currently this Cluster Resolver only supports Multi-Worker Mirrored Strategy. + It assumes all nodes in a SageMaker Cluster are workers. + """ + + def __init__(self, + port=2223, + task_type=None, + task_id=None, + rpc_layer=None, + environment=None): + """Creates a new SageMakerClusterResolver. + + Args: + port: (integer, optional) Override default port usage of 2223 + task_type: (String, optional) Overrides the task type. + task_id: (Integer, optional) Overrides the task index. + rpc_layer: (String, optional) Overrides the rpc layer TensorFlow uses. + environment: (String, optional) Overrides the environment TensorFlow + operates in. + """ + self._task_type = task_type + self._task_id = task_id + self._rpc_layer = rpc_layer + self._environment = environment + self._port = str(port) + + @property + def task_type(self): + if self._task_type is None: + task_info = _get_value_in_tfconfig(_TASK_KEY, self._port, {}) + return str(task_info['type']) if 'type' in task_info else None + else: + return str(self._task_type) + + @property + def task_id(self): + if self._task_id is None: + task_info = _get_value_in_tfconfig(_TASK_KEY, self._port, {}) + return int(task_info['index']) if 'index' in task_info else None + else: + return int(self._task_id) + + @task_type.setter + def task_type(self, task_type): + self._task_type = task_type + + @task_id.setter + def task_id(self, task_id): + self._task_id = task_id + + @property + def environment(self): + return self._environment + + @property + def rpc_layer(self): + if self._rpc_layer is None: + return _get_value_in_tfconfig(_RPC_LAYER_KEY, self._port) + else: + return self._rpc_layer + + @rpc_layer.setter + def rpc_layer(self, rpc_layer): + self._rpc_layer = rpc_layer + + def num_accelerators(self, task_type=None, task_id=None, config_proto=None): + task_type = self.task_type if task_type is None else task_type + task_id = self.task_id if task_id is None else task_id + return super(SageMakerClusterResolver, + self).num_accelerators(task_type, task_id, config_proto) + + def cluster_spec(self): + """Returns a ClusterSpec based on the SageMaker environment variables. + + Returns: + A ClusterSpec with information from the SageMaker environment variables. + """ + tf_config = _load_tf_config(self._port) + if 'cluster' not in tf_config: + return ClusterSpec({}) + return ClusterSpec(tf_config['cluster']) + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Returns the master address to use when creating a TensorFlow session. + + Note: this is only useful for TensorFlow 1.x. + + Args: + task_type: (String, optional) Overrides and sets the task_type of the + master. + task_id: (Integer, optional) Overrides and sets the task id of the master. + rpc_layer: (String, optional) Overrides and sets the protocol over which + TensorFlow nodes communicate with each other. + + Returns: + The address of the master. + + Raises: + RuntimeError: If the task_type or task_id is not specified and the + SageMaker environment variables does not contain a task section. + """ + + # If `session_master` is set, just use that. + session_master = _get_value_in_tfconfig(_SESSION_MASTER_KEY, self._port) + if session_master is not None: + return session_master + + # Return an empty string if we are the only job in the ClusterSpec. + cluster_spec = self.cluster_spec() + if (not cluster_spec.jobs or + (len(cluster_spec.jobs) == 1 and + len(cluster_spec.job_tasks(cluster_spec.jobs[0])) == 1)): + return '' + + # We try to auto-detect the task type and id, but uses the user-supplied one + # where available + task_type = task_type if task_type is not None else self.task_type + task_id = task_id if task_id is not None else self.task_id + rpc_layer = rpc_layer if rpc_layer is not None else self.rpc_layer + + return format_master_url( + cluster_spec.task_address(task_type, task_id), rpc_layer) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/slurm_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/slurm_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..65208dab3e8540f9c4a315a1e7fd8d58abe78913 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/slurm_cluster_resolver.py @@ -0,0 +1,397 @@ +# Copyright 2018-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. +# ============================================================================== +"""Implementation of Cluster Resolvers for Slurm workload manager.""" + +import os +import re +import subprocess + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import format_master_url +from tensorflow.python.training.server_lib import ClusterSpec +from tensorflow.python.util.tf_export import tf_export + + +def expand_hostlist(hostlist): + """Create a list of hosts out of a SLURM hostlist. + + The order of nodes is preserved and no deduplication is done + Input: 'n[1-2],m5,o[3-4,6,7-9]') + Output: ['n1', 'n2', 'm5', 'o3', 'o4', 'o6', 'o7', 'o8', 'o9'] + """ + + def split_hostlist(hostlist): + """Split hostlist at commas outside of range expressions ('[3-5]').""" + in_brackets = False + cur_host = '' + for c in hostlist: + if in_brackets: + assert c != '[' + if c == ']': + in_brackets = False + elif c == '[': + in_brackets = True + elif c == ',': + assert cur_host != '' + yield cur_host + cur_host = '' + continue + cur_host += c + if cur_host: + yield cur_host + + def expand_range_expression(range_exp): + """Expand a range expression like '3-5' to values 3,4,5.""" + for part in range_exp.split(','): + sub_range = part.split('-') + if len(sub_range) == 1: + sub_range = sub_range * 2 + else: + assert len(sub_range) == 2 + num_digits = len(sub_range[0]) + for i in range(int(sub_range[0]), int(sub_range[1]) + 1): + yield str(i).zfill(num_digits) + + hosts = [] + try: + for part in split_hostlist(hostlist): + # Match prefix (anything but a range expression) and range expression + # Both are optional + m = re.match(r'([^,[\]]*)(\[([^\]]+)\])?$', part) + if m is None: + raise ValueError('Invalid part: %s' % part) + prefix = m.group(1) or '' + if m.group(3) is None: + hosts.append(prefix) + else: + hosts.extend(prefix + i for i in expand_range_expression(m.group(3))) + except Exception as e: + raise ValueError('Invalid hostlist format "%s": %s' % (hostlist, e)) + return hosts + + +def expand_tasks_per_node(tasks_per_node): + """Expands the tasks per node expression from SLURM. + + The order is preserved so it can be matched to the hostlist + Input: '3(x2),2,1' + Output: [3, 3, 2, 1] + """ + result = [] + try: + for part in tasks_per_node.split(','): + m = re.match(r'(\d+)(\(x(\d+)\))?$', part) + assert m is not None + num_tasks = int(m.group(1)) + num_repetitions = int(m.group(3) or 1) + result.extend([num_tasks] * num_repetitions) + except Exception as e: + raise ValueError('Invalid tasks-per-node list format "%s": %s' % + (tasks_per_node, e)) + return result + + +def _get_slurm_var(name): + """Gets the SLURM variable from the environment. + + Args: + name: Name of the step variable + + Returns: + SLURM_ from os.environ + Raises: + RuntimeError if variable is not found + """ + name = 'SLURM_' + name + try: + return os.environ[name] + except KeyError: + raise RuntimeError('%s not found in environment. ' + 'Not running inside a SLURM step?' % name) + + +def _get_num_slurm_tasks(): + """Returns the number of SLURM tasks of the current job step. + + Returns: + The number of tasks as an int + """ + return int(_get_slurm_var('STEP_NUM_TASKS')) + + +def _get_num_nvidia_gpus(): + """Gets the number of NVIDIA GPUs by using CUDA_VISIBLE_DEVICES and nvidia-smi. + + Returns: + Number of GPUs available on the node + Raises: + RuntimeError if executing nvidia-smi failed + """ + try: + return len(os.environ['CUDA_VISIBLE_DEVICES'].split(',')) + except KeyError: + pass # Ignore and fallback to using nvidia-smi + try: + output = subprocess.check_output(['nvidia-smi', '--list-gpus'], + encoding='utf-8') + return sum(l.startswith('GPU ') for l in output.strip().split('\n')) + except subprocess.CalledProcessError as e: + raise RuntimeError('Could not get number of GPUs from nvidia-smi. ' + 'Maybe it is missing?\nOutput: %s' % e.output) + + +def get_num_gpus(): + """Returns the number of GPUs visible on the current node. + + Currently only implemented for NVIDIA GPUs. + """ + return _get_num_nvidia_gpus() + + +@tf_export('distribute.cluster_resolver.SlurmClusterResolver') +class SlurmClusterResolver(ClusterResolver): + """ClusterResolver for system with Slurm workload manager. + + This is an implementation of ClusterResolver for Slurm clusters. This allows + the specification of jobs and task counts, number of tasks per node, number + of GPUs on each node and number of GPUs for each task. It retrieves system + attributes by Slurm environment variables, resolves allocated computing node + names, constructs a cluster and returns a ClusterResolver object which can be + used for distributed TensorFlow. + """ + + def __init__(self, + jobs=None, + port_base=8888, + gpus_per_node=None, + gpus_per_task=None, + tasks_per_node=None, + auto_set_gpu=True, + rpc_layer='grpc'): + """Creates a new SlurmClusterResolver object. + + For any parameter not set it will query the environment for the value. + It uses those parameters to check which nodes have processes reside on and + resolves their hostnames. + With the number tasks per node it offsets the port number for each process. + With the number of GPUs per node and per task it allocates GPUs to tasks by + setting environment variables. + Using the resolver works best (and is easier) with homogeneous tasks but + heterogeneous tasks (number of tasks varying per node) are also possible as + long as the number of GPUs per task stays constant. + + Used environment variables: + - SLURM_PROCID + - (opt) SLURM_STEP_NUM_TASKS + - (opt) SLURM_STEP_NODELIST + - (opt) SLURM_STEP_TASKS_PER_NODE + + Args: + jobs: Dictionary with job names as key and number of tasks in the job as + value. Defaults to as many 'worker's as there are (Slurm) tasks. + port_base: The first port number to start with for processes on a node. + gpus_per_node: Number of GPUs available on each node. Defaults to the + number of GPUs reported by nvidia-smi + gpus_per_task: Number of GPUs to be used for each task. Default is to + evenly distribute the gpus_per_node to tasks_per_node. + tasks_per_node: Number of tasks running on each node. Can be an integer if + the number of tasks per node is constant or a dictionary mapping + hostnames to number of tasks on that node. If not set the Slurm + environment is queried for the correct mapping. + auto_set_gpu: Set the visible CUDA devices automatically while resolving + the cluster by setting CUDA_VISIBLE_DEVICES environment variable. + Defaults to True. + rpc_layer: The protocol TensorFlow used to communicate between nodes. + Defaults to 'grpc'. + + Returns: + A ClusterResolver object which can be used with distributed TensorFlow. + + Raises: + RuntimeError: If requested more GPUs per node than available or + requested more tasks than assigned tasks or + resolving missing values from the environment failed. + """ + + self._rank = self._resolve_own_rank() + + if jobs is None: + jobs = {'worker': self._resolve_num_tasks()} + + self._jobs = jobs + self._port_base = port_base + + if tasks_per_node is None: + self._task_configuration = self._resolve_task_configuration() + elif isinstance(tasks_per_node, dict): + # User can pass in an explicit configuration as a dict + self._task_configuration = tasks_per_node + else: + # User can pass a fixed number of tasks per node + hostlist = self._resolve_hostlist() + self._task_configuration = { + host: int(tasks_per_node) for host in hostlist + } + + max_tasks_per_node = max(self._task_configuration.values()) + num_tasks = sum(self._task_configuration.values()) + + if gpus_per_node is None: + gpus_per_node = get_num_gpus() + if gpus_per_task is None: + gpus_per_task = gpus_per_node // max_tasks_per_node + self._gpus_per_node = gpus_per_node + self._gpus_per_task = gpus_per_task + + self._auto_set_gpu = auto_set_gpu + self.task_type = None + self.task_id = None + self.rpc_layer = rpc_layer + + self._gpu_allocation = [] + self._cluster_allocation = {} + + if max_tasks_per_node * self._gpus_per_task > self._gpus_per_node: + raise RuntimeError('Requested more GPUs per node than available.') + + if sum(self._jobs.values()) != num_tasks: + raise RuntimeError('Requested {} tasks but only {} were assigned.'.format( + sum(self._jobs.values()), num_tasks)) + + def _resolve_own_rank(self): + """Returns the rank of the current task in range [0, num_tasks).""" + return int(_get_slurm_var('PROCID')) + + def _resolve_num_tasks(self): + """Returns the number of tasks for the current job step.""" + return _get_num_slurm_tasks() + + def _resolve_hostlist(self): + """Returns a list of hostnames for nodes running the current job step.""" + return expand_hostlist(_get_slurm_var('STEP_NODELIST')) + + def _resolve_task_configuration(self): + """Creates a mapping of hostnames to the number of tasks allocated on it. + + Reads the SLURM environment to determine the nodes involved in the current + job step and number of tasks running on each node. + + Returns a dictionary mapping each hostname to the number of tasks. + """ + hostlist = self._resolve_hostlist() + tasks_per_node = expand_tasks_per_node( + _get_slurm_var('STEP_TASKS_PER_NODE')) + return { + host: num_tasks for (host, num_tasks) in zip(hostlist, tasks_per_node) + } + + def cluster_spec(self): + """Returns a ClusterSpec object based on the latest instance group info. + + This returns a ClusterSpec object for use based on information from the + specified initialization parameters and Slurm environment variables. The + cluster specification is resolved each time this function is called. The + resolver extract hostnames of nodes by scontrol and pack tasks in that + order until a node a has number of tasks that is equal to specification. + GPUs on nodes are allocated to tasks by specification through setting + CUDA_VISIBLE_DEVICES environment variable. + + Returns: + A ClusterSpec containing host information retrieved from Slurm's + environment variables. + """ + + task_list = [] + self._gpu_allocation = [] + self._cluster_allocation = {} + + # Sort to make sure the order is the same for each run + for host, num_tasks in sorted(self._task_configuration.items()): + for port_offset, gpu_offset in zip( + range(num_tasks), range(0, self._gpus_per_node, self._gpus_per_task)): + + host_addr = '%s:%d' % (host, self._port_base + port_offset) + task_list.append(host_addr) + gpu_id_list = [] + + for gpu_id in range(gpu_offset, gpu_offset + self._gpus_per_task): + gpu_id_list.append(str(gpu_id)) + + self._gpu_allocation.append(','.join(gpu_id_list)) + + cluster_rank_offset_start = 0 + cluster_rank_offset_end = 0 + + # Sort to make sure the order is the same for each run + for task_type, num_tasks in sorted(self._jobs.items()): + cluster_rank_offset_end = cluster_rank_offset_start + num_tasks + + self._cluster_allocation[task_type] = ( + task_list[cluster_rank_offset_start:cluster_rank_offset_end]) + + if cluster_rank_offset_start <= self._rank < cluster_rank_offset_end: + self.task_type = task_type + self.task_id = self._rank - cluster_rank_offset_start + + cluster_rank_offset_start = cluster_rank_offset_end + + if self._auto_set_gpu: + os.environ['CUDA_VISIBLE_DEVICES'] = self._gpu_allocation[self._rank] + + return ClusterSpec(self._cluster_allocation) + + def get_task_info(self): + """Returns job name and task_id for the process which calls this. + + This returns the job name and task index for the process which calls this + function according to its rank and cluster specification. The job name and + task index are set after a cluster is constructed by cluster_spec otherwise + defaults to None. + + Returns: + A string specifying job name the process belongs to and an integer + specifying the task index the process belongs to in that job. + """ + return self.task_type, self.task_id + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Returns the master string for connecting to a TensorFlow master. + + Args: + task_type: (Optional) Overrides the default auto-selected task type. + task_id: (Optional) Overrides the default auto-selected task index. + rpc_layer: (Optional) Overrides the default RPC protocol TensorFlow uses + to communicate across nodes. + + Returns: + A connection string for connecting to a TensorFlow master. + """ + task_type = task_type if task_type is not None else self.task_type + task_id = task_id if task_id is not None else self.task_id + + if task_type is not None and task_id is not None: + return format_master_url( + self.cluster_spec().task_address(task_type, task_id), + rpc_layer or self.rpc_layer) + + return '' + + def num_accelerators(self, + task_type=None, + task_id=None, + config_proto=None): + # Unused, since this is set in __init__ manually. + del task_type, task_id, config_proto + return {'GPU': self._gpus_per_task} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tfconfig_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tfconfig_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..cb944d6cd601710aba9ad4b08319dfb184756566 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tfconfig_cluster_resolver.py @@ -0,0 +1,200 @@ +# 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. +# ============================================================================== +"""Implementation of Cluster Resolvers for TF_CONFIG Environment Variables.""" + + +import json +import os + +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver +from tensorflow.python.training.server_lib import ClusterSpec +from tensorflow.python.util.tf_export import tf_export + +_TF_CONFIG_ENV = 'TF_CONFIG' +_SESSION_MASTER_KEY = 'session_master' +_RPC_LAYER_KEY = 'rpc_layer' +_TASK_KEY = 'task' + + +def format_master_url(master, rpc_layer=None): + if rpc_layer: + return '%s://%s' % (rpc_layer, master) + else: + return master + + +def _load_tf_config(): + return json.loads(os.environ.get(_TF_CONFIG_ENV, '{}')) + + +def _get_value_in_tfconfig(key, default=None): + tf_config = _load_tf_config() + return tf_config[key] if key in tf_config else default + + +@tf_export('distribute.cluster_resolver.TFConfigClusterResolver') +class TFConfigClusterResolver(ClusterResolver): + """Implementation of a ClusterResolver which reads the TF_CONFIG EnvVar. + + This is an implementation of cluster resolvers when using TF_CONFIG to set + information about the cluster. The cluster spec returned will be + initialized from the TF_CONFIG environment variable. + + An example to set TF_CONFIG is: + + ```Python + os.environ['TF_CONFIG'] = json.dumps({ + 'cluster': { + 'worker': ["localhost:12345", "localhost:23456"] + }, + 'task': {'type': 'worker', 'index': 0} + }) + ``` + + However, sometimes the container orchestration framework will set TF_CONFIG + for you. In this case, you can just create an instance without passing in any + arguments. You can find an example here to let Kuburnetes set TF_CONFIG for + you: https://github.com/tensorflow/ecosystem/tree/master/kubernetes. Then you + can use it with `tf.distribute.Strategy` as: + + ```Python + # `TFConfigClusterResolver` is already the default one in the following + # strategy. + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( + cluster_resolver=TFConfigClusterResolver()) + ``` + """ + + def __init__(self, + task_type=None, + task_id=None, + rpc_layer=None, + environment=None): + """Creates a new TFConfigClusterResolver. + + Args: + task_type: (String, optional) Overrides the task type specified in the + TF_CONFIG environment variable. + task_id: (Integer, optional) Overrides the task index specified in the + TF_CONFIG environment variable. + rpc_layer: (String, optional) Overrides the rpc layer TensorFlow uses. + environment: (String, optional) Overrides the environment TensorFlow + operates in. + """ + self._task_type = task_type + self._task_id = task_id + self._rpc_layer = rpc_layer + self._environment = environment + + @property + def task_type(self): + if self._task_type is None: + task_info = _get_value_in_tfconfig(_TASK_KEY, {}) + return str(task_info['type']) if 'type' in task_info else None + else: + return str(self._task_type) + + @property + def task_id(self): + if self._task_id is None: + task_info = _get_value_in_tfconfig(_TASK_KEY, {}) + return int(task_info['index']) if 'index' in task_info else None + else: + return int(self._task_id) + + @task_type.setter + def task_type(self, task_type): + self._task_type = task_type + + @task_id.setter + def task_id(self, task_id): + self._task_id = task_id + + @property + def environment(self): + return self._environment + + @property + def rpc_layer(self): + if self._rpc_layer is None: + return _get_value_in_tfconfig(_RPC_LAYER_KEY) + else: + return self._rpc_layer + + @rpc_layer.setter + def rpc_layer(self, rpc_layer): + self._rpc_layer = rpc_layer + + def num_accelerators(self, + task_type=None, + task_id=None, + config_proto=None): + task_type = self.task_type if task_type is None else task_type + task_id = self.task_id if task_id is None else task_id + return super(TFConfigClusterResolver, self).num_accelerators( + task_type, task_id, config_proto) + + def cluster_spec(self): + """Returns a ClusterSpec based on the TF_CONFIG environment variable. + + Returns: + A ClusterSpec with information from the TF_CONFIG environment variable. + """ + tf_config = _load_tf_config() + if 'cluster' not in tf_config: + return ClusterSpec({}) + return ClusterSpec(tf_config['cluster']) + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Returns the master address to use when creating a TensorFlow session. + + Note: this is only useful for TensorFlow 1.x. + + Args: + task_type: (String, optional) Overrides and sets the task_type of the + master. + task_id: (Integer, optional) Overrides and sets the task id of the + master. + rpc_layer: (String, optional) Overrides and sets the protocol over which + TensorFlow nodes communicate with each other. + + Returns: + The address of the master. + + Raises: + RuntimeError: If the task_type or task_id is not specified and the + `TF_CONFIG` environment variable does not contain a task section. + """ + + # If `session_master` is set, just use that. + session_master = _get_value_in_tfconfig(_SESSION_MASTER_KEY) + if session_master is not None: + return session_master + + # Return an empty string if we are the only job in the ClusterSpec. + cluster_spec = self.cluster_spec() + if (not cluster_spec.jobs or + (len(cluster_spec.jobs) == 1 and + len(cluster_spec.job_tasks(cluster_spec.jobs[0])) == 1)): + return '' + + # We try to auto-detect the task type and id, but uses the user-supplied one + # where available + task_type = task_type if task_type is not None else self.task_type + task_id = task_id if task_id is not None else self.task_id + rpc_layer = rpc_layer if rpc_layer is not None else self.rpc_layer + + return format_master_url(cluster_spec.task_address(task_type, task_id), + rpc_layer) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..4af2925ebd86502a92f6a86774d1892c9d421456 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver.py @@ -0,0 +1,480 @@ +# 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. +# ============================================================================== +"""Implementation of Cluster Resolvers for Cloud TPUs.""" + +import collections +import re + +from tensorflow.core.protobuf.tpu import topology_pb2 +from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib +from tensorflow.python.eager import remote +from tensorflow.python.framework import config as framework_config +from tensorflow.python.framework import errors +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.tpu import tpu_strategy_util +from tensorflow.python.tpu import tpu_system_metadata as tpu_system_metadata_lib +from tensorflow.python.training import server_lib +from tensorflow.python.util import compat + +try: + from cloud_tpu_client import client # pylint: disable=g-import-not-at-top +except ImportError: + logging.debug( + 'Falling back to TensorFlow client; we recommended you install the Cloud ' + 'TPU client directly with pip install cloud-tpu-client.') + from tensorflow.python.tpu.client import client # pylint: disable=g-import-not-at-top + + +def is_running_in_gce(): + return True + + +class _LocalCloudTpuClient(object): + """Dummy local Cloud TPU client.""" + + def api_available(self): + return False + + +_TPU_DEVICE_REGEX = re.compile( + r'.*task:(?P\d+)/.*device:TPU:(?P\d+)$') +_TPU_CONN_RETRIES = 120 +DeviceDetails = collections.namedtuple( + 'DeviceDetails', ['device_map', 'total_cores']) + + +def initialize_tpu_system(cluster_resolver=None): + """Initialize the TPU devices. + + Args: + cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, + which provides information about the TPU cluster. + Returns: + The tf.tpu.Topology object for the topology of the TPU cluster. If called + inside tf.function, it returns the serialized topology object instead. + + Raises: + RuntimeError: If running inside a tf.function. + NotFoundError: If no TPU devices found in eager mode. + """ + return tpu_strategy_util.initialize_tpu_system_impl( + cluster_resolver, TPUClusterResolver) + + +def shutdown_tpu_system(cluster_resolver=None): + """Shuts down the TPU devices. + + This will clear all caches, even those that are maintained through sequential + calls to tf.tpu.experimental.initialize_tpu_system, such as the compilation + cache. + + Args: + cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, + which provides information about the TPU cluster. + + Raises: + RuntimeError: If no TPU devices found for eager execution or if run in a + tf.function. + """ + tpu_strategy_util.shutdown_tpu_system_impl( + cluster_resolver, TPUClusterResolver) + + +class TPUClusterResolver(cluster_resolver_lib.ClusterResolver): + """Cluster Resolver for Google Cloud TPUs. + + This is an implementation of cluster resolvers for the Google Cloud TPU + service. + + TPUClusterResolver supports the following distinct environments: + Google Compute Engine + Google Kubernetes Engine + Google internal + + It can be passed into `tf.distribute.TPUStrategy` to support TF2 training on + Cloud TPUs. + """ + + @staticmethod + def connect(tpu=None, + zone=None, + project=None): + """Initializes TPU and returns a TPUClusterResolver. + + This API will connect to remote TPU cluster and initialize the TPU + hardwares. Example usage: + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver.connect( + ... tpu='') + + It can be viewed as convenient wrapper of the following code: + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + >>> tf.config.experimental_connect_to_cluster(resolver) + >>> tf.tpu.experimental.initialize_tpu_system(resolver) + + Args: + tpu: A string corresponding to the TPU to use. It can be the TPU name or + TPU worker gRPC address. If not set, it will try automatically resolve + the TPU address on Cloud TPUs. + zone: Zone where the TPUs are located. If omitted or empty, we will assume + that the zone of the TPU is the same as the zone of the GCE VM, which we + will try to discover from the GCE metadata service. + project: Name of the GCP project containing Cloud TPUs. If omitted or + empty, we will try to discover the project name of the GCE VM from the + GCE metadata service. + + Returns: + An instance of TPUClusterResolver object. + + Raises: + NotFoundError: If no TPU devices found in eager mode. + """ + resolver = TPUClusterResolver(tpu, zone, project) + remote.connect_to_cluster(resolver) + tpu_strategy_util.initialize_tpu_system_impl(resolver) + return resolver + + @staticmethod + def _get_device_dict_and_cores(devices): + """Returns a dict of hosts to cores and total cores given devices names. + + Returns a namedtuple with two attributes: + device_map: A map of host_ids to a list of core_ids. + total_cores: The total number of cores within the TPU system. + + Args: + devices: A list of devices returned by session.list_devices() + """ + device_map = collections.defaultdict(list) + num_cores = 0 + for device in devices: + match = _TPU_DEVICE_REGEX.match(device.name) + if match: + host_id = match.group('host_id') + core_id = match.group('core_id') + device_map[host_id].append(core_id) + num_cores += 1 + return DeviceDetails(device_map, num_cores) + + @staticmethod + def _verify_and_return_same_core_count(device_dict): + """Verifies that every device in device_dict has the same # of cores.""" + num_cores_per_host_set = ( + {len(core_ids) for core_ids in device_dict.values()}) + if len(num_cores_per_host_set) != 1: + raise RuntimeError('TPU cores on each device is not the same. This ' + 'should never happen. Devices: {}'.format(device_dict)) + return num_cores_per_host_set.pop() + + def __init__(self, + tpu=None, + zone=None, + project=None, + job_name='worker', + coordinator_name=None, + coordinator_address=None, + credentials='default', + service=None, + discovery_url=None): + """Creates a new TPUClusterResolver object. + + The ClusterResolver will then use the parameters to query the Cloud TPU APIs + for the IP addresses and ports of each Cloud TPU listed. + + Args: + tpu: A string corresponding to the TPU to use. It can be the TPU name or + TPU worker gRPC address. If not set, it will try automatically resolve + the TPU address on Cloud TPUs. If set to "local", it will assume that + the TPU is directly connected to the VM instead of over the network. + zone: Zone where the TPUs are located. If omitted or empty, we will assume + that the zone of the TPU is the same as the zone of the GCE VM, which we + will try to discover from the GCE metadata service. + project: Name of the GCP project containing Cloud TPUs. If omitted or + empty, we will try to discover the project name of the GCE VM from the + GCE metadata service. + job_name: Name of the TensorFlow job the TPUs belong to. + coordinator_name: The name to use for the coordinator. Set to None if the + coordinator should not be included in the computed ClusterSpec. + coordinator_address: The address of the coordinator (typically an ip:port + pair). If set to None, a TF server will be started. If coordinator_name + is None, a TF server will not be started even if coordinator_address is + None. + credentials: GCE Credentials. If None, then we use default credentials + from the oauth2client + service: The GCE API object returned by the googleapiclient.discovery + function. If you specify a custom service object, then the credentials + parameter will be ignored. + discovery_url: A URL template that points to the location of the discovery + service. It should have two parameters {api} and {apiVersion} that when + filled in produce an absolute URL to the discovery document for that + service. The environment variable 'TPU_API_DISCOVERY_URL' will override + this. + + Raises: + ImportError: If the googleapiclient is not installed. + ValueError: If no TPUs are specified. + RuntimeError: If an empty TPU name is specified and this is running in a + Google Cloud environment. + """ + + if tpu != 'local': + # Default Cloud environment + self._cloud_tpu_client = client.Client( + tpu=tpu, + zone=zone, + project=project, + credentials=credentials, + service=service, + discovery_url=discovery_url) + self._tpu = self._cloud_tpu_client.name() + else: + # Directly connected TPU environment + self._cloud_tpu_client = _LocalCloudTpuClient() + self._tpu = 'local' + + # By default the task_type is 'worker` and the task_id is 0 (which is the + # first worker in the task). + self.task_type = job_name + self.task_id = 0 + self._coordinator_name = coordinator_name + if (coordinator_name and not coordinator_address): + self._start_local_server() + else: + self._coordinator_address = coordinator_address + + self._tpu_topology = None + + def __enter__(self): + self._cloud_tpu_client.enter() + + def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin + self._cloud_tpu_client.exit(type, value, traceback) + + def master(self, task_type=None, task_id=None, rpc_layer=None): + """Get the Master string to be used for the session. + + In the normal case, this returns the grpc path (grpc://1.2.3.4:8470) of + first instance in the ClusterSpec returned by the cluster_spec function. + + If a non-TPU name is used when constructing a TPUClusterResolver, that will + be returned instead (e.g. If the tpus argument's value when constructing + this TPUClusterResolver was 'grpc://10.240.1.2:8470', + 'grpc://10.240.1.2:8470' will be returned). + + Args: + task_type: (Optional, string) The type of the TensorFlow task of the + master. + task_id: (Optional, integer) The index of the TensorFlow task of the + master. + rpc_layer: (Optional, string) The RPC protocol TensorFlow should use to + communicate with TPUs. + + Returns: + string, the connection string to use when creating a session. + + Raises: + ValueError: If none of the TPUs specified exists. + """ + + if self._tpu != 'local': + cluster_spec = self.cluster_spec() + if task_type is not None and task_id is not None: + # task_type and task_id is from the function parameter + master = cluster_spec.task_address(task_type, task_id) + elif self.task_type is not None and self.task_id is not None: + # task_type and task_id is from the object + master = cluster_spec.task_address(self.task_type, self.task_id) + else: + # by default we take the first item in the cluster with the right name + job_tasks = cluster_spec.job_tasks(self.task_type) + if not job_tasks: + raise ValueError('No TPUs with the specified names exist.') + master = job_tasks[0] + return cluster_resolver_lib.format_master_url(master, 'grpc') + else: + return '' + + def get_master(self): + return self.master() + + def get_job_name(self): + return self.task_type + + def get_coordination_service_leader(self): + """Returns the location for coordination service. + + The coordination service should be located on TPU worker0. + + Returns: + A string indicate the location path. + """ + return '/job:' + self.get_job_name() + '/task:0' + + def get_tpu_system_metadata(self): + """Returns the metadata of the TPU system. + + Users can call this method to get some facts of the TPU system, like + total number of cores, number of TPU workers and the devices. E.g. + ```python + + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + tpu_system_metadata = resolver.get_tpu_system_metadata() + num_hosts = tpu_system_metadata.num_hosts + ``` + + Returns: + A `tf.tpu.experimental.TPUSystemMetadata` object. + """ + cluster_spec = self.cluster_spec() + cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None + tpu_system_metadata = ( + tpu_system_metadata_lib._query_tpu_system_metadata( # pylint: disable=protected-access + self.master(), + cluster_def=cluster_def, + query_topology=False)) + + return tpu_system_metadata + + def cluster_spec(self): + """Returns a ClusterSpec object based on the latest TPU information. + + We retrieve the information from the GCE APIs every time this method is + called. + + Returns: + A ClusterSpec containing host information returned from Cloud TPUs, + or None. + + Raises: + RuntimeError: If the provided TPU is not healthy. + """ + ############################################################################ + # There are 6 potential cases this code must handle: + # 0. [Local case.] When a TPU is connected directly to the VM. + # 1. [Normal case.] We should resolve the TPU name to a set of tasks, and + # a. Create a ClusterSpec that includes the coordinator job + # b. Create a ClusterSpec without the coordinator job. + # 2. [GKE / No API Access.] We should not resolve the TPU name to a set of + # tasks and + # a. Create a ClusterSpec with the coordinator + # b. Create a ClusterSpec without the coordinator + ############################################################################ + + if self._tpu != 'local': + network_endpoints = self._cloud_tpu_client.network_endpoints() + worker_list = [ + '%s:%s' % (endpoint['ipAddress'], endpoint['port']) + for endpoint in network_endpoints + ] + cluster_spec = {self.task_type: worker_list} + if self._coordinator_address: + # {1, 2}.a + cluster_spec[self._coordinator_name] = [self._coordinator_address] + return server_lib.ClusterSpec(cluster_spec) + else: + return server_lib.ClusterSpec({}) + + def num_accelerators(self, + task_type=None, + task_id=None, + config_proto=None): + """Returns the number of TPU cores per worker. + + Connects to the master and list all the devices present in the master, + and counts them up. Also verifies that the device counts per host in the + cluster is the same before returning the number of TPU cores per host. + + Args: + task_type: Unused. + task_id: Unused. + config_proto: Used to create a connection to a TPU master in order to + retrieve the system metadata. + + Raises: + RuntimeError: If we cannot talk to a TPU worker after retrying or if the + number of TPU devices per host is different. + """ + if self._tpu == 'local': + return { + 'TPU': + len([ + d for d in framework_config.list_logical_devices() + if d.device_type == 'TPU' + ]) + } + + retry_count = 1 + # TODO(b/120564445): Replace with standard library for retries. + while True: + try: + device_details = TPUClusterResolver._get_device_dict_and_cores( + cluster_resolver_lib.get_accelerator_devices( + self.master(), config_proto=config_proto)) + break + except errors.DeadlineExceededError: + error_message = ('Failed to connect to master. The TPU might not be ' + 'ready (e.g. still scheduling) or the master ' + 'address is incorrect: got (%s)' % self.master()) + if retry_count <= _TPU_CONN_RETRIES: + logging.warning(error_message) + logging.warning('Retrying (%d/%d)...', retry_count, _TPU_CONN_RETRIES) + retry_count += 1 + else: + raise RuntimeError(error_message) + + if device_details.total_cores: + return { + 'TPU': + TPUClusterResolver._verify_and_return_same_core_count( + device_details.device_map) + } + return {'TPU': 0} + + def set_tpu_topology(self, serialized_tpu_topology): + """Sets the tpu topology info stored in this resolver.""" + self._tpu_topology = topology_pb2.TopologyProto() + self._tpu_topology.ParseFromString(serialized_tpu_topology) + + @property + def tpu_hardware_feature(self): + """Returns the tpu topology info stored.""" + if self._tpu_topology is None: + return self._tpu_topology + return self._tpu_topology.tpu_hardware_feature + + @property + def environment(self): + """Returns the current environment which TensorFlow is running in.""" + return '' + + def _start_local_server(self): + address = compat.as_text(self._cloud_tpu_client.get_local_ip()) + self._server = server_lib.Server({'local': ['0.0.0.0:0']}, + protocol='grpc', + config=None, + start=True) + # self._server.target is of the form: grpc://ipaddress:port + target = compat.as_bytes(self._server.target) + splits = target.split(compat.as_bytes(':')) + assert len(splits) == 3, self._server.target + assert splits[0] == compat.as_bytes('grpc'), self._server.target + self._coordinator_port = compat.as_text(splits[2]) + self._coordinator_address = '%s:%s' % ( + address, compat.as_text(self._coordinator_port)) + + def __deepcopy__(self, memo): + # TODO(b/73668574): Remove this once RunConfig avoids performing deepcopy. + return self diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu_cluster_resolver.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu_cluster_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..4aebbf27cfcbb5c5a15034b0939f342ed8b92188 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cluster_resolver/tpu_cluster_resolver.py @@ -0,0 +1,26 @@ +# 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. +# ============================================================================== +"""Shim so that direct imports of tpu_cluster_resolver get correct symbols. +""" + +from tensorflow.python.distribute.cluster_resolver.tpu.tpu_cluster_resolver import initialize_tpu_system +from tensorflow.python.distribute.cluster_resolver.tpu.tpu_cluster_resolver import is_running_in_gce # pylint: disable=unused-import +from tensorflow.python.distribute.cluster_resolver.tpu.tpu_cluster_resolver import shutdown_tpu_system +from tensorflow.python.distribute.cluster_resolver.tpu.tpu_cluster_resolver import TPUClusterResolver +from tensorflow.python.util.tf_export import tf_export + +tf_export('distribute.cluster_resolver.TPUClusterResolver')(TPUClusterResolver) +tf_export('tpu.experimental.initialize_tpu_system')(initialize_tpu_system) +tf_export('tpu.experimental.shutdown_tpu_system')(shutdown_tpu_system) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/collective_all_reduce_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/collective_all_reduce_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..b87ded9aee90a708fac40f5c2c6fe53ac89e58e1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/collective_all_reduce_strategy.py @@ -0,0 +1,1014 @@ +# 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. +# ============================================================================== +"""Class CollectiveAllReduceStrategy implementing DistributionStrategy.""" + +import copy +import threading +import time +import weakref + +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.core.protobuf import tensorflow_server_pb2 +from tensorflow.python.distribute import collective_util +from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib +from tensorflow.python.distribute import cross_device_utils +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import input_util +from tensorflow.python.distribute import mirrored_strategy +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute import numpy_dataset +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import values +from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib +from tensorflow.python.distribute.cluster_resolver import tfconfig_cluster_resolver +from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver +from tensorflow.python.distribute.v1 import input_lib as input_lib_v1 +from tensorflow.python.eager import context +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import collective_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tsl.protobuf import coordination_config_pb2 + + +# pylint: disable=line-too-long +@tf_export("distribute.MultiWorkerMirroredStrategy", v1=[]) +class CollectiveAllReduceStrategy(distribute_lib.Strategy): + """A distribution strategy for synchronous training on multiple workers. + + This strategy implements synchronous distributed training across multiple + workers, each with potentially multiple GPUs. Similar to + `tf.distribute.MirroredStrategy`, it replicates all variables and computations + to each local device. The difference is that it uses a distributed collective + implementation (e.g. all-reduce), so that multiple workers can work together. + + You need to launch your program on each worker and configure + `cluster_resolver` correctly. For example, if you are using + `tf.distribute.cluster_resolver.TFConfigClusterResolver`, each worker needs to + have its corresponding `task_type` and `task_id` set in the `TF_CONFIG` + environment variable. An example TF_CONFIG on worker-0 of a two worker cluster + is: + + ``` + TF_CONFIG = '{"cluster": {"worker": ["localhost:12345", "localhost:23456"]}, "task": {"type": "worker", "index": 0} }' + ``` + + Your program runs on each worker as-is. Note that collectives require each + worker to participate. All `tf.distribute` and non `tf.distribute` API may use + collectives internally, e.g. checkpointing and saving since reading a + `tf.Variable` with `tf.VariableSynchronization.ON_READ` all-reduces the value. + Therefore it's recommended to run exactly the same program on each worker. + Dispatching based on `task_type` or `task_id` of the worker is error-prone. + + `cluster_resolver.num_accelerators()` determines the number of GPUs the + strategy uses. If it's zero, the strategy uses the CPU. All workers need to + use the same number of devices, otherwise the behavior is undefined. + + This strategy is not intended for TPU. Use `tf.distribute.TPUStrategy` + instead. + + After setting up TF_CONFIG, using this strategy is similar to using + `tf.distribute.MirroredStrategy` and `tf.distribute.TPUStrategy`. + + ``` + strategy = tf.distribute.MultiWorkerMirroredStrategy() + + with strategy.scope(): + model = tf.keras.Sequential([ + tf.keras.layers.Dense(2, input_shape=(5,)), + ]) + optimizer = tf.keras.optimizers.SGD(learning_rate=0.1) + + def dataset_fn(ctx): + x = np.random.random((2, 5)).astype(np.float32) + y = np.random.randint(2, size=(2, 1)) + dataset = tf.data.Dataset.from_tensor_slices((x, y)) + return dataset.repeat().batch(1, drop_remainder=True) + dist_dataset = strategy.distribute_datasets_from_function(dataset_fn) + + model.compile() + model.fit(dist_dataset) + ``` + + You can also write your own training loop: + + ``` + @tf.function + def train_step(iterator): + + def step_fn(inputs): + features, labels = inputs + with tf.GradientTape() as tape: + logits = model(features, training=True) + loss = tf.keras.losses.sparse_categorical_crossentropy( + labels, logits) + + grads = tape.gradient(loss, model.trainable_variables) + optimizer.apply_gradients(zip(grads, model.trainable_variables)) + + strategy.run(step_fn, args=(next(iterator),)) + + for _ in range(NUM_STEP): + train_step(iterator) + ``` + + See + [Multi-worker training with Keras](https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras) + for a detailed tutorial. + + __Saving__ + + You need to save and checkpoint on all workers instead of just one. This is + because variables whose synchronization=ON_READ triggers aggregation during + saving. It's recommended to save to a different path on each worker to avoid + race conditions. Each worker saves the same thing. See + [Multi-worker training with Keras](https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras#model_saving_and_loading) + tutorial for examples. + + __Known Issues__ + + * `tf.distribute.cluster_resolver.TFConfigClusterResolver` does not return the + correct number of accelerators. The strategy uses all available GPUs if + `cluster_resolver` is `tf.distribute.cluster_resolver.TFConfigClusterResolver` + or `None`. + * In eager mode, the strategy needs to be created before calling any other + Tensorflow API. + + """ + # pylint: enable=line-too-long + + # TODO(anjalisridhar): Update our guides with examples showing how we can use + # the cluster_resolver argument. + + # The starting number for collective keys. This should only be set in tests. + _collective_key_base = 0 + + def __init__(self, + cluster_resolver=None, + communication_options=None): + """Creates the strategy. + + Args: + cluster_resolver: optional + `tf.distribute.cluster_resolver.ClusterResolver`. If `None`, + `tf.distribute.cluster_resolver.TFConfigClusterResolver` is used. + communication_options: optional + `tf.distribute.experimental.CommunicationOptions`. This configures the + default options for cross device communications. It can be overridden by + options provided to the communication APIs like + `tf.distribute.ReplicaContext.all_reduce`. See + `tf.distribute.experimental.CommunicationOptions` for details. + """ + if communication_options is None: + communication_options = collective_util.Options() + super(CollectiveAllReduceStrategy, self).__init__( + CollectiveAllReduceExtended( + self, + cluster_resolver=cluster_resolver, + communication_options=communication_options)) + + distribute_lib.distribution_strategy_gauge.get_cell("V2").set( + "MultiWorkerMirroredStrategy") + # pylint: disable=protected-access + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_workers").set(self.extended._num_workers) + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_replicas_per_worker").set(self.extended._num_devices_per_worker) + + @classmethod + def _from_local_devices(cls, devices, communication_options=None): + """A convenience method to create an object with a list of devices.""" + obj = cls(communication_options=communication_options) + obj.extended._initialize_local( # pylint: disable=protected-access + tfconfig_cluster_resolver.TFConfigClusterResolver(), devices=devices) + return obj + + @property + def cluster_resolver(self): + """Returns the cluster resolver associated with this strategy. + + As a multi-worker strategy, `tf.distribute.MultiWorkerMirroredStrategy` + provides the associated `tf.distribute.cluster_resolver.ClusterResolver`. If + the user provides one in `__init__`, that instance is returned; if the user + does not, a default `TFConfigClusterResolver` is provided. + """ + return self.extended._cluster_resolver # pylint: disable=protected-access + + +class _CollectiveAllReduceStrategyExperimentalMeta(type): + + @classmethod + def __instancecheck__(cls, instance): + # This is to make isinstance(tf.distribute.MultiWorkerMirroredStrategy(), + # tf.distribute.experimental.MultiWorkerMirroredStrategy). Some libraries is + # performing such check. + return isinstance(instance, CollectiveAllReduceStrategy) + + +@tf_export("distribute.experimental.MultiWorkerMirroredStrategy", v1=[]) +class _CollectiveAllReduceStrategyExperimental( + CollectiveAllReduceStrategy, + metaclass=_CollectiveAllReduceStrategyExperimentalMeta): + + __doc__ = CollectiveAllReduceStrategy.__doc__ + + @deprecation.deprecated( + None, "use distribute.MultiWorkerMirroredStrategy instead") + def __init__(self, + communication=collective_util.CommunicationImplementation.AUTO, + cluster_resolver=None): + """Creates the strategy. + + Args: + communication: optional + `tf.distribute.experimental.CommunicationImplementation`. This is a hint + on the preferred collective communication implementation. Possible + values include `AUTO`, `RING`, and `NCCL`. + cluster_resolver: optional + `tf.distribute.cluster_resolver.ClusterResolver`. If `None`, + `tf.distribute.cluster_resolver.TFConfigClusterResolver` is used. + """ + communication_options = collective_util.Options( + implementation=communication) + super(_CollectiveAllReduceStrategyExperimental, + self).__init__(cluster_resolver, communication_options) + + @classmethod + def _from_local_devices( + cls, + devices, + communication=collective_util.CommunicationImplementation.AUTO): + """A convenience method to create an object with a list of devices.""" + obj = cls(communication) + obj.extended._initialize_local(tfconfig_cluster_resolver.TFConfigClusterResolver(), devices=devices) # pylint: disable=protected-access + return obj + + +_CollectiveAllReduceStrategyExperimental.__name__ = CollectiveAllReduceStrategy.__name__ + + +@tf_export(v1=["distribute.experimental.MultiWorkerMirroredStrategy"]) # pylint: disable=missing-docstring +class CollectiveAllReduceStrategyV1(distribute_lib.StrategyV1): + + __doc__ = CollectiveAllReduceStrategy.__doc__ + + # The starting number for collective keys. This should only be set in tests. + _collective_key_base = 0 + + def __init__(self, + communication=collective_util.CommunicationImplementation.AUTO, + cluster_resolver=None): + """Initializes the object.""" + communication_options = collective_util.Options( + implementation=communication) + super(CollectiveAllReduceStrategyV1, self).__init__( + CollectiveAllReduceExtended( + self, + cluster_resolver=cluster_resolver, + communication_options=communication_options)) + distribute_lib.distribution_strategy_gauge.get_cell("V1").set( + "MultiWorkerMirroredStrategy") + # pylint: disable=protected-access + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_workers").set(self.extended._num_workers) + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_gpu_per_worker").set( + self.extended._num_devices_per_worker + if self.extended._local_device_type == "GPU" + else 0) + + +def _is_gpu_device(device): + return tf_device.DeviceSpec.from_string(device).device_type == "GPU" + + +class CollectiveAllReduceExtended(mirrored_strategy.MirroredExtended): + """Implementation of CollectiveAllReduceStrategy.""" + + # Whether to perdically check the health of the cluster. If any worker is not + # reachable, collectives are aborted and the user program should get a + # tf.errors.UnavailableError. It's required to restart in order to recover. + _enable_check_health = True + # Check health interval in seconds. + _check_health_interval = 30 + # Timeout in seconds for the first check health. The first check health needs + # to wait for cluster, which may make a longer time. + _check_health_initial_timeout = 0 + # Times to retry before considering the peer is down. + _check_health_retry_limit = 3 + # Timeout in seconds the each check health. + _check_health_timeout = 10 + + def __init__(self, container_strategy, cluster_resolver, + communication_options, devices=None): + if not isinstance(communication_options, collective_util.Options): + raise ValueError("communication_options must be an instance of " + "tf.distribute.experimental.CommunicationOptions") + if cluster_resolver and devices: + raise ValueError( + "cluster_resolver and devices cannot be set at the same time") + + self._cluster_resolver = cluster_resolver or tfconfig_cluster_resolver.TFConfigClusterResolver() + if not isinstance(self._cluster_resolver, cluster_resolver_lib.ClusterResolver): + raise ValueError("cluster_resolver must be an instance of " + "tf.distribute.cluster_resolver.ClusterResolver") + distribute_lib.StrategyExtendedV1.__init__(self, container_strategy) + self._communication_options = communication_options + self._collective_key_base = container_strategy._collective_key_base # pylint: disable=protected-access + self._initialize_strategy(self._cluster_resolver, devices=devices) + self._cfer_fn_cache = weakref.WeakKeyDictionary() + self.experimental_enable_get_next_as_optional = True + assert isinstance(self._cross_device_ops, + cross_device_ops_lib.CollectiveAllReduce) + + def _use_merge_call(self): + # We currently only disable merge_call when XLA is used to compile the `fn` + # passed to `strategy.run` and all devices are GPU. + return not control_flow_util.GraphOrParentsInXlaContext( + ops.get_default_graph()) or not all( + [_is_gpu_device(d) for d in self._devices]) + + def _initialize_strategy(self, cluster_resolver, devices): + # If devices are provided or cluster_spec is not specified, initialize + # single worker. Otherwise initialize multi workers. + if devices or not cluster_resolver.cluster_spec().as_dict(): + self._initialize_local(cluster_resolver, devices=devices) + else: + self._initialize_multi_worker(cluster_resolver) + + def _initialize_local_devices(self, cluster_resolver, worker_device): + # TODO(b/126786766): TFConfigClusterResolver returns wrong number of GPUs in + # some cases. + if isinstance(cluster_resolver, tfconfig_cluster_resolver.TFConfigClusterResolver): + num_gpus = context.num_gpus() + num_tpus = 0 + else: + num_gpus = cluster_resolver.num_accelerators().get("GPU", 0) + num_tpus = cluster_resolver.num_accelerators().get("TPU", 0) + + if num_gpus: + local_device_type = "GPU" + num_local_devices = num_gpus + elif num_tpus: + local_device_type = "TPU" + num_local_devices = num_tpus + else: + local_device_type = "CPU" + num_local_devices = 1 + local_devices = tuple( + f"{worker_device}/device:{local_device_type}:{i}" + for i in range(num_local_devices)) + return local_devices, local_device_type + + def _initialize_local(self, cluster_resolver, devices=None): + """Initializes the object for local training.""" + self._is_chief = True + self._num_workers = 1 + + if ops.executing_eagerly_outside_functions(): + try: + context.context().configure_collective_ops( + scoped_allocator_enabled_ops=("CollectiveReduce",)) + except RuntimeError: + logging.warning("Collective ops is not configured at program startup. " + "Some performance features may not be enabled.") + self._collective_ops_configured = True + + if devices: + local_devices = devices + if "GPU" in devices[0]: + local_device_type = "GPU" + elif "TPU" in devices[0]: + local_device_type = "TPU" + else: + local_device_type = "CPU" + else: + local_devices, local_device_type = self._initialize_local_devices( + cluster_resolver, worker_device="") + + self._worker_device = device_util.canonicalize("/device:CPU:0") + self._host_input_device = numpy_dataset.SingleDevice(self._worker_device) + + self._collective_keys = cross_device_utils.CollectiveKeys( + group_key_start=1 + self._collective_key_base) + self._cross_device_ops = cross_device_ops_lib.CollectiveAllReduce( + devices=local_devices, + group_size=len(local_devices), + options=self._communication_options, + collective_keys=self._collective_keys) + # CrossDeviceOps for per host tensors. + self._host_cross_device_ops = cross_device_ops_lib.CollectiveAllReduce( + devices=[self._worker_device], + group_size=self._num_workers, + options=self._communication_options, + collective_keys=self._collective_keys) + super(CollectiveAllReduceExtended, self)._initialize_single_worker( + local_devices) + + self._cluster_spec = None + self._task_type = None + self._task_id = None + self._id_in_cluster = 0 + + # This is a mark to tell whether we are running with standalone client or + # independent worker. Right now with standalone client, strategy object is + # created as local strategy and then turn into multi-worker strategy via + # configure call. + self._local_or_standalone_client_mode = True + + # Save the num_devices_per_worker and rpc_layer for configure method. + self._num_devices_per_worker = len(local_devices) + self._local_device_type = local_device_type + self._rpc_layer = cluster_resolver.rpc_layer + self._warn_nccl_no_gpu() + + logging.info( + "Single-worker MultiWorkerMirroredStrategy with local_devices " + "= %r, communication = %s", local_devices, + self._communication_options.implementation) + + def _initialize_multi_worker(self, cluster_resolver): + """Initializes the object for multi-worker training.""" + cluster_spec = multi_worker_util.normalize_cluster_spec( + cluster_resolver.cluster_spec()) + task_type = cluster_resolver.task_type + task_id = cluster_resolver.task_id + if task_type is None or task_id is None: + raise ValueError("When `cluster_spec` is given, you must also specify " + "`task_type` and `task_id`.") + self._cluster_spec = cluster_spec + self._task_type = task_type + self._task_id = task_id + self._id_in_cluster = multi_worker_util.id_in_cluster( + self._cluster_spec, self._task_type, self._task_id) + + self._num_workers = multi_worker_util.worker_count(cluster_spec, task_type) + if not self._num_workers: + raise ValueError("No `worker`, `chief` or `evaluator` tasks can be found " + "in `cluster_spec`.") + + self._is_chief = multi_worker_util.is_chief(cluster_spec, task_type, + task_id) + + self._worker_device = "/job:%s/task:%d" % (task_type, task_id) + self._host_input_device = numpy_dataset.SingleDevice(self._worker_device) + + if (ops.executing_eagerly_outside_functions() and + not getattr(self, "_local_or_standalone_client_mode", False)): + context.context().configure_collective_ops( + collective_leader=multi_worker_util.collective_leader( + cluster_spec, task_type, task_id), + scoped_allocator_enabled_ops=("CollectiveReduce",), + device_filters=("/job:%s/task:%d" % (task_type, task_id),)) + self._collective_ops_configured = True + if context.context().coordination_service is None: + coordinated_jobs = ["chief", "worker"] + if task_type in coordinated_jobs: + coordinated_job_config = [] + for job in coordinated_jobs: + if job in cluster_spec.jobs: + coordinated_job_config.append( + coordination_config_pb2.CoordinatedJob( + name=job, + num_tasks=cluster_spec.num_tasks(job))) + context.context().configure_coordination_service( + service_type="standalone", + service_leader=multi_worker_util.coordination_leader( + cluster_spec), + coordinated_jobs=coordinated_job_config) + + # Starting a std server in eager mode and in independent worker mode. + if (context.executing_eagerly() and + not getattr(self, "_std_server_started", False) and + not getattr(self, "_local_or_standalone_client_mode", False)): + # Checking _local_or_standalone_client_mode as well because we should not + # create the std server in standalone client mode. + config_proto = copy.deepcopy(context.context().config) + config_proto = self._update_config_proto(config_proto) + + # If coordination service is enabled, use its internal heartbeat to detect + # peer failures instead of the Python-level health check. + if config_proto.experimental.coordination_config.service_type: + self._enable_check_health = False + + if hasattr(cluster_resolver, "port"): + port = cluster_resolver.port + else: + port = 0 + server_def = tensorflow_server_pb2.ServerDef( + cluster=cluster_spec.as_cluster_def(), + default_session_config=config_proto, + job_name=task_type, + task_index=task_id, + protocol=cluster_resolver.rpc_layer or "grpc", + port=port) + context.context().enable_collective_ops(server_def) + self._std_server_started = True + # The `ensure_initialized` is needed before calling + # `context.context().devices()`. + context.context().ensure_initialized() + logging.info( + "Enabled multi-worker collective ops with available devices: %r", + context.context().devices()) + + # TODO(yuefengz): The `num_gpus` is only for this particular task. It + # assumes all workers have the same number of GPUs. We should remove this + # assumption by querying all tasks for their numbers of GPUs. + # TODO(b/126786766): TFConfigClusterResolver returns wrong number of GPUs in + # some cases. + local_devices, local_device_type = self._initialize_local_devices( + cluster_resolver, self._worker_device) + if local_device_type == "TPU": + tpu_cluster_resolver.initialize_tpu_system() + + self._collective_keys = cross_device_utils.CollectiveKeys( + group_key_start=1 + self._collective_key_base) + self._cross_device_ops = cross_device_ops_lib.CollectiveAllReduce( + devices=local_devices, + group_size=len(local_devices) * self._num_workers, + options=self._communication_options, + collective_keys=self._collective_keys) + # CrossDeviceOps for per host tensors. + self._host_cross_device_ops = cross_device_ops_lib.CollectiveAllReduce( + devices=[self._worker_device], + group_size=self._num_workers, + options=self._communication_options, + collective_keys=self._collective_keys) + super(CollectiveAllReduceExtended, self)._initialize_single_worker( + local_devices) + + # Add a default device so that ops without specified devices will not end up + # on other workers. + self._default_device = "/job:%s/task:%d" % (task_type, task_id) + + # Save the num_devices_per_worker and rpc_layer for configure method. + self._num_devices_per_worker = len(local_devices) + self._local_device_type = local_device_type + self._rpc_layer = cluster_resolver.rpc_layer + self._warn_nccl_no_gpu() + + if self._enable_check_health and context.executing_eagerly(): + self._start_check_health_thread() + else: + logging.info("Check health not enabled.") + + logging.info( + "MultiWorkerMirroredStrategy with cluster_spec = %r, task_type = %r, " + "task_id = %r, num_workers = %r, local_devices = %r, " + "communication = %s", cluster_spec.as_dict(), task_type, task_id, + self._num_workers, local_devices, + self._communication_options.implementation) + + def __del__(self): + self._stop_check_health_thread() + + def _input_workers_with_options(self, options=None): + host_device = device_util.get_host_for_device(self._worker_device) + if not options or options.experimental_fetch_to_device: + return input_lib.InputWorkers([(host_device, self.worker_devices)]) + else: + return input_lib.InputWorkers([( + host_device, + [device_util.get_host_for_device(worker) for worker in + self.worker_devices])]) + + @property + def _input_workers(self): + return self._input_workers_with_options() + + def _get_variable_creator_initial_value(self, + replica_id, + device, + primary_var, + **kwargs): + if replica_id == 0: # First replica on each worker. + assert device is not None + assert primary_var is None + + def initial_value_fn(): # pylint: disable=g-missing-docstring + # Only the first device participates in the broadcast of initial values. + group_key = self._collective_keys.get_group_key([device]) + group_size = self._num_workers + collective_instance_key = ( + self._collective_keys.get_instance_key(group_key, device)) + + with ops.device(device): + initial_value = kwargs["initial_value"] + if callable(initial_value): + initial_value = initial_value() + if isinstance(initial_value, base.CheckpointInitialValue): + initial_value = initial_value.wrapped_value + assert not callable(initial_value) + initial_value = ops.convert_to_tensor( + initial_value, dtype=kwargs.get("dtype", None)) + + if self._num_workers > 1: + if self._is_chief: + bcast_send = collective_ops.broadcast_send( + initial_value, initial_value.shape, initial_value.dtype, + group_size, group_key, collective_instance_key) + with ops.control_dependencies([bcast_send]): + return array_ops.identity(initial_value) + else: + return collective_ops.broadcast_recv(initial_value.shape, + initial_value.dtype, + group_size, group_key, + collective_instance_key) + return initial_value + + return initial_value_fn + else: + return super(CollectiveAllReduceExtended, + self)._get_variable_creator_initial_value( + replica_id=replica_id, + device=device, + primary_var=primary_var, + **kwargs) + + def _make_input_context(self): + input_context = distribute_lib.InputContext( + num_input_pipelines=self._num_workers, + input_pipeline_id=self._id_in_cluster, + num_replicas_in_sync=self._num_replicas_in_sync) + return input_context + + def _experimental_distribute_dataset(self, dataset, options): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`distribute_datasets_from_function` " + "of tf.distribute.MirroredStrategy" + ) + input_context = self._make_input_context() + return input_util.get_distributed_dataset( + dataset, + self._input_workers_with_options(options), + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync, + input_context=input_context, + options=options) + + def _distribute_datasets_from_function(self, dataset_fn, options): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`distribute_datasets_from_function` " + "of tf.distribute.MirroredStrategy") + input_context = self._make_input_context() + return input_util.get_distributed_datasets_from_function( + dataset_fn=dataset_fn, + input_workers=self._input_workers_with_options(options), + input_contexts=[input_context], + strategy=self._container_strategy(), + options=options) + + def _experimental_distribute_values_from_function(self, value_fn): + per_replica_values = [] + num_local_replicas = len(self.worker_devices) + for local_replica_id in range(num_local_replicas): + replica_id = (self._id_in_cluster * num_local_replicas + + local_replica_id) + value_context = distribute_lib.ValueContext( + replica_id, self._num_replicas_in_sync) + per_replica_values.append(value_fn(value_context)) + return distribute_utils.regroup(per_replica_values, always_wrap=True) + + def _make_dataset_iterator(self, dataset): + """Distributes the dataset to each local GPU.""" + input_context = self._make_input_context() + return input_lib_v1.DatasetIterator( + dataset, + self._input_workers, + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync, + input_context=input_context) + + def _make_input_fn_iterator( + self, + input_fn, + replication_mode=distribute_lib.InputReplicationMode.PER_WORKER): + """Distributes the input function to each local GPU.""" + input_context = self._make_input_context() + return input_lib_v1.InputFunctionIterator(input_fn, self._input_workers, + [input_context], + self._container_strategy()) + + def _configure(self, + session_config=None, + cluster_spec=None, + task_type=None, + task_id=None): + """Configures the object. + + Args: + session_config: a `tf.compat.v1.ConfigProto` + cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the + cluster configurations. + task_type: the current task type, such as "worker". + task_id: the current task id. + + Raises: + ValueError: if `task_type` is not in the `cluster_spec`. + """ + if cluster_spec: + cluster_resolver = cluster_resolver_lib.SimpleClusterResolver( + cluster_spec=multi_worker_util.normalize_cluster_spec(cluster_spec), + task_type=task_type, + task_id=task_id, + num_accelerators={ + self._local_device_type: self._num_devices_per_worker}, + rpc_layer=self._rpc_layer) + self._initialize_multi_worker(cluster_resolver) + assert isinstance(self._cross_device_ops, + cross_device_ops_lib.CollectiveAllReduce) + + if session_config: + session_config.CopyFrom(self._update_config_proto(session_config)) + + def _update_config_proto(self, config_proto): + updated_config = copy.deepcopy(config_proto) + # Enable the scoped allocator optimization for CollectiveOps. This + # optimization converts many small all-reduces into fewer larger + # all-reduces. + rewrite_options = updated_config.graph_options.rewrite_options + rewrite_options.scoped_allocator_optimization = ( + rewriter_config_pb2.RewriterConfig.ON) + # We turn on ScopedAllocator only for CollectiveReduce op, i.e. enable_op = + # ["CollectiveReduce"]. Since we can't assign to a repeated proto field, we + # clear and then append. + del rewrite_options.scoped_allocator_opts.enable_op[:] + rewrite_options.scoped_allocator_opts.enable_op.append("CollectiveReduce") + + if (not ops.executing_eagerly_outside_functions() and + self._communication_options.implementation == + collective_util.CommunicationImplementation.NCCL): + updated_config.experimental.collective_nccl = True + + if not self._cluster_spec: + return updated_config + + assert self._task_type + assert self._task_id is not None + + # Collective group leader is needed for collective ops to coordinate + # workers. + updated_config.experimental.collective_group_leader = ( + multi_worker_util.collective_leader(self._cluster_spec, self._task_type, + self._task_id)) + + # The device filters prevent communication between workers. + del updated_config.device_filters[:] + updated_config.device_filters.append( + "/job:%s/task:%d" % (self._task_type, self._task_id)) + + return updated_config + + def _get_cross_device_ops(self, value): + # CollectiveAllReduce works on a predefined set of devices. In most cases + # they should be the compute devices, but certain use cases may reduce host + # tensors as well (e.g. early stopping). We infer the cross_device_ops to + # use based on the number of devices, since inputs don't always have device + # annotations. The compute devices one is preferred since we can potentially + # leverage NCCL. + if isinstance(value, values.DistributedValues): + num_devices = len(value._values) # pylint: disable=protected-access + else: + num_devices = 1 + if num_devices == len(self.worker_devices): + return self._cross_device_ops + else: + return self._host_cross_device_ops + + def _gather_to_implementation(self, value, destinations, axis, options): + return self._get_cross_device_ops(value)._gather( # pylint: disable=protected-access + value, + destinations=destinations, + axis=axis, + options=options) + + def _reduce_to(self, reduce_op, value, destinations, options): + if (isinstance(value, values.Mirrored) and + reduce_op == reduce_util.ReduceOp.MEAN): + return value + assert not isinstance(value, values.Mirrored) + + if (isinstance(value, values.DistributedValues) and + len(self.worker_devices) == 1): + value = value.values[0] + + # When there are multiple workers, we need to reduce across workers using + # collective ops. + if (not isinstance(value, values.DistributedValues) and + self._num_workers == 1): + # This function handles reducing values that are not PerReplica or + # Mirrored values. For example, the same value could be present on all + # replicas in which case `value` would be a single value or value could + # be 0. + return cross_device_ops_lib.reduce_non_distributed_value( + reduce_op, value, destinations, len(self.worker_devices)) + return self._get_cross_device_ops(value).reduce( + reduce_op, + value, + destinations=destinations, + options=self._communication_options.merge(options)) + + def _replica_ctx_all_reduce(self, reduce_op, value, options=None): + """Implements `StrategyExtendedV2._replica_ctx_all_reduce`.""" + # This implementation avoids using `merge_call` and just launches collective + # ops in one replica. + if options is None: + options = collective_util.Options() + + if context.executing_eagerly(): + # In eager mode, falls back to the default implemenation that uses + # `merge_call`. Replica functions are running sequentially in eager mode, + # and due to the blocking nature of collective ops, execution will hang if + # collective ops are to be launched sequentially. + return super()._replica_ctx_all_reduce(reduce_op, value, options) + + replica_context = distribute_lib.get_replica_context() + assert replica_context, ( + "`StrategyExtended._replica_ctx_all_reduce` must be called in a " + "replica context") + return self._cross_device_ops._all_reduce( # pylint: disable=protected-access + reduce_op, + value, + replica_context._replica_id, # pylint: disable=protected-access + options) + + def _check_health(self): + while True: + if self._check_health_thread_should_stop.is_set(): + return + for job in self._cluster_spec.jobs: + for task_id in range(self._cluster_spec.num_tasks(job)): + peer = "/job:{}/replica:0/task:{}".format(job, task_id) + attempts = 0 + while True: + attempts += 1 + try: + context.context().check_collective_ops_peer_health( + peer, timeout_in_ms=self._check_health_timeout * 1000) + # If check_collective_ops_peer_health doesn't raise an Exception, + # the peer is healthy. + break + except (errors.UnavailableError, errors.FailedPreconditionError, + errors.DeadlineExceededError) as e: + # TODO(b/151232436): Always raise UnavailableError when a peer + # fails. Now there could be many kinds of errors: + # - Unavailable: when the peer is not reachable, e.g. it's down. + # - FailedPrecondition: when the peer has restarted. + if attempts < self._check_health_retry_limit: + logging.warning("%s seems down, retrying %d/%d", peer, attempts, + self._check_health_retry_limit) + continue + logging.error( + "Cluster check alive failed, %s is down, " + "aborting collectives: %s", peer, e) + context.context().abort_collective_ops( + errors.UNAVAILABLE, + "cluster check alive failed, {} is down".format(peer)) + return + except Exception as e: # pylint: disable=broad-except + logging.error("Unexpected exception in check alive: %s", e) + context.context().abort_collective_ops( + errors.INTERNAL, + "unexecpted exception in check alive: %s" % e) + return + time.sleep(self._check_health_interval) + + def _start_check_health_thread(self): + # Use a dummy all-reduce as a barrier to wait for all workers to be up, + # otherwise the check health may fail immediately. + + # Use array_ops.identity to create the dummy tensor so that we have a new + # Tensor. If we use constant it may be a cached from on a /job:localhost + # device, which will cause some code that relies on tensor.device to error. + # + # TODO(b/151232436): change to an explicit barrier if we have it. + dummy_value = array_ops.identity([]) + logging.info("Waiting for the cluster, timeout = %s", + self._check_health_initial_timeout or "inf") + try: + self._host_cross_device_ops.reduce( + reduce_util.ReduceOp.SUM, + dummy_value, + dummy_value, + options=collective_util.Options( + timeout_seconds=self._check_health_initial_timeout, + implementation=collective_util.CommunicationImplementation.RING)) + if context.is_async(): + context.async_wait() + except errors.DeadlineExceededError: + raise RuntimeError( + "Timeout waiting for the cluster, timeout is %d seconds" % + self._check_health_initial_timeout) + logging.info("Cluster is ready.") + self._check_health_thread_should_stop = threading.Event() + # Start the thread as daemon to avoid it blocking the program from exiting. + # We try best to shutdown the thread but __del__ is not guaranteed to be + # called when program exists. + self._check_health_thread = threading.Thread( + target=self._check_health, + daemon=True) + self._check_health_thread.start() + + def _stop_check_health_thread(self): + if getattr(self, "_check_health_thread", None): + logging.info("stopping check health thread") + self._check_health_thread_should_stop.set() + self._check_health_thread.join() + self._check_health_thread = None + logging.info("check health thread stopped") + + def _warn_nccl_no_gpu(self): + if ((self._communication_options.implementation == + collective_util.CommunicationImplementation.NCCL) and + self._local_device_type != "GPU"): + logging.warning("Enabled NCCL communication but no GPUs detected/" + "specified.") + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings.""" + return self._num_workers > 1 + + @property + def experimental_between_graph(self): + return True + + @property + def experimental_should_init(self): + return True + + @property + def should_checkpoint(self): + return self._is_chief + + @property + def should_save_summary(self): + return self._is_chief + + @property + def _num_replicas_in_sync(self): + return len(self.worker_devices) * self._num_workers + + # TODO(priyag): Delete this once all strategies use global batch size. + @property + def _global_batch_size(self): + """`make_dataset_iterator` and `make_numpy_iterator` use global batch size. + + `make_input_fn_iterator` assumes per-replica batching. + + Returns: + Boolean. + """ + return True + + def _get_replica_id_in_sync_group(self, replica_id): + return self._id_in_cluster * len(self.worker_devices) + replica_id + + def _get_local_replica_id(self, replica_id_in_sync_group): + return (replica_id_in_sync_group - + self._id_in_cluster * len(self.worker_devices)) + + def __deepcopy__(self, memo): + # We check the check health thread instead of whether we are in eager mode + # to limit the backward incompatibility. + if hasattr(self, "_check_health_thread"): + raise ValueError( + "MultiWorkerMirroredStrategy cannot be deep copied in eager mode. " + "If you're using Estimator and see this error message, call " + "tf.compat.v1.disable_eager_execution() at the beginning of your " + "program") + # Otherwise, do a regular deepcopy. + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + setattr(result, k, copy.deepcopy(v, memo)) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/collective_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/collective_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0470f5898434bc07820a26c745e94378573f4d01 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/collective_util.py @@ -0,0 +1,233 @@ +# coding=utf-8 +# 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. +# ============================================================================== +"""Utilities for collectives.""" + +import copy +import enum + +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +# TODO(b/170340570): print deprecation warning for CollectiveCommunication. +@tf_export("distribute.experimental.CommunicationImplementation", + "distribute.experimental.CollectiveCommunication") +class CommunicationImplementation(enum.Enum): + """Cross device communication implementation. + + Warning: The alias `tf.distribute.experimental.CollectiveCommunication` is + deprecated and will be removed in a future version. Use + `tf.distribute.experimental.CommunicationImplementation` instead. + + * `AUTO`: Automatically chosen by Tensorflow. + * `RING`: TensorFlow's ring algorithms for all-reduce and + all-gather. + * `NCCL`: NVIDIA®'s NCCL library. This is now only used for all-reduce on + GPUs; all-reduce on CPU, all-gather and broadcast fallbacks to RING. + """ + AUTO = "AUTO" + RING = "RING" + NCCL = "NCCL" + # TODO(ayushd): add ncclAllGather implementation. + + +CollectiveCommunication = CommunicationImplementation + + +@tf_export("distribute.experimental.CommunicationOptions") +class _OptionsExported(object): + """Options for cross device communications like All-reduce. + + This can be passed to methods like + `tf.distribute.get_replica_context().all_reduce()` to optimize collective + operation performance. Note that these are only hints, which may or may not + change the actual behavior. Some options only apply to certain strategy and + are ignored by others. + + One common optimization is to break gradients all-reduce into multiple packs + so that weight updates can overlap with gradient all-reduce. + + Examples: + + ```python + options = tf.distribute.experimental.CommunicationOptions( + bytes_per_pack=50 * 1024 * 1024, + timeout_seconds=120.0, + implementation=tf.distribute.experimental.CommunicationImplementation.NCCL + ) + grads = tf.distribute.get_replica_context().all_reduce( + 'sum', grads, options=options) + optimizer.apply_gradients(zip(grads, vars), + experimental_aggregate_gradients=False) + ``` + + """ + + def __new__(cls, *args, **kwargs): + # We expose a dummy class so that we can separate internal and public APIs. + # Note that __init__ won't be called on the returned object if it's a + # different class [1]. + # [1] https://docs.python.org/3/reference/datamodel.html#object.__new__ + return Options(*args, **kwargs) + + def __init__(self, + bytes_per_pack=0, + timeout_seconds=None, + implementation=CommunicationImplementation.AUTO): + """Creates a CollectiveHints. + + Args: + bytes_per_pack: a non-negative integer. Breaks collective operations into + packs of certain size. If it's zero, the value is determined + automatically. This hint is respected by all multi-replica strategies + except `TPUStrategy`. + timeout_seconds: a float or None, timeout in seconds. If not None, the + collective raises `tf.errors.DeadlineExceededError` if it takes longer + than this timeout. Zero disables timeout. This can be useful when + debugging hanging issues. This should only be used for debugging since + it creates a new thread for each collective, i.e. an overhead of + `timeout_seconds * num_collectives_per_second` more threads. This only + works for `tf.distribute.experimental.MultiWorkerMirroredStrategy`. + implementation: a + `tf.distribute.experimental.CommunicationImplementation`. This is a hint + on the preferred communication implementation. Possible values include + `AUTO`, `RING`, and `NCCL`. NCCL is generally more performant for GPU, + but doesn't work for CPU. This only works for + `tf.distribute.experimental.MultiWorkerMirroredStrategy`. + + Raises: + ValueError: When arguments have invalid value. + """ + pass + + +class Options(object): + """Implementation of OptionsInterface.""" + + def __init__(self, + bytes_per_pack=0, + timeout_seconds=None, + implementation=CommunicationImplementation.AUTO): + if bytes_per_pack < 0: + raise ValueError( + f"Argument `bytes_per_pack` must be >=0, Received {bytes_per_pack}.") + if isinstance(implementation, str): + implementation = CommunicationImplementation(implementation.upper()) + if not isinstance(implementation, CommunicationImplementation): + raise ValueError( + "Argument `implementation` must be instance of " + "`tf.distribute.experimental.CommunicationImplementation`.") + self.bytes_per_pack = bytes_per_pack + self.timeout_seconds = timeout_seconds + self.implementation = implementation + + __init__.__doc__ = _OptionsExported.__init__.__doc__ + + def merge(self, options): + """Merges with another options and returns a new one. + + Values specified in the `options` takes precedence if they're not the + default. + + Args: + options: a `tf.distribute.experimental.CollectiveCommunication`. + + Returns: + A new `tf.distribute.experimental.CollectiveCommunication`. + """ + merged = copy.deepcopy(self) + if options is None: + return merged + if options.bytes_per_pack != 0: + merged.bytes_per_pack = options.bytes_per_pack + if options.timeout_seconds is not None: + merged.timeout_seconds = options.timeout_seconds + if options.implementation != CommunicationImplementation.AUTO: + merged.implementation = options.implementation + return merged + + def __str__(self): + return (f"Options(bytes_per_pack={self.bytes_per_pack}," + f"timeout_seconds={self.timeout_seconds}, " + f"implementation={self.implementation})") + + +@tf_export("distribute.experimental.CollectiveHints") +class Hints(object): + """Hints for collective operations like AllReduce. + + This can be passed to methods like + `tf.distribute.get_replica_context().all_reduce()` to optimize collective + operation performance. Note that these are only hints, which may or may not + change the actual behavior. Some options only apply to certain strategy and + are ignored by others. + + One common optimization is to break gradients all-reduce into multiple packs + so that weight updates can overlap with gradient all-reduce. + + Examples: + + - bytes_per_pack + + ```python + hints = tf.distribute.experimental.CollectiveHints( + bytes_per_pack=50 * 1024 * 1024) + grads = tf.distribute.get_replica_context().all_reduce( + 'sum', grads, experimental_hints=hints) + optimizer.apply_gradients(zip(grads, vars), + experimental_aggregate_gradients=False) + ``` + + - timeout_seconds + + ```python + strategy = tf.distribute.MirroredStrategy() + hints = tf.distribute.experimental.CollectiveHints( + timeout_seconds=120.0) + try: + strategy.reduce("sum", v, axis=None, experimental_hints=hints) + except tf.errors.DeadlineExceededError: + do_something() + ``` + + """ + + @deprecation.deprecated( + None, "use distribute.experimental.CommunicationOptions instead") + def __new__(cls, bytes_per_pack=0, timeout_seconds=None): + return Options( + bytes_per_pack=bytes_per_pack, timeout_seconds=timeout_seconds) + + def __init__(self, bytes_per_pack=0, timeout_seconds=None): + """Creates a CollectiveHints. + + Args: + bytes_per_pack: a non-negative integer. Breaks collective operations into + packs of certain size. If it's zero, the value is determined + automatically. This only applies to all-reduce with + `MultiWorkerMirroredStrategy` currently. + timeout_seconds: a float or None, timeout in seconds. If not None, the + collective raises `tf.errors.DeadlineExceededError` if it takes longer + than this timeout. This can be useful when debugging hanging issues. + This should only be used for debugging since it creates a new thread for + each collective, i.e. an overhead of `timeout_seconds * + num_collectives_per_second` more threads. This only works for + `tf.distribute.experimental.MultiWorkerMirroredStrategy`. + + Raises: + ValueError: When arguments have invalid value. + """ + pass diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/combinations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/combinations.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7ce52b92a8c325ebb60e157eaeaa6da320d118 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/combinations.py @@ -0,0 +1,652 @@ +# 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. +# ============================================================================== +"""This module customizes `test_combinations` for `tf.distribute.Strategy`. + +Additionally it provides `generate()`, `combine()` and `times()` with +`tf.distribute.Strategy` customizations as a default. +""" + +import collections +import copy +import re +import sys +import types +import unittest + +from absl import app +import six + + +from tensorflow.python.client import session +from tensorflow.python.distribute import collective_all_reduce_strategy +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import multi_process_runner +from tensorflow.python.distribute import multi_worker_test_base +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import combinations as framework_combinations +from tensorflow.python.framework import config +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_combinations as combinations_lib +from tensorflow.python.framework import test_util +from tensorflow.python.platform import flags +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +# TODO(rchao): Rename `distribution` parameter to `strategy` or +# `distribute_strategy` in all tests. +class DistributionParameter(combinations_lib.ParameterModifier): + """Transforms arguments of type `NamedDistribution`. + + Convert all arguments of type `NamedDistribution` to the value of their + `strategy` property. + """ + + def modified_arguments(self, kwargs, requested_parameters): + # Get the parameter that indicates if we need to set the `_use_policy` flag + # on the strategy object. This is a temporary flag for testing the variable + # policy rollout. + use_var_policy = kwargs.get("use_var_policy", None) + distribution_arguments = {} + for k, v in kwargs.items(): + if isinstance(v, NamedDistribution): + strategy = v.strategy + if use_var_policy: + strategy.extended._use_var_policy = use_var_policy + distribution_arguments[k] = strategy + return distribution_arguments + + +class ClusterParameters(combinations_lib.ParameterModifier): + """Adds cluster parameters if a `NamedDistribution` has it. + + It needs to be before DistributionParameter. + """ + + def modified_arguments(self, kwargs, requested_parameters): + strategy = None + for _, v in kwargs.items(): + if isinstance(v, NamedDistribution): + if strategy is not None and _num_total_workers(v.has_chief, + v.num_workers) > 1: + raise ValueError("Only support one NamedDistribution for multi worker" + "tests.") + strategy = v + + if strategy: + has_chief = strategy.has_chief + num_workers = strategy.num_workers + runner = strategy.runner + share_gpu = strategy.share_gpu + num_ps = strategy.num_ps + if "has_chief" in kwargs and kwargs["has_chief"] != has_chief: + raise ValueError( + "both has_chief and strategy specified but are not compatible") + if "num_workers" in kwargs and kwargs["num_workers"] != num_workers: + raise ValueError( + "both num_workers and strategy specified but are not compatible") + else: + has_chief = kwargs.get("has_chief", False) + num_workers = kwargs.get("num_workers", 1) + runner = kwargs.get("runner", None) + share_gpu = kwargs.get("share_gpu", True) + num_ps = kwargs.get("num_ps", 0) + + # Always set cluster parameters if they're requested. So that generate() + # works when there's no startegy in the combinations. + update = {} + if "has_chief" in requested_parameters: + update["has_chief"] = has_chief + if "num_workers" in requested_parameters: + update["num_workers"] = num_workers + if "runner" in requested_parameters: + update["runner"] = runner + if "share_gpu" in requested_parameters: + update["share_gpu"] = share_gpu + if "num_ps" in requested_parameters: + update["num_ps"] = num_ps + return update + + +class DistributionCombination(combinations_lib.TestCombination): + """Sets up distribution strategy for tests.""" + + def should_execute_combination(self, kwargs): + distributions = [ + v for v in kwargs.values() if isinstance(v, NamedDistribution) + ] + if test_util.is_xla_enabled() and any(d.no_xla for d in distributions): + return ( + False, + "n/a: skipping strategy combination with no_xla=True in XLA tests") + return (True, None) + + def parameter_modifiers(self): + return [ + DistributionParameter(), + combinations_lib.OptionalParameter("use_var_policy"), + ] + + +class ClusterCombination(combinations_lib.TestCombination): + """Sets up multi worker tests.""" + + def parameter_modifiers(self): + return [ClusterParameters()] + + +class GPUCombination(combinations_lib.TestCombination): + """Enable tests to request GPU hardware and skip non-GPU combinations. + + This class expects test_combinations to be generated with `NamedDistribution` + wrapping instances of `tf.distribute.Strategy`. + + Optionally, the `required_gpus` argument is supported. GPU hardware is + required, if its value is `True` or > 0. + + Attributes: + GPU_TEST: The environment is considered to have GPU hardware available if + the name of the program contains "test_gpu" or "test_xla_gpu". + """ + GPU_TEST = False + if sys.argv: + GPU_TEST = re.search(r"(test_2?gpu|test_xla_2?gpu)$", sys.argv[0]) + + def should_execute_combination(self, kwargs): + distributions = [ + v for v in kwargs.values() if isinstance(v, NamedDistribution) + ] + required_gpus = kwargs.get("required_gpus", 0) + required_physical_gpus = kwargs.get("required_physical_gpus", 0) + + if distributions and required_gpus: + raise ValueError("Do not use `required_gpus` and arguments of type " + "NamedDistribution together.") + + number_of_required_gpus = max( + [required_gpus] + [required_physical_gpus] + + [d.required_physical_gpus or 0 for d in distributions] + + [d.required_gpus or 0 for d in distributions]) + number_of_required_physical_gpus = max( + [required_physical_gpus] + + [d.required_physical_gpus or 0 for d in distributions]) + + if (required_physical_gpus and required_gpus): + raise ValueError("Only one of `required_physical_gpus`(number of physical" + " GPUs required) and `required_gpus`(total number of " + "GPUs required) should be set. ") + if not number_of_required_gpus and GPUCombination.GPU_TEST: + return (False, "Test that doesn't require GPUs.") + elif (number_of_required_gpus > 0 + and context.num_gpus() < number_of_required_gpus): + return (False, ("Only {} of {} required GPUs are available.".format( + context.num_gpus(), number_of_required_gpus))) + elif number_of_required_physical_gpus > len( + config.list_physical_devices("GPU")): + return (False, + ("Only {} of {} required physical GPUs are available.".format( + config.list_physical_devices("GPU"), required_physical_gpus))) + else: + return (True, None) + + def parameter_modifiers(self): + return [combinations_lib.OptionalParameter("required_gpus"), + combinations_lib.OptionalParameter("required_physical_gpus")] + + +class TPUCombination(combinations_lib.TestCombination): + """Allow to request TPU hardware and skip non-TPU combinations. + + This class expects test_combinations to be generated with `NamedDistribution` + wrapping instances of `tf.distribute.Strategy`. + + Optionally, the `required_tpus` parameter is supported. TPU hardware is + required, if its argument is `True` or > 0. + + Optionally, the `use_cloud_tpu` parameter is supported. If TPU hardware is + required by `required_tpus`, it specifically must be a Cloud TPU (specified + with `--tpu`) if `use_cloud_tpu` is `True`. + + Attributes: + TPU_TEST: The environment is considered to have TPU hardware available if + the name of the program contains "test_tpu". + """ + + TPU_TEST = False + if sys.argv: + TPU_TEST = "test_tpu" in sys.argv[0] + + def should_execute_combination(self, kwargs): + distributions = [ + v for v in kwargs.values() if isinstance(v, NamedDistribution) + ] + # TODO(isaprykin): Migrate all tests away from using 'required_tpu' in favor + # of 'required_tpus'. + if "required_tpus" in kwargs and "required_tpu" in kwargs: + raise ValueError("Do not use `required_tpu`. Both `required_tpus` and " + "`required_tpu` were specified.") + required_tpus = kwargs.get("required_tpus", None) or kwargs.get( + "required_tpu", None) + + if distributions and required_tpus: + raise ValueError("Do not use `required_tpus` and arguments of type " + "NamedDistribution together.") + + # TODO(isaprykin): Add support for a particular number of TPUs. Right now + # it's binary. + number_of_required_tpus = max([required_tpus or 0] + + [d.required_tpu or 0 for d in distributions]) + use_cloud_tpu = any([kwargs.get("use_cloud_tpu")] + + [d.use_cloud_tpu for d in distributions]) + tpu = hasattr(flags.FLAGS, "tpu") and flags.FLAGS.tpu or "" + + if not number_of_required_tpus and TPUCombination.TPU_TEST: + return (False, "Test that doesn't require TPUs.") + if number_of_required_tpus and not TPUCombination.TPU_TEST: + return (False, "Test requires a TPU, but it's not available.") + if use_cloud_tpu and not tpu: + return (False, "Test requires a Cloud TPU, but none specified.") + if not use_cloud_tpu and tpu: + return (False, "Test requires local TPU, but Cloud TPU specified.") + return (True, None) + + def parameter_modifiers(self): + return [ + combinations_lib.OptionalParameter("required_tpus"), + combinations_lib.OptionalParameter("required_tpu"), + combinations_lib.OptionalParameter("use_cloud_tpu"), + ] + + +class NamedDistribution(object): + """Wraps a `tf.distribute.Strategy` and adds a name for test titles.""" + + def __init__(self, + name, + distribution_fn, + required_gpus=None, + required_physical_gpus=0, + required_tpu=False, + use_cloud_tpu=False, + has_chief=False, + num_workers=1, + num_ps=0, + share_gpu=True, + pool_runner_fn=None, + no_xla=False): + """Initialize NamedDistribution. + + Args: + name: Name that will be a part of the name of the test case. + distribution_fn: A callable that creates a `tf.distribute.Strategy`. + required_gpus: The number of GPUs that the strategy requires. Only one of + `required_gpus` and `required_physical_gpus` should be set. + required_physical_gpus: Number of physical GPUs required. Only one of + `required_gpus` and `required_physical_gpus` should be set. + required_tpu: Whether the strategy requires TPU. + use_cloud_tpu: Whether the strategy requires cloud TPU. + has_chief: Whether the strategy requires a chief worker. + num_workers: The number of workers that the strategy requires. + num_ps: The number of parameter servers. + share_gpu: Whether to share GPUs among workers. + pool_runner_fn: An optional callable that returns a MultiProcessPoolRunner + to run the test. + no_xla: Whether to skip in XLA tests. + """ + object.__init__(self) + self._name = name + self._distribution_fn = distribution_fn + self.required_gpus = required_gpus + self.required_physical_gpus = required_physical_gpus + self.required_tpu = required_tpu + self.use_cloud_tpu = use_cloud_tpu + self.has_chief = has_chief + self.num_workers = num_workers + self.num_ps = num_ps + self.share_gpu = share_gpu + self._pool_runner_fn = pool_runner_fn + self.no_xla = no_xla + + @property + def runner(self): + if self._pool_runner_fn is not None: + return self._pool_runner_fn() + return None + + @property + def strategy(self): + return self._distribution_fn() + + def __repr__(self): + return self._name + + +# This is to allow adding combinations that runs a function both as a +# tf.function and eagerly. +# +# @combinations.generate( +# combinations.combine( +# tf_function = [combinations.tf_function, combinations.no_tf_function] +# ) +# ) +# def testXXX(tf_function): +# @tf_function +# def foo(): +# tf.add(1., 1.) +# +# foo() +tf_function = combinations_lib.NamedObject("TfFunction", def_function.function) +no_tf_function = combinations_lib.NamedObject("NoTfFunction", lambda f: f) + + +def concat(*combined): + """Concats combinations.""" + result = [] + for one in combined: + result += one + return result + + +@tf_export("__internal__.distribute.combinations.generate", v1=[]) +def generate(combinations, test_combinations=()): + # pylint: disable=g-doc-args,g-doc-return-or-yield + """Distributed adapter of `tf.__internal__.test.combinations.generate`. + + All tests with distributed strategy should use this one instead of + `tf.__internal__.test.combinations.generate`. This function has support of + strategy combinations, GPU/TPU and multi worker support. + + See `tf.__internal__.test.combinations.generate` for usage. + """ + # pylint: enable=g-doc-args,g-doc-return-or-yield + default_combinations = ( + framework_combinations.EagerGraphCombination(), + framework_combinations.TFVersionCombination(), + ClusterCombination(), + DistributionCombination(), + GPUCombination(), + TPUCombination(), + ) + # We apply our own decoration to handle multi worker tests before applying + # framework.test_combinations.generate. The order is important since we need + # framework.test_combinations.generate to apply all parameter modifiers first. + combination_decorator = combinations_lib.generate( + combinations, test_combinations=default_combinations + test_combinations) + + def decorator(test_method_or_class): + if isinstance(test_method_or_class, type): + # If it's a test class. + class_object = test_method_or_class + # Decorate each test method with _multi_worker_test. + for name, test_method in six.iteritems(class_object.__dict__.copy()): + if (name.startswith(unittest.TestLoader.testMethodPrefix) and + isinstance(test_method, types.FunctionType)): + setattr(class_object, name, _multi_worker_test(test_method)) + return combination_decorator(class_object) + else: + return combination_decorator(_multi_worker_test(test_method_or_class)) + + return decorator + + +combine = combinations_lib.combine +times = combinations_lib.times +NamedObject = combinations_lib.NamedObject + + +# Identifies whether we're in the main process or worker processes. +# `_multi_worker_test` decoration behaves differently in the main processs and +# the worker processes. See the documentation of _multi_worker_test for detail. +_running_in_worker = False + + +@tf_export("__internal__.distribute.combinations.in_main_process", v1=[]) +def in_main_process(): + """Whether it's in the main test process. + + This is normally used to prepare the test environment which should only happen + in the main process. + + Returns: + A boolean. + """ + return not _running_in_worker + + +class TestEnvironment(object): + """Holds the test environment information. + + Tests should modify the attributes of the instance returned by `env()` in the + main process if needed, and it will be passed to the worker processes each + time a test case is run. + """ + + def __init__(self): + self.tf_data_service_dispatcher = None + # Note that this includes GPUs that may not be visible to the current + # worker. + self.total_phsyical_gpus = None + + def __setattr__(self, name, value): + if not in_main_process(): + raise ValueError( + "combinations.env() should only be modified in the main process. " + "Condition your code on combinations.in_main_process().") + super().__setattr__(name, value) + + +_env = TestEnvironment() + + +@tf_export("__internal__.distribute.combinations.env", v1=[]) +def env(): + """Returns the object holds the test environment information. + + Tests should modify this in the main process if needed, and it will be passed + to the worker processes each time a test case is run. + + Returns: + a TestEnvironment object. + """ + return _env + + +def _set_total_phsyical_gpus(): + if in_main_process(): + env().total_phsyical_gpus = len( + context.context().list_physical_devices("GPU")) + + +# This is needed in case CUDA is lazily loaded. +app.call_after_init(_set_total_phsyical_gpus) + + +_TestResult = collections.namedtuple("_TestResult", ["status", "message"]) + + +def _test_runner(test_id, test_env): + """Executes the test with the given test_id. + + This is a simple wrapper around TestRunner to be used with + multi_process_runner. Similar to test.main(), but it executes only one test + specified by test_id and returns whether the test succeeds. If the test fails, + the function prints failures and errors to stdout. + + Args: + test_id: TestCase.id() + test_env: a TestEnvironment object. + + Returns: + A boolean indicates whether the test succeeds. + """ + global _running_in_worker, _env + # No need to restore the value of _running_in_worker since it should always be + # True in worker processes. + _running_in_worker = True + _env = test_env + test = unittest.defaultTestLoader.loadTestsFromName(test_id) + runner = unittest.TextTestRunner() + result = runner.run(test) + # Treat expected failures as failures, so that the main process can get + # them and fail as expected. Also treat errors as failures to simplify the + # handling. + failures = result.failures + result.expectedFailures + result.errors + if failures: + ret = _TestResult(status="failure", message=failures[0][1]) + elif result.skipped: + ret = _TestResult(status="skipped", message=result.skipped[0][1]) + else: + # Treat unexpectedSuccesses as OK so that the test case in the main process + # succeed as well. + ret = _TestResult(status="ok", message=None) + # Print tracebacks to stdout and multi_process_runner will collect + # them and stream back to the main process. + if ret.message: + print(ret.message) + return ret + + +def _multi_worker_test(test_method): + """Decorate test_method so that it runs in each worker. + + We use `multi_process_runner` to simulate multiple workers. Since we run the + this function in the main process and all worker processes, this decoration + behaves differently in the main process and worker procssses. In the main + process, it spawns subprocesses and runs the test on each of them; in a worker + process, it executes test in the same way as a normal test, e.g. + setUp()/tearDown() are called before/after the test. + + Args: + test_method: a function which must be a test method. + + Returns: + Decorated `test_method`. Note that the decorated function has additional + arguments. + """ + + def decorator(self, has_chief, num_workers, num_ps, share_gpu, runner, + **kwargs): + if _num_total_workers(has_chief, + num_workers) == 1 or _running_in_worker or ( + # Use in-process cluster for PS combinations + # when XLA is enabled. + test_util.is_xla_enabled() and num_ps > 0): + # We're in worker process or the test is for single worker. Either case we + # execute the test method directly instead of spawning subprocesses. + + # For MultiWorkerMirroredStrategy(CollectiveAllReduceStrategy), install a + # session that connects to the local server. This is necessary for multi + # worker graph mode tests to work. Those tests cannot use their graphs or + # sessions, including the one returned by self.cached_session(). Since + # existing tests may already be doing so, we only install the session for + # multi worker tests. + with _multi_worker_session(kwargs): + test_method(self, **kwargs) + return + + # We're in the main process. We spawn subprocesses and run the *test* on + # each of them. Note that we're not directly executing test_method passed to + # _multi_worker_test, because we need setUp()/tearDown() to be called and + # all the decorations on the test method. The conceptual call stack is: + # [main process]test.main() + # [main process]test_runner.run(test) + # [main process]wrapper by combinations.generate() + # [main process]_multi_worker_test.decorator() + # # A sub process goes through the same code path as the main + # # process. + # [sub process]_test_runner() + # [sub process]test_runner.run(test) + # [sub process]wrapper by combinations.generate() + # [sub process]_multi_worker_test.decorator() + # # _running_in_worker is True + # [sub process]test_method() + test_id = self.id() + if runner: + results = runner.run(_test_runner, args=(test_id, _env)) + else: + cluster_spec = multi_worker_test_base.create_cluster_spec( + has_chief=has_chief, + num_workers=num_workers, + num_ps=num_ps, + has_eval=False) + ephemeral_runner = multi_process_runner.MultiProcessRunner( + _test_runner, + cluster_spec, + share_gpu=share_gpu, + args=(test_id, _env), + dependence_on_chief=has_chief) + ephemeral_runner.start() + results = ephemeral_runner.join().return_value + + skip_reason = None + for result in results: + if result.status == "failure": + # We can't tell which worker the return value come from, so we fail on + # the first error. + self.fail(result.message) + break + elif result.status == "skipped": + # Record the skip reason, but do not actually skip the test in case some + # processes fail instead. + skip_reason = result.message + if skip_reason is not None: + self.skipTest(skip_reason) + + argspec = tf_inspect.getfullargspec(test_method) + decorator_args = (argspec.args or []) + [ + "has_chief", "num_workers", "num_ps", "share_gpu", "runner" + ] + decorator_argspec = argspec._replace(args=decorator_args) + return tf_decorator.make_decorator( + test_method, decorator, decorator_argspec=decorator_argspec) + + +def _num_total_workers(has_chief, num_workers): + """Returns the number of workers including the chief.""" + if has_chief: + return num_workers + 1 + return num_workers + + +def _multi_worker_session(kwargs): + """Returns a context manager that enters a session that is configured for the MultiWorkerMirroredStrategy. + + Args: + kwargs: a dict. Keyword arguments passed to the test. + + Returns: + A context manager. If MultiWorkerMirroredStrategy is the one and only one + strategy in kwargs and it's in graph mode, it's the seesion that is + configured for that strategy. Otherwise, it's a no-op context manager. + """ + strategy = None + for _, v in kwargs.items(): + if isinstance(v, distribute_lib.StrategyBase): + if strategy is not None: + logging.warning( + "The test uses multiple strategies. Skipping " + "entering a session that is configured for the strategy.") + return ops.NullContextmanager() + strategy = v + if context.executing_eagerly() or not isinstance( + strategy, collective_all_reduce_strategy.CollectiveAllReduceStrategy): + return ops.NullContextmanager() + sess_config = copy.deepcopy(context.context().config) + sess_config = strategy.update_config_proto(sess_config) + target = strategy.cluster_resolver.master() + return session.Session(config=sess_config, target=target).as_default() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/cluster_coordinator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/cluster_coordinator.py new file mode 100644 index 0000000000000000000000000000000000000000..ca4bbbc2d8c2c191cc072790cfe79dd23398dd1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/cluster_coordinator.py @@ -0,0 +1,1852 @@ +# 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. +# ============================================================================== +"""Module for `ClusterCoordinator` and relevant cluster-worker related library. + +This is currently under development and the API is subject to change. +""" + +import collections +import contextlib +import os +import re +import threading +import time +import weakref + +from six.moves import queue + +from tensorflow.python.distribute.coordinator import coordinator_context +from tensorflow.python.distribute.coordinator import metric_utils +from tensorflow.python.distribute.coordinator import remote_value +from tensorflow.python.distribute.coordinator import utils +from tensorflow.python.distribute.coordinator import values as values_lib +from tensorflow.python.distribute.coordinator import watchdog +from tensorflow.python.eager import cancellation +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import executor +from tensorflow.python.eager import function as tf_function +from tensorflow.python.framework import errors +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +# Maximum time for failed worker to come back is 1 hour +_WORKER_MAXIMUM_RECOVERY_SEC = 3600 +# How often to poll task states from the coordination service. In testing, a +# value of 1 led to some spurious reports of unavailability, so a higher value +# is used. Refer to the discussion in b/249134783 for more. +_POLL_FREQ_IN_SEC = 5 + +# Maximum size for queued closures, "infinite" if set to 0. +# When the maximum queue size is reached, further schedule calls will become +# blocking until some previously queued closures are executed on workers. +# Note that using an "infinite" queue size can take a non-trivial portion of +# memory, and even lead to coordinator OOM. Modify the size to a smaller value +# for coordinator with constrained memory resource (only recommended for +# advanced users). Also used in unit tests to ensure the correctness when the +# queue is full. +_CLOSURE_QUEUE_MAX_SIZE = 256 * 1024 + +# RPC error message from PS +_RPC_ERROR_FROM_PS = "GRPC error information from remote target /job:ps" + +# InvalidArgumentError (unknown device) will not have "GRPC error..." string. +_JOB_WORKER_STRING_IDENTIFIER = "/job:worker" + + +RemoteValueStatus = remote_value.RemoteValueStatus +RemoteValue = remote_value.RemoteValue +RemoteValueImpl = values_lib.RemoteValueImpl +RemoteVariable = values_lib.RemoteVariable +PerWorkerValues = values_lib.PerWorkerValues + + +class ClosureInputError(Exception): + """Wrapper for errors from resource building. + + When a closure starts, it first checks for errors in any of its inputs, which + are RemoteValues from resource closures. If there were any errors, it wraps + the exception in this class and raises so it can be handled by the worker + failure handler. + + Attributes: + original_exception: + """ + + def __init__(self, original_exception): + # Avoid doubly-nested errors + if isinstance(original_exception, + (ClosureInputError, ClosureAbortedError)): + self.original_exception = original_exception.original_exception + else: + self.original_exception = original_exception + message = ("Input has an error, the original exception is %r, " + "error message is %s." % + (self.original_exception, str(self.original_exception))) + super().__init__(message) + self.with_traceback(original_exception.__traceback__) + + +class ClosureAbortedError(Exception): + """Wrapper for errors from training closures, to attach to resource closures. + + This wrapper is used when a dependent training closure fails to set errors on + its required resource closures. + + Attributes: + original_exception: The Exception to wrap + """ + + def __init__(self, original_exception): + # Avoid doubly-nested errors + if isinstance(original_exception, + (ClosureInputError, ClosureAbortedError)): + self.original_exception = original_exception.original_exception + else: + self.original_exception = original_exception + message = ("Other function has an execution error, as a result, the " + "current value is not available. The original exception is %r, " + "error message is %s." % + (self.original_exception, str(self.original_exception))) + super().__init__(message) + self.with_traceback(original_exception.__traceback__) + + +class PSUnavailableError(errors.UnavailableError): + """Specifies that a parameter server is the unavailable task.""" + + def __init__(self, original_exception): + assert isinstance(original_exception, errors.UnavailableError) + # TF Errors should have init args set as attributes for serialization. + self.original_exception = original_exception + super().__init__( + original_exception.node_def, + original_exception.op, + original_exception.message, + ) + + +def _get_error_from_remote_values(structure): + """Attempts to return errors from `RemoteValue`s. Rebuilds them if needed.""" + errors_in_structure = [] + + def _get_error(val): + if isinstance(val, RemoteValue): + error = val._get_error() # pylint: disable=protected-access + if error: + errors_in_structure.append(error) + + nest.map_structure(_get_error, structure) + if errors_in_structure: + return errors_in_structure[0] + else: + return None + + +def _maybe_as_type_spec(val): + if isinstance(val, (RemoteValue, PerWorkerValues)): + if val._type_spec is None: # pylint: disable=protected-access + raise ValueError("Output of a scheduled function that is not " + "tf.function cannot be the input of another function.") + return val._type_spec # pylint: disable=protected-access + else: + return val + + +def _select_worker_slice(worker_id, structured): + """Selects the worker slice of each of the items in `structured`.""" + + def _get(x): + return x._values[worker_id] if isinstance(x, PerWorkerValues) else x # pylint: disable=protected-access + + return nest.map_structure(_get, structured) + + +def _disallow_remote_value_as_input(structured): + """Raises if any element of `structured` is a RemoteValue.""" + + def _raise_if_remote_value(x): + if isinstance(x, RemoteValue): + raise ValueError( + "`tf.distribute.experimental.coordinator.RemoteValue` used " + "as an input to scheduled function is not yet " + "supported.") + + nest.map_structure(_raise_if_remote_value, structured) + + +class Closure(object): + """Hold a function to be scheduled and its arguments.""" + + def __init__(self, function, cancellation_mgr, args=None, kwargs=None): + if not callable(function): + raise ValueError("Function passed to `ClusterCoordinator.schedule` must " + "be a callable object.") + self._args = args or () + self._kwargs = kwargs or {} + + _disallow_remote_value_as_input(self._args) + _disallow_remote_value_as_input(self._kwargs) + + if isinstance(function, def_function.Function): + replica_args = _select_worker_slice(0, self._args) + replica_kwargs = _select_worker_slice(0, self._kwargs) + + # Note: no need to handle function registration failure since this kind of + # failure will not raise exceptions as designed in the runtime. The + # coordinator has to rely on subsequent operations that raise to catch + # function registration failure. + + # Record the function tracing overhead. Note that we pass in the tracing + # count of the def_function.Function as a state tracker, so that metrics + # will only record the time for actual function tracing (i.e., excluding + # function cache lookups). + with metric_utils.monitored_timer( + "function_tracing", state_tracker=function._get_tracing_count): # pylint: disable=protected-access + self._concrete_function = function.get_concrete_function( + *nest.map_structure(_maybe_as_type_spec, replica_args), + **nest.map_structure(_maybe_as_type_spec, replica_kwargs)) + elif isinstance(function, tf_function.ConcreteFunction): + self._concrete_function = function + + if hasattr(self, "_concrete_function"): + # If we have a concrete function, we get to retrieve the output type spec + # via the structured_output. + self._output_type_spec = func_graph.convert_structure_to_signature( + self._concrete_function.structured_outputs) + self._function = cancellation_mgr.get_cancelable_function( + self._concrete_function) + else: + # Otherwise (i.e. what is passed in is a regular python function), we have + # no such information. + self._output_type_spec = None + self._function = function + + self._output_remote_value_ref = None + + def build_output_remote_value(self): + if self._output_remote_value_ref is None: + ret = RemoteValueImpl(None, self._output_type_spec) + self._output_remote_value_ref = weakref.ref(ret) + return ret + else: + raise ValueError( + "The output of the Closure cannot be built more than once.") + + def maybe_call_with_output_remote_value(self, method): + if self._output_remote_value_ref is None: + return None + output_remote_value = self._output_remote_value_ref() + if output_remote_value is not None: + return method(output_remote_value) + return None + + def mark_cancelled(self): + e = errors.CancelledError( + None, None, "The corresponding function is " + "cancelled. Please reschedule the function.") + self.maybe_call_with_output_remote_value(lambda r: r._set_error(e)) # pylint: disable=protected-access + + def execute_on(self, worker): + """Executes the closure on the given worker. + + Args: + worker: a `Worker` object. + """ + replica_args = _select_worker_slice(worker.worker_index, self._args) + replica_kwargs = _select_worker_slice(worker.worker_index, self._kwargs) + + e = ( + _get_error_from_remote_values(replica_args) or + _get_error_from_remote_values(replica_kwargs)) + if e: + if not isinstance(e, ClosureInputError): + e = ClosureInputError(e) + raise e + + with ops.device(worker.device_name): + with context.executor_scope(worker.executor): + with coordinator_context.with_dispatch_context(worker): + with metric_utils.monitored_timer("closure_execution"): + output_values = self._function( + *nest.map_structure(coordinator_context.maybe_get_remote_value, + replica_args), + **nest.map_structure(coordinator_context.maybe_get_remote_value, + replica_kwargs)) + self.maybe_call_with_output_remote_value( + lambda r: r._set_values(output_values)) # pylint: disable=protected-access + + +class ResourceClosure(Closure): + """A closure that builds a resource on a worker. + + ResourceClosures keep a reference to the closure object, which is used to + rerun the closure upon recovery to ensure workers have access to the + resources they need. + """ + + def _init_remote_value(self): + return RemoteValueImpl(self, self._output_type_spec) + + def build_output_remote_value(self): + if self._output_remote_value_ref is None: + # We need to remember the Closure object in the `RemoteValue` here. + ret = self._init_remote_value() + self._output_remote_value_ref = weakref.ref(ret) + return ret + else: + return self._output_remote_value_ref() + + +class PerWorkerVariableClosure(ResourceClosure): + + def _init_remote_value(self): + return RemoteVariable(self, self._output_type_spec) + + +class _CoordinatedClosureQueue(object): + """Manage a queue of closures, inflight count and errors from execution. + + This class is thread-safe. + """ + + def __init__(self): + # `self._inflight_closure_count` only tracks the number of inflight closures + # that are "in generation". Once an error occurs, error generation is + # incremented and all subsequent arriving closures (from inflight) are + # considered "out of generation". + self.inflight_closure_count = 0 + + self._queue_lock = threading.Lock() + + # Condition indicating that all pending closures (either queued or inflight) + # have been processed, failed, or cancelled. + self._stop_waiting_condition = threading.Condition(self._queue_lock) + + # Condition indicating that an item becomes available in queue (not empty). + self._closures_queued_condition = threading.Condition(self._queue_lock) + self._should_process_closures = True + + # Condition indicating that a queue slot becomes available (not full). + # Note that even with "infinite" queue size, there is still a "practical" + # size limit for the queue depending on host memory capacity, and thus the + # queue will eventually become full with a lot of enqueued closures. + self._queue_free_slot_condition = threading.Condition(self._queue_lock) + + # Condition indicating there is no inflight closures. + self._no_inflight_closure_condition = threading.Condition(self._queue_lock) + + # Use to cancel in-flight closures. + self._cancellation_mgr = cancellation.CancellationManager() + + if _CLOSURE_QUEUE_MAX_SIZE <= 0: + logging.warning( + "In a `ClusterCoordinator`, creating an infinite closure queue can " + "consume a significant amount of memory and even lead to OOM.") + self._queue = queue.Queue(maxsize=_CLOSURE_QUEUE_MAX_SIZE) + metric_utils.monitor_int("queued_closures", self._queue.qsize()) + self._tagged_queue = collections.defaultdict(queue.Queue) + self._error = None + + # The following is a lock to make sure when `wait` is called and before it + # returns no `put` can be executed during this period. It is because `wait` + # won't know what to do with newly put closures. This lock adds an cutoff + # for `wait` so that closures put into the queue while waiting would not be + # taken responsible by this `wait`. + # + # We cannot reuse the `self._queue_lock` since when `wait` waits for a + # condition, the `self._queue_lock` will be released. + # + # We don't use a reader/writer's lock on purpose to reduce the complexity + # of the code. + self._put_wait_lock = threading.Lock() + + self._watchdog = watchdog.WatchDog(on_triggered=self._on_watchdog_timeout) + + def _on_watchdog_timeout(self): + logging.info("inflight_closure_count is %d", self._inflight_closure_count) + logging.info("current error is %s:%r", self._error, self._error) + + @property + def inflight_closure_count(self): + return self._inflight_closure_count + + @inflight_closure_count.setter + def inflight_closure_count(self, value): + self._inflight_closure_count = value + metric_utils.monitor_int("inflight_closures", self._inflight_closure_count) + + def stop(self): + with self._queue_lock: + self._should_process_closures = False + self._cancellation_mgr.start_cancel() + self._closures_queued_condition.notify_all() + self._watchdog.stop() + + def _cancel_all_closures(self): + """Clears the queue and sets remaining closures cancelled error. + + This method expects self._queue_lock to be held prior to entry. + """ + self._cancellation_mgr.start_cancel() + logging.info("Canceling all closures: waiting for inflight closures to " + "finish") + while self._inflight_closure_count > 0: + self._no_inflight_closure_condition.wait() + logging.info("Canceling all closures: canceling remaining closures on the " + "queue") + while True: + try: + closure = self._queue.get(block=False) + metric_utils.monitor_int("queued_closures", self._queue.qsize()) + self._queue_free_slot_condition.notify() + closure.mark_cancelled() + except queue.Empty: + break + # The cancellation manager cannot be reused once cancelled. After all + # closures (queued or inflight) are cleaned up, recreate the cancellation + # manager with clean state. + # Note on thread-safety: this is triggered when one of theses + # ClusterCoordinator APIs are called: `schedule`, `wait`, and `done`. At the + # same time, no new closures can be constructed (which reads the + # _cancellation_mgr to get cancellable functions). + self._cancellation_mgr = cancellation.CancellationManager() + + def _raise_if_error(self): + """Raises the error if one exists. + + If an error exists, cancel the closures in queue, raises it, and clear + the error. + + This method expects self._queue_lock to be held prior to entry. + """ + if self._error: + logging.error("Start cancelling closures due to error %r: %s", + self._error, self._error) + self._cancel_all_closures() + try: + raise self._error # pylint: disable=raising-bad-type + finally: + self._error = None + + def put(self, closure, tag=None): + """Put a closure into the queue for later execution. + + If `mark_failed` was called before `put`, the error from the first + invocation of `mark_failed` will be raised. + + Args: + closure: The `Closure` to put into the queue. + tag: if not None, put into a queue with the given tag. + """ + closure.tag = tag + if tag is not None: + with self._queue_lock: + self._tagged_queue[tag].put(closure, block=False) + self._closures_queued_condition.notify_all() + else: + with self._put_wait_lock, self._queue_lock: + self._queue_free_slot_condition.wait_for(lambda: not self._queue.full()) + self._queue.put(closure, block=False) + metric_utils.monitor_int("queued_closures", self._queue.qsize()) + self._raise_if_error() + self._closures_queued_condition.notify() + + def get(self, timeout=None, tag=None): + """Return a closure from the queue to be executed. + + It will try to fetch an item from the queue with the given tag. If this + queue is empty, it will then check the global queue. + + Args: + timeout: timeout when waiting for a closure to be put. + tag: optional tag to specify which queue to query first before querying + the global queue. + + Returns: + a closure or None after timeout. + """ + with self._queue_lock: + while (self._should_process_closures and self._queue.empty() and + (tag is None or self._tagged_queue[tag].empty())): + if not self._closures_queued_condition.wait(timeout=timeout): + return None + if not self._should_process_closures: + return None + if tag is not None and not self._tagged_queue[tag].empty(): + closure = self._tagged_queue[tag].get(block=False) + return closure + closure = self._queue.get(block=False) + metric_utils.monitor_int("queued_closures", self._queue.qsize()) + assert closure.tag is None + assert tag is None or self._tagged_queue[tag].empty() + self._queue_free_slot_condition.notify() + self.inflight_closure_count += 1 + return closure + + def mark_finished(self): + """Let the queue know that a closure has been successfully executed.""" + with self._queue_lock: + if self._inflight_closure_count < 1: + raise AssertionError("There is no inflight closures to mark_finished.") + self.inflight_closure_count -= 1 + if self._inflight_closure_count == 0: + self._no_inflight_closure_condition.notify_all() + if self._queue.empty() and self._inflight_closure_count == 0: + self._stop_waiting_condition.notify_all() + self._watchdog.report_closure_done() + + def put_back(self, closure): + """Put the closure back into the queue as it was not properly executed.""" + assert closure.tag is None + with self._queue_lock: + if self._inflight_closure_count < 1: + raise AssertionError("There is no inflight closures to put_back.") + if self._error: + closure.mark_cancelled() + else: + self._queue_free_slot_condition.wait_for(lambda: not self._queue.full()) + self._queue.put(closure, block=False) + metric_utils.monitor_int("queued_closures", self._queue.qsize()) + self._closures_queued_condition.notify() + self.inflight_closure_count -= 1 + if self._inflight_closure_count == 0: + self._no_inflight_closure_condition.notify_all() + + def wait(self, timeout=None): + """Wait for all closures to be finished before returning. + + If `mark_failed` was called before or during `wait`, the error from the + first invocation of `mark_failed` will be raised. + + Args: + timeout: A float specifying a timeout for the wait in seconds. + + Returns: + True unless the given timeout expired, in which case it returns False. + """ + with self._put_wait_lock, self._queue_lock: + logging.info("Waiting for all global closures to be finished.") + while (not self._error and + (not self._queue.empty() or self._inflight_closure_count > 0)): + if not self._stop_waiting_condition.wait(timeout=timeout): + return False + self._raise_if_error() + return True + + def mark_failed(self, e): + """Sets error and unblocks any wait() call.""" + with self._queue_lock: + # TODO(yuefengz): maybe record all failure and give users more + # information? + if self._inflight_closure_count < 1: + raise AssertionError("There is no inflight closures to mark_failed.") + if self._error is None: + self._error = e + self.inflight_closure_count -= 1 + if self._inflight_closure_count == 0: + self._no_inflight_closure_condition.notify_all() + self._stop_waiting_condition.notify_all() + + def done(self): + """Returns true if the queue is empty and there is no inflight closure. + + If `mark_failed` was called before `done`, the error from the first + invocation of `mark_failed` will be raised. + """ + with self._queue_lock: + self._raise_if_error() + return self._queue.empty() and self._inflight_closure_count == 0 + + def clear_tag_unlocked(self, tag): + self._tagged_queue[tag] = queue.Queue() + + +class CoordinationServicePreemptionHandler(object): + """Handles preemptions of workers and parameter servers. + + Starts a thread to regularly poll the coordination service (hosted on PS 0) + for task states. When a worker's task state reflects an error, it inspects the + error. If the error is recoverable (i.e. a preemption), it waits for the + worker to recover, then updates the server def. Otherwise, it raises the error + to the user. + + A worker error is detected to be recoverable if it is the result of missing a + heartbeat that workers regularly send to the coordination service. + + The thread also checks for parameter server errors. If these are detected, the + thread and coordinator shutdown. To resume training in this case, the whole + job must be restarted and resumed from the latest checkpoint. + """ + + def __init__(self, server_def, cluster): + self._server_def = server_def + self._cluster = cluster + self._cluster_update_lock = threading.Lock() + self._cluster_due_for_update_or_finish = threading.Event() + self._worker_up_cond = threading.Condition(self._cluster_update_lock) + + self._next_task_state_cond = threading.Condition() + self._task_states = None + + self._error_from_recovery = None + self._should_preemption_thread_run = True + self._task_state_poller_thread = utils.RepeatedTimer( + interval=_POLL_FREQ_IN_SEC, + function=self._get_task_states) + self._preemption_handler_thread = threading.Thread( + target=self._preemption_handler, + name="WorkerPreemptionHandler", + daemon=True) + self._preemption_handler_thread.start() + + self._num_workers = self._cluster._num_workers + self._num_ps = self._cluster._num_ps + + def stop(self): + """Ensure the worker preemption thread is closed.""" + self._task_state_poller_thread.stop() + self._should_preemption_thread_run = False + with self._cluster_update_lock: + self._cluster_due_for_update_or_finish.set() + # TODO(yuefengz): The preemption handler thread shouldn't be terminated + # asynchronously since it touches eager context which is a process-wide + # singleton. The problem is in OSS unit tests will time out. + + @contextlib.contextmanager + def wait_on_failure(self, + on_failure_fn=None, + on_transient_failure_fn=None, + on_recovery_fn=None, + worker_device_name="(unknown)"): + """Catches errors during closure execution and handles them. + + Args: + on_failure_fn: an optional function to run if preemption happens. + on_transient_failure_fn: an optional function to run if transient failure + happens. + on_recovery_fn: an optional function to run when a worker is recovered + from preemption. + worker_device_name: the device name of the worker instance that is passing + through the failure. + + Yields: + None. + """ + assert self._should_preemption_thread_run + try: + yield + except (errors.OpError, ClosureInputError, + ClosureAbortedError) as e: + # The next state could reflect stale heartbeats, so wait for two rounds. + # Example: + # - Worker sends healthy heartbeat at T=0. + # - Coordination service receives healthy heartbeat at T=0. + # - Worker gets preempted at T=0.1. + # - Coordinator catches error at T=0.2, and waits here for next states. + # - Coordinator polls states at T=1.9. Heartbeat time has not elapsed yet, + # so coordination service does not know it is down yet. + # - Coordination service learns of worker unavailability at T=2, the next + # heartbeat. + # - Coordinator polls states at T=3.9 and learns of worker unavailability. + with self._next_task_state_cond: + # Give some buffer time to make sure task states are updated during the + # wait interval + self._next_task_state_cond.wait(_POLL_FREQ_IN_SEC * 1.25) + with self._next_task_state_cond: + self._next_task_state_cond.wait(_POLL_FREQ_IN_SEC * 1.25) + + # Check for coordination service failure + if not self._task_states: + self._log_ps_failure_and_raise(e, 0) + + worker_states = self._task_states[:self._num_workers] + ps_states = self._task_states[self._num_workers:] + + # Check for PS failure + if any(ps_states): + failed_ps_index = [ + ix for ix, ps_state in enumerate(ps_states) if ps_state + ] + self._log_ps_failure_and_raise(e, failed_ps_index[0]) + + # Check for preemption of this worker + worker_ix = int(worker_device_name.split(":")[-1]) + if worker_states[worker_ix]: + # Raise error if all closures are being cancelled + if self._cluster.closure_queue._cancellation_mgr.is_cancelled: # pylint: disable=protected-access + if isinstance(e, errors.CancelledError): + raise e + # It's possible the caught error `e` here is due to worker preemption + # and is thus not a `CancelledError`, because a different + # unrecoverable error on another worker caused closure cancellation, + # while this thread was waiting for task states. So raise a new + # CancelledError. + else: + raise errors.CancelledError( + None, None, "The corresponding function was cancelled while " + "attempting to recover from worker failure.") + # Else, preemption + self._handle_failure_and_recovery(e, on_failure_fn, + on_transient_failure_fn, + on_recovery_fn, worker_device_name) + return + + # else, if timeout: log + if self._cluster._record_and_ignore_transient_timeouts(e): # pylint: disable=protected-access + logging.error( + "Remote function on worker %s failed with %r:%s\n" + "This derived error is ignored and not reported to users.", + worker_device_name, e, e) + if on_transient_failure_fn: + on_transient_failure_fn() + return + raise e + + def _handle_failure_and_recovery(self, + e, + on_failure_fn, + on_transient_failure_fn, + on_recovery_fn, + worker_device_name): + """Call failure fn, wait for cluster to recover, then call recovery fn. + + Args: + e: the Exception thrown during closure execution. + on_failure_fn: an optional function to run if preemption happens. + on_transient_failure_fn: an optional function to run if transient failure + happens. + on_recovery_fn: an optional function to run when a worker is recovered + from preemption. + worker_device_name: the device name of the worker instance that is passing + through the failure. + """ + if on_failure_fn: + on_failure_fn(e) + # update server def + with self._cluster_update_lock: + self._cluster_due_for_update_or_finish.set() + self._worker_up_cond.wait(_WORKER_MAXIMUM_RECOVERY_SEC) + if self._error_from_recovery: + # TODO(yuefengz): there is only one worker that will get this error. + # Ideally we should let all workers notified by `_worker_up_cond` get + # this error. + try: + raise self._error_from_recovery + finally: + self._error_from_recovery = None + logging.info("Worker %s has been recovered.", worker_device_name) + + if on_recovery_fn: + logging.info("Worker %s calling on_recovery_fn", worker_device_name) + with self.wait_on_failure( + on_recovery_fn=on_recovery_fn, + on_transient_failure_fn=on_transient_failure_fn, + worker_device_name=worker_device_name): + on_recovery_fn() + + def _log_ps_failure_and_raise(self, e, ps_index): + logging.info("Parameter server failure detected at PS task %d", ps_index) + self.stop() + raise PSUnavailableError(e) + + def _get_task_states(self): + """Get task states and reset to None if coordination service is down.""" + try: + self._task_states = context.context().get_task_states( + [("worker", self._num_workers), ("ps", self._num_ps)] + ) + except (errors.UnavailableError, errors.InternalError) as e: + if isinstance( + e, errors.InternalError + ) and "coordination service is not enabled" not in str(e).lower(): + raise + # Coordination service is down + self._task_states = None + with self._next_task_state_cond: + self._next_task_state_cond.notify_all() + + def _preemption_handler(self): + """A loop that handles preemption. + + This loop waits for signal of worker preemption and upon worker preemption, + it waits until all workers are back and updates the cluster about the + restarted workers. + """ + assert self._should_preemption_thread_run + while True: + self._cluster_due_for_update_or_finish.wait() + if not self._should_preemption_thread_run: + logging.info("Stopping the failure handing thread.") + break + + with self._cluster_update_lock: + try: + # TODO(haoyuzhang): support partial cluster recovery + logging.info("Cluster now being recovered.") + context.context().update_server_def(self._server_def) + + # Cluster updated successfully, clear the update signal, and notify + # all workers that they are recovered from failure. + logging.info("Cluster successfully recovered.") + self._notify_cluster_update() + except Exception as e: # pylint: disable=broad-except + logging.info("Error occurred while updating server def: %s", e) + # Wait for the next set of states from the task state poller + with self._next_task_state_cond: + self._next_task_state_cond.wait(_POLL_FREQ_IN_SEC * 2) + # If a PS is preempted, set the error + if not self._task_states: + self._error_from_recovery = e + else: + ps_states = self._task_states[self._num_workers:] + # Check for PS failure + if any(ps_states): + self._error_from_recovery = e + # Else, likely another worker failed. Just log and retry + self._notify_cluster_update() + # NOTE: Since the first RPC (GetStatus) of update_server_def is + # currently blocking by default, error should only happen if: + # (1) More workers failed while waiting for the previous workers to + # come back; + # (2) Worker failed when exchanging subsequent RPCs after the first + # RPC returns. + # Consider adding backoff retry logic if we see the error logged + # too frequently. + logging.error("Cluster update failed with error: %s. Retrying...", e) + + def _notify_cluster_update(self): + self._worker_up_cond.notify_all() + # The check for _should_preemption_thread_run is necessary since the + # `stop` may have already set _cluster_due_for_update_or_finish. + if self._should_preemption_thread_run: + self._cluster_due_for_update_or_finish.clear() + + +class WorkerPreemptionHandler(object): + """Handles worker preemptions.""" + + def __init__(self, server_def, cluster): + self._server_def = server_def + self._cluster = cluster + self._cluster_update_lock = threading.Lock() + self._cluster_due_for_update_or_finish = threading.Event() + self._worker_up_cond = threading.Condition(self._cluster_update_lock) + self._error_from_recovery = None + self._should_preemption_thread_run = True + self._preemption_handler_thread = threading.Thread( + target=self._preemption_handler, + name="WorkerPreemptionHandler", + daemon=True) + self._preemption_handler_thread.start() + + def stop(self): + """Ensure the worker preemption thread is closed.""" + self._should_preemption_thread_run = False + with self._cluster_update_lock: + self._cluster_due_for_update_or_finish.set() + # TODO(yuefengz): The preemption handler thread shouldn't be terminated + # asynchronously since it touches eager context which is a process-wide + # singleton. The problem is in OSS unit tests will time out. + + def _validate_preemption_failure(self, e): + """Validates that the given exception represents worker preemption.""" + + # Only categorize the failure as a worker preemption if the cancellation + # manager did not attempt to cancel the blocking operations. + if _is_worker_failure(e) and ( + not self._cluster.closure_queue._cancellation_mgr.is_cancelled): # pylint: disable=protected-access + metric_utils.monitor_increment_counter("worker_failures") + return + raise e + + @contextlib.contextmanager + def wait_on_failure(self, + on_failure_fn=None, + on_transient_failure_fn=None, + on_recovery_fn=None, + worker_device_name="(unknown)"): + """Catches worker preemption error and wait until failed workers are back. + + Args: + on_failure_fn: an optional function to run if preemption happens. + on_transient_failure_fn: an optional function to run if transient failure + happens. + on_recovery_fn: an optional function to run when a worker is recovered + from preemption. + worker_device_name: the device name of the worker instance that is passing + through the failure. + + Yields: + None. + """ + assert self._should_preemption_thread_run + try: + yield + except (errors.OpError, ClosureInputError, + ClosureAbortedError, TypeError) as e: + # If the error is due to temporary connectivity issues between worker and + # ps, put back closure, ignore error and do not mark worker as failure. + if self._cluster._record_and_ignore_transient_ps_failure(e): # pylint: disable=protected-access + logging.error( + "Remote function on worker %s failed with %r:%s\n" + "It is treated as a transient connectivity failure for now.", + worker_device_name, e, e) + if on_transient_failure_fn: + on_transient_failure_fn() + return + + # If the error is due to temporary connectivity issues that cause the + # server-side RPCs to be cancelled, TF might not abort the step and the + # closure might timeout. The coordinator ignores certain amount of such + # failures without marking worker as failure. + if self._cluster._record_and_ignore_transient_timeouts(e): # pylint: disable=protected-access + logging.error( + "Remote function on worker %s failed with %r:%s\n" + "This derived error is ignored and not reported to users.", + worker_device_name, e, e) + if on_transient_failure_fn: + on_transient_failure_fn() + return + + # Ignoring derived CancelledErrors to tolerate transient failures in + # PS-worker communication, which initially exposed as an UnavailableError + # and then lead to sub-function cancellation, subsequently getting + # reported from worker to chief as CancelledError. + # We do not mark either worker or PS as failed due to only CancelledError. + # If there are real (non-transient) failures, they must also be reported + # as other errors (UnavailableError most likely) in closure executions. + if isinstance(e, errors.CancelledError) and "/job:" in str(e): + logging.error( + "Remote function on worker %s failed with %r:%s\n" + "This derived error is ignored and not reported to users.", + worker_device_name, e, e) + if on_transient_failure_fn: + on_transient_failure_fn() + return + + # This reraises the error, if it's not considered recoverable; otherwise, + # the following failure recovery logic run. At this time, only worker + # unavailability is recoverable. PS unavailability as well as other + # errors in the user function is not recoverable. + self._validate_preemption_failure(e) + + logging.error("Worker %s failed with %r:%s", worker_device_name, e, e) + if on_failure_fn: + on_failure_fn(e) + + with self._cluster_update_lock: + self._cluster_due_for_update_or_finish.set() + self._worker_up_cond.wait(_WORKER_MAXIMUM_RECOVERY_SEC) + if self._error_from_recovery: + # TODO(yuefengz): there is only one worker that will get this error. + # Ideally we shuold let all workers notified by `_worker_up_cond` get + # this error. + try: + raise self._error_from_recovery + finally: + self._error_from_recovery = None + logging.info("Worker %s has been recovered.", worker_device_name) + + if on_recovery_fn: + logging.info("Worker %s calling on_recovery_fn", worker_device_name) + with self.wait_on_failure( + on_recovery_fn=on_recovery_fn, + on_transient_failure_fn=on_transient_failure_fn, + worker_device_name=worker_device_name): + on_recovery_fn() + + def _preemption_handler(self): + """A loop that handles preemption. + + This loop waits for signal of worker preemption and upon worker preemption, + it waits until all workers are back and updates the cluster about the + restarted workers. + """ + assert self._should_preemption_thread_run + while True: + self._cluster_due_for_update_or_finish.wait() + if not self._should_preemption_thread_run: + logging.info("Stopping the failure handing thread.") + break + + with self._cluster_update_lock: + try: + # TODO(haoyuzhang): support partial cluster recovery + logging.info("Cluster now being recovered.") + with metric_utils.monitored_timer("server_def_update"): + context.context().update_server_def(self._server_def) + + # Cluster updated successfully, clear the update signal, and notify + # all workers that they are recovered from failure. + logging.info("Cluster successfully recovered.") + self._worker_up_cond.notify_all() + # The check for _should_preemption_thread_run is necessary since the + # `stop` may have already set _cluster_due_for_update_or_finish. + if self._should_preemption_thread_run: + self._cluster_due_for_update_or_finish.clear() + except Exception as e: # pylint: disable=broad-except + logging.info("Error occurred while updating server def: %s", e) + try: + self._validate_preemption_failure(e) + except Exception as ps_e: # pylint: disable=broad-except + logging.info("Error that occurred while updating server def is not " + "a worker failure. So set it as _error_from_recovery") + # In this case, a parameter server fails. So we raise this error to + # the caller of `wait_on_failure`. + self._error_from_recovery = ps_e + self._worker_up_cond.notify_all() + if self._should_preemption_thread_run: + self._cluster_due_for_update_or_finish.clear() + # NOTE: Since the first RPC (GetStatus) of update_server_def is + # currently blocking by default, error should only happen if: + # (1) More workers failed while waiting for the previous workers to + # come back; + # (2) Worker failed when exchanging subsequent RPCs after the first + # RPC returns. + # Consider adding backoff retry logic if we see the error logged + # too frequently. + logging.error("Cluster update failed with error: %s. Retrying...", e) + + +class Worker(object): + """A worker in a cluster. + + Attributes: + worker_index: The index of the worker in the cluster. + device_name: The device string of the worker, e.g. "/job:worker/task:1". + executor: The worker's executor for remote function execution. + failure_handler: The failure handler used to handler worker preemption + failure. + """ + + def __init__(self, worker_index, device_name, cluster): + self.worker_index = worker_index + self.device_name = device_name + self.executor = executor.new_executor(enable_async=False) + self.failure_handler = cluster.failure_handler + self._cluster = cluster + self._resource_tracking_lock = threading.Lock() + self._resource_remote_value_refs = [] + self._is_dead_with_error = None + self._should_worker_thread_run = True + + # Worker threads need to start after `Worker`'s initialization. + threading.Thread(target=self._process_queue, + name="WorkerClosureProcessingLoop-%d" % self.worker_index, + daemon=True).start() + + def stop(self): + """Ensure the worker thread is closed.""" + self._should_worker_thread_run = False + + def _schedule_resource(self, closure): + self._cluster.closure_queue.put(closure, tag=self.worker_index) + + def _set_resources_aborted(self, e): + """Set the resource ABORTED and add an error to it.""" + # TODO(yuefengz): maybe we can query whether a tensor is valid or not + # instead of marking a tensor aborted? + logging.info("[Worker %d] Clearing all resources.", self.worker_index) + for weakref_resource in self._resource_remote_value_refs: + resource = weakref_resource() + if resource: + # It is important to set an error on an aborted RemoteValue from a + # ResourceClosure because its failure will not trigger the worker thread + # to raise error immediately and the worker may continue executing + # closures taking it as an input. The error will then be correctly + # reported to users. + resource._set_aborted(ClosureAbortedError(e)) # pylint: disable=protected-access + + def _on_closure_failure(self, closure, e): + logging.info("[Worker %d] Putting back a closure after it failed.", + self.worker_index) + self._cluster.closure_queue.put_back(closure) + + with self._resource_tracking_lock: + self._is_dead_with_error = e + self._set_resources_aborted(e) + + def _on_resource_closure_failure(self, e): + """Clear tagged queue to ensure resource closures are rebuilt. + + Args: + e: The exception arisen from the resource closure. + """ + logging.info("[Worker %d] Clearing tagged queue after resource closure " + "failure.", self.worker_index) + with self._resource_tracking_lock: + self._is_dead_with_error = e + # No locking on queue is needed since + # * get will not happen concurrently here. + # * put to the specific tagged queue will be guarded by + # `self._resource_tracking_lock`. + self._cluster.closure_queue.clear_tag_unlocked(self.worker_index) + self._set_resources_aborted(e) + + def _on_worker_recovery(self): + logging.info("[Worker %d] calling _on_worker_recovery", self.worker_index) + with self._resource_tracking_lock: + for weakref_resource in self._resource_remote_value_refs: + resource = weakref_resource() + if resource: + self._schedule_resource(resource._closure) # pylint: disable=protected-access + self._is_dead_with_error = False + + def _process_closure(self, closure): + """Runs a closure with preemption handling.""" + try: + with self.failure_handler.wait_on_failure( + on_failure_fn=lambda e: self._on_closure_failure(closure, e), + on_transient_failure_fn=( + lambda: self._cluster.closure_queue.put_back(closure)), + on_recovery_fn=self._on_worker_recovery, + worker_device_name=self.device_name): + closure.execute_on(self) + with metric_utils.monitored_timer("remote_value_fetch"): + # Copy the remote tensor to local (the coordinator) in case worker + # becomes unavailable at a later time. + closure.maybe_call_with_output_remote_value(lambda r: r.get()) + self._cluster.closure_queue.mark_finished() + except Exception as e: # pylint: disable=broad-except + # Avoid logging the derived cancellation error + if not isinstance(e, errors.CancelledError): + logging.error( + " /job:worker/task:%d encountered the following error when " + "processing closure: %r:%s", self.worker_index, e, e) + closure.maybe_call_with_output_remote_value(lambda r: r._set_error(e)) # pylint: disable=protected-access + self._cluster.closure_queue.mark_failed(e) + + def _process_resource_closure(self, closure): + """Run the given resource closure with preemption handling.""" + assert closure.tag == self.worker_index + try: + with self.failure_handler.wait_on_failure( + on_failure_fn=self._on_resource_closure_failure, + on_transient_failure_fn=( + lambda: self._process_resource_closure(closure)), + on_recovery_fn=self._on_worker_recovery, + worker_device_name=self.device_name): + closure.execute_on(self) + except Exception as e: # pylint: disable=broad-except + # Avoid logging the derived cancellation error + logging.info("[Worker %d] got an exception when processing resource " + "closure", self.worker_index) + if not isinstance(e, errors.CancelledError): + logging.error( + " /job:worker/task:%d encountered the following error when " + "processing resource closure: %r:%s", self.worker_index, e, e) + closure.maybe_call_with_output_remote_value(lambda r: r._set_error(e)) # pylint: disable=protected-access + + def _maybe_delay(self): + """Delay if corresponding env vars are set.""" + # If the following two env vars variables are set. Scheduling for workers + # will start in a staggered manner. Worker i will wait for + # `TF_COORDINATOR_SCHEDULE_START_DELAY` * i seconds, not exceeding + # `TF_COORDINATOR_SCHEDULE_START_DELAY_MAX`. + delay_secs = int(os.environ.get("TF_COORDINATOR_SCHEDULE_START_DELAY", "0")) + delay_secs *= self.worker_index + delay_cap = int( + os.environ.get("TF_COORDINATOR_SCHEDULE_START_DELAY_MAX", "0")) + if delay_cap: + delay_secs = min(delay_secs, delay_cap) + if delay_secs > 0: + logging.info(" Worker %d sleeping for %d seconds before running function", + self.worker_index, delay_secs) + time.sleep(delay_secs) + + def _process_queue(self): + """Function running in a worker thread to process closure queues.""" + self._maybe_delay() + while self._should_worker_thread_run: + closure = self._cluster.closure_queue.get(tag=self.worker_index) + if not self._should_worker_thread_run or closure is None: + if closure is not None: + closure.mark_cancelled() + return + if isinstance(closure, ResourceClosure): + self._process_resource_closure(closure) + else: + self._process_closure(closure) + # To properly stop the worker and preemption threads, it is important that + # `ClusterCoordinator` object is not held onto so its `__del__` can be + # called. By removing the reference to the `closure` that has already been + # processed, we ensure that the `closure` object is released, while + # getting the next `closure` at above `self._cluster.closure_queue.get()` + # call. + del closure + + def create_resource(self, function, args=None, kwargs=None): + """Asynchronously creates a per-worker resource represented by a `RemoteValue`. + + Args: + function: the resource function to be run remotely. It should be a + `tf.function`, a concrete function or a Python function. + args: positional arguments to be passed to the function. + kwargs: keyword arguments to be passed to the function. + + Returns: + one or several RemoteValue objects depending on the function return + values. + """ + closure = ResourceClosure( + function, + self._cluster.resource_cancellation_mgr, + args=args, + kwargs=kwargs) + return self._register_and_schedule_resource_closure(closure) + + def create_variable_resource(self, function, args=None, kwargs=None): + """Create a per-worker variable.""" + closure = PerWorkerVariableClosure( + function, + self._cluster.resource_cancellation_mgr, + args=args, + kwargs=kwargs) + return self._register_and_schedule_resource_closure(closure) + + def _register_and_schedule_resource_closure(self, closure): + """Build remote value for, register for reconstruction, and schedule.""" + # Some notes about the concurrency: currently all the activities related to + # the same worker such as creating resources, setting resources' aborted + # status, and executing closures happen on the same thread. This allows us + # to have simpler logic of concurrency. + + resource_remote_value = closure.build_output_remote_value() + with self._resource_tracking_lock: + self._register_resource(resource_remote_value) + if self._is_dead_with_error: + resource_remote_value._set_aborted( # pylint: disable=protected-access + ClosureAbortedError(self._is_dead_with_error)) + else: + self._schedule_resource(closure) + return resource_remote_value + + def _register_resource(self, resource_remote_value): + if not isinstance(resource_remote_value, RemoteValue): + raise ValueError("Resource being registered is not of type " + "`tf.distribute.experimental.coordinator.RemoteValue`.") + self._resource_remote_value_refs.append(weakref.ref(resource_remote_value)) + + +class Cluster(object): + """A cluster with workers. + + We assume all function errors are fatal and based on this assumption our + error reporting logic is: + 1) Both `schedule` and `join` can raise a non-retryable error which is the + first error seen by the coordinator from any previously scheduled functions. + 2) When an error is raised, there is no guarantee on how many previously + scheduled functions have been executed; functions that have not been executed + will be thrown away and marked as cancelled. + 3) After an error is raised, the internal state of error will be cleared. + I.e. functions can continue to be scheduled and subsequent calls of `schedule` + or `join` will not raise the same error again. + + Attributes: + failure_handler: The failure handler used to handler worker preemption + failure. + workers: a list of `Worker` objects in the cluster. + closure_queue: the global Closure queue. + resource_cancellation_mgr: the cancellation manager used to cancel resource + closures. + """ + + def __init__(self, strategy): + """Initializes the cluster instance.""" + + self._num_workers = strategy._num_workers + self._num_ps = strategy._num_ps + + # Ignore PS failures reported by workers due to transient connection errors. + # Transient connectivity issues between workers and PS are relayed by the + # workers to the coordinator, leading the coordinator to believe that there + # are PS failures. The difference between transient vs. permanent PS failure + # is the number of reports from the workers. When this env var is set to a + # positive integer K, the coordinator ignores up to K reports of a failed PS + # task, i.e., only when there are more than K trials of executing closures + # fail due to errors from the same PS instance do we consider the PS + # instance encounters a failure. + # TODO(b/164279603): Remove this workaround when the underlying connectivity + # issue in gRPC server is resolved. + self._transient_ps_failures_threshold = int( + os.environ.get("TF_COORDINATOR_IGNORE_TRANSIENT_PS_FAILURES", 3)) + self._potential_ps_failures_lock = threading.Lock() + self._potential_ps_failures_count = [0] * self._num_ps + + # Ignore worker timeouts due to transient connection errors. + # Transient connectivity issues might cause the server side to unexpectedly + # cancel RPC handling logic, leading to closure execution timeouts. When + # the _transient_timeout_threshold is set to a positive number, the cluster + # coordinator ignores DeadlineExceeded errors from workers for the specified + # times before raising the error to users. + self._transient_timeouts_threshold = int( + os.environ.get("TF_COORDINATOR_IGNORE_TRANSIENT_TIMEOUTS", + self._num_workers // 10)) + self._transient_timeouts_lock = threading.Lock() + self._transient_timeouts_count = 0 + + self.closure_queue = _CoordinatedClosureQueue() + # Set this environment variable to use an experimental + # integration with the runtime coordination service to aid in failure + # detection and handling. This will not affect the functionality of + # the strategy or cluster coordinator, but is off by default. + if os.getenv("TF_PSS_ENABLE_COORDINATION_SERVICE"): + self.failure_handler = CoordinationServicePreemptionHandler( + context.get_server_def(), self, + ) + else: + self.failure_handler = WorkerPreemptionHandler(context.get_server_def(), + self) + worker_device_strings = [ + "/job:worker/replica:0/task:%d" % i for i in range(self._num_workers) + ] + self.workers = [ + Worker(i, w, self) for i, w in enumerate(worker_device_strings) + ] + + # Cancellation manager for all resource closures. + self.resource_cancellation_mgr = cancellation.CancellationManager() + + def stop(self): + """Stop worker, worker preemption threads, and the closure queue.""" + logging.info("Stopping cluster, starting with failure handler") + self.failure_handler.stop() + + logging.info("Stopping workers") + for worker in self.workers: + worker.stop() + logging.info("Stopping queue") + self.closure_queue.stop() + logging.info("Start cancelling remote resource-building functions") + self.resource_cancellation_mgr.start_cancel() + + def _record_and_ignore_transient_ps_failure(self, e): + """Records potential PS failures and return if failure should be ignored.""" + if self._transient_ps_failures_threshold <= 0 or not _is_ps_failure(e): + return False + + ps_tasks = _extract_failed_ps_instances(str(e)) + with self._potential_ps_failures_lock: + for t in ps_tasks: + self._potential_ps_failures_count[t] += 1 + # The number of UnavailableError encountered on this PS task exceeds the + # maximum number of ignored error + if (self._potential_ps_failures_count[t] >= + self._transient_ps_failures_threshold): + return False + return True + + def _record_and_ignore_transient_timeouts(self, e): + """Records observed timeout error and return if it should be ignored.""" + if self._transient_timeouts_threshold <= 0: + return False + if not isinstance(e, errors.DeadlineExceededError): + return False + with self._transient_timeouts_lock: + self._transient_timeouts_count += 1 + if self._transient_timeouts_count >= self._transient_timeouts_threshold: + return False + return True + + def schedule(self, function, args, kwargs): + """Schedules `function` to be dispatched to a worker for execution. + + Args: + function: The function to be dispatched to a worker for execution + asynchronously. + args: Positional arguments for `fn`. + kwargs: Keyword arguments for `fn`. + + Returns: + A `RemoteValue` object. + """ + closure = Closure( + function, + self.closure_queue._cancellation_mgr, # pylint: disable=protected-access + args=args, + kwargs=kwargs) + ret = closure.build_output_remote_value() + self.closure_queue.put(closure) + return ret + + def join(self): + """Blocks until all scheduled functions are executed.""" + self.closure_queue.wait() + + def done(self): + """Returns true if all scheduled functions are executed.""" + return self.closure_queue.done() + + +@tf_export("distribute.experimental.coordinator.ClusterCoordinator", + "distribute.coordinator.ClusterCoordinator", v1=[]) +class ClusterCoordinator(object): + """An object to schedule and coordinate remote function execution. + + This class is used to create fault-tolerant resources and dispatch functions + to remote TensorFlow servers. + + Currently, this class is not supported to be used in a standalone manner. It + should be used in conjunction with a `tf.distribute` strategy that is designed + to work with it. The `ClusterCoordinator` class currently only works + `tf.distribute.experimental.ParameterServerStrategy`. + + __The `schedule`/`join` APIs__ + + The most important APIs provided by this class is the `schedule`/`join` pair. + The `schedule` API is non-blocking in that it queues a `tf.function` and + returns a `RemoteValue` immediately. The queued functions will be dispatched + to remote workers in background threads and their `RemoteValue`s will be + filled asynchronously. Since `schedule` doesn’t require worker assignment, the + `tf.function` passed in can be executed on any available worker. If the worker + it is executed on becomes unavailable before its completion, it will be + migrated to another worker. Because of this fact and function execution is not + atomic, a function may be executed more than once. + + __Handling Task Failure__ + + This class when used with + `tf.distribute.experimental.ParameterServerStrategy`, comes with built-in + fault tolerance for worker failures. That is, when some workers are not + available for any reason to be reached from the coordinator, the training + progress continues to be made with the remaining workers. Upon recovery of a + failed worker, it will be added for function execution after datasets created + by `create_per_worker_dataset` are re-built on it. + + When a parameter server fails, a `tf.errors.UnavailableError` is raised by + `schedule`, `join` or `done`. In this case, in addition to bringing back the + failed parameter server, users should restart the coordinator so that it + reconnects to workers and parameter servers, re-creates the variables, and + loads checkpoints. If the coordinator fails, after the user brings it back, + the program will automatically connect to workers and parameter servers, and + continue the progress from a checkpoint. + + It is thus essential that in user's program, a checkpoint file is periodically + saved, and restored at the start of the program. If an + `tf.keras.optimizers.Optimizer` is checkpointed, after restoring from a + checkpoiont, its `iterations` property roughly indicates the number of steps + that have been made. This can be used to decide how many epochs and steps are + needed before the training completion. + + See `tf.distribute.experimental.ParameterServerStrategy` docstring for an + example usage of this API. + + This is currently under development, and the API as well as implementation + are subject to changes. + """ + + def __new__(cls, strategy): + # `ClusterCoordinator` is kept as a single instance to a given `Strategy`. + # TODO(rchao): Needs a lock for thread-safety + if strategy._cluster_coordinator is None: + strategy._cluster_coordinator = super( + ClusterCoordinator, cls).__new__(cls) + return strategy._cluster_coordinator + + def __init__(self, strategy): + """Initialization of a `ClusterCoordinator` instance. + + Args: + strategy: a supported `tf.distribute.Strategy` object. Currently, only + `tf.distribute.experimental.ParameterServerStrategy` is supported. + + Raises: + ValueError: if the strategy being used is not supported. + """ + if not getattr(self, "_has_initialized", False): + if not hasattr(strategy, "_is_parameter_server_strategy_v2"): + raise ValueError( + "Only `tf.distribute.experimental.ParameterServerStrategy` " + "is supported to work with " + "`tf.distribute.experimental.coordinator.ClusterCoordinator` " + "currently.") + self._strategy = strategy + self.strategy.extended._used_with_coordinator = True + self._cluster = Cluster(strategy) + self._has_initialized = True + + def __del__(self): + logging.info("ClusterCoordinator destructor: stopping cluster") + self._cluster.stop() + + @property + def strategy(self): + """Returns the `Strategy` associated with the `ClusterCoordinator`.""" + return self._strategy + + def schedule(self, fn, args=None, kwargs=None): + """Schedules `fn` to be dispatched to a worker for asynchronous execution. + + This method is non-blocking in that it queues the `fn` which will be + executed later and returns a + `tf.distribute.experimental.coordinator.RemoteValue` object immediately. + `fetch` can be called on it to wait for the function execution to finish + and retrieve its output from a remote worker. On the other hand, call + `tf.distribute.experimental.coordinator.ClusterCoordinator.join` to wait for + all scheduled functions to finish. + + `schedule` guarantees that `fn` will be executed on a worker at least once; + it could be more than once if its corresponding worker fails in the middle + of its execution. Note that since worker can fail at any point when + executing the function, it is possible that the function is partially + executed, but `tf.distribute.experimental.coordinator.ClusterCoordinator` + guarantees that in those events, the function will eventually be executed on + any worker that is available. + + If any previously scheduled function raises an error, `schedule` will raise + any one of those errors, and clear the errors collected so far. What happens + here, some of the previously scheduled functions may have not been executed. + User can call `fetch` on the returned + `tf.distribute.experimental.coordinator.RemoteValue` to inspect if they have + executed, failed, or cancelled, and reschedule the corresponding function if + needed. + + When `schedule` raises, it guarantees that there is no function that is + still being executed. + + At this time, there is no support of worker assignment for function + execution, or priority of the workers. + + `args` and `kwargs` are the arguments passed into `fn`, when `fn` is + executed on a worker. They can be + `tf.distribute.experimental.coordinator.PerWorkerValues` and in this case, + the argument will be substituted with the corresponding component on the + target worker. Arguments that are not + `tf.distribute.experimental.coordinator.PerWorkerValues` will be passed into + `fn` as-is. Currently, `tf.distribute.experimental.coordinator.RemoteValue` + is not supported to be input `args` or `kwargs`. + + Args: + fn: A `tf.function`; the function to be dispatched to a worker for + execution asynchronously. Regular python function is not supported to be + scheduled. + args: Positional arguments for `fn`. + kwargs: Keyword arguments for `fn`. + + Returns: + A `tf.distribute.experimental.coordinator.RemoteValue` object that + represents the output of the function scheduled. + + Raises: + Exception: one of the exceptions caught by the coordinator from any + previously scheduled function, since the last time an error was thrown + or since the beginning of the program. + """ + if not isinstance(fn, + (def_function.Function, tf_function.ConcreteFunction)): + raise TypeError( + "`tf.distribute.experimental.coordinator.ClusterCoordinator.schedule`" + " only accepts a `tf.function` or a concrete function.") + # Slot variables are usually created during function tracing time; thus + # `schedule` needs to be called within the `strategy.scope()`. + with self.strategy.scope(): + self.strategy.extended._being_scheduled = True # pylint: disable=protected-access + schedule_remote_value = self._cluster.schedule( + fn, args=args, kwargs=kwargs) + self.strategy.extended._being_scheduled = False # pylint: disable=protected-access + return schedule_remote_value + + def join(self): + """Blocks until all the scheduled functions have finished execution. + + If any previously scheduled function raises an error, `join` will fail by + raising any one of those errors, and clear the errors collected so far. If + this happens, some of the previously scheduled functions may have not been + executed. Users can call `fetch` on the returned + `tf.distribute.experimental.coordinator.RemoteValue` to inspect if they have + executed, failed, or cancelled. If some that have been cancelled need to be + rescheduled, users should call `schedule` with the function again. + + When `join` returns or raises, it guarantees that there is no function that + is still being executed. + + Raises: + Exception: one of the exceptions caught by the coordinator by any + previously scheduled function since the last time an error was thrown or + since the beginning of the program. + """ + self._cluster.join() + + def done(self): + """Returns whether all the scheduled functions have finished execution. + + If any previously scheduled function raises an error, `done` will fail by + raising any one of those errors. + + When `done` returns True or raises, it guarantees that there is no function + that is still being executed. + + Returns: + Whether all the scheduled functions have finished execution. + Raises: + Exception: one of the exceptions caught by the coordinator by any + previously scheduled function since the last time an error was thrown or + since the beginning of the program. + """ + return self._cluster.done() + + def create_per_worker_dataset(self, dataset_fn): + """Create dataset on each worker. + + This creates dataset on workers from the input which can be either a + `tf.data.Dataset`, a `tf.distribute.DistributedDataset` or a function which + returns a dataset, and returns an object that represents the collection of + those individual datasets. Calling `iter` on such collection of datasets + returns a `tf.distribute.experimental.coordinator.PerWorkerValues`, which is + a collection of iterators, where the iterators have been placed on + respective workers. + + Calling `next` on a `PerWorkerValues` of iterator is unsupported. The + iterator is meant to be passed as an argument into + `tf.distribute.experimental.coordinator.ClusterCoordinator.schedule`. When + the scheduled function is about to be executed by a worker, the + function will receive the individual iterator that corresponds to the + worker. The `next` method can be called on an iterator inside a + scheduled function when the iterator is an input of the function. + + Currently the `schedule` method assumes workers are all the same and thus + assumes the datasets on different workers are the same, except they may be + shuffled differently if they contain a `dataset.shuffle` operation and a + random seed is not set. Because of this, we also recommend the datasets to + be repeated indefinitely and schedule a finite number of steps instead of + relying on the `OutOfRangeError` from a dataset. + + + Example: + + ```python + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=...) + coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( + strategy=strategy) + + @tf.function + def worker_fn(iterator): + return next(iterator) + + def per_worker_dataset_fn(): + return strategy.distribute_datasets_from_function( + lambda x: tf.data.Dataset.from_tensor_slices([3] * 3)) + + per_worker_dataset = coordinator.create_per_worker_dataset( + per_worker_dataset_fn) + per_worker_iter = iter(per_worker_dataset) + remote_value = coordinator.schedule(worker_fn, args=(per_worker_iter,)) + assert remote_value.fetch() == 3 + ``` + + Args: + dataset_fn: The dataset function that returns a dataset. This is to be + executed on the workers. + + Returns: + An object that represents the collection of those individual + datasets. `iter` is expected to be called on this object that returns + a `tf.distribute.experimental.coordinator.PerWorkerValues` of the + iterators (that are on the workers). + """ + return values_lib.get_per_worker_dataset(dataset_fn, self) + + def _create_per_worker_resources(self, fn, args=None, kwargs=None): + """Synchronously create resources on the workers. + + The resources are represented by + `tf.distribute.experimental.coordinator.RemoteValue`s. + + Args: + fn: The function to be dispatched to all workers for execution + asynchronously. + args: Positional arguments for `fn`. + kwargs: Keyword arguments for `fn`. + + Returns: + A `tf.distribute.experimental.coordinator.PerWorkerValues` object, which + wraps a tuple of `tf.distribute.experimental.coordinator.RemoteValue` + objects. + """ + results = [] + for w in self._cluster.workers: + results.append(w.create_resource(fn, args=args, kwargs=kwargs)) + return PerWorkerValues(tuple(results)) + + def _create_per_worker_variables(self, fn, args=None, kwargs=None): + """Asynchronously create variables on workers.""" + results = [] + for w in self._cluster.workers: + results.append(w.create_variable_resource(fn, args=args, kwargs=kwargs)) + return PerWorkerValues(tuple(results)) + + def fetch(self, val): + """Blocking call to fetch results from the remote values. + + This is a wrapper around + `tf.distribute.experimental.coordinator.RemoteValue.fetch` for a + `RemoteValue` structure; it returns the execution results of + `RemoteValue`s. If not ready, wait for them while blocking the caller. + + Example: + ```python + strategy = ... + coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( + strategy) + + def dataset_fn(): + return tf.data.Dataset.from_tensor_slices([1, 1, 1]) + + with strategy.scope(): + v = tf.Variable(initial_value=0) + + @tf.function + def worker_fn(iterator): + def replica_fn(x): + v.assign_add(x) + return v.read_value() + return strategy.run(replica_fn, args=(next(iterator),)) + + distributed_dataset = coordinator.create_per_worker_dataset(dataset_fn) + distributed_iterator = iter(distributed_dataset) + result = coordinator.schedule(worker_fn, args=(distributed_iterator,)) + assert coordinator.fetch(result) == 1 + ``` + + Args: + val: The value to fetch the results from. If this is structure of + `tf.distribute.experimental.coordinator.RemoteValue`, `fetch()` will be + called on the individual + `tf.distribute.experimental.coordinator.RemoteValue` to get the result. + + Returns: + If `val` is a `tf.distribute.experimental.coordinator.RemoteValue` or a + structure of `tf.distribute.experimental.coordinator.RemoteValue`s, + return the fetched `tf.distribute.experimental.coordinator.RemoteValue` + values immediately if they are available, or block the call until they are + available, and return the fetched + `tf.distribute.experimental.coordinator.RemoteValue` values with the same + structure. If `val` is other types, return it as-is. + """ + + def _maybe_fetch(val): + if isinstance(val, RemoteValue): + return val.fetch() + else: + return val + + # TODO(yuefengz): we should fetch values in a batch. + return nest.map_structure(_maybe_fetch, val) + + +def _extract_failed_ps_instances(err_msg): + """Return a set of potentially failing ps instances from error message.""" + tasks = re.findall("/job:ps/replica:0/task:[0-9]+", err_msg) + return set(int(t.split(":")[-1]) for t in tasks) + + +def _is_ps_failure(error): + """Whether the error is considered a parameter server failure.""" + if isinstance(error, PSUnavailableError): + return True + + # For an `ClosureInputError` or `ClosureAbortedError`, extract + # the original error and assess it accordingly. + if isinstance(error, (ClosureInputError, ClosureAbortedError)): + error = error.original_exception + + if _RPC_ERROR_FROM_PS not in str(error): + return False + + if isinstance(error, (errors.UnavailableError, errors.AbortedError)): + return True + + # The following error could happen when the remote task fails and restarts + # in a very short interval during which no RPCs were exchanged to detect the + # failure. In that case, gRPC allows channel (which is different from a + # connection) to be reused for a replaced server listening to same address. + if isinstance(error, errors.InvalidArgumentError): + if ("unknown device" in str(error).lower() or + "Unable to find the relevant tensor remote_handle" in str(error)): + return True + + return False + + +def _handle_graph_execution_error_as_worker_failure(): + return int(os.environ.get("TF_PS_HANDLE_UNKNOWN_ERROR", "0")) > 0 + + +def _is_worker_failure(error): + """Whether the error is considered a worker failure.""" + + # TODO(b/216666282): Understand why worker failure can manifest as a + # "Graph execution error" `UnknownError`. + if (_handle_graph_execution_error_as_worker_failure() and + isinstance(error, errors.UnknownError) and + "Graph execution error" in str(error)): + logging.info(f"Handling {type(error)}: {str(error)} as worker failure.") + return True + + # For an `ClosureInputError` or `ClosureAbortedError`, extract + # the original error and assess it accordingly. + if isinstance(error, (ClosureInputError, ClosureAbortedError)): + error = error.original_exception + + if _JOB_WORKER_STRING_IDENTIFIER not in str(error): + return False + if _RPC_ERROR_FROM_PS in str(error): + return False + + # TODO(haoyuzhang): Consider using special status code if error from a + # remote is derived from RPC errors originated from other hosts. + if isinstance(error, (errors.UnavailableError, errors.AbortedError)): + return True + + # The following error could happen when the remote task fails and restarts + # in a very short interval during which no RPCs were exchanged to detect the + # failure. In that case, gRPC allows channel (which is different from a + # connection) to be reused for a replaced server listening to same address. + if isinstance(error, errors.InvalidArgumentError): + if ("unknown device" in str(error).lower() or + "Primary device is not remote" in str(error) or + "Unable to find the relevant tensor remote_handle" in str(error)): + return True + + # TODO(b/162541228): The following 2 types of errors are very rare and only + # observed in large-scale testing. The types of errors should be reduced. + # This could happen when the function registration fails. In the observed + # cases this only happens to the dataset related functions. + if isinstance(error, errors.NotFoundError): + if ("is neither a type of a primitive operation nor a name of a function " + "registered" in str(error)): + return True + + # NOTE(b/179061495): During worker preemptions, if multiple functions are + # running concurrently (especially with subfunctions spanning chief/PS), + # CancelledError can be returned due to chief/PS cancelling outstanding RPCs + # to the failing workers. + if isinstance(error, errors.CancelledError): + return True + + # This can occur when preparing closures for execution when doing exact + # evaluation, because the iterator creation, which occurs within the + # tf.function, needs to access the worker device, so it fails if the worker is + # down. + if isinstance(error, TypeError) and "Binding inputs to tf.function" in str( + error): + return True + + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/coordinator_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/coordinator_context.py new file mode 100644 index 0000000000000000000000000000000000000000..eef520a95a2bfea4f1664556bcf24880398e5f41 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/coordinator_context.py @@ -0,0 +1,145 @@ +# 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. +# ============================================================================== +"""The execution context for ClusterCoordinator.""" + +import contextlib +import threading + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.distribute.coordinator import remote_value +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + +_dispatch_context = threading.local() + + +def get_current_dispatch_context(): + try: + return _dispatch_context.current + except AttributeError: + return None + + +@contextlib.contextmanager +def with_dispatch_context(worker_obj): + previous_context = getattr(_dispatch_context, "current", None) + _dispatch_context.current = DispatchContext(worker_obj) + yield + _dispatch_context.current = previous_context + + +class DispatchContext(object): + """Context entered when executing a closure on a given worker.""" + + def __init__(self, worker_obj): + self._worker = worker_obj + self._worker_index = worker_obj.worker_index + + @property + def worker(self): + return self._worker + + @property + def worker_index(self): + return self._worker_index + + def maybe_get_remote_value(self, ret): + return maybe_get_remote_value(ret) + + +def maybe_get_remote_value(val): + """Gets the value of `val` if it is a `RemoteValue`.""" + if isinstance(val, remote_value.RemoteValue): + error = val._get_error() # pylint: disable=protected-access + if error: + raise AssertionError( + "RemoteValue doesn't have a value because it has error %r:%s" % + (error, error)) + elif val._status is not remote_value.RemoteValueStatus.READY: # pylint: disable=protected-access + raise AssertionError("The input RemoteValue has not been executed.") + else: + return val._get_values() # pylint: disable=protected-access + else: + return val + + +@tf_export("distribute.coordinator.experimental_get_current_worker_index", + v1=[]) +def get_current_worker_index(): + """Returns the current worker index, when called within a worker closure. + + Some parameter server training workloads may require the worker to know its + index, for example for data sharding for reduced-variance training. + + This method may be used within a `tf.function` that is executed on a worker. + That is, either a `dataset_fn` that runs via + `ClusterCoordinator.create_per_worker_dataset`, or any other function + scheduled via `ClusterCoordinator.schedule`. + + Example (sharding data by worker): + + ```python + strategy = tf.distribute.ParameterServerStrategy( + cluster_resolver=...) + coordinator = ( + tf.distribute.coordinator.ClusterCoordinator(strategy)) + + def dataset_fn(context): + dataset = tf.data.Dataset.range(10) + worker_index = ( + tf.distribute.coordinator.experimental_get_current_worker_index() + ) + dataset = dataset.shard( + num_shards=num_workers, + index=worker_index, + ) + return dataset + + @tf.function + def per_worker_dataset_fn(): + return strategy.distribute_datasets_from_function(dataset_fn) + + per_worker_dataset = coordinator.create_per_worker_dataset( + per_worker_dataset_fn) + ``` + + Raises: + RuntimeError: if called from outside a `tf.function` or outside of a remote + closure execution context (that is, on a non-worker machine). + """ + + msg = ("Cannot retrieve the worker index. `get_worker_idx_and_num_workers` " + "should be called from within a tf.function being executed on a " + "worker. This method should only be called from either a dataset_fn " + "that is passed into `ClusterCoordinator.create_per_worker_dataset`, " + "or a tf.function that is passed into `ClusterCoordinator.schedule`.") + if not ops.inside_function(): + raise RuntimeError(msg) + + def call_time_worker_index(): + dispatch_context = get_current_dispatch_context() + if not dispatch_context: + raise RuntimeError(msg) + return dispatch_context.worker_index + + worker_index = ops.get_default_graph().capture_call_time_value( + call_time_worker_index, tensor.TensorSpec([], dtype=dtypes.int64)) + worker_index.op._set_attr( # pylint: disable=protected-access + "_user_specified_name", + attr_value_pb2.AttrValue(s=compat.as_bytes("worker_index"))) + return worker_index diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ca68282ca0ba3f292eaab94756ed0eb14dc6cba0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/fault_tolerance_test_base.py @@ -0,0 +1,697 @@ +# 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. +# ============================================================================== +"""Fault tolerance test base class for parameter server training in TF2.""" + +import gc +import os +import sys +import threading +import time + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.distribute import multi_worker_test_base +from tensorflow.python.distribute import parameter_server_strategy_v2 +from tensorflow.python.distribute import test_util +from tensorflow.python.distribute.cluster_resolver.cluster_resolver import SimpleClusterResolver +from tensorflow.python.distribute.coordinator import cluster_coordinator +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import coordinator as thread_coordinator +from tensorflow.python.training import server_lib + + +_RPC_ERROR_FROM_WORKER = "GRPC error information from remote target /job:worker" +_RPC_ERROR_FROM_PS = "GRPC error information from remote target /job:ps" +_WORKER_PREEMPTION_THREAD_NAME = "WorkerPreemptionHandler" +_WORKER_THREAD_PREFIX = "WorkerClosureProcessingLoop" + + +class Model(object): + + def __init__(self, coordinator): + self.cluster_coord = coordinator + self.strategy = self.cluster_coord.strategy + with self.cluster_coord.strategy.scope(): + self.build() + + def build(self): + self.w = variables.Variable( + initial_value=random_ops.random_uniform((10, 10)), dtype=dtypes.float32) + self.iterations = variables.Variable(initial_value=0, dtype=dtypes.int32) + # Allow external control to make the model run its train_fn in an infinite + # loop. This allows us to reliably test worker preemption in the middle of + # function execution. + self.do_infinite_step = variables.Variable(False) + + self.rebuild_iterators() + + def rebuild_iterators(self, use_dataset_fn=True): + if use_dataset_fn: + + def dataset_fn(): + data = random_ops.random_uniform((10, 10)) + dataset = dataset_ops.DatasetV2.from_tensors([data]).repeat() + return dataset + + def distribute_dataset_fn(): + return self.cluster_coord.strategy.distribute_datasets_from_function( + lambda _: dataset_fn()) + + self.iterator = iter( + self.cluster_coord.create_per_worker_dataset(distribute_dataset_fn)) + self.iterator2 = iter( + self.cluster_coord.create_per_worker_dataset(distribute_dataset_fn)) + else: + data = random_ops.random_uniform((10, 10)) + dataset = dataset_ops.DatasetV2.from_tensors([data]).repeat() + + self.iterator = iter( + self.cluster_coord.create_per_worker_dataset(dataset)) + self.iterator2 = iter( + self.cluster_coord.create_per_worker_dataset(dataset)) + + def _train_fn_internal(self, iterator, iterator2): + x = math_ops.matmul(array_ops.squeeze(next(iterator)), self.w) + x = math_ops.matmul(array_ops.squeeze(next(iterator2)), x) + x = math_ops.matmul(random_ops.random_uniform((10, 10)), x) + self.w.assign_add(x) + + @def_function.function + def train_fn(self, iterator, iterator2): + self._train_fn_internal(iterator, iterator2) + while self.do_infinite_step: + self._train_fn_internal(iterator, iterator2) + self.iterations.assign_add(1) + + def schedule_training_functions(self, num_steps): + with self.strategy.scope(): + for _ in range(num_steps): + self.cluster_coord.schedule( + self.train_fn, args=(self.iterator, self.iterator2)) + + def join_training_functions(self): + self.do_infinite_step.assign(False) + self.cluster_coord.join() + + +class BaseFaultToleranceTest(object): # pylint: disable=missing-docstring + + def setUp(self, num_workers, num_ps, use_cs=False): + super(BaseFaultToleranceTest, self).setUp() + + self._cluster = multi_worker_test_base.create_multi_process_cluster( + num_workers=num_workers, + num_ps=num_ps, + rpc_layer="grpc", + stream_output=True, + ) + self._cluster_def = self._cluster.cluster_resolver.cluster_spec().as_dict() + self._cluster_def["chief"] = [ + "localhost:%d" % multi_worker_test_base.pick_unused_port() + ] + cluster_resolver = SimpleClusterResolver( + server_lib.ClusterSpec(self._cluster_def), rpc_layer="grpc" + ) + + if use_cs: + os.environ["TF_PSS_ENABLE_COORDINATION_SERVICE"] = "1" + # The strategy's constructor would connect to the cluster. + self.strategy = parameter_server_strategy_v2.ParameterServerStrategyV2( + cluster_resolver + ) + self.cluster_coord = cluster_coordinator.ClusterCoordinator(self.strategy) + + self.thread_coord = thread_coordinator.Coordinator( + clean_stop_exception_types=[] + ) + self.num_workers = num_workers + self.num_ps = num_ps + + def tearDown(self): + super(BaseFaultToleranceTest, self).tearDown() + self._cluster.stop() + self._cluster = None + + def _restart(self, downtime_secs, job): + """Kills `job` (index: 0) and restarts it after `downtime_secs`. + + Args: + downtime_secs: secs before restarting the job. + job: a string specifying the job to restart. + """ + self._cluster.kill_task(job, 0) + time.sleep(downtime_secs) + self.assertFalse(context.check_alive("/job:%s/replica:0/task:0" % job)) + self._cluster.start_task(job, 0) + while not context.check_alive("/job:%s/replica:0/task:0" % job): + time.sleep(1) + + def _restart_in_thread(self, downtime_secs, restart_job): + + def _restart_fn(): + with self.thread_coord.stop_on_exception(): + self._restart(downtime_secs, restart_job) + + restart_thread = threading.Thread(target=_restart_fn) + restart_thread.start() + return restart_thread + + def _ensure_threads_closed(self): + """Ensures worker and preemption threads are closed.""" + # Worker and preemption threads should exist before releasing + # ClusterCoordinator. + running_threads = test_util.get_running_threads() + self.assertTrue( + test_util.has_thread(_WORKER_THREAD_PREFIX, running_threads)) + self.assertIn(_WORKER_PREEMPTION_THREAD_NAME, running_threads) + + # Print object graph if ClusterCoordinator may leak. + if sys.getrefcount(self.cluster_coord) > 2: + try: + test_util.show_backref(self.cluster_coord) + except: # pylint: disable=bare-except + pass + + # Wait for threads to close. + self.cluster_coord = None + self.strategy = None + gc.collect() + time.sleep(1) + + # Verify thread names. + running_threads = test_util.get_running_threads() + self.assertNotIn(_WORKER_PREEMPTION_THREAD_NAME, running_threads) + self.assertFalse( + test_util.has_thread(_WORKER_THREAD_PREFIX, running_threads), + "Worker thread is not stopped properly.") + + def _create_model_and_run_indefinitely(self): + model = Model(self.cluster_coord) + model.do_infinite_step.assign(True) + model.schedule_training_functions(10) + # Model does infinite training step, so at this moment, we expect to have + # `self.num_workers` infinite closures inflight, and `10-self.num_workers` + # closures in the queue. + while (self.cluster_coord._cluster.closure_queue._inflight_closure_count < + self.num_workers): + time.sleep(0.1) + return model + + def testClusterCoordinatorDestroyed(self): + self._ensure_threads_closed() + + def testWorkerPreemptionBetweenFunctions(self): + model = Model(self.cluster_coord) + model.schedule_training_functions(2) + model.join_training_functions() + self.assertEqual(model.iterations.numpy(), 2) + + self._restart(downtime_secs=2, job="worker") + + model.schedule_training_functions(2) + model.join_training_functions() + self.assertEqual(model.iterations.numpy(), 4) + + def testWorkerPreemptionMidstFunction(self): + model = Model(self.cluster_coord) + model.do_infinite_step.assign(True) + + model.schedule_training_functions(4) + # Model does infinite training step, so at this moment, we expect to have + # `self.num_workers` infinite closures inflight, and `4-self.num_workers` + # closures in the queue. + while (self.cluster_coord._cluster.closure_queue._inflight_closure_count < + self.num_workers): + time.sleep(0.1) + self.assertFalse(self.cluster_coord.done()) + self._restart(downtime_secs=2, job="worker") + model.join_training_functions() + self.assertGreaterEqual(model.iterations.numpy(), 4) + + def testOneWorkerPreemptionWithCancellation(self): + + @def_function.function + def normal_function(): + x = random_ops.random_uniform((2, 10)) + y = random_ops.random_uniform((10, 2)) + return math_ops.reduce_mean(math_ops.matmul(x, y)) + + @def_function.function + def error_function(): + x = random_ops.random_uniform((2, 10)) + y = random_ops.random_uniform((10, 2)) + check_ops.assert_non_positive_v2( + math_ops.reduce_sum(math_ops.matmul(x, y))) + return x + + @def_function.function + def long_function(): + x = random_ops.random_uniform((1000, 1000)) + for _ in math_ops.range(10000): + a = random_ops.random_uniform((1000, 1000)) + b = random_ops.random_uniform((1000, 1000)) + x += math_ops.matmul(a, b) + return x + + for _ in range(3): + self.cluster_coord.schedule(normal_function) + long_function_result = self.cluster_coord.schedule(long_function) + self.cluster_coord.schedule(error_function) + + time.sleep(1) # Let it run a couple steps. + self._restart(2, "worker") + + # InvalidArgumentError thrown from the error_function. + with self.assertRaises(errors.InvalidArgumentError): + self.cluster_coord.join() + + # CancelledError thrown by ClusterCoordinator after cancelling due to user + # error. + with self.assertRaises(errors.CancelledError): + long_function_result.fetch() + + for _ in range(3): + self.cluster_coord.schedule(normal_function) + self.cluster_coord.join() + + # The cluster is likely still being recovered since `join` returned early + # due to the error_function. + failure_handler = self.cluster_coord._cluster.failure_handler + failure_handler.stop() + failure_handler._preemption_handler_thread.join() + + def testHandleDatasetCreationFailureWithDatasetFn(self): + model = Model(self.cluster_coord) + + restart_thread = self._restart_in_thread(5, "worker") + + model.schedule_training_functions(3) + model.rebuild_iterators() + model.schedule_training_functions(3) + model.rebuild_iterators() + model.schedule_training_functions(3) + + model.join_training_functions() + + self.thread_coord.join([restart_thread]) + self.assertGreaterEqual(model.iterations.numpy(), 3) + + # TODO(yuefengz): consider using combinations when there is more code + # duplication. + def testHandleDatasetCreationFailureWithDataset(self): + model = Model(self.cluster_coord) + + restart_thread = self._restart_in_thread(5, "worker") + + model.schedule_training_functions(3) + model.rebuild_iterators(use_dataset_fn=False) + model.schedule_training_functions(3) + model.rebuild_iterators(use_dataset_fn=False) + model.schedule_training_functions(3) + + model.join_training_functions() + + self.thread_coord.join([restart_thread]) + self.assertGreaterEqual(model.iterations.numpy(), 3) + + def testWorkerPreemptionErrorType(self): + + @def_function.function + def worker_train_fn(): + x = random_ops.random_uniform((2, 10)) + y = random_ops.random_uniform((10, 2)) + return math_ops.reduce_mean(math_ops.matmul(x, y)) + + def run_fn(): + with self.thread_coord.stop_on_exception(): + with ops.device("/job:worker/replica:0/task:0"): + for _ in range(3): + for _ in range(3): + worker_train_fn() + time.sleep(5) + + run_thread = threading.Thread(target=run_fn) + run_thread.start() + time.sleep(1) # Let it run a couple steps. + self._restart(2, "worker") + + try: + self.thread_coord.join([run_thread]) + except (errors.UnavailableError, errors.AbortedError) as e: + logging.info("Got exception %r, error message is %s", e, e) + + self.assertIn(_RPC_ERROR_FROM_WORKER, str(e)) # pylint: disable=g-assert-in-except + self.assertNotIn(_RPC_ERROR_FROM_PS, str(e)) + + self.assertTrue("failed to connect to all addresses" in str(e) or + "Unable to find a context_id" in str(e) or + "Socket closed" in str(e) or + "Connection reset by peer" in str(e) or + "Transport closed" in str(e)) + + def testWorkerPreemptionErrorTypeWithPythonFunction(self): + + def worker_train_fn(): + x = random_ops.random_uniform((2, 10)) + y = random_ops.random_uniform((10, 2)) + return math_ops.reduce_mean(math_ops.matmul(x, y)) + + def run_fn(): + with self.thread_coord.stop_on_exception(): + with ops.device("/job:worker/replica:0/task:0"): + for _ in range(3): + for _ in range(3): + worker_train_fn() + time.sleep(5) + + run_thread = threading.Thread(target=run_fn) + run_thread.start() + time.sleep(1) # Let it run a couple steps. + self._restart(2, "worker") + + try: + self.thread_coord.join([run_thread]) + except (errors.UnavailableError, errors.AbortedError) as e: + logging.info("Got exception %r, error message is %s", e, e) + + self.assertIn(_RPC_ERROR_FROM_WORKER, str(e)) # pylint: disable=g-assert-in-except + self.assertNotIn(_RPC_ERROR_FROM_PS, str(e)) + + self.assertTrue("failed to connect to all addresses" in str(e) or + "Unable to find a context_id" in str(e) or + "Socket closed" in str(e) or + "Connection reset by peer" in str(e) or + "Transport closed" in str(e)) + + def testPSPreemptionErrorType(self): + + with ops.device("/job:ps/replica:0/task:0"): + v = variables.Variable( + initial_value=random_ops.random_uniform((2, 10)), + dtype=dtypes.float32) + + @def_function.function + def worker_train_fn(): + y = random_ops.random_uniform((10, 2)) + return math_ops.reduce_mean(math_ops.matmul(v, y)) + + def run_fn(): + with self.thread_coord.stop_on_exception(): + with ops.device("/job:worker/replica:0/task:0"): + for _ in range(3): + for _ in range(3): + worker_train_fn() + time.sleep(5) + + run_thread = threading.Thread(target=run_fn) + run_thread.start() + time.sleep(1) # Let it run a couple steps. + + # Use a short restart delay to cover the case that RPC channel is reused + self._restart(1, "ps") + + try: + self.thread_coord.join([run_thread]) + except (errors.UnavailableError, errors.AbortedError) as e: + logging.info("Got exception %r, error message is %s", e, e) + self.assertIn(_RPC_ERROR_FROM_PS, str(e)) # pylint: disable=g-assert-in-except + + if isinstance(e, errors.UnavailableError): + self.assertTrue("failed to connect to all addresses" in str(e) or + "Socket closed" in str(e) or + "Connection reset by peer" in str(e) or + "Transport closed" in str(e)) + + if isinstance(e, errors.AbortedError): + self.assertTrue( + "RecvTensor expects a different device incarnation" in str(e) or + "Unable to find a context_id" in str(e)) + self._ensure_threads_closed() + + def testTwoWorkersPreempted(self): + if self.num_workers < 2: + self.skipTest("Worker number is less than 2.") + model = self._create_model_and_run_indefinitely() + + self.assertFalse(self.cluster_coord.done()) + self._cluster.kill_task("worker", 0) + self._cluster.kill_task("worker", 1) + time.sleep(2) + self.assertFalse(context.check_alive("/job:worker/replica:0/task:0")) + self.assertFalse(context.check_alive("/job:worker/replica:0/task:1")) + self._cluster.start_task("worker", 0) + self._cluster.start_task("worker", 1) + time.sleep(2) + self.assertTrue(context.check_alive("/job:worker/replica:0/task:0")) + self.assertTrue(context.check_alive("/job:worker/replica:0/task:1")) + + model.join_training_functions() + self.assertGreaterEqual(model.iterations.numpy(), 10) + + def testWorkerContinuousFailure(self): + model = self._create_model_and_run_indefinitely() + + self.assertFalse(self.cluster_coord.done()) + self._cluster.kill_task("worker", 0) + time.sleep(2) + self.assertFalse(context.check_alive("/job:worker/replica:0/task:0")) + self._cluster.start_task("worker", 0) + time.sleep(2) + self.assertTrue(context.check_alive("/job:worker/replica:0/task:0")) + self._cluster.kill_task("worker", 0) + time.sleep(2) + self.assertFalse(context.check_alive("/job:worker/replica:0/task:0")) + self._cluster.start_task("worker", 0) + time.sleep(2) + self.assertTrue(context.check_alive("/job:worker/replica:0/task:0")) + + model.join_training_functions() + self.assertGreaterEqual(model.iterations.numpy(), 10) + + def testPSFailureWhileRecoveryFromWokerFailure(self): + model = self._create_model_and_run_indefinitely() + + time.sleep(1) + self.assertFalse(self.cluster_coord.done()) + + def kill(task): + self._cluster.kill_task(task, 0) + self.sleep(1) + self._cluster.start_task(task, 0) + + kill_thread_1 = threading.Thread(target=kill, args=("worker",)) + kill_thread_2 = threading.Thread(target=kill, args=("ps",)) + kill_thread_1.start() + kill_thread_2.start() + kill_thread_1.join() + kill_thread_2.join() + + with self.assertRaises( + (errors.UnavailableError, errors.InvalidArgumentError)): + model.join_training_functions() + + def testNumpyFetchedAfterWorkerFailure(self): + + with self.strategy.scope(): + v = variables.Variable(initial_value=0, dtype=dtypes.int32) + + @def_function.function + def worker_fn(): + return v + 1, v - 1 + + remote_value = self.cluster_coord.schedule(worker_fn) + # Attempt to fetch before killing worker task should succeed. + self.assertEqual((1, -1), remote_value.fetch()) + self._cluster.kill_task("worker", 0) + # So should attempt to fetch after killing worker task. + self.assertEqual((1, -1), remote_value.fetch()) + + def testTensorGotAfterWorkerFailure(self): + + with self.strategy.scope(): + v = variables.Variable(initial_value=0, dtype=dtypes.int32) + + @def_function.function + def worker_fn(): + return v + 1, v - 1 + + remote_value = self.cluster_coord.schedule(worker_fn) + + # Attempt to fetch before killing worker task should succeed. + fetched = remote_value.get()[0] + self.assertIsInstance(fetched, tensor.Tensor) + self.assertEqual(fetched.device, "/job:chief/replica:0/task:0/device:CPU:0") + self.assertEqual((1, -1), remote_value.get()) + remote_value.get()[0].numpy() + + # As well as the remote tensors that point to worker0 or worker1. + values = remote_value._values[0] + self.assertIsInstance(values, tensor.Tensor) + self.assertRegex(values.device, + "/job:worker/replica:0/task:[0-1]/device:CPU:0") + self.assertEqual((1, -1), remote_value._values) + remote_value._values[0].numpy() + + # Terminate the workers and wait a little so that they are indeed killed. + for i in range(self.num_workers): + self._cluster.kill_task("worker", i) + time.sleep(5) + + # Attempt to fetch after killing worker tasks should succeed as well. + remote_value.get()[0].numpy() + self.assertEqual((1, -1), remote_value.get()) + + # Attempting to copy the tensor from worker now should fail. + with self.assertRaises(errors.UnavailableError) as cm: + remote_value._values[0].numpy() + self.assertIn("failed to connect to all addresses", cm.exception.message) + self.assertIn("/job:worker/replica:0/task:", cm.exception.message) + + def testFetchFromPSAfterWorkerFailure(self): + # Test for flaky failures when reading from a parameter server while a + # worker is recovering. + # Place some variables on PSes, kill a worker, and continuously poll one of + # those variables. + + model = Model(self.cluster_coord) + + # kill the worker after a delay to make sure variable reading runs while + # worker is up, while it's down, and while it restarts + def kill_after_delay(): + time.sleep(3) + logging.info("Killing worker 0") + self._cluster.kill_task("worker", 0) + time.sleep(1) + logging.info("Restarting worker 0") + self._cluster.start_task("worker", 0) + + kill_thread = threading.Thread(target=kill_after_delay) + kill_thread.start() + + model.do_infinite_step.assign(True) + model.schedule_training_functions(1) + + num_reads = 0 + num_reads_after_restart = 0 + read_interval_secs = 0.1 + worker_has_stopped = False + # limit runtime of the test: stop after doing a few reads after worker + # is back up, or after a fixed maximum number of reads + while num_reads_after_restart <= 5 and num_reads < 200: + worker_up = context.check_alive("/job:worker/replica:0/task:0") + if not worker_up: + worker_has_stopped = True + if worker_up and worker_has_stopped: + num_reads_after_restart += 1 + + model.join_training_functions() + start = time.time() + while time.time() < start + read_interval_secs: + model.iterations.read_value() + + num_reads += 1 + # run another epoch + model.do_infinite_step.assign(True) + model.schedule_training_functions(1) + + def testClusterStateNotDisrupted(self): + # This test has side effects and can disrupt other tests, even if the + # resource created by it will not be used in following tests. + # TODO(b/155209534): enable this test. + # self.testPSPreemptionErrorType() + + self.thread_coord = thread_coordinator.Coordinator( + clean_stop_exception_types=[]) + self.testWorkerPreemptionMidstFunction() + + self.thread_coord = thread_coordinator.Coordinator( + clean_stop_exception_types=[]) + self.testWorkerPreemptionErrorType() + + # In previous tests, workers may fail after training is done. But the + # following tests start with creating resources where failure is not + # handled. + # TODO(b/153888707): enable the following two tests. + # self.testTwoWorkersPreempted() + # self.testWorkerContinuousFailure() + + def _run_and_kill_ps_task(self): + self._create_model_and_run_indefinitely() + self._cluster.kill_task("ps", 0) + while self.cluster_coord._cluster.closure_queue._error is None: + time.sleep(1) + logging.info("Trying to join, expecting error") + + def testJoinRaisesUnavailableErrorAtPsFailure(self): + self._run_and_kill_ps_task() + with self.assertRaises((errors.UnavailableError, errors.NotFoundError, + errors.FailedPreconditionError)): + self.cluster_coord.join() + + def testScheduleRaisesUnavailableErrorAtPsFailure(self): + self._run_and_kill_ps_task() + with self.assertRaises((errors.UnavailableError, errors.NotFoundError, + errors.FailedPreconditionError)): + self.cluster_coord.schedule(def_function.function(lambda: None)) + + def testWorkerExecutionAfterPsFailureRaisesExpectedError(self): + model = self._create_model_and_run_indefinitely() + for i in range(self.num_ps): + self._cluster.kill_task("ps", i) + while self.cluster_coord._cluster.closure_queue._error is None: + time.sleep(1) + + @def_function.function + def trivial_function(): + return model.iterations + 1 + + for i in range(self.num_workers): + try: + with ops.device("/job:worker/replica:0/task:{}".format(i)): + trivial_function() + except Exception as e: # pylint: disable=broad-except + if cluster_coordinator._is_ps_failure(e): # pylint: disable=protected-access + if i < self.num_workers - 1: + continue + return + raise AssertionError("Executing a function after PS fails, should " + "result in a PS failure.") + + def testAsyncWaitIsNoOp(self): + if self.num_workers < 2: + self.skipTest("Worker number is less than 2.") + model = self._create_model_and_run_indefinitely() + + self.assertFalse(self.cluster_coord.done()) + self._cluster.kill_task("worker", 0) + time.sleep(2) + self.assertFalse(context.check_alive("/job:worker/replica:0/task:0")) + # Should pass without exception even with failed remote workers + context.async_wait() + + model.join_training_functions() + self.assertGreaterEqual(model.iterations.numpy(), 10) + + self._cluster.start_task("worker", 0) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/metric_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/metric_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..99c68d95e7d4623ddd235d69642e92552c0cb8e6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/metric_utils.py @@ -0,0 +1,158 @@ +# 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. +# ============================================================================== +"""Metrics collecting utilities for single client training.""" + +import time + +from tensorflow.python.eager import monitoring +from tensorflow.python.util import tf_contextlib + +enable_metrics = True +_METRICS_MAPPING = {} + + +def _init(): + """Initialize the metrics mapping.""" + global _METRICS_MAPPING + + # Define the boundaries for bucketing times of distribution (Sampler) metrics. + + # Closure execution: range from 0.1s to 10000s, i.e. [(0.1, 1), (1, 10), ...] + execution_time_buckets = monitoring.ExponentialBuckets( + scale=0.1, growth_factor=10, bucket_count=6) + # Tracing: same range as execution + tracing_time_buckets = execution_time_buckets + # Remote value fetch: range from 0.001s (i.e. 1ms) to 1000s + fetch_time_buckets = monitoring.ExponentialBuckets( + scale=0.001, growth_factor=10, bucket_count=7) + # Server def update: range from 1s to 10000s + server_update_time_buckets = monitoring.ExponentialBuckets( + scale=1, growth_factor=10, bucket_count=5) + + function_tracing_sampler = monitoring.Sampler( + '/tensorflow/api/ps_strategy/coordinator/function_tracing', + tracing_time_buckets, + 'Sampler to track the time (in seconds) for tracing functions.') + + closure_execution_sampler = monitoring.Sampler( + '/tensorflow/api/ps_strategy/coordinator/closure_execution', + execution_time_buckets, + 'Sampler to track the time (in seconds) for executing closures.') + + remote_value_fetch_sampler = monitoring.Sampler( + '/tensorflow/api/ps_strategy/coordinator/remote_value_fetch', + fetch_time_buckets, + 'Sampler to track the time (in seconds) for fetching remote_value.') + + server_def_update_sampler = monitoring.Sampler( + '/tensorflow/api/ps_strategy/coordinator/server_def_update', + server_update_time_buckets, + 'Sample to track the time (in seconds) for updating the server def upon ' + 'worker recovery.') + + queued_closure_gauge = monitoring.IntGauge( + '/tensorflow/api/ps_strategy/coordinator/queued_closures', + 'Track how many closures are in the coordinator queue pending execution.') + + inflight_closure_gauge = monitoring.IntGauge( + '/tensorflow/api/ps_strategy/coordinator/inflight_closures', + 'Track how many closures are currently being processed by workers.') + + worker_failure_counter = monitoring.Counter( + '/tensorflow/api/ps_strategy/coordinator/recoverable_worker_failure_count', + 'Track how many recoverable worker failures have been encountered.') + + _METRICS_MAPPING = { + 'function_tracing': function_tracing_sampler, + 'closure_execution': closure_execution_sampler, + 'remote_value_fetch': remote_value_fetch_sampler, + 'server_def_update': server_def_update_sampler, + 'queued_closures': queued_closure_gauge, + 'inflight_closures': inflight_closure_gauge, + 'worker_failures': worker_failure_counter, + } + + +@tf_contextlib.contextmanager +def monitored_timer(metric_name, state_tracker=None): + """Monitor the execution time and collect it into the specified metric.""" + if not enable_metrics: + yield + else: + if not _METRICS_MAPPING: + _init() + start_time = time.time() + start_state = state_tracker() if state_tracker else None + yield + duration_sec = time.time() - start_time + # If a state_checker is provided, record the metric only if the end state is + # different from the start state. + if state_tracker is None or state_tracker() != start_state: + metric = _METRICS_MAPPING[metric_name] + metric.get_cell().add(duration_sec) + + +def monitor_int(metric_name, value): + if not enable_metrics: + return + else: + if not _METRICS_MAPPING: + _init() + metric = _METRICS_MAPPING[metric_name] + metric.get_cell().set(value) + + +def monitor_increment_counter(metric_name): + if not enable_metrics: + return + else: + if not _METRICS_MAPPING: + _init() + metric = _METRICS_MAPPING[metric_name] + metric.get_cell().increase_by(1) + + +def _get_metric_histogram(histogram_proto): + """Convert a histogram proto into a dict. + + Args: + histogram_proto: a proto containing a Sampler metric's result histogram. + + Returns: + A dict containing summary statistics and the raw histogram values. + """ + ret = dict() + ret['min'] = histogram_proto.min + ret['max'] = histogram_proto.max + ret['num'] = histogram_proto.num + ret['sum'] = histogram_proto.sum + + bucket_limits = histogram_proto.bucket_limit + bucket_vals = histogram_proto.bucket + ret['histogram'] = {} + # Add lower limit as 0, since all these metrics are durations + bucket_limits.insert(0, 0) + for lb, ub, val in zip(bucket_limits[:-1], bucket_limits[1:], bucket_vals): + ret['histogram'][(lb, ub)] = val + return ret + + +def get_metric_summary(metric_name): + """Get summary for the specified metric.""" + metric = _METRICS_MAPPING[metric_name] + result = metric.get_cell().value() + if isinstance(metric, monitoring.Sampler): + result = _get_metric_histogram(result) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/remote_value.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/remote_value.py new file mode 100644 index 0000000000000000000000000000000000000000..5faa2f7213822604f186645987cd9b1ff04bbb2b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/remote_value.py @@ -0,0 +1,131 @@ +# 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. +# ============================================================================== +"""RemoteValue interface class.""" + +import enum + +from tensorflow.python.util.tf_export import tf_export + + +class RemoteValueStatus(enum.Enum): + """The status of a `RemoteValue` object. + + A `RemoteValue` object can have three states: + 1) not ready: no value, no non-retryable error and not aborted; + 2) aborted: i.e. the execution of function was aborted because of task + failure, but can be retried; + 3) ready: i.e. has value or has non-tryable error; + + The initial state of a `RemoteValue` is "not ready". When its corresponding + closure has + been executed at least once, it will become aborted or ready. The state + transitions are: + 1) not ready -> 2) aborted: + when the corresponding closure is aborted due to worker failure, and the + worker failure is not immediately handled. + 1) not ready -> 3) ready: + when the corresponding closure has been executed successfully. + 2) aborted -> 3) ready: + when the `RemoteValue` is rebuilt by rerunning the corresponding closure + and the closure has been executed successfully. + 3) ready -> 2) aborted: + when the corresponding closure had been executed successfully but later + the corresponding remote worker failed. This is currently only implemented + for resource `RemoteValue` like iterators. + """ + NOT_READY = "NOT_READY" + ABORTED = "ABORTED" + READY = "READY" + + +@tf_export("distribute.experimental.coordinator.RemoteValue", + "distribute.coordinator.RemoteValue", v1=[]) +class RemoteValue(object): + """An asynchronously available value of a scheduled function. + + This class is used as the return value of + `tf.distribute.experimental.coordinator.ClusterCoordinator.schedule` where + the underlying value becomes available at a later time once the function has + been executed. + + Using `tf.distribute.experimental.coordinator.RemoteValue` as an input to + a subsequent function scheduled with + `tf.distribute.experimental.coordinator.ClusterCoordinator.schedule` is + currently not supported. + + Example: + + ```python + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=...) + coordinator = ( + tf.distribute.experimental.coordinator.ClusterCoordinator(strategy)) + + with strategy.scope(): + v1 = tf.Variable(initial_value=0.0) + v2 = tf.Variable(initial_value=1.0) + + @tf.function + def worker_fn(): + v1.assign_add(0.1) + v2.assign_sub(0.2) + return v1.read_value() / v2.read_value() + + result = coordinator.schedule(worker_fn) + # Note that `fetch()` gives the actual result instead of a `tf.Tensor`. + assert result.fetch() == 0.125 + + for _ in range(10): + # `worker_fn` will be run on arbitrary workers that are available. The + # `result` value will be available later. + result = coordinator.schedule(worker_fn) + ``` + """ + + def fetch(self): + """Wait for the result of `RemoteValue` and return the numpy result. + + This makes the value concrete by copying the remote value to local. + + Returns: + The numpy array structure of the actual output of the `tf.function` + associated with this `RemoteValue`, previously returned by a + `tf.distribute.experimental.coordinator.ClusterCoordinator.schedule` call. + This can be a single value, or a structure of values, depending on the + output of the `tf.function`. + + Raises: + tf.errors.CancelledError: If the function that produces this `RemoteValue` + is aborted or cancelled due to failure. + """ + raise NotImplementedError("Must be implemented in subclasses.") + + def get(self): + """Wait for the result of `RemoteValue` and return the tensor result. + + This makes the value concrete by copying the remote tensor to local. + + Returns: + The actual output (in the form of `tf.Tensor`s) of the `tf.function` + associated with this `RemoteValue`, previously returned by a + `tf.distribute.experimental.coordinator.ClusterCoordinator.schedule` call. + This can be a single Tensor, or a structure of Tensors, depending on the + output of the `tf.function`. + + Raises: + tf.errors.CancelledError: If the function that produces this `RemoteValue` + is aborted or cancelled due to failure. + """ + raise NotImplementedError("Must be implemented in subclasses.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..499e23518815eeb18476672f45466d4f12e8e471 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/utils.py @@ -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. +# ============================================================================== +"""TF2 parameter server training utilities. + +Parameter server training in TF2 is currently under development. +""" +import threading +import time + +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import server_lib + + +def start_server(cluster_resolver, protocol): + """Start a server and block the process from exiting.""" + # This function is for multi-processing test or users who would like to have + # every job run the same binary for simplicity. + if not (cluster_resolver.task_type == 'worker' or + cluster_resolver.task_type == 'ps'): + raise ValueError('Unexpected task_type to start a server: {}'.format( + cluster_resolver.task_type)) + + server = server_lib.Server( + cluster_resolver.cluster_spec().as_cluster_def(), + job_name=cluster_resolver.task_type, + task_index=cluster_resolver.task_id, + protocol=protocol) + + logging.info('TensorFlow server started for job %s, task %d.', + cluster_resolver.task_type, cluster_resolver.task_id) + + # Blocking the process that starts a server from exiting. + server.join() + + +class RepeatedTimer(object): + """Threaded Repeated Timer from http://shortn/_3hMZTFr1Iv.""" + + def __init__(self, interval, function, *args): + self._timer = None + self.interval = interval + self.function = function + self.args = args + self.start_time = time.time() + self.is_running = False + self.start() + + def _get_duration_sec(self): + return int(time.time() - self.start_time) + + def _run(self): + self.is_running = False + self.start() + self.function(*self.args) + + def start(self): + if not self.is_running: + self._timer = threading.Timer(self.interval, self._run) + self._timer.start() + self.is_running = True + + def stop(self): + duration = self._get_duration_sec() + self._timer.cancel() + self.is_running = False + return duration + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/values.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/values.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf868e07316f8aa84add858186311f608ecdd31 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/values.py @@ -0,0 +1,386 @@ +# 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. +# ============================================================================== +"""Important value classes relevant to `ClusterCoordinator`. + +This is currently under development and the API is subject to change. +""" + +import threading + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops.options import ExternalStatePolicy +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute.coordinator import remote_value +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as tf_function +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import type_spec as type_spec_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_dataset_ops +from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# TODO(yuefengz): create an implementation for resource RemoteValue which needs +# to remember the closure object while a normal RemoteValue doesn't. +class RemoteValueImpl(remote_value.RemoteValue): + """Implementation of `RemoteValue`.""" + + def __init__(self, closure, type_spec): # pylint: disable=super-init-not-called + """Initializes a `RemoteValueImpl`. + + Args: + closure: The closure from which the `RemoteValue` is created. + type_spec: The type spec for this `RemoteValue` which is used to trace + functions that take this `RemoteValue` as input. + """ + self._closure = closure + self._type_spec = type_spec + self._values = None + self._has_fetched_to_local = False + self._has_fetched_to_local_lock = threading.Lock() + self._fetched_tensors = None + self._error = None + self._status_available_event = threading.Event() + self._status = remote_value.RemoteValueStatus.NOT_READY + + def _set_aborted(self, error): + self._status = remote_value.RemoteValueStatus.ABORTED + self._values = None + self._error = error + + # Wake up any waiting thread and clear the event. + self._status_available_event.set() + + def _rebuild_on(self, worker): + self._status_available_event.clear() + # TODO(yuefengz): we may need to rebuild its inputs as well. + self._closure.execute_on(worker) + + def _set_values(self, tensors): + self._status = remote_value.RemoteValueStatus.READY + self._values = tensors + self._error = None + self._status_available_event.set() + + def _set_error(self, error): + self._status = remote_value.RemoteValueStatus.READY + self._values = None + self._error = error + self._status_available_event.set() + + def _get_values(self): + self._status_available_event.wait() + return self._values + + def _get_error(self): + self._status_available_event.wait() + return self._error + + def _wait_and_maybe_error(self): + self._status_available_event.wait() + if self._status is remote_value.RemoteValueStatus.ABORTED: + raise errors.CancelledError( + None, None, + "The corresponding function is aborted. Please reschedule the " + "function.") + if self._error is not None: + raise self._error + + def fetch(self): + # TODO(rchao): Discuss the possibility of letting users perform `numpy` + # themselves at API graduation. + return nest.map_structure( + lambda x: x.numpy() if hasattr(x, "numpy") else x, self.get()) + + def _copy_to_local(self): + def copy_tensor(composite_tensor_obj): + """Copy a remote tensor to local (coordinator).""" + if isinstance(composite_tensor_obj, input_lib.DistributedIterator): + # A DistributedIterator cannot be copied to local; users should not + # access that anyway. + return composite_tensor_obj + + with ops.device("/job:%s" % context.get_server_def().job_name): + # Copying to local (the coordinator) with `tf.device`. + return array_ops.identity(composite_tensor_obj) + + fetched_result = None + if self._values is not None: + # When `self._values` is `None`, it indicates the associated function + # does not have a return value. + fetched_result = nest.map_structure(copy_tensor, self._values) + return fetched_result + + def get(self): + self._wait_and_maybe_error() + + with self._has_fetched_to_local_lock: + if not self._has_fetched_to_local: + self._fetched_tensors = self._copy_to_local() + self._has_fetched_to_local = True + + return self._fetched_tensors + + +class RemoteVariable(RemoteValueImpl): + """A RemoteValue that represents a mutable per-worker variable.""" + + def get(self): + """Retrieve value with no caching to ensure we get the up-to-date value.""" + self._wait_and_maybe_error() + return self._copy_to_local() + + +@tf_export("distribute.experimental.coordinator.PerWorkerValues", + "distribute.coordinator.PerWorkerValue", v1=[]) +class PerWorkerValues(composite_tensor.CompositeTensor): + """A container that holds a list of values, one value per worker. + + `tf.distribute.experimental.coordinator.PerWorkerValues` contains a collection + of values, where each of the values is located on its corresponding worker, + and upon being used as one of the `args` or `kwargs` of + `tf.distribute.experimental.coordinator.ClusterCoordinator.schedule()`, the + value specific to a worker will be passed into the function being executed at + that corresponding worker. + + Currently, the only supported path to create an object of + `tf.distribute.experimental.coordinator.PerWorkerValues` is through calling + `iter` on a `ClusterCoordinator.create_per_worker_dataset`-returned + distributed dataset instance. The mechanism to create a custom + `tf.distribute.experimental.coordinator.PerWorkerValues` is not yet supported. + """ + + def __init__(self, values): + for v in values: + if not isinstance(v, remote_value.RemoteValue): + raise AssertionError( + "`PerWorkerValues` should only take `RemoteValue`s.") + self._values = tuple(values) + + @property + def _type_spec(self): + return PerWorkerValuesTypeSpec( + self._values[0]._type_spec, # pylint: disable=protected-access + type(self)) + + +class PerWorkerValuesTypeSpec(type_spec_lib.TypeSpec): + """TypeSpec for PerWorkerValues. + + It only support tracing a function using a PerWorkerValues. + """ + + def __init__(self, value_spec, descendant_type): + assert value_spec + self._value_spec = value_spec + self._descendant_type = descendant_type + + def _serialize(self): + return (self._value_spec,) + + @property + def value_type(self): + return self._descendant_type + + def most_specific_common_supertype(self, others): + raise NotImplementedError( + "most_specific_common_supertype is not implemented") + + @property + def _component_specs(self): + return self._value_spec + + def _to_components(self, value): + return self._value_spec + + def _from_components(self, value): + return value + + +class PerWorkerDatasetFromDatasetFunction(object): + """Represents worker-distributed datasets created from dataset function.""" + + def __init__(self, dataset_fn, coordinator): + """Makes an iterable from datasets created by the given function. + + Args: + dataset_fn: A function that returns a `Dataset`. + coordinator: a `ClusterCoordinator` object, used to create dataset + resources. + """ + + def disallow_variable_creation(next_creator, **kwargs): + raise ValueError("Creating variables in `dataset_fn` is not allowed.") + + if isinstance(dataset_fn, def_function.Function): + with variable_scope.variable_creator_scope(disallow_variable_creation): + dataset_fn = dataset_fn.get_concrete_function() + elif not isinstance(dataset_fn, tf_function.ConcreteFunction): + with variable_scope.variable_creator_scope(disallow_variable_creation): + dataset_fn = def_function.function(dataset_fn).get_concrete_function() + self._dataset_fn = dataset_fn + self._coordinator = coordinator + self._element_spec = None + + def build(self): + """Trigger dataset creation on workers without creating an iterator. + + Returns: + A PerWorkerValues object containing a tuple of RemoteValues, themselves + containing the built Dataset for each worker + """ + def _create_per_worker_dataset(): + dataset = self._dataset_fn() + return dataset + + # pylint: disable=protected-access + per_worker_dataset = self._coordinator._create_per_worker_resources( + _create_per_worker_dataset) + # hack type_spec of RemoteValues + dataset_fn_output_type_spec = self._dataset_fn.structured_outputs._type_spec + for dataset_remote_value in per_worker_dataset._values: + dataset_remote_value._type_spec = dataset_fn_output_type_spec + return per_worker_dataset + + def __iter__(self): + # We would like users to create iterators outside `tf.function`s so that we + # can track them. + if (not context.executing_eagerly() or + ops.get_default_graph().building_function): + raise RuntimeError( + "__iter__() is not supported inside of tf.function or in graph mode.") + + def _create_per_worker_iterator(): + dataset = self._dataset_fn() + return iter(dataset) + + # If PerWorkerDatasetFromDatasetFunction.__iter__ is called multiple + # times, for the same object it should only create and register resource + # once. Using object id to distinguish different iterator resources. + per_worker_iterator = self._coordinator._create_per_worker_resources( + _create_per_worker_iterator) + + # Setting type_spec of each RemoteValue so that functions taking these + # RemoteValues as inputs can be traced. + for iterator_remote_value in per_worker_iterator._values: + iterator_remote_value._type_spec = ( + input_lib.get_iterator_spec_from_dataset( + self._coordinator.strategy, self._dataset_fn.structured_outputs)) + + return PerWorkerDistributedIterator(per_worker_iterator._values) + + @property + def element_spec(self): + """The type specification of an element of this dataset. + + This property is subject to change without notice. + """ + if not isinstance(self._dataset_fn, tf_function.ConcreteFunction): + raise NotImplementedError( + "`element_spec` is not supported when the `dataset_fn` is not " + "a `ConcreteFunction`.") + return self._dataset_fn.structured_outputs.element_spec + + +def serialize_dataset_to_graph(dataset): + dataset = dataset._apply_debug_options() # pylint: disable=protected-access + graph_def = gen_dataset_ops.dataset_to_graph_v2( + dataset._variant_tensor, # pylint: disable=protected-access + external_state_policy=ExternalStatePolicy.WARN.value, + strip_device_assignment=True) + return graph_def + + +class _RemoteDataset(dataset_ops.DatasetSource): + """Creates a dataset given a graph def.""" + + def __init__(self, graph_def, element_spec): + self._elem_spec = element_spec + variant_tensor = ged_ops.dataset_from_graph(graph_def) + super(_RemoteDataset, self).__init__(variant_tensor) + + @property + def element_spec(self): + return self._elem_spec + + +def deserialize_dataset_from_graph(graph_def, element_spec): + return _RemoteDataset(graph_def, element_spec) + + +class PerWorkerDatasetFromDataset(PerWorkerDatasetFromDatasetFunction): + """Represents worker-distributed datasets created from a dataset.""" + + def __init__(self, dataset, coordinator): + """Makes an iterable from datasets created by the given dataset. + + It creates a dataset_fn which deserializes a dataset from a graph under the + hood. + + Args: + dataset: A tf.data.Dataset, a DistributedDataset or a + DistributedDatasetsFromFunction + coordinator: a `ClusterCoordinator` object, used to create dataset + resources. + """ + if isinstance(dataset, input_lib.DistributedDataset): + original_dataset = dataset._original_dataset + serialized = serialize_dataset_to_graph(original_dataset) + + def dataset_fn(): + deserialized = deserialize_dataset_from_graph( + serialized, original_dataset.element_spec) + dataset.build(dataset_to_replace=deserialized) + return dataset + elif isinstance(dataset, input_lib.DistributedDatasetsFromFunction): + def dataset_fn(): + dataset.build() + return dataset + elif isinstance(dataset, dataset_ops.Dataset): + serialized = serialize_dataset_to_graph(dataset) + + def dataset_fn(): + return deserialize_dataset_from_graph(serialized, dataset.element_spec) + else: + raise ValueError("Unexpected dataset type!") + + super(PerWorkerDatasetFromDataset, self).__init__(dataset_fn, coordinator) + + +def get_per_worker_dataset(dataset_or_dataset_fn, coordinator): + """Returns a per-worker dataset from a dataset or a dataset function.""" + if callable(dataset_or_dataset_fn): + return PerWorkerDatasetFromDatasetFunction(dataset_or_dataset_fn, + coordinator) + else: + return PerWorkerDatasetFromDataset(dataset_or_dataset_fn, coordinator) + + +class PerWorkerDistributedIterator(PerWorkerValues): + """Distributed iterator for `ClusterCoordinator`.""" + + def __next__(self): + return self.get_next() + + def get_next(self, name=None): + """Returns the next input from the iterator for all replicas.""" + raise NotImplementedError("Iterating over an `AsyncDistributedIterator` " + "is not supported right now.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/watchdog.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/watchdog.py new file mode 100644 index 0000000000000000000000000000000000000000..11a42c21d4e083f3bfc7813ad413beca7c9ef0d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/coordinator/watchdog.py @@ -0,0 +1,63 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Watchdog that monitors activity of ClusterCoordinator.""" + +import faulthandler +import os +import sys +import threading +import time +from absl import logging + + +class WatchDog(object): + """A class to dump stack traces if no activity happens in ClusterCoordinator.""" + + def __init__(self, timeout=-1, traceback_file=sys.stdout, on_triggered=None): + if os.environ.get("TF_CLUSTER_COORDINATOR_WATCH_DOG_TIMEOUT", + "").isnumeric(): + timeout = int(os.environ["TF_CLUSTER_COORDINATOR_WATCH_DOG_TIMEOUT"]) + self._timeout = timeout + self._last_activity_time = time.time() + self._traceback_file = traceback_file + self._on_triggered = on_triggered + self._stopped = False + if timeout > 0: + self._watchdog_thread = threading.Thread( + target=self._watchdog_function, name="WatchDog", daemon=True) + self._watchdog_thread.start() + + def stop(self): + self._stopped = True + + def _watchdog_function(self): + """The watchdog thread.""" + logging.info("Starting watchdog thread with timeout %r", self._timeout) + while not self._stopped: + time.sleep(self._timeout / 10.0) + current_time = time.time() + if current_time - self._last_activity_time >= self._timeout: + logging.warning( + "No activity for ClusterCoordinator for %r seconds. " + "Dumping stack traces.", self._timeout) + if self._on_triggered: + self._on_triggered() + faulthandler.dump_traceback(file=self._traceback_file) + self._traceback_file.write("==== End of stack traces ====\n") + self._last_activity_time = current_time + + def report_closure_done(self): + if self._timeout > 0: + self._last_activity_time = time.time() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cross_device_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cross_device_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..002cb1d41e807077a68bc36c7bac715b79270444 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cross_device_ops.py @@ -0,0 +1,1398 @@ +# 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. +# ============================================================================== +"""Classes for different algorithms of reduction and broadcasting.""" + +import collections +import copy +import multiprocessing.dummy +import multiprocessing.pool +import threading + +import numpy as np +import six + +from tensorflow.python.client import device_lib +from tensorflow.python.distribute import collective_util +from tensorflow.python.distribute import cross_device_utils +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import ps_values +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import tpu_values +from tensorflow.python.distribute import values as value_lib +from tensorflow.python.distribute import values_util +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import kernels +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + + +def check_destinations(destinations): + """Checks whether `destinations` is not empty. + + Args: + destinations: a `DistributedValues`, variable, or string object. + + Returns: + Boolean which is True if `destinations` is not empty. + """ + # Calling bool() on a ResourceVariable is not allowed. + if isinstance(destinations, + (resource_variable_ops.BaseResourceVariable, + tensor_lib.Tensor)): + return bool(destinations.device) + return bool(destinations) + + +def validate_destinations(destinations): + """Validates the `destination` is one of expected types.""" + if not isinstance( + destinations, + (value_lib.DistributedValues, tensor_lib.Tensor, + indexed_slices.IndexedSlices, ps_values.AggregatingVariable, + six.string_types, tpu_values.TPUMirroredVariable + )) and not resource_variable_ops.is_resource_variable(destinations): + raise ValueError("destinations must be one of a `DistributedValues` object," + " a tf.Variable object, or a device string.") + + if not check_destinations(destinations): + raise ValueError("destinations can not be empty") + + +def reduce_non_distributed_value(reduce_op, + value, + destinations, + num_replicas_in_graph, + canonicalize_devices=True): + """Reduce a non-DistributedValue `value` to `destinations`.""" + if isinstance(value, value_lib.DistributedValues): + raise ValueError("You are passing a `DistributedValues` to " + "`reduce_non_distributed_value`, which is not allowed.") + + # If the same value is present on all replicas then the PerReplica value will + # be a single value. We also handle the case when `value` is a single value + # and equal to 0. + # TODO(b/138823479): handle the tensor value properly. + if not tensor_util.is_tf_type(value) and np.all(value == 0): + return np.zeros(value.shape, dtype=value.dtype) + # If there is only a single value and the reduce op is MEAN, + # that value should be on all destinations. + if reduce_op == reduce_util.ReduceOp.MEAN: + return value + elif num_replicas_in_graph != 1: + # We do not support a reduce op of SUM if the value is the same across + # all replicas. We call this as part of assign functions for + # MirroredVariables and summing up identical values across replicas is not + # clearly defined. + raise ValueError("A non-DistributedValues value %s cannot be reduced with " + "the given reduce op %s." % (value, reduce_op)) + else: + validate_destinations(destinations) + return simple_broadcast( + value, destinations, canonicalize_devices=canonicalize_devices) + + +def _make_tensor_into_per_replica(input_tensor): + """Converts a single tensor into a PerReplica object.""" + if isinstance(input_tensor, value_lib.DistributedValues): + return input_tensor + + # If input is not a Tensor, convert it to a Tensor first. + if not tensor_util.is_tensor(input_tensor): + input_tensor = ops.convert_to_tensor(input_tensor) + + if hasattr(input_tensor, "device"): + return value_lib.PerReplica((input_tensor,)) + + raise ValueError("Cannot convert `input_tensor` to a `PerReplica` object " + "because it doesn't have device set.") + + +def _normalize_value_destination_pairs(value_destination_pairs): + """Converts each tensor into a PerReplica object in the input list.""" + result = [] + + value_destination_pairs = list(value_destination_pairs) + + if not isinstance(value_destination_pairs, (list, tuple)): + raise ValueError("`value_destination_pairs` should be a list or tuple") + for pair in value_destination_pairs: + if not isinstance(pair, tuple): + raise ValueError( + "Each element of `value_destination_pairs` should be a tuple.") + if len(pair) != 2: + raise ValueError("Each element of `value_destination_pairs` should be a " + "tuple of size 2.") + + per_replica = _make_tensor_into_per_replica(pair[0]) + result.append((per_replica, pair[1])) + return result + + +def _validate_value_destination_pairs(value_destination_pairs): + """Validates value_destination_pairs are valid.""" + # TODO(yuefengz): raise exceptions instead of returning False. + if not value_destination_pairs: return False + if not isinstance(value_destination_pairs, (list, tuple)): return False + if not all(isinstance(pair, tuple) for pair in value_destination_pairs): + return False + if not all(isinstance(v[0], value_lib.PerReplica) + for v in value_destination_pairs): + return False + return True + + +# TODO(yuefengz): consider calling this function in the caller of +# CrossDeviceOps. +def get_devices_from(destinations, canonicalize_devices=True): + if isinstance(destinations, value_lib.DistributedValues): + return destinations._devices # pylint: disable=protected-access + if canonicalize_devices: + if isinstance(destinations, six.string_types): + return (device_util.resolve(destinations),) + return (device_util.resolve(destinations.device),) + + # Let placer canonicalize and resolve destination devices. + if isinstance(destinations, six.string_types): + return (device_util.canonicalize_without_job_and_task(destinations),) + return (device_util.canonicalize_without_job_and_task(destinations.device),) + + +def _devices_match(left, right, canonicalize_devices=True): + return left is right or set(get_devices_from( + left, canonicalize_devices)) == set( + get_devices_from(right, canonicalize_devices)) + + +def _all_devices_match(value_destination_pairs, canonicalize_devices=True): + if not all( + _devices_match(v, d, canonicalize_devices) + for v, d in value_destination_pairs): + return False + if not all( + _devices_match(v, value_destination_pairs[0][0], canonicalize_devices) + for v, _ in value_destination_pairs[1:]): + return False + return True + + +def simple_broadcast(value, + destinations, + always_mirrored=False, + canonicalize_devices=True): + """Broadcast `value` to `destinations` using simple copies.""" + devices = get_devices_from(destinations, canonicalize_devices) + if len(devices) == 1 and not always_mirrored: + return cross_device_utils.copy_tensor_or_indexed_slices_to_device( + value, devices[0]) + else: + value_updates = [] + for d in devices: + value_updates.append( + cross_device_utils.copy_tensor_or_indexed_slices_to_device(value, d)) + return distribute_utils.regroup(value_updates, + wrap_class=value_lib.Mirrored) + + +def _simple_reduce(per_replica_value, reduce_to_device, accumulation_fn, + reduce_op): + """Reduces the value by accumulation_fn and reduce_op.""" + all_values = per_replica_value.values + if not all_values: + raise ValueError("`per_replica_value` must be non-empty") + count = len(all_values) + + with ops.device(reduce_to_device): + with context.device_policy(context.DEVICE_PLACEMENT_SILENT): + reduced = cross_device_utils.aggregate_tensors_or_indexed_slices( + all_values, accumulation_fn) + if reduce_op == reduce_util.ReduceOp.MEAN: + reduced = cross_device_utils.divide_by_n_tensors_or_indexed_slices( + reduced, count) + elif reduce_op != reduce_util.ReduceOp.SUM: + raise ValueError("`reduce_op` must be Reduce.SUM or Reduce.MEAN.") + return reduced + + +def _simple_gather(per_replica_value, reduce_to_device, axis): + """Concatenate all values in the DistributedValues input and return.""" + all_values = per_replica_value.values + if not all_values: + raise ValueError("`per_replica_value` must be non-empty") + + with ops.device(reduce_to_device): + with context.device_policy(context.DEVICE_PLACEMENT_SILENT): + gathered = array_ops.concat(all_values, axis) + return gathered + + +@tf_export("distribute.CrossDeviceOps") +class CrossDeviceOps(object): + """Base class for cross-device reduction and broadcasting algorithms. + + The main purpose of this class is to be passed to + `tf.distribute.MirroredStrategy` in order to choose among different cross + device communication implementations. Prefer using the methods of + `tf.distribute.Strategy` instead of the ones of this class. + + Implementations: + * `tf.distribute.ReductionToOneDevice` + * `tf.distribute.NcclAllReduce` + * `tf.distribute.HierarchicalCopyAllReduce` + """ + + def __init__(self): + self._canonicalize_devices = True + pass + + @property + def _num_between_graph_workers(self): + # Returns 1 by default, the value may be overridden by sub classes. + return 1 + + def reduce(self, reduce_op, per_replica_value, destinations, options=None): + """Reduce `per_replica_value` to `destinations`. + + See `tf.distribute.StrategyExtended.reduce_to`. This can only be called in + the cross-replica context. + + Args: + reduce_op: a `tf.distribute.ReduceOp` specifying how values should be + combined. + per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` + like object. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to reduce to. To perform an all-reduce, pass the same to `value` and + `destinations`. Note that if it's a `tf.Variable`, the value is reduced + to the devices of that variable, and this method doesn't update the + variable. + options: a `tf.distribute.experimental.CommunicationOptions`. See + `tf.distribute.experimental.CommunicationOptions` for details. + + Returns: + A `tf.Tensor` or `tf.distribute.DistributedValues`. + + Raises: + ValueError: if per_replica_value can't be converted to a + `tf.distribute.DistributedValues` or if destinations is not a string, + `tf.Variable` or `tf.distribute.DistributedValues`. + """ + if options is None: + options = collective_util.Options() + + per_replica_value = _make_tensor_into_per_replica(per_replica_value) + + validate_destinations(destinations) + + # Shortcut if `per_replica_value` only contains one value. + if self._num_between_graph_workers == 1 and len( + per_replica_value.values) == 1 and _devices_match( + per_replica_value, destinations, self._canonicalize_devices): + with ops.device(per_replica_value.values[0].device): + v = array_ops.identity(per_replica_value.values[0]) + return distribute_utils.regroup((v,), wrap_class=value_lib.Mirrored) + + if options is None: + options = collective_util.Options() + return self.reduce_implementation(reduce_op, per_replica_value, + destinations, options) + + def _gather(self, per_replica_value, destinations, axis, options=None): + """Gather `per_replica_value` to `destinations`. + + Args: + per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` + like object. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to gather to. To perform an all-gather, pass the same to `value` and + `destinations`. Note that if it's a `tf.Variable`, the value is gathered + to the devices of that variable, and this method doesn't update the + variable. + axis: specifies the dimension to gather along within each replica's + tensor. + options: a `tf.distribute.experimental.CommunicationOptions`. See + `tf.distribute.experimental.CommunicationOptions` for details. + + Returns: + A `tf.Tensor` or `tf.distribute.DistributedValues` + + Raises: + ValueError: if per_replica_value can't be converted to a + `tf.distribute.DistributedValues` or if destinations is not a string, + `tf.Variable` or `tf.distribute.DistributedValues`. + """ + if isinstance(per_replica_value, indexed_slices.IndexedSlices): + raise NotImplementedError("gather/all_gather does not support " + "IndexedSlices") + if options is None: + options = collective_util.Options() + + per_replica_value = _make_tensor_into_per_replica(per_replica_value) + + validate_destinations(destinations) + + # Shortcut if `per_replica_value` only contains one value. + if self._num_between_graph_workers == 1 and len( + per_replica_value.values) == 1 and _devices_match( + per_replica_value, destinations, self._canonicalize_devices): + with ops.device(per_replica_value.values[0].device): + v = array_ops.identity(per_replica_value.values[0]) + return distribute_utils.regroup((v,), wrap_class=value_lib.Mirrored) + + return self._gather_implementation(per_replica_value, destinations, axis, + options) + + def _gather_implementation(self, per_replica_value, destinations, axis, + options): + """Implementation of `gather` method of `tf.distribute.CrossDeviceOps`. + + Overriding this method is useful for subclass implementers. + + Args: + per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` + like object. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to gather to. To perform an all-gather, pass the same to `value` and + `destinations`. Note that if it's a `tf.Variable`, the value is gathered + to the devices of that variable, this method doesn't update the + variable. + axis: specifies the dimension to gather along within each replica's + tensor. + options: a `tf.distribute.experimental.CommunicationOptions`. See + `tf.distribute.experimental.CommunicationOptions` for details. + + Returns: + A `tf.Tensor` or `tf.distribute.DistributedValues`. + + Raises: + ValueError: if per_replica_value can't be converted to a + `tf.distribute.DistributedValues` or if destinations is not a string, + `tf.Variable` or `tf.distribute.DistributedValues`. + """ + raise NotImplementedError( + "_gather method must be implemented in descendants.") + + def batch_reduce(self, reduce_op, value_destination_pairs, options=None): + """Reduce values to destinations in batches. + + See `tf.distribute.StrategyExtended.batch_reduce_to`. This can only be + called in the cross-replica context. + + Args: + reduce_op: a `tf.distribute.ReduceOp` specifying how values should be + combined. + value_destination_pairs: a sequence of (value, destinations) pairs. See + `tf.distribute.CrossDeviceOps.reduce` for descriptions. + options: a `tf.distribute.experimental.CommunicationOptions`. See + `tf.distribute.experimental.CommunicationOptions` for details. + + Returns: + A list of `tf.Tensor` or `tf.distribute.DistributedValues`, one per pair + in `value_destination_pairs`. + + Raises: + ValueError: if `value_destination_pairs` is not an iterable of + tuples of `tf.distribute.DistributedValues` and destinations. + """ + if options is None: + options = collective_util.Options() + # TODO(yuefengz): if destinations are different, split into several + # `_batch_reduce` invocations. + if not _validate_value_destination_pairs(value_destination_pairs): + # If the first element of each pair is a tensor, we try to turn it into a + # PerReplica object. + value_destination_pairs = _normalize_value_destination_pairs( + value_destination_pairs) + + for _, d in value_destination_pairs: + validate_destinations(d) + + # Shortcut all PerReplica objects only contain one value. + if self._num_between_graph_workers == 1 and _all_devices_match( + value_destination_pairs, self._canonicalize_devices) and len( + value_destination_pairs[0][0].values) == 1: + return [ + distribute_utils.regroup(v.values, wrap_class=value_lib.Mirrored) + for v, _ in value_destination_pairs + ] + + if options is None: + options = collective_util.Options() + return self.batch_reduce_implementation(reduce_op, value_destination_pairs, + options) + + def broadcast(self, tensor, destinations): + """Broadcast `tensor` to `destinations`. + + This can only be called in the cross-replica context. + + Args: + tensor: a `tf.Tensor` like object. The value to broadcast. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to broadcast to. Note that if it's a `tf.Variable`, the value is + broadcasted to the devices of that variable, this method doesn't update + the variable. + + Returns: + A `tf.Tensor` or `tf.distribute.DistributedValues`. + """ + validate_destinations(destinations) + return self.broadcast_implementation(tensor, destinations) + + @doc_controls.for_subclass_implementers + def reduce_implementation(self, reduce_op, per_replica_value, destinations, + options): + """Implementation of `reduce`. + + Overriding this method is useful for subclass implementers. + + Args: + reduce_op: a `tf.distribute.ReduceOp` specifying how values should be + combined. + per_replica_value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` + like object. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to reduce to. To perform an all-reduce, pass the same to `value` and + `destinations`. Note that if it's a `tf.Variable`, the value is reduced + to the devices of that variable, this method doesn't update the + variable. + options: a `tf.distribute.experimental.CommunicationOptions`. See + `tf.distribute.experimental.CommunicationOptions` for details. + + Returns: + A `tf.Tensor` or `tf.distribute.DistributedValues`. + + Raises: + ValueError: if per_replica_value can't be converted to a + `tf.distribute.DistributedValues` or if destinations is not a string, + `tf.Variable` or `tf.distribute.DistributedValues`. + """ + raise NotImplementedError( + "_reduce method must be implemented in descendants.") + + @doc_controls.for_subclass_implementers + def batch_reduce_implementation(self, reduce_op, value_destination_pairs, + options): + """Implementation of `batch_reduce`. + + Overriding this method is useful for subclass implementers. + + Args: + reduce_op: a `tf.distribute.ReduceOp` specifying how values should be + combined. + value_destination_pairs: a sequence of (value, destinations) pairs. See + `reduce` for descriptions. + options: a `tf.distribute.experimental.CommunicationOptions`. See + `tf.distribute.experimental.CommunicationOptions` for details. + + Returns: + A list of `tf.Tensor` or `tf.distribute.DistributedValues`, one per pair + in `value_destination_pairs`. + + Raises: + ValueError: if `value_destination_pairs` is not an iterable of + tuples of `tf.distribute.DistributedValues` and destinations. + """ + raise NotImplementedError( + "batch_reduce_implementation method must be implemented in descendants." + ) + + @doc_controls.for_subclass_implementers + def broadcast_implementation(self, tensor, destinations): + """Implementation of `broadcast`. + + Args: + tensor: a `tf.Tensor` like object. The value to broadcast. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to broadcast to. + `destinations`. Note that if it's a `tf.Variable`, the value is + broadcasted to the devices of that variable, this method doesn't update + the variable. + + Returns: + A `tf.Tensor` or `tf.distribute.DistributedValues`. + """ + return simple_broadcast( + tensor, + destinations, + always_mirrored=True, + canonicalize_devices=self._canonicalize_devices) + + # ========================== Collective APIs ================================ + # + # Different than `reduce`, `batch_reduce` and `broadcast` which must be called + # in cross-replcia context, collective APIs are to be called in replica + # context. + + def _all_reduce(self, reduce_op, value, replica_id, options): + """All-reduce the `value` across all replicas so that all get the result. + + `value` can be a nested structure of tensors or `IndexedSlices`. The + implementation should generally batch the all-reduces when possible. + `options` can be set to hint the batching behavior. + + This API must be called in a replica context. + + Args: + reduce_op: A `tf.distribute.ReduceOp` value specifying how values should + be combined. + value: Value to be reduced. A tensor or a nested structure of tensors or + `IndexedSlices`. + replica_id: An interger indicating the id of the replica where this + all_reduce is called under. This is the local replica id that ranges + from 0 to len(local_devices) - 1. + options: A `tf.distribute.experimental.CommunicationOptions`. + + Returns: + A tensor/IndexedSlices or a nested strucutre of tensors/IndexedSlices with + the reduced values. The structure is the same as `value`. + """ + raise NotImplementedError("_all_reduce must be implemented in descendants.") + + +@tf_export("distribute.ReductionToOneDevice") +class ReductionToOneDevice(CrossDeviceOps): + """A CrossDeviceOps implementation that copies values to one device to reduce. + + This implementation always copies values to one device to reduce them, then + broadcast reduced values to the destinations. It doesn't support efficient + batching. + + Here is how you can use `ReductionToOneDevice` in + `tf.distribute.MirroredStrategy`: + + ``` + strategy = tf.distribute.MirroredStrategy( + cross_device_ops=tf.distribute.ReductionToOneDevice()) + ``` + """ + + def __init__(self, reduce_to_device=None, accumulation_fn=None): + """Initializes with a device to reduce to and a way to accumulate. + + Args: + reduce_to_device: the intermediate device to reduce to. If None, reduce + to the first device in `destinations` of the `reduce` method. + accumulation_fn: a function that does accumulation. If None, + `tf.math.add_n` is used. + """ + self.reduce_to_device = reduce_to_device + self.accumulation_fn = accumulation_fn or math_ops.add_n + super(ReductionToOneDevice, self).__init__() + + def reduce_implementation(self, reduce_op, per_replica_value, destinations, + options): + del options # Unused. + if check_destinations(destinations): + devices = get_devices_from(destinations, self._canonicalize_devices) + else: + devices = get_devices_from(per_replica_value, self._canonicalize_devices) + reduce_to_device = self.reduce_to_device or devices[0] + logging.log_first_n( + logging.INFO, + "Reduce to %s then broadcast to %r." % (reduce_to_device, devices), 10) + reduced = _simple_reduce(per_replica_value, reduce_to_device, + self.accumulation_fn, reduce_op) + return self.broadcast(reduced, destinations) + + def _gather_implementation(self, per_replica_value, destinations, axis, + options): + del options # Unused. + if check_destinations(destinations): + devices = get_devices_from(destinations, self._canonicalize_devices) + else: + devices = get_devices_from(per_replica_value, self._canonicalize_devices) + reduce_to_device = self.reduce_to_device or devices[0] + logging.log_first_n( + logging.INFO, + "Gather to %s then broadcast to %r." % (reduce_to_device, devices), 10) + gathered = _simple_gather(per_replica_value, reduce_to_device, axis) + return self.broadcast(gathered, destinations) + + def batch_reduce_implementation(self, reduce_op, value_destination_pairs, + options): + return [ + self.reduce_implementation( + reduce_op, t, destinations=v, options=options) + for t, v in value_destination_pairs + ] + + +def _group_value_by_device(per_replica_values): + """Group values into sublists by their devices. + + This grouping is needed to call the all-reduce library because it expects a + list of the following form: + [[(grad0_gpu0, v0_gpu0), (grad1_gpu0, v1_gpu0), (grad2_gpu0, v2_gpu0) ...], + [(grad0_gpu1, v0_gpu1), (grad1_gpu1, v1_gpu1), (grad2_gpu1, v2_gpu1) ...], + [(grad0_gpu2, v0_gpu2), (grad1_gpu0, v1_gpu2), (grad2_gpu0, v2_gpu2) ...], + ... + ] + + Args: + per_replica_values: a list of PerReplica objects. + + Returns: + a list of lists, each sublist has components for its corresponding device of + PerReplica objects, paired with a None. + """ + destinations = per_replica_values[0]._devices # pylint: disable=protected-access + grouped = [[] for _ in range(len(destinations))] + for per_replica_value in per_replica_values: + # pylint: disable=protected-access + for i, v in enumerate(per_replica_value.values): + assert per_replica_value._devices == destinations + grouped[i].append((v, None)) + return grouped + + +def _ungroup_and_make_mirrored(grouped_reduced, + destinations, + reduce_op, + num_between_graph_workers=1): + """Ungroup results from all-reduce and make Mirrored objects. + + Each all-reduce result will be divided by the number of destinations before + Mirrored objects are created if reduce_op is "mean". + + Args: + grouped_reduced: a list of lists, each sublist has components for each + device, paired with a None. It is the result from + cross_device_utils.aggregate_gradients_using*. + destinations: a value to colocate the result with. + reduce_op: Indicates how values will be aggregated. Accepted values + are `tf.distribute.ReduceOp.SUM`, `tf.distribute.ReduceOp.MEAN`. + num_between_graph_workers: number of workers in the between-graph + replication. + + Returns: + a list of Mirrored objects. + """ + num_replicas = len(get_devices_from(destinations)) * num_between_graph_workers + index = [[] for _ in range(len(grouped_reduced[0]))] + for per_replica_reduced in grouped_reduced: + for i, (v, _) in enumerate(per_replica_reduced): + if reduce_op == reduce_util.ReduceOp.MEAN: + with ops.device(v.device): + index[i].append(v / num_replicas) + else: + index[i].append(v) + return [distribute_utils.regroup( + v, wrap_class=value_lib.Mirrored) for v in index] + + +class _ConcatAndSplitPacker(object): + """Concatenate and split tensors for reduction.""" + + def __init__(self, num_packs=1): + """Initialize the _ConcatAndSplitPacker object. + + Args: + num_packs: specifies the number of split packs that will be + formed. + + Raises: + ValueError: if num_packs is not greater than 0. + """ + if num_packs <= 0: + raise ValueError("num_packs must be greater than zero.") + self.num_packs = num_packs + + def pack(self, grouped_grads_and_vars): + """Pack tensors.""" + self.grouped_grads_and_vars = grouped_grads_and_vars + self.all_device_shapes = [] + self.all_device_sizes = [] + + device_grad_packs = [] + for device_grads_and_vars in grouped_grads_and_vars: + with ops.colocate_with(device_grads_and_vars[0][0]): + # Flatten all the grads. + flat_grads = [ + array_ops.reshape(g, [-1]) for g, _ in device_grads_and_vars + ] + # Remember the original shape of all the grads. + device_shapes = [array_ops.shape(g) for g, _ in device_grads_and_vars] + # Remember the original sizes of all the grads. + device_sizes = [array_ops.size(g) for g, _ in device_grads_and_vars] + # Concat all the flat grads into a big flat tensor. + concat_grads = array_ops.concat(flat_grads, 0) + + # Split the big tensor into num_splits packs. In cases where the + # total size is not divisible num_splits, the last pack gets + # more elements. + # TODO(zhengxq): it is also possible to optimize away all the concat + # as well. + num_splits = self.num_packs + + # The array_ops.size function will sometimes remove static shapes. So if + # all gradient shapes are defined, we use another method to get the + # total size. + # TODO(yuefengz): move this logic to array_ops.size. + if all(g.shape.is_fully_defined() for g, _ in device_grads_and_vars): + total_grad_size = sum( + [g.shape.num_elements() for g, _ in device_grads_and_vars]) + else: + total_grad_size = array_ops.size(concat_grads) + + split_size = total_grad_size // num_splits + split_size_last = total_grad_size - split_size * (num_splits - 1) + split_sizes = [split_size] * (num_splits - 1) + [split_size_last] + grad_packs = array_ops.split(concat_grads, split_sizes) + + # Ready to aggregate the repacked gradients, with fake variables. + # TODO(zhengxq): It is hacky to have to use fake variables. + # We should remove the need for variables in + # aggregate_gradients_using*. + device_grad_packs.append(zip(grad_packs, [None] * num_splits)) + self.all_device_shapes.append(device_shapes) + self.all_device_sizes.append(device_sizes) + + return device_grad_packs + + def unpack(self, summed_device_grad_packs): + """Reverse the pack.""" + aggregated_device_grads = [] + for (summed_device_grad_packs, + device_grads_and_vars, device_shapes, device_sizes) in zip( + summed_device_grad_packs, self.grouped_grads_and_vars, + self.all_device_shapes, self.all_device_sizes): + # pylint: enable=line-too-long + # Reverse the packing operations in the previous steps. Form the + # summed gradients back into their original shapes. + with ops.colocate_with(summed_device_grad_packs[0][0]): + # Form a list of the summed grad packs. + device_grad_packs = [g for g, _ in summed_device_grad_packs] + + # Concat them back into a big flat tensor. + device_grads_concat = array_ops.concat(device_grad_packs, 0) + + # Split the tensors back into their original sizes. + grads_with_sizes = array_ops.split(device_grads_concat, device_sizes) + + # Reshape the tensors back into their original shapes. + grads_with_shapes = [ + array_ops.reshape(grad, shape) + for shape, grad in zip(device_shapes, grads_with_sizes) + ] + + # Form the list with the original list of variables. + summed_device_grads = [ + (g, v) for g, (_, v) in zip(grads_with_shapes, + device_grads_and_vars) + ] + aggregated_device_grads.append(summed_device_grads) + return aggregated_device_grads + + +def _pack_tensors(device_grads, num_packs=0): + """Pack tensors if specified.""" + if num_packs > 0: + tensor_packer = _ConcatAndSplitPacker(num_packs) + device_grad_packs = tensor_packer.pack(device_grads) + else: + tensor_packer = None + device_grad_packs = device_grads + return device_grad_packs, tensor_packer + + +def _unpack_tensors(reduced, tensor_packer=None): + """Unpack tensors if they are packed before all-reduce.""" + if tensor_packer: + return tensor_packer.unpack(reduced) + return reduced + + +class AllReduceCrossDeviceOps(CrossDeviceOps): + """All-reduce implementation of CrossDeviceOps. + + It performs all-reduce when applicable using NCCL or hierarchical copy. For + the batch API, tensors will be repacked or aggregated for more efficient + cross-device transportation. + + For reduces that are not all-reduce, it falls back to + `tf.distribute.ReductionToOneDevice`. + """ + + def __init__(self, all_reduce_alg="nccl", num_packs=1): + """Initializes the object. + + Args: + all_reduce_alg: the all-reduce algorithm to use, currently only "nccl" or + "hierarchical_copy" are supported. + num_packs: a non-negative integer. The number of packs to split values + into. If zero, no packing will be done. + """ + self._all_reduce_alg = all_reduce_alg + self._num_packs = num_packs + self._simple_cross_replica_ops = ReductionToOneDevice() + super(AllReduceCrossDeviceOps, self).__init__() + + def reduce_implementation(self, reduce_op, per_replica_value, destinations, + options): + del options # Unused. + # To use NCCL or all-reduce, source and destination devices should match, + # and none of the devices should be CPU. + if (_devices_match(per_replica_value, destinations) and + not any("cpu" in d.lower() for d in get_devices_from(destinations))): + return self._batch_all_reduce(reduce_op, [per_replica_value])[0] + else: + return self._simple_cross_replica_ops.reduce(reduce_op, per_replica_value, + destinations) + + def batch_reduce_implementation(self, reduce_op, value_destination_pairs, + options): + if _all_devices_match(value_destination_pairs): + return self._batch_all_reduce(reduce_op, + [v[0] for v in value_destination_pairs]) + else: + return [ + self.reduce_implementation(reduce_op, value, dest, options) + for value, dest in value_destination_pairs + ] + + def _batch_all_reduce(self, reduce_op, per_replica_values): + """All-reduce algorithm in a batch.""" + dense_values, dense_indices, sparse_values, sparse_indices = ( + cross_device_utils.split_by_sparsity(per_replica_values)) + if dense_values: + dense_results = self._do_batch_all_reduce(reduce_op, dense_values) + else: + dense_results = [] + if sparse_values: + sparse_results = self._do_batch_all_reduce_sparse(reduce_op, + sparse_values) + else: + sparse_results = [] + return cross_device_utils.stitch_values(((dense_results, dense_indices), + (sparse_results, sparse_indices))) + + def _do_batch_all_reduce(self, reduce_op, dense_values): + """Run batch all-reduces.""" + logging.log_first_n( + logging.INFO, + "batch_all_reduce: %d all-reduces with algorithm = %s, num_packs = %d" % + (len(dense_values), self._all_reduce_alg, self._num_packs), 10) + + destinations = dense_values[0]._devices # pylint: disable=protected-access + grouped = _group_value_by_device(dense_values) + + # device_grad_packs: + # [[(t0_gpu0, None), (t1_gpu0, None)], [(t0_gpu1, None), (t1_gpu1, None)]] + device_grad_packs, tensor_packer = _pack_tensors(grouped, self._num_packs) + + # The actual aggregation of the repacked gradients. Note that they are + # sharded among different aggregation trees. So it is important to strike + # the balance on num_splits. + if self._all_reduce_alg == "nccl": + # TODO(yuefengz): merge this into the all-reduce library. + reduced = cross_device_utils.aggregate_gradients_using_nccl( + device_grad_packs) + else: + # TODO(yuefengz): check that gpu ids in `destinations` are in ascending + # order. + reduced = ( + cross_device_utils.aggregate_gradients_using_hierarchical_copy( + destinations, device_grad_packs)) + + reduced = _unpack_tensors(reduced, tensor_packer) + return _ungroup_and_make_mirrored(reduced, dense_values[0], reduce_op) + + def _do_batch_all_reduce_sparse(self, reduce_op, sparse_values): + """Run batch all-reduce for sparse values.""" + logging.log_first_n( + logging.WARN, + "Efficient allreduce is not supported for %d IndexedSlices" % + len(sparse_values), 10) + # Use `sparse_values` as destinations to do all-reduces. It is effectively + # an allgather under the hood but not an efficient one. + return self._simple_cross_replica_ops.batch_reduce( + reduce_op, zip(sparse_values, sparse_values)) + + def _gather_implementation(self, per_replica_value, destinations, axis, + options): + logging.log_first_n( + logging.WARN, + "gather/all_gather with NCCL or HierarchicalCopy is not supported. " + "Falling back to gather on one device and then broadcast. We're working" + " on a more efficient implementation.", 3) + return ReductionToOneDevice()._gather(per_replica_value, destinations, axis, # pylint: disable=protected-access + options) + + +# For compatibility with code using the old name of `AllReduceCrossDeviceOps`. +AllReduceCrossTowerOps = AllReduceCrossDeviceOps + + +AllReduceSpecTuple = collections.namedtuple("AllReduceSpecTuple", + "alg shards limit") + + +@tf_export("distribute.NcclAllReduce") +class NcclAllReduce(AllReduceCrossDeviceOps): + """NCCL all-reduce implementation of CrossDeviceOps. + + It uses Nvidia NCCL for all-reduce. For the batch API, tensors will be + repacked or aggregated for more efficient cross-device transportation. + + For reduces that are not all-reduce, it falls back to + `tf.distribute.ReductionToOneDevice`. + + Here is how you can use `NcclAllReduce` in `tf.distribute.MirroredStrategy`: + + + ``` + strategy = tf.distribute.MirroredStrategy( + cross_device_ops=tf.distribute.NcclAllReduce()) + ``` + """ + + def __init__(self, num_packs=1): + """Initializes the object. + + Args: + num_packs: a non-negative integer. The number of packs to split values + into. If zero, no packing will be done. + + Raises: + ValueError: if `num_packs` is negative. + """ + if num_packs < 0: + raise ValueError( + "NCCL all-reduce requires num_packs >= 0, but {} is specified".format( + num_packs)) + super(NcclAllReduce, self).__init__( + all_reduce_alg="nccl", num_packs=num_packs) + + +@tf_export("distribute.HierarchicalCopyAllReduce") +class HierarchicalCopyAllReduce(AllReduceCrossDeviceOps): + """Hierarchical copy all-reduce implementation of CrossDeviceOps. + + It reduces to one GPU along edges in some hierarchy and broadcasts back to + each GPU along the same path. For the batch API, tensors will be repacked or + aggregated for more efficient cross-device transportation. + + This is a reduction created for Nvidia DGX-1 which assumes GPUs connects like + that on DGX-1 machine. If you have different GPU inter-connections, it is + likely that it would be slower than `tf.distribute.ReductionToOneDevice`. + + For reduces that are not all-reduce, it falls back to + `tf.distribute.ReductionToOneDevice`. + + Here is how you can use `HierarchicalCopyAllReduce` in + `tf.distribute.MirroredStrategy`: + + ``` + strategy = tf.distribute.MirroredStrategy( + cross_device_ops=tf.distribute.HierarchicalCopyAllReduce()) + ``` + """ + + def __init__(self, num_packs=1): + """Initializes the object. + + Args: + num_packs: a non-negative integer. The number of packs to split values + into. If zero, no packing will be done. + + Raises: + ValueError if `num_packs` is negative. + """ + if num_packs < 0: + raise ValueError( + "HierarchicalCopy requires num_packs >= 0, but {} is specified" + .format(num_packs)) + super(HierarchicalCopyAllReduce, self).__init__( + all_reduce_alg="hierarchical_copy", + num_packs=num_packs) + + +# TODO(crccw): remove after migrating all callers. +CollectiveCommunication = collective_util.CommunicationImplementation +CommunicationImplementation = collective_util.CommunicationImplementation + + +# TODO(yuefengz): support in-graph collective all-reduce. +class CollectiveAllReduce(CrossDeviceOps): + """All-reduce cross device ops using collective ops. + + In the between-graph replicated training, it will still do all-reduces across + all workers and then put results on the right destinations. + """ + + def __init__(self, + devices, + group_size, + options, + collective_keys=None, + canonicalize_devices=True): + """Initializes the object. + + Args: + devices: a list of device strings to run collectives on. + group_size: the global group size. For between-graph replicated training + it's the total number of devices across all workers. + options: a `tf.distribute.experimental.CommunicationOptions`. + collective_keys: an optional CollectiveKey object. + canonicalize_devices: Whether to canonicalize devices for workers or not. + """ + if group_size % len(devices) > 0: + raise ValueError("group_size must be divisible by the number of devices.") + + self._group_size = group_size + self._options = options + self._collective_keys = (collective_keys or + cross_device_utils.CollectiveKeys()) + # This lock guards all collective launches, i.e. calls to + # cross_device_utils.build_collectve_*. + # + # In a multi threaded eager program we need to ensure different groups of + # collectives don't interleave each other, otherwise there could be + # deadlocks. E.g. if two user threads both are launching collectives: + # user-thread-0 device0 device1 + # user-thread-1 device0 device1 + # In eager mode, we use one thread per device to launch collective ops, so + # the above launch sequences end up with the following queues: + # device-0 collective-0 collective-1 + # device-1 collective-1 collective-0 + # This deadlocks since neither collective is able to finish. + self._lock = threading.Lock() + + if canonicalize_devices: + self._devices = tuple(device_util.canonicalize(d) for d in devices) + else: + self._devices = tuple( + device_util.canonicalize_without_job_and_task(d) for d in devices) + group_key = self._collective_keys.get_group_key(self._devices) + self._launchers = [] + # Whether to only use NCCL for batched all-reduce when NCCL is requested. + # This is because of the lack of mechanism to order NCCL operations + # deterministically. + self._limited_nccl = False + for device in self._devices: + launcher = cross_device_utils.CollectiveReplicaLauncher( + group_key, group_size, self._collective_keys, device, options) + self._launchers.append(launcher) + if not launcher.can_order_nccl(): + self._limited_nccl = True + + super(CollectiveAllReduce, self).__init__() + self._canonicalize_devices = canonicalize_devices + + @property + def _num_between_graph_workers(self): + # Currently we only support equal number of devices on each worker. + return self._group_size / len(self._devices) + + def _all_reduce(self, reduce_op, value, replica_id, options): + """Implements CrossDeviceOps.all_reduce.""" + # TODO(b/122840926): reuse this method in _batch_all_reduce. + flat_values = nest.flatten(value) + + # If NCCL launches can't be ordered (self._limited_nccl == True), we only + # use NCCL when batch_size > 1, hoping that there's only one batched + # all-reduce, which is the gradient aggregation in optimizer. For TF 2.x, + # NCCL launches are always ordered. + if (self._limited_nccl and options.implementation + == collective_util.CommunicationImplementation.NCCL and + len(flat_values) == 1): + options = options.merge( + collective_util.Options( + implementation=collective_util.CommunicationImplementation.RING)) + + launcher = self._launchers[replica_id] + dense_values, dense_indices, sparse_values, sparse_indices = ( + cross_device_utils.split_by_sparsity(flat_values)) + dense_results = [] + sparse_results = [] + + if dense_values: + # Reverse the lists so that there's better chance that values follows + # the order in which they are calculated (e.g. when they're gradients), so + # as to overlap calculation with communication. However, this may not be + # optimal for cases like gradients of complicated non-sequential models. + # + # Note that we reverse the list before packing so that the first pack + # won't be too small, since it's more likely for first few packs to have + # long queuing time due to concurrent intense computation. + # + # TODO(b/147393503): explore solutions for optimal ordering. + dense_values.reverse() + packs = cross_device_utils.group_by_size(dense_values, + options.bytes_per_pack) + + if not context.executing_eagerly() and replica_id == 0: + logging.info( + "Collective all_reduce tensors: %d all_reduces, num_devices = %d, " + "group_size = %d, implementation = %s, num_packs = %d", + len(dense_values), len(self._launchers), self._group_size, + options.implementation, len(packs)) + + dense_results = launcher.batch_all_reduce(packs, options) + if reduce_op == reduce_util.ReduceOp.MEAN: + for i, v in enumerate(dense_results): + with ops.device(self._devices[replica_id]): + dense_results[i] = v / self._group_size + dense_results.reverse() + + if sparse_values: + if not context.executing_eagerly() and replica_id == 0: + logging.info( + "Collective all_reduce IndexedSlices: %d all_reduces, num_devices =" + "%d, group_size = %d, implementation = %s", len(sparse_values), + len(self._launchers), self._group_size, options.implementation) + + for indexed_slice in sparse_values: + sparse_results.append( + launcher.all_reduce_indexed_slices(indexed_slice, options)) + + if reduce_op == reduce_util.ReduceOp.MEAN: + for i, v in enumerate(sparse_results): + with ops.device(self._devices[replica_id]): + sparse_results[i] = indexed_slices.IndexedSlices( + values=sparse_results[i].values / self._group_size, + indices=sparse_results[i].indices, + dense_shape=sparse_results[i].dense_shape) + + flat_results = cross_device_utils.stitch_values( + ((dense_results, dense_indices), (sparse_results, sparse_indices))) + return nest.pack_sequence_as(value, flat_results) + + def _all_reduce_per_replica_values(self, reduce_op, per_replica_values, + options): + """All reduce a list of per_replica_value.""" + values_by_device = [[] for _ in self._devices] + num_devices = len(self._devices) + for per_replica in per_replica_values: + for i in range(num_devices): + values_by_device[i].append(per_replica.values[i]) + + if context.executing_eagerly(): + + def thread_fn(device_id): + with context.eager_mode(): + return self._all_reduce(reduce_op, values_by_device[device_id], + device_id, options) + + with self._lock: + pool = multiprocessing.pool.ThreadPool(len(self._devices)) + outputs_by_device = pool.map(thread_fn, list(range(num_devices))) + pool.close() + else: + outputs_by_device = [] + with self._lock: + for i in range(num_devices): + outputs_by_device.append( + self._all_reduce(reduce_op, values_by_device[i], i, options)) + + result = [] + for values in zip(*outputs_by_device): + result.append( + distribute_utils.regroup(values, wrap_class=value_lib.Mirrored)) + return result + + def reduce_implementation(self, reduce_op, per_replica_value, destinations, + options): + values_util.mark_as_unsaveable() + all_reduced = self._all_reduce_per_replica_values(reduce_op, + [per_replica_value], + options)[0] + devices = get_devices_from(destinations, self._canonicalize_devices) + + if _devices_match(per_replica_value, destinations, + self._canonicalize_devices): + return all_reduced + + # Convert `all_reduced` to a `Mirrored` object, as a simple and uniform + # utility to access component for a particular device. + if not isinstance(all_reduced, value_lib.Mirrored): + all_reduced = value_lib.Mirrored([all_reduced]) + + # If we got this far, the destination devices do not match the all-reduce + # devices, so we must map from one to the other. + index = [] + # We must add these control dependencies, otherwise we can get deadlock. + with ops.control_dependencies(all_reduced.values): + for d in devices: + with ops.device(d): + for v in all_reduced.values: + if v.device == d: + index.append(array_ops.identity(v)) + break + else: + # TODO(josh11b): Once we add support for model parallelism, get the + # copy from the corresponding replica instead of the primary. + index.append(array_ops.identity(all_reduced._primary)) # pylint: disable=protected-access + return distribute_utils.regroup(index, wrap_class=value_lib.Mirrored) + + def batch_reduce_implementation(self, reduce_op, value_destination_pairs, + options): + values_util.mark_as_unsaveable() + all_devices_match = _all_devices_match(value_destination_pairs, + self._canonicalize_devices) + if all_devices_match: + return self._all_reduce_per_replica_values( + reduce_op, [v[0] for v in value_destination_pairs], options) + else: + if not all_devices_match: + logging.log_first_n( + logging.WARN, "Efficient batch_reduce is not supported if " + "destinations are different.", 10) + + return [ + self.reduce_implementation(reduce_op, value, dest, options) + for value, dest in value_destination_pairs + ] + + def _gather_implementation(self, per_replica_value, destinations, axis, + options): + all_gathered = self._batch_all_gather([per_replica_value], axis, options)[0] + values_util.mark_as_unsaveable() + devices = get_devices_from(destinations, self._canonicalize_devices) + + if _devices_match(per_replica_value, destinations, + self._canonicalize_devices): + return all_gathered + + # Convert `all_gathered` to a `Mirrored` object, as a simple and uniform + # utility to access component for a particular device. + if not isinstance(all_gathered, value_lib.Mirrored): + all_gathered = value_lib.Mirrored([all_gathered]) + + # If we got this far, the destination devices do not match the all-gather + # devices, so we must map from one to the other. + index = [] + # We must add these control dependencies, otherwise we can get deadlock. + with ops.control_dependencies(all_gathered.values): + for d in devices: + with ops.device(d): + for v in all_gathered.values: + if v.device == d: + index.append(array_ops.identity(v)) + break + else: + index.append(array_ops.identity(all_gathered._primary)) # pylint: disable=protected-access + return distribute_utils.regroup(index, wrap_class=value_lib.Mirrored) + + def _batch_all_gather(self, per_replica_values, axis, options): + """all gather multiple per-replica-values.""" + batch_size = len(per_replica_values) + # For now, we use NCCL only when batch_size > 1. + # TODO(b/132575814): switch to NCCL for all collectives when implementation + # is NCCL. + if (self._limited_nccl and options.implementation + == collective_util.CommunicationImplementation.NCCL and + batch_size == 1): + options = options.merge( + collective_util.Options( + implementation=collective_util.CommunicationImplementation.RING)) + + logging.log_first_n( + logging.INFO, "Collective batch_all_gather: %d all-gathers, " + "num_devices = %d, group_size = %d, implementation = %s, " % + (batch_size, len( + self._devices), self._group_size, options.implementation), 10) + + def compute_gathered_values(): + gathered_values = [] + with self._lock, ops.name_scope("allgather"): + for per_replica in per_replica_values: + outputs = [] + for i in range(len(self._devices)): + outputs.append(self._launchers[i].all_gather( + per_replica.values[i], axis, options)) + gathered_values.append(outputs) + return gathered_values + + if context.executing_eagerly(): + gathered_values = def_function.function(compute_gathered_values)() + else: + gathered_values = compute_gathered_values() + + mirrored = [] + for value in gathered_values: + mirrored.append( + distribute_utils.regroup(value, wrap_class=value_lib.Mirrored)) + return mirrored + + def __deepcopy__(self, memo): + # distribute_coordinator deep-copies the strategy object, so + # CollectiveAllReduce needs to support deep copy as well. + collective_keys = copy.deepcopy(self._collective_keys, memo) + return CollectiveAllReduce(self._devices, self._group_size, self._options, + collective_keys, self._canonicalize_devices) + + +def select_cross_device_ops(devices, session_config=None): + """Find the best `CrossDeviceOps` locally given a `tf.compat.v1.ConfigProto`. + + Args: + devices: a list of devices passed to `tf.distribute.Strategy`. + session_config: a `tf.compat.v1.ConfigProto` or `None`. If `None`, it will + make decision based on all logical devices. + + Returns: + A subclass of `CrossDeviceOps`. + """ + requested_devices = set(device_util.canonicalize(d) for d in devices) + if ops.executing_eagerly_outside_functions(): + logical_gpus = context.context().list_logical_devices(device_type="GPU") + physical_gpus = context.context().list_physical_devices(device_type="GPU") + if len(logical_gpus) != len(physical_gpus): + logging.warning("NCCL is not supported when using virtual GPUs, falling" + "back to reduction to one device") + return ReductionToOneDevice() + + machine_devices = context.context().list_logical_devices() + else: + machine_devices = device_lib.list_local_devices( + session_config=session_config) + using_devices = set() + for d in machine_devices: + if device_util.canonicalize(d.name) in requested_devices: + using_devices.add(d.name) + + if len(using_devices) != len(requested_devices): + logging.warning( + "Some requested devices in `tf.distribute.Strategy` are not visible " + "to TensorFlow: %s", ",".join(list(requested_devices - using_devices))) + + if any("gpu" not in d.lower() for d in requested_devices): + logging.warning("There are non-GPU devices in `tf.distribute.Strategy`, " + "not using nccl allreduce.") + return ReductionToOneDevice() + + if kernels.get_registered_kernels_for_op("NcclAllReduce"): + return NcclAllReduce(num_packs=1) + else: + logging.warning("Nccl kernel is not found, not using nccl allreduce.") + return ReductionToOneDevice() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cross_device_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cross_device_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b203aec3bc7f78ee8fd46c7aacf0aa905103fba1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/cross_device_utils.py @@ -0,0 +1,730 @@ +# 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. +# ============================================================================== +"""Utilities for cross_device_ops.""" + +import copy +import threading +from typing import Callable, List, Optional, Union + +from tensorflow.python.distribute import collective_util +from tensorflow.python.distribute import values as value_lib +from tensorflow.python.eager import backprop_util +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import collective_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nccl_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import core + +INSTANCE_KEY_START_NUMBER = 100 + + +def aggregate_gradients_using_nccl(replica_grads): + """Aggregate gradients using nccl allreduce.""" + agg_all_g_and_v = [] + for single_g_and_v in zip(*replica_grads): + single_grads = [g for g, _ in single_g_and_v] + agg_grads = nccl_ops.all_sum(single_grads) + agg_all_g_and_v.append( + [(g, v) for g, (_, v) in zip(agg_grads, single_g_and_v)]) + + agg_all_g_and_v = list(zip(*agg_all_g_and_v)) + + return agg_all_g_and_v + + +def aggregate_gradients_using_hierarchical_copy(avail_devices, replica_grads): + """Aggregate gradients using hierarchical copies. + + Args: + avail_devices: available GPU devices. + replica_grads: List of lists of (gradient, variable) tuples. The outer list + is over replicas. The inner list is over individual gradients. + + Returns: + The list of (aggregated_gradient, variable), where the gradient has been + summed across all replicas and the variable is chosen from the first + replica. + """ + # This only works for DGX-1 type of machine topology + # Device peer to peer matrix + # DMA: 0 1 2 3 4 5 6 7 + # 0: Y Y Y Y Y N N N + # 1: Y Y Y Y N Y N N + # 2: Y Y Y Y N N Y N + # 3: Y Y Y Y N N N Y + # 4: Y N N N Y Y Y Y + # 5: N Y N N Y Y Y Y + # 6: N N Y N Y Y Y Y + # 7: N N N Y Y Y Y Y + agg_grads = [] + num_devices = len(avail_devices) + # In the special case of DGX-1 machine topology, the two groups have equal + # size. + group_size = num_devices // 2 + for i, single_grads in enumerate(zip(*replica_grads)): + group_0_main_device = i % num_devices + group_1_main_device = (group_0_main_device + group_size) % num_devices + if group_0_main_device < group_size: + group_0_begin = 0 + group_1_begin = group_size + else: + group_0_begin = group_size + group_1_begin = 0 + + # Aggregate the first group. + group_0_device_grads = single_grads[group_0_begin: + group_0_begin + group_size] + with ops.device(avail_devices[group_0_main_device]): + group_0_agg_grads, _ = aggregate_single_gradient_using_copy( + group_0_device_grads, False, False) + + # Aggregate the second group. + group_1_device_grads = single_grads[group_1_begin: + group_1_begin + group_size] + with ops.device(avail_devices[group_1_main_device]): + group_1_agg_grads, _ = aggregate_single_gradient_using_copy( + group_1_device_grads, False, False) + + # Aggregate between the groups. + with ops.device(avail_devices[group_0_main_device]): + (agg_total_grads, _), _ = aggregate_single_gradient_using_copy( + [group_0_agg_grads, group_1_agg_grads], False, False) + + # Broadcast the result back into the root of each group. + with ops.device(avail_devices[group_0_main_device]): + group_0_agg_grads_bcast = array_ops.identity(agg_total_grads) + with ops.device(avail_devices[group_1_main_device]): + group_1_agg_grads_bcast = array_ops.identity(agg_total_grads) + + agg_grads_bcast = [] + for j in range(len(single_grads)): + with ops.device(avail_devices[j]): + # Broadcast the result back to each member in the group from the root. + if (group_0_main_device < group_size) == (j < group_size): + src_device_grad = group_0_agg_grads_bcast + else: + src_device_grad = group_1_agg_grads_bcast + agg_grads_bcast.append(array_ops.identity(src_device_grad)) + + agg_grads.append( + [(g, v) for g, (_, v) in zip(agg_grads_bcast, single_grads)]) + + agg_grads = list(zip(*agg_grads)) + + return agg_grads + + +def aggregate_single_gradient_using_copy(grad_and_vars, use_mean, + check_inf_nan): + """Calculate the average gradient for a shared variable across all replicas. + + Note that this function provides a synchronization point across all replicas. + + Args: + grad_and_vars: A list or tuple of (gradient, variable) tuples. Each + (gradient, variable) pair within the outer list represents the gradient + of the variable calculated for a single replica, and the number of pairs + equals the number of replicas. + use_mean: if True, mean is taken, else sum of gradients is taken. + check_inf_nan: check grads for nans and infs. + + Returns: + The tuple ([(average_gradient, variable),], has_nan_or_inf) where the + gradient has been averaged across all replicas. The variable is chosen + from the first replica. The has_nan_or_inf indicates the grads has nan or + inf. + """ + grads = [g for g, _ in grad_and_vars] + grad = math_ops.add_n(grads) + + if use_mean and len(grads) > 1: + grad = array_ops.multiply(grad, 1.0 / len(grads)) + + v = grad_and_vars[0][1] + if check_inf_nan: + has_nan_or_inf = array_ops.logical_not( + array_ops.reduce_all(array_ops.is_finite(grads))) + return (grad, v), has_nan_or_inf + else: + return (grad, v), None + + +# TODO(yuefengz): use random key starts to avoid reusing keys? +class CollectiveKeys(object): + """Class that manages collective keys. + + We need to manage three different keys for collective: + + *Group key*: an integer key to identify the set of cooperative devices. + Collective ops work under the same set of devices must using the same group + key. + + *Instance key*: an integer key to identify the set of same counterpart of + tensors on different devices in a device group that need to be all-reduced. + + This class is thread safe. + """ + + def __init__(self, group_key_start=1): + """Initializes the object. + + Args: + group_key_start: the starting integer of group key. + """ + self._group_key = group_key_start + self._instance_key_table = {} + self._lock = threading.Lock() + self._known_groups = {} + + def get_group_key(self, devices): + """Returns a group key for the list of local devices. + + The same group key is returned if the list of local devices is the same. + + Args: + devices: a list of local canonical device strings in a collective group. + + Returns: + a group key. + """ + with self._lock: + devices_key = ','.join(devices) + if devices_key not in self._known_groups: + self._known_groups[devices_key] = self._get_new_group_key(devices) + return self._known_groups[devices_key] + + def _get_new_group_key(self, devices): + """Returns a new group key. + + The caller should store and reuse the same group key for the same set of + devices. Calling this method always returns a new group key. + + This method is not thread-safe. + + Args: + devices: a list of canonical device strings in a collective group. + + Returns: + a new group key. + """ + new_key = self._group_key + self._group_key += 1 + self._instance_key_table[new_key] = {} + for device in devices: + self._instance_key_table[new_key][device] = INSTANCE_KEY_START_NUMBER + return new_key + + def get_instance_key(self, group_key, device): + """Returns a new instance key for use in defining a collective op. + + You should call this once per each collective op of a collective instance. + + Args: + group_key: the group key returned by get_group_key(). You should not + assign the group key yourself. + device: a canonical device string. It should be the device this collective + op is on. + + Returns: + a new instance key. + + Raises: + ValueError: when the group key is invalid or the device is not in the + group. + """ + with self._lock: + group = self._instance_key_table.get(group_key, None) + if group is None: + raise ValueError(f'Group {group_key} is not found.') + if device not in group: + raise ValueError(f'Device {device} is not present in group {group_key}') + v = group[device] + group[device] += 1 + return v + + def __deepcopy__(self, memo): + # distribute_coordinator deep-copies the strategy object, so + # CollectiveKeys needs to support deep copy as well. + copied = CollectiveKeys() + copied._group_key = self._group_key + copied._instance_key_table = copy.deepcopy(self._instance_key_table, memo) + return copied + + +class CollectiveReplicaLauncher(object): + """Launch collectives on one replica.""" + + _prefer_unique_instance_key = True + _prefer_ordering_token = True + + def __init__(self, group_key: int, group_size: int, + collective_keys: CollectiveKeys, device: str, + options: collective_util.Options): + self._group_key = group_key + self._group_size = group_size + self._collective_keys = collective_keys + self._device = device + self._options = options + if self._use_ordering_token(): + with ops.init_scope(), ops.device(device): + self._ordering_token = resource_variable_ops.ResourceVariable(0.) + else: + self._ordering_token = None + + def _control_input(self, control_input: Union[core.TensorLike, + ops.Operation]): + if control_input is not None and not self._use_ordering_token(): + return ops.control_dependencies([control_input]) + return ops.NullContextmanager() + + def _use_unique_instance_key(self): + if not ops.executing_eagerly_outside_functions(): + return False + return CollectiveReplicaLauncher._prefer_unique_instance_key + + def _use_ordering_token(self): + # We rely on auto control dep to insert control edges between NCCL calls, + # but for tf1 graph mode auto control dep is not used. + if not ops.executing_eagerly_outside_functions(): + return False + return CollectiveReplicaLauncher._prefer_ordering_token + + def _next_instance_key(self): + """Returns the next instance key.""" + if self._use_unique_instance_key(): + # Assigning instance keys at function building time have issues since + # different workers may retrace the function at different times. With + # collective V2 we can use capture_call_time_value to use a placeholder as + # the instance key and feed it at function call time. In this way we also + # don't reuse instance keys, which allows for per-instance cancellation. + graph = ops.get_default_graph() + # Control flow ops don't work with capture_call_time_value, so we put the + # capture in the function graph of that control flow op. + while getattr(graph, 'is_control_flow_graph', False): + graph = graph.outer_graph + if not context.executing_eagerly() and graph.building_function: + with graph.as_default(): + # Capture self._next_instance_key so that when building a function + # that calls another tf.function, the instance key assignment is + # further delayed until we actually call the function in eager. Note + # that capture_call_time_value doesn't automatically propagate the + # deferred capture to the outer function. + return graph.capture_call_time_value( + self._next_instance_key, tensor_spec.TensorSpec([], dtypes.int32)) + else: + instance_key = self._collective_keys.get_instance_key( + self._group_key, self._device) + with ops.device('CPU:0'): + return ops.convert_to_tensor(instance_key, dtype=dtypes.int32) + else: + return self._collective_keys.get_instance_key(self._group_key, + self._device) + + def _get_ordering_token(self): + if self._use_ordering_token(): + return self._ordering_token.handle # pytype: disable=attribute-error + + def can_order_nccl(self): + """Whether this launcher can order NCCL operations.""" + return self._use_ordering_token() + + def all_reduce( + self, + input_tensor: core.TensorLike, + control_input: Optional[Union[core.TensorLike, ops.Operation]] = None, + options: Optional[collective_util.Options] = None) -> core.Tensor: + """All-reduce a dense tensor. + + Args: + input_tensor: a dense tensor. It must have the same shape on all replicas. + control_input: if not None, add control edges between control_input and + the all-reduce. + options: an optional tf.distribute.experimental.CommunicationOptions. If + provided, it overrides the default options. + + Returns: + The reduced tensor. + """ + instance_key = self._next_instance_key() + options = self._options.merge(options) + ordering_token = self._get_ordering_token() + with ops.device(self._device), \ + self._control_input(control_input): + return collective_ops.all_reduce_v2( + input_tensor, + self._group_size, + self._group_key, + instance_key, + communication_hint=options.implementation.value, + timeout=options.timeout_seconds, + ordering_token=ordering_token) + + def _all_gather(self, input_tensor: core.TensorLike, + options: Optional[collective_util.Options]) -> core.Tensor: + """All-gather a dense tensor. + + Args: + input_tensor: a dense tensor. It must have the same shape on all replicas. + options: an optional tf.distribute.experimental.CommunicationOptions. If + provided, it overrides the default options. + + Returns: + The reduced tensor. + """ + instance_key = self._next_instance_key() + options = self._options.merge(options) + ordering_token = self._get_ordering_token() + with ops.device(self._device): + return collective_ops.all_gather_v2( + input_tensor, + self._group_size, + self._group_key, + instance_key, + communication_hint=options.implementation.value, + timeout=options.timeout_seconds, + ordering_token=ordering_token) + + def batch_all_reduce( + self, + input_tensor_packs: List[List[core.TensorLike]], + options: Optional[collective_util.Options] = None) -> core.Tensor: + """Batch all-reduce dense tensors. + + This takes a list of batches of tensors. Using multiple batches have the + benefit that it doesn't need to wait for all inputs to be ready to start the + all-reduce. + + Args: + input_tensor_packs: a list of lists of dense tensors. + options: an optional tf.distribute.experimental.CommunicationOptions. If + provided, it overrides the default options. + + Returns: + A flat list of reduced tensors. + """ + options = self._options.merge(options) + outputs = [] + for pack in input_tensor_packs: + if context.executing_eagerly(): + # We don't batch in eager as it sometimes makes the performance worse + # due the concat/split ops. + for input_tensor in pack: + outputs.append(self.all_reduce(input_tensor, None, options)) + else: + # TODO(b/169168846): inserts a parallel all_gather to verify packings + # are the same on each replica. + with ops.device(self._device): + flat_tensors = [array_ops.reshape(t, [-1]) for t in pack] + shapes = [array_ops.shape(t) for t in pack] + if (options.implementation + == collective_util.CommunicationImplementation.NCCL and outputs): + control_input = outputs[-1] + else: + control_input = None + reduced = self.all_reduce( + array_ops.concat(flat_tensors, axis=0), control_input, options) + num_elements = [math_ops.reduce_prod(s) for s in shapes] + flat_outputs = array_ops.split(reduced, num_elements, axis=0) + for shape, flat_output in zip(shapes, flat_outputs): + outputs.append(array_ops.reshape(flat_output, shape)) + + return outputs + + def all_gather( + self, + input_tensor: core.TensorLike, + axis: core.TensorLike, + options: Optional[collective_util.Options] = None) -> core.Tensor: + """All-gather a dense tensor. + + This method must be called inside a tf.function. + + Args: + input_tensor: a dense tensor. It must have the same rank on all replicas, + and dimensions other than `axis` need to be the same as well. + axis: 0-D int32 Tensor. Dimension along which to gather. Must be in the + range [0, rank(value)). + options: an optional tf.distribute.experimental.CommunicationOptions. If + provided, it overrides the default options. + + Returns: + The gathered Tensor. + + Raises: + RuntimeError: if called in eager mode. + """ + if context.executing_eagerly(): + raise RuntimeError('all_gather is not supported in eager mode.') + + with ops.device(self._device), \ + ops.control_dependencies([array_ops.identity(input_tensor)]): + # 1. Transpose + # E.g. Given an input_tensor with shape [2,2,5,1] and axis to gather is 3, + # we use perm_pre=[3 0 1 2] to reshape it to [1,2,2,5], which + # brings the 3rd dim first; afterwards we use perm_after=[1,2,3,0] to + # place it back. + perm_pre = array_ops.concat( + ([axis], math_ops.range(axis), + math_ops.range(axis + 1, array_ops.rank(input_tensor))), + axis=0) + input_tensor_t = array_ops.transpose(input_tensor, perm=perm_pre) + # 2. Pad + gathered_shape = self._all_gather( + array_ops.expand_dims_v2(array_ops.shape_v2(input_tensor_t), axis=0), + options) + first_dims = gathered_shape[:, 0] + full_axis_dim = math_ops.reduce_max(first_dims) + padded_input_tensor = _pad_util(input_tensor_t, full_axis_dim) + + # 3. Gather + gather_padded_out_tensor = self._all_gather(padded_input_tensor, options) + # 4. Unpad + split_tensors = [] + for i in range(self._group_size): + start_pos = i * full_axis_dim + split_tensors.append(gather_padded_out_tensor[start_pos:start_pos + + first_dims[i]]) + out_tensor_t = array_ops.concat(split_tensors, 0) + + # 5. Transpose back + perm_after = array_ops.concat( + (math_ops.range(1, axis + 1), [0], + math_ops.range(axis + 1, array_ops.rank(input_tensor_t))), + axis=0) + return array_ops.transpose(out_tensor_t, perm=perm_after) + + def all_reduce_indexed_slices( + self, + input_slices: indexed_slices.IndexedSlices, + options: Optional[collective_util.Options] = None + ) -> indexed_slices.IndexedSlices: + """All-reduce an IndexedSlices. + + This method can be called outside tf.function. + + Args: + input_slices: an IndexedSlices. + options: an optional tf.distribute.experimental.CommunicationOptions. If + provided, it overrides the default options. + + Returns: + The reduced IndexedSlices. + """ + + # Current CollectiveAllGather implementations require input IndexedSlices to + # have consistent length across the board, we handle the reduction of + # IndexedSlices as follows: + # 1. Gather the lengths of IndexedSlices from all participants. + # 2. If they have consistent length, apply all_gather. + # 3. Otherwise pad IndexedSlices to be the same length across all + # participants and apply_gather. + options = self._options.merge(options) + with ops.device(self._device): + + def all_gather_indexed_slices( + all_gather_fn: Callable[ + [core.TensorLike, Optional[collective_util.Options]], core.Tensor] + ) -> indexed_slices.IndexedSlices: + """Use all_gather_fn to aggregate `IndexedSlices`.""" + all_values = all_gather_fn(input_slices.values, options) + # Add control dependency to order the all-gather. + if (options.implementation == + collective_util.CommunicationImplementation.NCCL): + control = [all_values] + else: + control = [] + with ops.control_dependencies(control): + all_indices = all_gather_fn(input_slices.indices, options) + return indexed_slices.IndexedSlices( + values=all_values, + indices=all_indices, + dense_shape=input_slices.dense_shape) + + length = array_ops.shape(input_slices.indices) + all_lengths = self._all_gather(length, options) + + def all_gather_with_padding( + input_tensor: core.TensorLike, + options: Optional[collective_util.Options]) -> core.Tensor: + """all_gather tensors of different sizes using padding.""" + max_length = math_ops.reduce_max(all_lengths) + padded_tensor = _pad_util(input_tensor, max_length) + all_padded_tensors = self._all_gather(padded_tensor, options) + split_tensors = [] + for i in range(self._group_size): + start_pos = i * max_length + split_tensors.append(all_padded_tensors[start_pos:start_pos + + all_lengths[i]]) + return array_ops.concat(split_tensors, 0) + + return cond.cond( + math_ops.equal( + math_ops.reduce_max(all_lengths), + math_ops.reduce_min(all_lengths)), + lambda: all_gather_indexed_slices(self._all_gather), + lambda: all_gather_indexed_slices(all_gather_with_padding)) + + +def aggregate_tensors_or_indexed_slices(values, accumulation_fn=math_ops.add_n): + """Aggregate tensors using `accumulation_fn` and IndexedSlices via concat.""" + if any(isinstance(v, indexed_slices.IndexedSlices) for v in values): + return backprop_util.AggregateIndexedSlicesGradients(values) + else: + return accumulation_fn(values) + + +def divide_by_n_tensors_or_indexed_slices(value, n): + if isinstance(value, indexed_slices.IndexedSlices): + value = backprop_util.FlattenNestedIndexedSlices(value) + return indexed_slices.IndexedSlices(value.values / n, value.indices, + value.dense_shape) + else: + return value / n + + +def copy_tensor_or_indexed_slices_to_device(value, device): + """Copies a tensor or IndexedSlices to a device.""" + with ops.device(device): + if isinstance(value, indexed_slices.IndexedSlices): + copied_values = array_ops.identity(value.values) + copied_indices = array_ops.identity(value.indices) + if value.dense_shape is not None: + copied_shape = array_ops.identity(value.dense_shape) + else: + copied_shape = None + result = indexed_slices.IndexedSlices(copied_values, copied_indices, + copied_shape) + else: + result = array_ops.identity(value) + return result + + +def is_indexed_slices(value): + if isinstance(value, indexed_slices.IndexedSlices): + return True + if isinstance(value, value_lib.DistributedValues): + return all( + isinstance(v, indexed_slices.IndexedSlices) for v in value.values) + return False + + +def split_by_sparsity(values): + """Split values into dense and sparse values. + + Args: + values: a list of tensors or `PerReplica`s. + + Returns: + Four lists: + a list of dense values, a list of their indices in `values` and + a list of sparse values, a list of their indices in `values`. + """ + dense_values = [] + dense_indices = [] + sparse_values = [] + sparse_indices = [] + for i, v in enumerate(values): + if is_indexed_slices(v): + sparse_values.append(v) + sparse_indices.append(i) + else: + dense_values.append(v) + dense_indices.append(i) + return dense_values, dense_indices, sparse_values, sparse_indices + + +def stitch_values(values_and_indices_list): + """Stitch values together according to their indices. + + Args: + values_and_indices_list: a list of tuples of values and indices indicating + the values and positions in the returned list. + + Returns: + a stitched list of values. + """ + length = 0 + for values_and_indices in values_and_indices_list: + length += len(values_and_indices[0]) + + result = [None] * length + for values_and_indices in values_and_indices_list: + if values_and_indices and values_and_indices[0]: + for v, i in zip(*values_and_indices): + assert result[i] is None + result[i] = v + return result + + +def group_by_size(input_tensors, bytes_per_pack): + """Groups `input_tensors` into chunks of `bytes_per_pack`. + + The method preserves the original order of `input_tensors`. The grouping is + best effort, each pack could have more or less bytes than `bytes_per_pack`. + It only groups values with known shape. + + Args: + input_tensors: a list of Tensor. + bytes_per_pack: an integer. + + Returns: + A list of packs of Tensor. All values are grouped into one pack if + `bytes_per_pack` is zero or any of the value has unknown shape. + """ + + if bytes_per_pack == 0: + return [input_tensors] + packs = [] + last_pack_size = 0 + for value in input_tensors: + num_elements = value.shape.num_elements() + if num_elements is None: + # Can't pack values with unknown shape. + logging.warning( + 'not packing values due to the unknown or inconsistent shape of %s', + value) + return [input_tensors] + size = num_elements * value.dtype.size + # Try to keep each pack as close to bytes_per_pack as possible, while each + # pack is at least bytes_per_pack large. I.E. we err on the side of having + # few but large packs. + if not packs or last_pack_size > bytes_per_pack: + packs.append([]) + last_pack_size = 0 + packs[-1].append(value) + last_pack_size += size + return packs + + +def _pad_util(input_tensor, full_axis_dim): + """Pad the `input_tensor`'s first dimension to be `full_axis_dim`.""" + missing_axis_dim = full_axis_dim - array_ops.shape_v2(input_tensor)[0] + tensor_rank = array_ops.rank(input_tensor) + paddings_axis = [[0, missing_axis_dim]] + paddings = array_ops.concat([ + paddings_axis, + array_ops.zeros(shape=(tensor_rank - 1, 2), dtype=dtypes.int32) + ], + axis=0) + padded_input_tensor = array_ops.pad(input_tensor, paddings) + return padded_input_tensor diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/device_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/device_util.py new file mode 100644 index 0000000000000000000000000000000000000000..a7631c3c38c538a4351e065bb95db46a57ac3a50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/device_util.py @@ -0,0 +1,159 @@ +# 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. +# ============================================================================== +"""Device-related support functions.""" + + +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import ops + + +def canonicalize(d, default=None): + """Canonicalize device string. + + If d has missing components, the rest would be deduced from the `default` + argument or from '/replica:0/task:0/device:CPU:0'. For example: + If d = '/cpu:0', default='/job:worker/task:1', it returns + '/job:worker/replica:0/task:1/device:CPU:0'. + If d = '/cpu:0', default='/job:worker', it returns + '/job:worker/replica:0/task:0/device:CPU:0'. + If d = '/gpu:0', default=None, it returns + '/replica:0/task:0/device:GPU:0'. + + Note: This uses "job:localhost" as the default if executing eagerly. + + Args: + d: a device string or tf.config.LogicalDevice + default: a string for default device if d doesn't have all components. + + Returns: + a canonicalized device string. + """ + if isinstance(d, context.LogicalDevice): + d = tf_device.DeviceSpec.from_string(d.name) + else: + d = tf_device.DeviceSpec.from_string(d) + + assert d.device_type is None or d.device_type == d.device_type.upper(), ( + "Device type '%s' must be all-caps." % (d.device_type,)) + # Fill in missing device fields using defaults. + result = tf_device.DeviceSpec( + replica=0, task=0, device_type="CPU", device_index=0) + if ops.executing_eagerly_outside_functions(): + # Try to deduce job, replica and task in case it's in a multi worker setup. + # TODO(b/151452748): Using list_logical_devices is not always safe since it + # may return remote devices as well, but we're already doing this elsewhere. + host_cpu = tf_device.DeviceSpec.from_string( + config.list_logical_devices("CPU")[0].name) + if host_cpu.job: + result = result.make_merged_spec(host_cpu) + else: + # The default job is localhost if eager execution is enabled + result = result.replace(job="localhost") + if default: + # Overrides any defaults with values from the default device if given. + result = result.make_merged_spec( + tf_device.DeviceSpec.from_string(default)) + + # Apply `d` last, so that it's values take precedence over the defaults. + result = result.make_merged_spec(d) + return result.to_string() + + +def canonicalize_without_job_and_task(d): + """Partially canonicalize device string. + + This returns device string from `d` without including job and task. + This is most useful for parameter server strategy where the device strings are + generated on the chief, but executed on workers. + + For example: + If d = '/cpu:0', default='/job:worker/task:1', it returns + '/replica:0/device:CPU:0'. + If d = '/cpu:0', default='/job:worker', it returns + '/replica:0/device:CPU:0'. + If d = '/gpu:0', default=None, it returns + '/replica:0/device:GPU:0'. + + Note: This uses "job:localhost" as the default if executing eagerly. + + Args: + d: a device string or tf.config.LogicalDevice + + Returns: + a partially canonicalized device string. + """ + canonicalized_device = canonicalize(d) + spec = tf_device.DeviceSpec.from_string(canonicalized_device) + spec = spec.replace(job=None, task=None, replica=0) + return spec.to_string() + + +def resolve(d): + """Canonicalize `d` with current device as default.""" + return canonicalize(d, default=current()) + + +class _FakeNodeDef(object): + """A fake NodeDef for _FakeOperation.""" + + __slots__ = ["op", "name"] + + def __init__(self): + self.op = "" + self.name = "" + + +class _FakeOperation(object): + """A fake Operation object to pass to device functions.""" + + def __init__(self): + self.device = "" + self.type = "" + self.name = "" + self.node_def = _FakeNodeDef() + + def _set_device(self, device): + self.device = ops._device_string(device) # pylint: disable=protected-access + + def _set_device_from_string(self, device_str): + self.device = device_str + + +def current(): + """Return a string (not canonicalized) for the current device.""" + # TODO(josh11b): Work out how this function interacts with ops.colocate_with. + if ops.executing_eagerly_outside_functions(): + d = context.context().device_name + else: + op = _FakeOperation() + ops.get_default_graph()._apply_device_functions(op) # pylint: disable=protected-access + d = op.device + return d + + +def get_host_for_device(device): + """Returns the corresponding host device for the given device.""" + spec = tf_device.DeviceSpec.from_string(device) + return tf_device.DeviceSpec( + job=spec.job, replica=spec.replica, task=spec.task, + device_type="CPU", device_index=0).to_string() + + +def local_devices_from_num_gpus(num_gpus): + """Returns device strings for local GPUs or CPU.""" + return (tuple("/device:GPU:%d" % i for i in range(num_gpus)) or + ("/device:CPU:0",)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_config.py new file mode 100644 index 0000000000000000000000000000000000000000..295e2705017d0ccf7718e4bdd5c31750369fca14 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_config.py @@ -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. +# ============================================================================== +"""A configure tuple for high-level APIs for running distribution strategies.""" + +import collections + + +class DistributeConfig( + collections.namedtuple( + 'DistributeConfig', + ['train_distribute', 'eval_distribute', 'remote_cluster'])): + """A config tuple for distribution strategies. + + Attributes: + train_distribute: a `DistributionStrategy` object for training. + eval_distribute: an optional `DistributionStrategy` object for + evaluation. + remote_cluster: a dict, `ClusterDef` or `ClusterSpec` object specifying + the cluster configurations. If this is given, the `train_and_evaluate` + method will be running as a standalone client which connects to the + cluster for training. + """ + + def __new__(cls, + train_distribute=None, + eval_distribute=None, + remote_cluster=None): + return super(DistributeConfig, cls).__new__(cls, train_distribute, + eval_distribute, remote_cluster) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_coordinator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_coordinator.py new file mode 100644 index 0000000000000000000000000000000000000000..0f58e0d6cb06accee3c56a8d69fad489e41dc160 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_coordinator.py @@ -0,0 +1,872 @@ +# 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. +# ============================================================================== +"""A component for running distributed TensorFlow.""" + +import copy +import json +import os +import threading +import time + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session +from tensorflow.python.distribute import distribute_coordinator_context +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import coordinator +from tensorflow.python.training import monitored_session +from tensorflow.python.training import server_lib + + +_thread_local = threading.local() + + +class _TaskType(object): + PS = "ps" + WORKER = "worker" + CHIEF = "chief" + EVALUATOR = "evaluator" + CLIENT = "client" + + +# TODO(yuefengz): support another mode where the client colocates with one +# worker. +class CoordinatorMode(object): + """Specify how distribute coordinator runs.""" + # The default mode where distribute coordinator will run as a standalone + # client and connects to remote servers for training. Each remote server can + # use the distribute coordinator binary with task_type set correctly which + # will then turn into standard servers. + STANDALONE_CLIENT = "standalone_client" + + # The distribute coordinator runs on each worker. It will run a standard + # server on each worker and optionally run the `worker_fn` that is configured + # to talk to its standard server. + INDEPENDENT_WORKER = "independent_worker" + + +class _Barrier(object): + """A reusable barrier class for worker synchronization.""" + + def __init__(self, num_participants): + """Initializes the barrier object. + + Args: + num_participants: an integer which is the expected number of calls of + `wait` pass to through this barrier. + """ + self._num_participants = num_participants + self._counter = 0 + self._flag = False + self._local_sense = threading.local() + self._lock = threading.Lock() + self._condition = threading.Condition() + + def wait(self): + """Waits until all other callers reach the same wait call.""" + self._local_sense.value = not self._flag + with self._lock: + self._counter += 1 + if self._counter == self._num_participants: + self._counter = 0 + self._flag = self._local_sense.value + with self._condition: + while self._flag != self._local_sense.value: + self._condition.wait() + self._condition.notify_all() + + +def _get_num_workers(cluster_spec): + """Gets number of workers including chief.""" + if not cluster_spec: + return 0 + return len(cluster_spec.as_dict().get(_TaskType.WORKER, [])) + len( + cluster_spec.as_dict().get(_TaskType.CHIEF, [])) + + +class _WorkerContext(object): + """The worker context class. + + This context object provides configuration information for each task. One + context manager with a worker context object will be created per + invocation to the `worker_fn` where `get_current_worker_context` can be called + to access the worker context object. + """ + + def __init__(self, + strategy, + cluster_spec, + task_type, + task_id, + session_config=None, + rpc_layer="grpc", + worker_barrier=None): + """Initialize the worker context object. + + Args: + strategy: a `DistributionStrategy` object. + cluster_spec: a ClusterSpec object. It can be empty or None in the local + training case. + task_type: a string indicating the role of the corresponding task, such as + "worker" or "ps". It can be None if it is local training or in-graph + replicated training. + task_id: an integer indicating id of the corresponding task. It can be + None if it is local training or in-graph replicated training. + session_config: an optional `tf.compat.v1.ConfigProto` object. + rpc_layer: optional string specifying the RPC protocol for communication + with worker masters. If None or empty, hosts in the `cluster_spec` will + be used directly. + worker_barrier: optional, the barrier object for worker synchronization. + """ + self._strategy = strategy + self._cluster_spec = cluster_spec + self._task_type = task_type + self._task_id = task_id + self._session_config = session_config + self._worker_barrier = worker_barrier + self._rpc_layer = rpc_layer + self._master_target = self._get_master_target() + self._num_workers = _get_num_workers(cluster_spec) + self._is_chief_node = self._is_chief() + + def _debug_message(self): + if self._cluster_spec: + return "[cluster_spec: %r, task_type: %r, task_id: %r]" % ( + self._cluster_spec, self.task_type, self.task_id) + else: + return "[local]" + + def __enter__(self): + old_context = distribute_coordinator_context.get_current_worker_context() + if old_context: + raise ValueError( + "You cannot run distribute coordinator in a `worker_fn`.\t" + + self._debug_message()) + # pylint: disable=protected-access + distribute_coordinator_context._worker_context.current = self + + def __exit__(self, unused_exception_type, unused_exception_value, + unused_traceback): + # pylint: disable=protected-access + distribute_coordinator_context._worker_context.current = None + + def _get_master_target(self): + """Return the master target for a task.""" + # If cluster_spec is None or empty, we use local master. + if not self._cluster_spec or self._task_type == _TaskType.EVALUATOR: + return "" + + # If task_type is None, then it is in-graph replicated training. In this + # case we use the chief or first worker's master target. + if not self._task_type: + if _TaskType.CHIEF in self._cluster_spec.jobs: + task_type = _TaskType.CHIEF + task_id = 0 + else: + assert _TaskType.WORKER in self._cluster_spec.jobs + task_type = _TaskType.WORKER + task_id = 0 + else: + task_type = self._task_type + task_id = self._task_id + + prefix = "" + if self._rpc_layer: + prefix = self._rpc_layer + "://" + return prefix + self._cluster_spec.job_tasks(task_type)[task_id or 0] + + def _is_chief(self): + """Return whether the task is the chief worker.""" + if (not self._cluster_spec or + self._task_type in [_TaskType.CHIEF, _TaskType.EVALUATOR, None]): + return True + + # If not local and chief not in the cluster_spec, use the first worker as + # chief. + if (_TaskType.CHIEF not in self._cluster_spec.jobs and + self._task_type == _TaskType.WORKER and self._task_id == 0): + return True + return False + + def wait_for_other_workers(self): + """Waits for other workers to reach the same call to this method. + + Raises: + ValueError: if `worker_barrier` is not passed to the __init__ method. + """ + if not self._worker_barrier: + # TODO(yuefengz): we should throw an error in independent worker mode. + return + self._worker_barrier.wait() + + def session_creator(self, + scaffold=None, + config=None, + checkpoint_dir=None, + checkpoint_filename_with_path=None, + max_wait_secs=7200): + """Returns a session creator. + + The returned session creator will be configured with the correct master + target and session configs. It will also run either init ops or ready ops + by querying the `strategy` object when `create_session` is called on it. + + Args: + scaffold: A `Scaffold` used for gathering or building supportive ops. If + not specified a default one is created. It's used to finalize the graph. + config: `ConfigProto` proto used to configure the session. + checkpoint_dir: A string. Optional path to a directory where to restore + variables. + checkpoint_filename_with_path: Full file name path to the checkpoint file. + Only one of `checkpoint_dir` or `checkpoint_filename_with_path` can be + specified. + max_wait_secs: Maximum time to wait for the session to become available. + + Returns: + a descendant of SessionCreator. + """ + if config: + session_config = copy.deepcopy(config) + session_config.MergeFrom(self._session_config) + else: + session_config = self._session_config + + if not self._strategy or self._strategy.extended.experimental_should_init: + logging.info("Creating chief session creator with config: %r", config) + return monitored_session.ChiefSessionCreator( + scaffold, + master=self.master_target, + config=session_config, + checkpoint_dir=checkpoint_dir, + checkpoint_filename_with_path=checkpoint_filename_with_path) + else: + logging.info("Creating worker session creator with config: %r", config) + return monitored_session.WorkerSessionCreator( + scaffold, + master=self.master_target, + config=session_config, + max_wait_secs=max_wait_secs) + + @property + def session_config(self): + return copy.deepcopy(self._session_config) + + @property + def has_barrier(self): + """Whether the barrier is set or not.""" + return self._worker_barrier is not None + + @property + def distributed_mode(self): + """Whether it is distributed training or not.""" + return bool(self._cluster_spec) and self._task_type != _TaskType.EVALUATOR + + @property + def cluster_spec(self): + """Returns a copy of the cluster_spec object.""" + return copy.deepcopy(self._cluster_spec) + + @property + def task_type(self): + """Returns the role of the corresponding task.""" + return self._task_type + + @property + def task_id(self): + """Returns the id or index of the corresponding task.""" + return self._task_id + + @property + def master_target(self): + """Returns the session master for the corresponding task to connect to.""" + return self._master_target + + @property + def is_chief(self): + """Returns whether the task is a chief node.""" + return self._is_chief_node + + @property + def num_workers(self): + """Returns number of workers in the cluster, including chief.""" + return self._num_workers + + @property + def experimental_should_init(self): + """Whether to run init ops.""" + return self._strategy.extended.experimental_should_init + + @property + def should_checkpoint(self): + """Whether to save checkpoint.""" + return self._strategy.extended.should_checkpoint + + @property + def should_save_summary(self): + """Whether to save summaries.""" + return self._strategy.extended.should_save_summary + + +def _run_single_worker(worker_fn, + strategy, + cluster_spec, + task_type, + task_id, + session_config, + rpc_layer="", + worker_barrier=None, + coord=None): + """Runs a single worker by calling `worker_fn` under context.""" + session_config = copy.deepcopy(session_config) + strategy = copy.deepcopy(strategy) + # If there is an EVALUATOR task, we run single-machine eval on that task. + if task_type == _TaskType.EVALUATOR: + # It is possible to not have a strategy object for EVALUATOR task. + if strategy: + strategy.configure(session_config) + else: + assert strategy + strategy.configure(session_config, cluster_spec, task_type, task_id) + + context = _WorkerContext( + strategy, + cluster_spec, + task_type, + task_id, + session_config=session_config, + rpc_layer=rpc_layer, + worker_barrier=worker_barrier) + with context: + if coord: + with coord.stop_on_exception(): + return worker_fn(strategy) + else: + return worker_fn(strategy) + + +def _split_cluster_for_evaluator(cluster_spec, task_type): + """Split the cluster for evaluator since it needn't talk to other tasks.""" + # Splitting the cluster is important to prevent the evaluator from talking to + # other tasks in the cluster. Since we allow evaluator not to use + # distribution strategies and as a result ops in the evaluator task may have + # unspecified devices. Those ops may end up on other tasks if we don't split + # the cluster. + # Note: if you bypass distribute coordinator and bring the cluster yourself, + # you can equivalently set device filters to split clusters. This is already + # done by distribution strategy's `update_config_proto` method. + new_cluster_spec = multi_worker_util.normalize_cluster_spec( + cluster_spec).as_dict() + if task_type == _TaskType.EVALUATOR: + assert _TaskType.EVALUATOR in new_cluster_spec + new_cluster_spec = { + _TaskType.EVALUATOR: new_cluster_spec[_TaskType.EVALUATOR] + } + else: + new_cluster_spec.pop(_TaskType.EVALUATOR, None) + return multi_worker_util.normalize_cluster_spec(new_cluster_spec) + + +def _run_std_server(cluster_spec=None, + task_type=None, + task_id=None, + session_config=None, + rpc_layer=None, + environment=None): + """Runs a standard server.""" + # Check if the Server is already running. If so, assert that no configuration + # options have changed, and return the existing Server. This allows us to + # call `run_distribute_coordinator` multiple times. + if getattr(_thread_local, "server", None) is not None: + assert _thread_local.cluster_spec == cluster_spec + assert _thread_local.task_type == task_type + assert _thread_local.task_id == task_id + assert _thread_local.session_config_str == repr(session_config) + assert _thread_local.rpc_layer == rpc_layer + assert _thread_local.environment == environment + return _thread_local.server + else: + # This method is not thread-safe. + _thread_local.server_started = True + _thread_local.cluster_spec = cluster_spec + _thread_local.task_type = task_type + _thread_local.task_id = task_id + _thread_local.session_config_str = repr(session_config) + _thread_local.rpc_layer = rpc_layer + _thread_local.environment = environment + + assert cluster_spec + target = cluster_spec.task_address(task_type, task_id) + if rpc_layer: + target = rpc_layer + "://" + target + + class _FakeServer(object): + """A fake server that runs a master session.""" + + def start(self): + # A tensorflow server starts when a remote session is created. + logging.info( + "Creating a remote session to start a TensorFlow server, " + "target = %r, session_config=%r", target, session_config) + session.Session(target=target, config=session_config) + + def join(self): + while True: + time.sleep(5) + + if environment == "google": + server = _FakeServer() + else: + if session_config: + logging.info( + "Starting standard TensorFlow server, target = %r, session_config= " + "%r", target, session_config) + else: + logging.info("Starting standard TensorFlow server, target = %r", target) + cluster_spec = _split_cluster_for_evaluator(cluster_spec, task_type) + server = server_lib.Server( + cluster_spec, + job_name=task_type, + task_index=task_id, + config=session_config, + protocol=rpc_layer) + + server.start() + _thread_local.server = server + return server + + +def _run_between_graph_client(worker_fn, strategy, eval_fn, eval_strategy, + cluster_spec, session_config, rpc_layer): + """Runs a standalone client for between-graph replication.""" + coord = coordinator.Coordinator() + eval_thread = None + if _TaskType.EVALUATOR in cluster_spec.jobs: + eval_thread = threading.Thread( + target=_run_single_worker, + args=(eval_fn, eval_strategy, cluster_spec, _TaskType.EVALUATOR, 0, + session_config), + kwargs={ + "rpc_layer": rpc_layer, + "coord": coord, + }) + eval_thread.start() + + threads = [] + worker_barrier = _Barrier(_get_num_workers(cluster_spec)) + for task_type in [_TaskType.CHIEF, _TaskType.WORKER]: + for task_id in range(len(cluster_spec.as_dict().get(task_type, []))): + t = threading.Thread( + target=_run_single_worker, + args=(worker_fn, strategy, cluster_spec, task_type, task_id, + session_config), + kwargs={ + "rpc_layer": rpc_layer, + "worker_barrier": worker_barrier, + "coord": coord, + }) + t.start() + threads.append(t) + + if eval_thread: + # TODO(yuefengz): is it necessary to join eval thread? + threads_to_join = threads + [eval_thread] + else: + threads_to_join = threads + coord.join(threads_to_join) + + # TODO(yuefengz): we probably want to return results from all workers? + return None + + +def _run_in_graph_client(worker_fn, strategy, eval_fn, eval_strategy, + cluster_spec, session_config, rpc_layer): + """Runs a standalone client for in-graph replication.""" + coord = coordinator.Coordinator() + eval_thread = None + if _TaskType.EVALUATOR in cluster_spec.jobs: + eval_thread = threading.Thread( + target=_run_single_worker, + args=(eval_fn, eval_strategy, cluster_spec, _TaskType.EVALUATOR, 0, + session_config), + kwargs={ + "rpc_layer": rpc_layer, + "coord": coord, + }) + eval_thread.start() + + worker_result = _run_single_worker( + worker_fn, + strategy, + cluster_spec, + None, + None, + session_config, + rpc_layer=rpc_layer, + coord=coord) + + if eval_thread: + coord.join([eval_thread]) + + return worker_result + + +def _configure_session_config_for_std_servers( + strategy, eval_strategy, session_config, cluster_spec, task_type, task_id): + # pylint: disable=g-doc-args + """Call strategy's `configure` to mutate the session_config. + + The session_config is currently needed as default config for a TensorFlow + server. In the future, we should be able to remove this method and only pass + the session config to a client session. + """ + if task_type == _TaskType.EVALUATOR: + if eval_strategy: + eval_strategy.configure(session_config=session_config) + else: + # The strategy may be shared in standalone client mode. + strategy = copy.deepcopy(strategy) + strategy.configure( + session_config=session_config, + cluster_spec=cluster_spec, + task_type=task_type, + task_id=task_id) + # Remove the device filters specific to the strategy, so that the + # TensorFlow server brought up with one strategy can be used by other + # strategies. The device filters can be set in the client side as well. + del session_config.device_filters[:] + + +def run_standard_tensorflow_server(session_config=None): + """Starts a standard TensorFlow server. + + This method parses configurations from "TF_CONFIG" environment variable and + starts a TensorFlow server. The "TF_CONFIG" is typically a json string and + must have information of the cluster and the role of the server in the + cluster. One example is: + + TF_CONFIG='{ + "cluster": { + "worker": ["host1:2222", "host2:2222", "host3:2222"], + "ps": ["host4:2222", "host5:2222"] + }, + "task": {"type": "worker", "index": 1} + }' + + This "TF_CONFIG" specifies there are 3 workers and 2 ps tasks in the cluster + and the current role is worker 1. + + Valid task types are "chief", "worker", "ps" and "evaluator" and you can have + at most one "chief" and at most one "evaluator". + + An optional key-value can be specified is "rpc_layer". The default value is + "grpc". + + Args: + session_config: an optional `tf.compat.v1.ConfigProto` object. Users can + pass in the session config object to configure server-local devices. + + Returns: + a `tf.distribute.Server` object which has already been started. + + Raises: + ValueError: if the "TF_CONFIG" environment is not complete. + """ + tf_config = json.loads(os.environ.get("TF_CONFIG", "{}")) + if "cluster" not in tf_config: + raise ValueError("\"cluster\" is not found in TF_CONFIG.") + cluster_spec = multi_worker_util.normalize_cluster_spec(tf_config["cluster"]) + if "task" not in tf_config: + raise ValueError("\"task\" is not found in TF_CONFIG.") + task_env = tf_config["task"] + if "type" not in task_env: + raise ValueError( + "\"task_type\" is not found in the `task` part of TF_CONFIG.") + task_type = task_env["type"] + task_id = int(task_env.get("index", 0)) + + rpc_layer = tf_config.get("rpc_layer", "grpc") + + session_config = session_config or config_pb2.ConfigProto() + # Set the collective group leader for collective ops to initialize collective + # ops when server starts. + if "chief" in cluster_spec.jobs: + session_config.experimental.collective_group_leader = ( + "/job:chief/replica:0/task:0") + else: + if "worker" not in cluster_spec.jobs: + raise ValueError( + "You must have `chief` or `worker` jobs in the `cluster_spec`.") + session_config.experimental.collective_group_leader = ( + "/job:worker/replica:0/task:0") + + server = _run_std_server( + cluster_spec=cluster_spec, + task_type=task_type, + task_id=task_id, + session_config=session_config, + rpc_layer=rpc_layer) + server.start() + return server + + +# TODO(yuefengz): propagate cluster_spec in the STANDALONE_CLIENT mode. +# TODO(yuefengz): we may need a smart way to figure out whether the current task +# is the special task when we support cluster_spec propagation. +def run_distribute_coordinator(worker_fn, + strategy, + eval_fn=None, + eval_strategy=None, + mode=CoordinatorMode.STANDALONE_CLIENT, + cluster_spec=None, + task_type=None, + task_id=None, + session_config=None, + rpc_layer="grpc"): + """Runs the coordinator for distributed TensorFlow. + + This function runs a split coordinator for distributed TensorFlow in its + default mode, i.e the STANDALONE_CLIENT mode. Given a `cluster_spec` + specifying server addresses and their roles in a cluster, this coordinator + will figure out how to set them up, give the underlying function the right + targets for master sessions via a scope object and coordinate their training. + The cluster consisting of standard servers needs to be brought up either with + the standard server binary or with a binary running distribute coordinator + with `task_type` set to non-client type which will then turn into standard + servers. + + In addition to be the distribute coordinator, this is also the source of + configurations for each job in the distributed training. As there are multiple + ways to configure a distributed TensorFlow cluster, its context object + provides these configurations so that users or higher-level APIs don't have to + figure out the configuration for each job by themselves. + + In the between-graph replicated training, this coordinator will create + multiple threads and each calls the `worker_fn` which is supposed to create + its own graph and connect to one worker master given by its context object. In + the in-graph replicated training, it has only one thread calling this + `worker_fn`. + + Another mode is the INDEPENDENT_WORKER mode where each server runs a + distribute coordinator which will start a standard server and optionally runs + `worker_fn` depending whether it is between-graph training or in-graph + replicated training. + + The `strategy` object is expected to be a DistributionStrategy object which + has implemented methods needed by distributed coordinator such as + `configure(session_config, cluster_spec, task_type, task_id)` which configures + the strategy object for a specific task and `experimental_should_init` + property which instructs the distribute coordinator whether to run init ops + for a task. The distribute coordinator will make a copy of the `strategy` + object, call its `configure` method and pass it to `worker_fn` as an argument. + + The `worker_fn` defines the training logic and is called under its own + worker context which can be accessed to via `get_current_worker_context`. A + worker context provides access to configurations for each task, e.g. the + task_type, task_id, master target and so on. Since `worker_fn` will be called + in a thread and possibly multiple times, caller should be careful when it + accesses global data. For example, it is unsafe to define flags in a + `worker_fn` or to define different environment variables for different + `worker_fn`s. + + The `worker_fn` for the between-graph replication is defined as if there is + only one worker corresponding to the `worker_fn` and possibly ps jobs. For + example, when training with parameter servers, it assigns variables to + parameter servers and all other operations to that worker. In the in-graph + replication case, the `worker_fn` has to define operations for all worker + jobs. Using a distribution strategy can simplify the `worker_fn` by not having + to worry about the replication and device assignment of variables and + operations. + + This method is intended to be invoked by high-level APIs so that users don't + have to explicitly call it to run this coordinator. For those who don't use + high-level APIs, to change a program to use this coordinator, wrap everything + in a the program after global data definitions such as commandline flag + definition into the `worker_fn` and get task-specific configurations from + the worker context. + + The `cluster_spec` can be either passed by the argument or parsed from the + "TF_CONFIG" environment variable. Example of a TF_CONFIG: + ``` + cluster = {'chief': ['host0:2222'], + 'ps': ['host1:2222', 'host2:2222'], + 'worker': ['host3:2222', 'host4:2222', 'host5:2222']} + os.environ['TF_CONFIG'] = json.dumps({'cluster': cluster}) + ``` + + If `cluster_spec` is not given in any format, it becomes local training and + this coordinator will connect to a local session. + + For evaluation, if "evaluator" exists in the cluster_spec, a separate thread + will be created to call `eval_fn` with its `task_type` set to "evaluator". If + `eval_fn` is not defined, fall back to `worker_fn`. This implies that + evaluation will be done on a single machine if there is an "evaluator" task. + If "evaluator" doesn't exist in the cluster_spec, it entirely depends on the + `worker_fn` for how to do evaluation. + + Args: + worker_fn: the function to be called. The function should accept a + `strategy` object and will be given access to a context object via a + context manager scope. + strategy: a DistributionStrategy object specifying whether it should + run between-graph replicated training or not, whether to run init ops, + etc. This object will also be configured given `session_config`, + `cluster_spec`, `task_type` and `task_id`. + eval_fn: optional function for "evaluator" task. If `eval_fn` is not passed + in but a "evaluator" task is found in the `cluster_spec`, the `worker_fn` + will be used for this task. + eval_strategy: optional DistributionStrategy object for "evaluator" task. + mode: in which mode this distribute coordinator runs. + cluster_spec: a dict, ClusterDef or ClusterSpec specifying servers and roles + in a cluster. If not set or empty, fall back to local training. + task_type: the current task type, optional if this is a client. + task_id: the current task id, optional if this is a client. + session_config: an optional `tf.compat.v1.ConfigProto` object which will be + passed to `strategy`'s `configure` method and used to create a session. + rpc_layer: optional string, the protocol for RPC, e.g. "grpc". + + Raises: + ValueError: if `cluster_spec` is supplied but not a dict or a ClusterDef or + a ClusterSpec. + + Returns: + In the client job, return the value returned by `worker_fn` if + it is in-graph replication or INDEPENDENT_WORKER mode; return None + otherwise. + """ + tf_config = json.loads(os.environ.get("TF_CONFIG", "{}")) + rpc_layer = tf_config.get("rpc_layer", rpc_layer) + environment = tf_config.get("environment", None) + + if not cluster_spec: + cluster_spec = tf_config.get("cluster", {}) + task_env = tf_config.get("task", {}) + if task_env: + task_type = task_env.get("type", task_type) + task_id = int(task_env.get("index", task_id)) + + if cluster_spec: + # TODO(yuefengz): validate cluster_spec. + cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec) + elif hasattr(strategy.extended, "_cluster_resolver"): + cluster_resolver = strategy.extended._cluster_resolver # pylint: disable=protected-access + task_type = cluster_resolver.task_type + task_id = cluster_resolver.task_id + rpc_layer = cluster_resolver.rpc_layer or rpc_layer + environment = cluster_resolver.environment + cluster_spec = cluster_resolver.cluster_spec() + + # Setting the session config is necessary for some strategies such as + # CollectiveAllReduceStrategy. + session_config = session_config or config_pb2.ConfigProto( + allow_soft_placement=True) + + if cluster_spec: + logging.info( + "Running Distribute Coordinator with mode = %r, cluster_spec = %r, " + "task_type = %r, task_id = %r, environment = %r, rpc_layer = %r", mode, + cluster_spec.as_dict(), task_type, task_id, environment, rpc_layer) + + if not cluster_spec: + # `mode` is ignored in the local case. + logging.info("Running local Distribute Coordinator.") + _run_single_worker(worker_fn, strategy, None, None, None, session_config, + rpc_layer) + if eval_fn: + _run_single_worker(eval_fn, eval_strategy, None, None, None, + session_config, rpc_layer) + else: + logging.warning("Skipped evaluation since `eval_fn` is not passed in.") + elif mode == CoordinatorMode.STANDALONE_CLIENT: + if not eval_fn: + logging.warning("`eval_fn` is not passed in. The `worker_fn` will be " + "used if an \"evaluator\" task exists in the cluster.") + eval_fn = eval_fn or worker_fn + if not eval_strategy: + logging.warning("`eval_strategy` is not passed in. No distribution " + "strategy will be used for evaluation.") + + # The client must know the cluster but servers in the cluster don't have to + # know the client. + if task_type in [_TaskType.CLIENT, None]: + if strategy.extended.experimental_between_graph: + return _run_between_graph_client(worker_fn, strategy, eval_fn, + eval_strategy, cluster_spec, + session_config, rpc_layer) + else: + return _run_in_graph_client(worker_fn, strategy, eval_fn, eval_strategy, + cluster_spec, session_config, rpc_layer) + else: + # If not a client job, run the standard server. + _configure_session_config_for_std_servers(strategy, eval_strategy, + session_config, cluster_spec, + task_type, task_id) + server = _run_std_server( + cluster_spec=cluster_spec, + task_type=task_type, + task_id=task_id, + session_config=session_config, + rpc_layer=rpc_layer, + environment=environment) + server.join() + else: + if mode != CoordinatorMode.INDEPENDENT_WORKER: + raise ValueError("Unexpected coordinator mode: %r" % mode) + + if not eval_fn: + logging.warning("`eval_fn` is not passed in. The `worker_fn` will be " + "used if an \"evaluator\" task exists in the cluster.") + eval_fn = eval_fn or worker_fn + if not eval_strategy: + logging.warning("`eval_strategy` is not passed in. No distribution " + "strategy will be used for evaluation.") + + # Every one starts a standard server, get session config from `configure` + # method. + _configure_session_config_for_std_servers(strategy, eval_strategy, + session_config, cluster_spec, + task_type, task_id) + + if (task_type != _TaskType.EVALUATOR and + not getattr(strategy.extended, "_std_server_started", False)): + # Right now, with eager mode, context is configured with a std server at + # the very beginning while with graph mode the std server is started when + # distribute coordinator is called. We should consolidate these two paths. + server = _run_std_server( + cluster_spec=cluster_spec, + task_type=task_type, + task_id=task_id, + session_config=session_config, + rpc_layer=rpc_layer, + environment=environment) + if task_type in [_TaskType.CHIEF, _TaskType.WORKER]: + if strategy.extended.experimental_between_graph: + # All jobs run `worker_fn` if between-graph. + return _run_single_worker(worker_fn, strategy, cluster_spec, task_type, + task_id, session_config, rpc_layer) + else: + # Only one node runs `worker_fn` if in-graph. + context = _WorkerContext(strategy, cluster_spec, task_type, task_id) + if context.is_chief: + return _run_single_worker(worker_fn, strategy, cluster_spec, None, + None, session_config, rpc_layer) + else: + server.join() + elif task_type == _TaskType.EVALUATOR: + return _run_single_worker(eval_fn, eval_strategy, cluster_spec, task_type, + task_id, session_config, rpc_layer) + else: + if task_type != _TaskType.PS: + raise ValueError("Unexpected task_type: %r" % task_type) + server.join() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_coordinator_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_coordinator_context.py new file mode 100644 index 0000000000000000000000000000000000000000..15c0cd644e50ac23604940605dcfe052407b235b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_coordinator_context.py @@ -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. +# ============================================================================== +"""The context retrieval method for distribute coordinator.""" + +import threading + +_worker_context = threading.local() + + +def get_current_worker_context(): + """Returns the current task context.""" + try: + return _worker_context.current + except AttributeError: + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..55e7fb57e1f3e89b30eeea66f3de9ccd420bd8c0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_lib.py @@ -0,0 +1,4241 @@ +# 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. +# ============================================================================== +# pylint: disable=line-too-long +"""Library for running a computation across multiple devices. + +The intent of this library is that you can write an algorithm in a stylized way +and it will be usable with a variety of different `tf.distribute.Strategy` +implementations. Each descendant will implement a different strategy for +distributing the algorithm across multiple devices/machines. Furthermore, these +changes can be hidden inside the specific layers and other library classes that +need special treatment to run in a distributed setting, so that most users' +model definition code can run unchanged. The `tf.distribute.Strategy` API works +the same way with eager and graph execution. + +*Guides* + +* [TensorFlow v2.x](https://www.tensorflow.org/guide/distributed_training) +* [TensorFlow +v1.x](https://github.com/tensorflow/docs/blob/master/site/en/r1/guide/distribute_strategy.ipynb) + +*Tutorials* + +* [Distributed Training +Tutorials](https://www.tensorflow.org/tutorials/distribute/) + + The tutorials cover how to use `tf.distribute.Strategy` to do distributed + training with native Keras APIs, custom training loops, + and Estimator APIs. They also cover how to save/load model when using + `tf.distribute.Strategy`. + +*Glossary* + +* _Data parallelism_ is where we run multiple copies of the model + on different slices of the input data. This is in contrast to + _model parallelism_ where we divide up a single copy of a model + across multiple devices. + Note: we only support data parallelism for now, but + hope to add support for model parallelism in the future. +* A _device_ is a CPU or accelerator (e.g. GPUs, TPUs) on some machine that + TensorFlow can run operations on (see e.g. `tf.device`). You may have multiple + devices on a single machine, or be connected to devices on multiple + machines. Devices used to run computations are called _worker devices_. + Devices used to store variables are _parameter devices_. For some strategies, + such as `tf.distribute.MirroredStrategy`, the worker and parameter devices + will be the same (see mirrored variables below). For others they will be + different. For example, `tf.distribute.experimental.CentralStorageStrategy` + puts the variables on a single device (which may be a worker device or may be + the CPU), and `tf.distribute.experimental.ParameterServerStrategy` puts the + variables on separate machines called _parameter servers_ (see below). +* A _replica_ is one copy of the model, running on one slice of the + input data. Right now each replica is executed on its own + worker device, but once we add support for model parallelism + a replica may span multiple worker devices. +* A _host_ is the CPU device on a machine with worker devices, typically + used for running input pipelines. +* A _worker_ is defined to be the physical machine(s) containing the physical + devices (e.g. GPUs, TPUs) on which the replicated computation is executed. A + worker may contain one or more replicas, but contains at least one + replica. Typically one worker will correspond to one machine, but in the case + of very large models with model parallelism, one worker may span multiple + machines. We typically run one input pipeline per worker, feeding all the + replicas on that worker. +* _Synchronous_, or more commonly _sync_, training is where the updates from + each replica are aggregated together before updating the model variables. This + is in contrast to _asynchronous_, or _async_ training, where each replica + updates the model variables independently. You may also have replicas + partitioned into groups which are in sync within each group but async between + groups. +* _Parameter servers_: These are machines that hold a single copy of + parameters/variables, used by some strategies (right now just + `tf.distribute.experimental.ParameterServerStrategy`). All replicas that want + to operate on a variable retrieve it at the beginning of a step and send an + update to be applied at the end of the step. These can in principle support + either sync or async training, but right now we only have support for async + training with parameter servers. Compare to + `tf.distribute.experimental.CentralStorageStrategy`, which puts all variables + on a single device on the same machine (and does sync training), and + `tf.distribute.MirroredStrategy`, which mirrors variables to multiple devices + (see below). + +* _Replica context_ vs. _Cross-replica context_ vs _Update context_ + + A _replica context_ applies + when you execute the computation function that was called with `strategy.run`. + Conceptually, you're in replica context when executing the computation + function that is being replicated. + + An _update context_ is entered in a `tf.distribute.StrategyExtended.update` + call. + + An _cross-replica context_ is entered when you enter a `strategy.scope`. This + is useful for calling `tf.distribute.Strategy` methods which operate across + the replicas (like `reduce_to()`). By default you start in a _replica context_ + (the "default single _replica context_") and then some methods can switch you + back and forth. + +* _Distributed value_: Distributed value is represented by the base class + `tf.distribute.DistributedValues`. `tf.distribute.DistributedValues` is useful + to represent values on multiple devices, and it contains a map from replica id + to values. Two representative types of `tf.distribute.DistributedValues` + are `tf.types.experimental.PerReplica` and `tf.types.experimental.Mirrored` + values. + + `PerReplica` values exist on the worker devices, with a different value for + each replica. They are produced by iterating through a distributed dataset + returned by `tf.distribute.Strategy.experimental_distribute_dataset` and + `tf.distribute.Strategy.distribute_datasets_from_function`. They are also the + typical result returned by `tf.distribute.Strategy.run`. + + `Mirrored` values are like `PerReplica` values, except we know that the value + on all replicas are the same. `Mirrored` values are kept synchronized by the + distribution strategy in use, while `PerReplica` values are left + unsynchronized. `Mirrored` values typically represent model weights. We can + safely read a `Mirrored` value in a cross-replica context by using the value + on any replica, while PerReplica values can only be read within a replica + context. + +* _Unwrapping_ and _merging_: Consider calling a function `fn` on multiple + replicas, like `strategy.run(fn, args=[w])` with an + argument `w` that is a `tf.distribute.DistributedValues`. This means `w` will + have a map taking replica id `0` to `w0`, replica id `1` to `w1`, etc. + `strategy.run()` unwraps `w` before calling `fn`, so it calls `fn(w0)` on + device `d0`, `fn(w1)` on device `d1`, etc. It then merges the return + values from `fn()`, which leads to one common object if the returned values + are the same object from every replica, or a `DistributedValues` object + otherwise. + +* _Reductions_ and _all-reduce_: A _reduction_ is a method of aggregating + multiple values into one value, like "sum" or "mean". If a strategy is doing + sync training, we will perform a reduction on the gradients to a parameter + from all replicas before applying the update. _All-reduce_ is an algorithm for + performing a reduction on values from multiple devices and making the result + available on all of those devices. + +* _Mirrored variables_: These are variables that are created on multiple + devices, where we keep the variables in sync by applying the same + updates to every copy. Mirrored variables are created with + `tf.Variable(...synchronization=tf.VariableSynchronization.ON_WRITE...)`. + Normally they are only used in synchronous training. + +* _SyncOnRead variables_ + + _SyncOnRead variables_ are created by + `tf.Variable(...synchronization=tf.VariableSynchronization.ON_READ...)`, and + they are created on multiple devices. In replica context, each + component variable on the local replica can perform reads and writes without + synchronization with each other. When the + _SyncOnRead variable_ is read in cross-replica context, the values from + component variables are aggregated and returned. + + _SyncOnRead variables_ bring a lot of custom configuration difficulty to the + underlying logic, so we do not encourage users to instantiate and use + _SyncOnRead variable_ on their own. We have mainly used _SyncOnRead + variables_ for use cases such as batch norm and metrics. For performance + reasons, we often don't need to keep these statistics in sync every step and + they can be accumulated on each replica independently. The only time we want + to sync them is reporting or checkpointing, which typically happens in + cross-replica context. _SyncOnRead variables_ are also often used by advanced + users who want to control when variable values are aggregated. For example, + users sometimes want to maintain gradients independently on each replica for a + couple of steps without aggregation. + +* _Distribute-aware layers_ + + Layers are generally called in a replica context, except when defining a + Keras functional model. `tf.distribute.in_cross_replica_context` will let you + determine which case you are in. If in a replica context, + the `tf.distribute.get_replica_context` function will return the default + replica context outside a strategy scope, `None` within a strategy scope, and + a `tf.distribute.ReplicaContext` object inside a strategy scope and within a + `tf.distribute.Strategy.run` function. The `ReplicaContext` object has an + `all_reduce` method for aggregating across all replicas. + + +Note that we provide a default version of `tf.distribute.Strategy` that is +used when no other strategy is in scope, that provides the same API with +reasonable default behavior. +""" +# pylint: enable=line-too-long + +import collections +import contextlib +import copy +import enum # pylint: disable=g-bad-import-order +import functools +import threading +import weakref + +import six + +from tensorflow.python import tf2 +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.distribute import collective_util +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import numpy_dataset +from tensorflow.python.distribute import reduce_util +from tensorflow.python.eager import context as eager_context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import monitoring +from tensorflow.python.eager import tape +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import custom_gradient +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import ref_variable +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.platform import tf_logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import distribute as ds_types +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +# ------------------------------------------------------------------------------ +# Context tracking whether in a strategy.update() or .update_non_slot() call. + + +_update_replica_id = threading.local() + + +def get_update_replica_id(): + """Get the current device if in a `tf.distribute.Strategy.update()` call.""" + try: + return _update_replica_id.current + except AttributeError: + return None + + +class UpdateContext(object): + """Context manager when you are in `update()` or `update_non_slot()`.""" + + __slots__ = ["_replica_id", "_old_replica_id"] + + def __init__(self, replica_id): + self._replica_id = replica_id + self._old_replica_id = None + + def __enter__(self): + self._old_replica_id = get_update_replica_id() + _update_replica_id.current = self._replica_id + + def __exit__(self, exception_type, exception_value, traceback): + del exception_type, exception_value, traceback + _update_replica_id.current = self._old_replica_id + + +# ------------------------------------------------------------------------------ +# Internal API for validating the current thread mode + + +def _require_cross_replica_or_default_context_extended(extended, + error_message=None): + """Verify in cross-replica context.""" + context = _get_per_thread_mode() + cross_replica = context.cross_replica_context + if cross_replica is not None and cross_replica.extended is extended: + return + if context is _get_default_replica_mode(): + return + strategy = extended._container_strategy() # pylint: disable=protected-access + # We have an error to report, figure out the right message. + if context.strategy is not strategy: + _wrong_strategy_scope(strategy, context) + assert cross_replica is None + if not error_message: + error_message = ("Method requires being in cross-replica context, use " + "get_replica_context().merge_call()") + raise RuntimeError(error_message) + + +def _wrong_strategy_scope(strategy, context): + # Figure out the right error message. + if not has_strategy(): + raise RuntimeError( + 'Need to be inside "with strategy.scope()" for %s' % + (strategy,)) + else: + raise RuntimeError( + "Mixing different tf.distribute.Strategy objects: %s is not %s" % + (context.strategy, strategy)) + + +def require_replica_context(replica_ctx): + """Verify in `replica_ctx` replica context.""" + context = _get_per_thread_mode() + if context.replica_context is replica_ctx: return + # We have an error to report, figure out the right message. + if context.replica_context is None: + raise RuntimeError("Need to be inside `call_for_each_replica()`") + if context.strategy is replica_ctx.strategy: + # Two different ReplicaContexts with the same tf.distribute.Strategy. + raise RuntimeError("Mismatching ReplicaContext.") + raise RuntimeError( + "Mismatching tf.distribute.Strategy objects: %s is not %s." % + (context.strategy, replica_ctx.strategy)) + + +def _require_strategy_scope_strategy(strategy): + """Verify in a `strategy.scope()` in this thread.""" + context = _get_per_thread_mode() + if context.strategy is strategy: return + _wrong_strategy_scope(strategy, context) + + +def _require_strategy_scope_extended(extended): + """Verify in a `distribution_strategy.scope()` in this thread.""" + context = _get_per_thread_mode() + if context.strategy.extended is extended: return + # Report error. + strategy = extended._container_strategy() # pylint: disable=protected-access + _wrong_strategy_scope(strategy, context) + + +_creating_default_strategy_singleton = False + +# ------------------------------------------------------------------------------ +# Internal API for setting the current thread mode as being either in a +# replica or cross-replica context for a particular tf.distribute.Strategy. + + +class _ThreadMode(object): + + def __init__(self, dist, cross, replica): + self.strategy = dist + self.cross_replica_context = cross + self.replica_context = replica + + +class _CrossReplicaThreadMode(_ThreadMode): + + def __init__(self, strategy): + _ThreadMode.__init__(self, strategy, strategy, None) + + +class _InReplicaThreadMode(_ThreadMode): + + def __init__(self, replica_ctx): + _ThreadMode.__init__(self, replica_ctx.strategy, None, replica_ctx) + + +def _push_per_thread_mode(context): + ops.get_default_graph()._distribution_strategy_stack.append(context) # pylint: disable=protected-access + + +def _pop_per_thread_mode(): + ops.get_default_graph()._distribution_strategy_stack.pop(-1) # pylint: disable=protected-access + + +class _DefaultReplicaThreadMode(_ThreadMode): + """Type of default value returned by `_get_per_thread_mode()`. + + Used when the thread-local stack is empty. + """ + + def __init__(self): + _ThreadMode.__init__(self, _get_default_strategy(), None, + _get_default_replica_context()) + + +def _get_per_thread_mode(): + try: + return ops.get_default_graph()._distribution_strategy_stack[-1] # pylint: disable=protected-access + except (AttributeError, IndexError): + return _get_default_replica_mode() + + +_variable_sync_on_read_context = threading.local() + + +@tf_export("__internal__.distribute.variable_sync_on_read_context", v1=[]) +@contextlib.contextmanager +def variable_sync_on_read_context(): + """A context that forces SyncOnReadVariable to aggregate upon reading. + + This context is useful if one wants to read the aggregated value out of a + SyncOnReadVariable in replica context. By default the aggregation is turned + off per the definition of SyncOnReadVariable. + + When reading a SyncOnReadVariable in cross-replica context, aggregation is + always turned on so there is no need for such context. + + By reading a SyncOnReadVariable, we mean: + 1. Convert the variable to a tensor using `convert_to_tensor`. + 2. Calling `variable.value()` or `variable.read_value()`. + + Example usage: + + ``` + strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"]) + with strategy.scope(): + v = tf.Variable(1.0, synchronization=tf.VariableSynchronization.ON_READ, + aggregation=tf.VariableAggregation.SUM) + + def replica_fn(): + return v + 10.0 + + non_aggregated = strategy.run(replica_fn) + print(non_aggregated) # PerReplica: {0: 11.0, 1: 11.0} + + def replica_fn(): + with variable_sync_on_read_context(): + return v + 10.0 + + aggregated = strategy.run(replica_fn) + print(aggregated) # PerReplica: {0: 12.0, 1: 12.0} + ``` + + Yields: + Context manager for aggregating SyncOnReadVariable upon reading. + """ + try: + _variable_sync_on_read_context.entered = True + yield + finally: + _variable_sync_on_read_context.entered = False + + +def in_variable_sync_on_read_context(): + try: + return _variable_sync_on_read_context.entered + except AttributeError: + return False + +# ------------------------------------------------------------------------------ +# Public API for accessing the current thread mode + + +@tf_export("distribute.get_replica_context") +def get_replica_context(): + """Returns the current `tf.distribute.ReplicaContext` or `None`. + + Returns `None` if in a cross-replica context. + + Note that execution: + + 1. starts in the default (single-replica) replica context (this function + will return the default `ReplicaContext` object); + 2. switches to cross-replica context (in which case this will return + `None`) when entering a `with tf.distribute.Strategy.scope():` block; + 3. switches to a (non-default) replica context inside `strategy.run(fn, ...)`; + 4. if `fn` calls `get_replica_context().merge_call(merge_fn, ...)`, then + inside `merge_fn` you are back in the cross-replica context (and again + this function will return `None`). + + Most `tf.distribute.Strategy` methods may only be executed in + a cross-replica context, in a replica context you should use the + API of the `tf.distribute.ReplicaContext` object returned by this + method instead. + + ``` + assert tf.distribute.get_replica_context() is not None # default + with strategy.scope(): + assert tf.distribute.get_replica_context() is None + + def f(): + replica_context = tf.distribute.get_replica_context() # for strategy + assert replica_context is not None + tf.print("Replica id: ", replica_context.replica_id_in_sync_group, + " of ", replica_context.num_replicas_in_sync) + + strategy.run(f) + ``` + + Returns: + The current `tf.distribute.ReplicaContext` object when in a replica context + scope, else `None`. + + Within a particular block, exactly one of these two things will be true: + + * `get_replica_context()` returns non-`None`, or + * `tf.distribute.is_cross_replica_context()` returns True. + """ + return _get_per_thread_mode().replica_context + + +def get_cross_replica_context(): + """Returns the current tf.distribute.Strategy if in a cross-replica context. + + DEPRECATED: Please use `in_cross_replica_context()` and + `get_strategy()` instead. + + Returns: + Returns the current `tf.distribute.Strategy` object in a cross-replica + context, or `None`. + + Exactly one of `get_replica_context()` and `get_cross_replica_context()` + will return `None` in a particular block. + """ + return _get_per_thread_mode().cross_replica_context + + +@tf_export("distribute.in_cross_replica_context") +def in_cross_replica_context(): + """Returns `True` if in a cross-replica context. + + See `tf.distribute.get_replica_context` for details. + + ``` + assert not tf.distribute.in_cross_replica_context() + with strategy.scope(): + assert tf.distribute.in_cross_replica_context() + + def f(): + assert not tf.distribute.in_cross_replica_context() + + strategy.run(f) + ``` + + Returns: + `True` if in a cross-replica context (`get_replica_context()` returns + `None`), or `False` if in a replica context (`get_replica_context()` returns + non-`None`). + """ + return _get_per_thread_mode().cross_replica_context is not None + + +@tf_export("distribute.get_strategy") +def get_strategy() -> "StrategyBase": + """Returns the current `tf.distribute.Strategy` object. + + Typically only used in a cross-replica context: + + ``` + if tf.distribute.in_cross_replica_context(): + strategy = tf.distribute.get_strategy() + ... + ``` + + Returns: + A `tf.distribute.Strategy` object. Inside a `with strategy.scope()` block, + it returns `strategy`, otherwise it returns the default (single-replica) + `tf.distribute.Strategy` object. + """ + return _get_per_thread_mode().strategy + + +@tf_export("distribute.has_strategy") +def has_strategy(): + """Return if there is a current non-default `tf.distribute.Strategy`. + + ``` + assert not tf.distribute.has_strategy() + with strategy.scope(): + assert tf.distribute.has_strategy() + ``` + + Returns: + True if inside a `with strategy.scope():`. + """ + return get_strategy() is not _get_default_strategy() + + +def get_strategy_and_replica_context(): + per_thread_mode = _get_per_thread_mode() + return (per_thread_mode.strategy, per_thread_mode.replica_context) + + +@tf_export("distribute.experimental_set_strategy") +def experimental_set_strategy(strategy): + """Set a `tf.distribute.Strategy` as current without `with strategy.scope()`. + + ``` + tf.distribute.experimental_set_strategy(strategy1) + f() + tf.distribute.experimental_set_strategy(strategy2) + g() + tf.distribute.experimental_set_strategy(None) + h() + ``` + + is equivalent to: + + ``` + with strategy1.scope(): + f() + with strategy2.scope(): + g() + h() + ``` + + In general, you should use the `with strategy.scope():` API, but this + alternative may be convenient in notebooks where you would have to put + each cell in a `with strategy.scope():` block. + + Note: This should only be called outside of any TensorFlow scope to + avoid improper nesting. + + Args: + strategy: A `tf.distribute.Strategy` object or None. + + Raises: + RuntimeError: If called inside a `with strategy.scope():`. + """ + old_scope = ops.get_default_graph()._global_distribute_strategy_scope # pylint: disable=protected-access + if old_scope is not None: + old_scope.__exit__(None, None, None) + ops.get_default_graph()._global_distribute_strategy_scope = None # pylint: disable=protected-access + if has_strategy(): + raise RuntimeError( + "Must not be called inside a `tf.distribute.Strategy` scope.") + if strategy is not None: + new_scope = strategy.scope() + new_scope.__enter__() + ops.get_default_graph()._global_distribute_strategy_scope = new_scope # pylint: disable=protected-access + + +# ------------------------------------------------------------------------------ +# Internal helpers. + + +@contextlib.contextmanager +def enter_or_assert_strategy(strategy): + if has_strategy(): + _assert_strategy(strategy) + yield + else: + with strategy.scope(): + yield + + +# ------------------------------------------------------------------------------ +# Defaults that are used when no tf.distribute.Strategy is explicitly created. +# We create them lazily in a function so that we can workaround the circular +# dependency on distribute_lib. See lazy loader at the top of this file. + +_defaults = { + "strategy": None, + "replica_context": None, + "replica_mode": None +} +# Note: These need to be different locks since _get_default_replica_context +# calls _get_default_strategy inside its lock, and them using the same lock +# can lead to deadlock. +_default_strategy_lock = threading.Lock() +_default_replica_context_lock = threading.Lock() +_default_replica_mode_lock = threading.Lock() + + +def _assert_strategy(strategy): + if not has_strategy(): + raise RuntimeError('Need to be inside "with strategy.scope()" for %s' % + (strategy,)) + current_strategy = get_strategy() + if current_strategy is not strategy: + raise RuntimeError( + "Mixing different tf.distribute.Strategy objects: %s is not %s" % + (current_strategy, strategy)) + + +def _get_default_strategy(): + if _defaults["strategy"] is None: + # Avoid race condition causing two defaults to be created + with _default_strategy_lock: + if _defaults["strategy"] is None: + # pylint: disable=protected-access + # Make sure distribute_lib module is loaded by accessing some member. + global _creating_default_strategy_singleton + _creating_default_strategy_singleton = True + if tf2.enabled(): + _defaults["strategy"] = _DefaultDistributionStrategy() + else: + _defaults["strategy"] = ( + _DefaultDistributionStrategyV1()) + _creating_default_strategy_singleton = False + # pylint: enable=protected-access + return _defaults["strategy"] + + +def _get_default_replica_context(): + if _defaults["replica_context"] is None: + # Avoid race condition causing two defaults to be created + with _default_replica_context_lock: + if _defaults["replica_context"] is None: + # pylint: disable=protected-access + _defaults["replica_context"] = _DefaultReplicaContext( + _get_default_strategy(), replica_id_in_sync_group=0) + # pylint: enable=protected-access + return _defaults["replica_context"] + + +def _get_default_replica_mode(): + if _defaults["replica_mode"] is None: + # Avoid race condition causing two defaults to be created + with _default_replica_mode_lock: + if _defaults["replica_mode"] is None: + _defaults["replica_mode"] = _DefaultReplicaThreadMode() + return _defaults["replica_mode"] + + +# Aliases for compatibility with old names. +get_distribution_strategy = get_strategy +has_distribution_strategy = has_strategy + + +# ------------------------------------------------------------------------------ +# Internal context managers used to implement the DistributionStrategy +# base class + + +class _CurrentDistributionContext(object): + """Context manager setting the current `tf.distribute.Strategy`. + + Also: overrides the variable creator and optionally the current device. + """ + + def __init__( + self, + strategy, + var_creator_scope, + var_scope=None, + resource_creator_scope=None, + default_device_scope=None, + ): + self._context = _CrossReplicaThreadMode( # pylint: disable=protected-access + strategy) + self._var_creator_scope = var_creator_scope + self._var_scope = var_scope + self._resource_creator_scope = resource_creator_scope + if default_device_scope: + self._device_scope = default_device_scope + else: + self._device_scope = None + self._same_scope_again_count = 0 + + def __enter__(self): + # Allow this scope to be entered if this strategy is already in scope. + if has_strategy(): + _require_cross_replica_or_default_context_extended( + self._context.strategy.extended) + self._same_scope_again_count += 1 + else: + _push_per_thread_mode(self._context) + if self._var_scope: + self._var_scope.__enter__() + self._var_creator_scope.__enter__() + if self._resource_creator_scope: + nest.map_structure(lambda scope: scope.__enter__(), + self._resource_creator_scope) + if self._device_scope: + self._device_scope.__enter__() + return self._context.strategy + + def __exit__(self, exception_type, exception_value, traceback): + if hasattr(self._context.strategy.extended, "_lazy_variable_tracker"): + self._context.strategy.extended._lazy_variable_tracker.initialize_all() + + if self._same_scope_again_count > 0: + self._same_scope_again_count -= 1 + return + if self._device_scope: + try: + self._device_scope.__exit__(exception_type, exception_value, traceback) + except RuntimeError as e: + six.raise_from( + RuntimeError("Device scope nesting error: move call to " + "tf.distribute.set_strategy() out of `with` scope."), + e) + + try: + self._var_creator_scope.__exit__( + exception_type, exception_value, traceback) + except RuntimeError as e: + six.raise_from( + RuntimeError("Variable creator scope nesting error: move call to " + "tf.distribute.set_strategy() out of `with` scope."), + e) + + if self._resource_creator_scope: + try: + if isinstance(self._resource_creator_scope, list): + reversed_resource_creator_scope = self._resource_creator_scope[::-1] + nest.map_structure( + lambda scope: scope.__exit__(exception_type, exception_value, # pylint:disable=g-long-lambda + traceback), + reversed_resource_creator_scope) + + else: + self._resource_creator_scope.__exit__(exception_type, exception_value, + traceback) + except RuntimeError as e: + six.raise_from( + RuntimeError("Resource creator scope nesting error: move call " + "to tf.distribute.set_strategy() out of `with` " + "scope."), e) + + if self._var_scope: + try: + self._var_scope.__exit__(exception_type, exception_value, traceback) + except RuntimeError as e: + six.raise_from( + RuntimeError("Variable scope nesting error: move call to " + "tf.distribute.set_strategy() out of `with` scope."), + e) + _pop_per_thread_mode() + + +# TODO(yuefengz): add more replication modes. +@tf_export("distribute.InputReplicationMode") +class InputReplicationMode(enum.Enum): + """Replication mode for input function. + + * `PER_WORKER`: The input function will be called on each worker + independently, creating as many input pipelines as number of workers. + Replicas will dequeue from the local Dataset on their worker. + `tf.distribute.Strategy` doesn't manage any state sharing between such + separate input pipelines. + * `PER_REPLICA`: The input function will be called on each replica separately. + `tf.distribute.Strategy` doesn't manage any state sharing between such + separate input pipelines. + """ + PER_WORKER = "PER_WORKER" + PER_REPLICA = "PER_REPLICA" + + +@tf_export("distribute.InputContext") +class InputContext(object): + """A class wrapping information needed by an input function. + + This is a context class that is passed to the user's input function and + contains information about the compute replicas and input pipelines. The + number of compute replicas (in sync training) helps compute the local batch + size from the desired global batch size for each replica. The input pipeline + information can be used to return a different subset of the input in each + replica (for e.g. shard the input pipeline, use a different input + source etc). + """ + + __slots__ = [ + "_num_input_pipelines", "_input_pipeline_id", "_num_replicas_in_sync" + ] + + def __init__(self, + num_input_pipelines=1, + input_pipeline_id=0, + num_replicas_in_sync=1): + """Initializes an InputContext object. + + Args: + num_input_pipelines: the number of input pipelines in a cluster. + input_pipeline_id: the current input pipeline id, should be an int in + [0,`num_input_pipelines`). + num_replicas_in_sync: the number of replicas that are in sync. + """ + self._num_input_pipelines = num_input_pipelines + self._input_pipeline_id = input_pipeline_id + self._num_replicas_in_sync = num_replicas_in_sync + + @property + def num_replicas_in_sync(self): + """Returns the number of compute replicas in sync.""" + return self._num_replicas_in_sync + + @property + def input_pipeline_id(self): + """Returns the input pipeline ID.""" + return self._input_pipeline_id + + @property + def num_input_pipelines(self): + """Returns the number of input pipelines.""" + return self._num_input_pipelines + + def get_per_replica_batch_size(self, global_batch_size): + """Returns the per-replica batch size. + + Args: + global_batch_size: the global batch size which should be divisible by + `num_replicas_in_sync`. + + Returns: + the per-replica batch size. + + Raises: + ValueError: if `global_batch_size` not divisible by + `num_replicas_in_sync`. + """ + if global_batch_size % self._num_replicas_in_sync != 0: + raise ValueError("The `global_batch_size` %r is not divisible by " + "`num_replicas_in_sync` %r " % + (global_batch_size, self._num_replicas_in_sync)) + return global_batch_size // self._num_replicas_in_sync + + def __str__(self): + return "tf.distribute.InputContext(input pipeline id {}, total: {})".format( + self.input_pipeline_id, self.num_input_pipelines) + + +@tf_export("distribute.experimental.ValueContext", v1=[]) +class ValueContext(object): + """A class wrapping information needed by a distribute function. + + This is a context class that is passed to the `value_fn` in + `strategy.experimental_distribute_values_from_function` and contains + information about the compute replicas. The `num_replicas_in_sync` and + `replica_id` can be used to customize the value on each replica. + + Example usage: + + 1. Directly constructed. + + >>> def value_fn(context): + ... return context.replica_id_in_sync_group/context.num_replicas_in_sync + >>> context = tf.distribute.experimental.ValueContext( + ... replica_id_in_sync_group=2, num_replicas_in_sync=4) + >>> per_replica_value = value_fn(context) + >>> per_replica_value + 0.5 + + 2. Passed in by `experimental_distribute_values_from_function`. {: value=2} + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> def value_fn(value_context): + ... return value_context.num_replicas_in_sync + >>> distributed_values = ( + ... strategy.experimental_distribute_values_from_function( + ... value_fn)) + >>> local_result = strategy.experimental_local_results(distributed_values) + >>> local_result + (2, 2) + + """ + + __slots__ = ["_replica_id_in_sync_group", "_num_replicas_in_sync"] + + def __init__(self, + replica_id_in_sync_group=0, + num_replicas_in_sync=1): + """Initializes a ValueContext object. + + Args: + replica_id_in_sync_group: the current replica_id, should be an int in + [0,`num_replicas_in_sync`). + num_replicas_in_sync: the number of replicas that are in sync. + """ + self._replica_id_in_sync_group = replica_id_in_sync_group + self._num_replicas_in_sync = num_replicas_in_sync + + @property + def num_replicas_in_sync(self): + """Returns the number of compute replicas in sync.""" + return self._num_replicas_in_sync + + @property + def replica_id_in_sync_group(self): + """Returns the replica ID.""" + return self._replica_id_in_sync_group + + def __str__(self): + return (("tf.distribute.ValueContext(replica id {}, " + " total replicas in sync: ""{})") + .format(self.replica_id_in_sync_group, self.num_replicas_in_sync)) + + +@tf_export("distribute.RunOptions") +class RunOptions( + collections.namedtuple("RunOptions", [ + "experimental_enable_dynamic_batch_size", + "experimental_bucketizing_dynamic_shape", + "experimental_xla_options", + ])): + """Run options for `strategy.run`. + + This can be used to hold some strategy specific configs. + + Attributes: + experimental_enable_dynamic_batch_size: Boolean. Only applies to + TPUStrategy. Default to True. If True, TPUStrategy will enable dynamic + padder to support dynamic batch size for the inputs. Otherwise only static + shape inputs are allowed. + experimental_bucketizing_dynamic_shape: Boolean. Only applies to + TPUStrategy. Default to False. If True, TPUStrategy will automatic + bucketize inputs passed into `run` if the input shape is + dynamic. This is a performance optimization to reduce XLA recompilation, + which should not have impact on correctness. + experimental_xla_options: A `tf.tpu.XLAOptions` instance. Only applies to + TPUStrategy. Controls the XLA compiling options on TPUs. Default to None. + """ + + def __new__(cls, + experimental_enable_dynamic_batch_size=True, + experimental_bucketizing_dynamic_shape=False, + experimental_xla_options=None): + return super(RunOptions, + cls).__new__(cls, experimental_enable_dynamic_batch_size, + experimental_bucketizing_dynamic_shape, + experimental_xla_options) + + +@tf_export("distribute.InputOptions", v1=[]) +class InputOptions( + collections.namedtuple("InputOptions", [ + "experimental_fetch_to_device", + "experimental_replication_mode", + "experimental_place_dataset_on_device", + "experimental_per_replica_buffer_size", + ])): + """Run options for `experimental_distribute_dataset(s_from_function)`. + + This can be used to hold some strategy specific configs. + + ```python + # Setup TPUStrategy + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + tf.config.experimental_connect_to_cluster(resolver) + tf.tpu.experimental.initialize_tpu_system(resolver) + strategy = tf.distribute.TPUStrategy(resolver) + + dataset = tf.data.Dataset.range(16) + distributed_dataset_on_host = ( + strategy.experimental_distribute_dataset( + dataset, + tf.distribute.InputOptions( + experimental_replication_mode= + experimental_replication_mode.PER_WORKER, + experimental_place_dataset_on_device=False, + experimental_per_replica_buffer_size=1))) + ``` + + Attributes: + experimental_fetch_to_device: Boolean. If True, dataset + elements will be prefetched to accelerator device memory. When False, + dataset elements are prefetched to host device memory. Must be False when + using TPUEmbedding API. experimental_fetch_to_device can only be used + with experimental_replication_mode=PER_WORKER. Default behavior is same as + setting it to True. + experimental_replication_mode: Replication mode for the input function. + Currently, the InputReplicationMode.PER_REPLICA is only supported with + tf.distribute.MirroredStrategy. + experimental_distribute_datasets_from_function. + The default value is InputReplicationMode.PER_WORKER. + experimental_place_dataset_on_device: Boolean. Default to False. When True, + dataset will be placed on the device, otherwise it will remain on the + host. experimental_place_dataset_on_device=True can only be used with + experimental_replication_mode=PER_REPLICA + experimental_per_replica_buffer_size: Integer. Default to 1. Indicates the + prefetch buffer size in the replica device memory. Users can set it + to 0 to completely disable prefetching behavior, or a number greater than + 1 to enable larger buffer size. Note that this option is still + valid with `experimental_fetch_to_device=False`. + """ + + def __new__(cls, + experimental_fetch_to_device=None, + experimental_replication_mode=InputReplicationMode.PER_WORKER, + experimental_place_dataset_on_device=False, + experimental_per_replica_buffer_size=1): + if experimental_fetch_to_device is None: + experimental_fetch_to_device = True + + return super(InputOptions, + cls).__new__(cls, experimental_fetch_to_device, + experimental_replication_mode, + experimental_place_dataset_on_device, + experimental_per_replica_buffer_size) + +# ------------------------------------------------------------------------------ +# Base classes for all distribution strategies. + + +# Base class for v1 Strategy and v2 Strategy classes. For API's specific to +# v1/v2 Strategy, add to implementing classes of StrategyBase. +# pylint: disable=line-too-long +class StrategyBase(object): + """A state & compute distribution policy on a list of devices. + + See [the guide](https://www.tensorflow.org/guide/distributed_training) + for overview and examples. See `tf.distribute.StrategyExtended` and + [`tf.distribute`](https://www.tensorflow.org/api_docs/python/tf/distribute) + for a glossary of concepts mentioned on this page such as "per-replica", + _replica_, and _reduce_. + + In short: + + * To use it with Keras `compile`/`fit`, + [please + read](https://www.tensorflow.org/guide/distributed_training#using_tfdistributestrategy_with_keras). + * You may pass descendant of `tf.distribute.Strategy` to + `tf.estimator.RunConfig` to specify how a `tf.estimator.Estimator` + should distribute its computation. See + [guide](https://www.tensorflow.org/guide/distributed_training#using_tfdistributestrategy_with_estimator_limited_support). + * Otherwise, use `tf.distribute.Strategy.scope` to specify that a + strategy should be used when building an executing your model. + (This puts you in the "cross-replica context" for this strategy, which + means the strategy is put in control of things like variable placement.) + * If you are writing a custom training loop, you will need to call a few more + methods, + [see the + guide](https://www.tensorflow.org/guide/distributed_training#using_tfdistributestrategy_with_custom_training_loops): + + * Start by creating a `tf.data.Dataset` normally. + * Use `tf.distribute.Strategy.experimental_distribute_dataset` to convert + a `tf.data.Dataset` to something that produces "per-replica" values. + If you want to manually specify how the dataset should be partitioned + across replicas, use + `tf.distribute.Strategy.distribute_datasets_from_function` + instead. + * Use `tf.distribute.Strategy.run` to run a function + once per replica, taking values that may be "per-replica" (e.g. + from a `tf.distribute.DistributedDataset` object) and returning + "per-replica" values. + This function is executed in "replica context", which means each + operation is performed separately on each replica. + * Finally use a method (such as `tf.distribute.Strategy.reduce`) to + convert the resulting "per-replica" values into ordinary `Tensor`s. + + A custom training loop can be as simple as: + + ``` + with my_strategy.scope(): + @tf.function + def distribute_train_epoch(dataset): + def replica_fn(input): + # process input and return result + return result + + total_result = 0 + for x in dataset: + per_replica_result = my_strategy.run(replica_fn, args=(x,)) + total_result += my_strategy.reduce(tf.distribute.ReduceOp.SUM, + per_replica_result, axis=None) + return total_result + + dist_dataset = my_strategy.experimental_distribute_dataset(dataset) + for _ in range(EPOCHS): + train_result = distribute_train_epoch(dist_dataset) + ``` + + This takes an ordinary `dataset` and `replica_fn` and runs it + distributed using a particular `tf.distribute.Strategy` named + `my_strategy` above. Any variables created in `replica_fn` are created + using `my_strategy`'s policy, and library functions called by + `replica_fn` can use the `get_replica_context()` API to implement + distributed-specific behavior. + + You can use the `reduce` API to aggregate results across replicas and use + this as a return value from one iteration over a + `tf.distribute.DistributedDataset`. Or + you can use `tf.keras.metrics` (such as loss, accuracy, etc.) to + accumulate metrics across steps in a given epoch. + + See the + [custom training loop + tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training) + for a more detailed example. + + Note: `tf.distribute.Strategy` currently does not support TensorFlow's + partitioned variables (where a single variable is split across multiple + devices) at this time. + """ + # pylint: enable=line-too-long + + # TODO(josh11b): Partitioned computations, state; sharding + # TODO(josh11b): Model parallelism: "replicas" with multiple devices; shuffling + + def __init__(self, extended): + self._extended = extended + + # Flag that is used to indicate whether distribution strategy is used with + # Estimator. This is required for backward compatibility of loss scaling + # when using v1 optimizer with estimator. + self._scale_loss_for_estimator = False + + if not hasattr(extended, "_retrace_functions_for_each_device"): + # pylint: disable=protected-access + # `extended._retrace_functions_for_each_device` dictates + # whether the same function will be retraced when it is called on + # different devices. + try: + extended._retrace_functions_for_each_device = ( + len(extended.worker_devices) > 1) + distribution_strategy_replica_gauge.get_cell("num_replicas").set( + self.num_replicas_in_sync) + except: # pylint: disable=bare-except + # Default for the case where extended.worker_devices can't return + # a sensible value. + extended._retrace_functions_for_each_device = True + + # Below are the dicts of axis(int) -> `tf.function`. + self._mean_reduce_helper_fns = {} + self._reduce_sum_fns = {} + + # Whether this strategy is designed to work with `ClusterCoordinator`. + self._should_use_with_coordinator = False + + @property + def extended(self): + """`tf.distribute.StrategyExtended` with additional methods.""" + return self._extended + + @tf_contextlib.contextmanager + def _scale_loss_for_estimator_enabled(self): + """Scope which sets a flag used for scaling losses in optimizer. + + Yields: + `_scale_loss_for_estimator_enabled` is a context manager with a + side effect, but doesn't return a value. + """ + self._scale_loss_for_estimator = True + try: + yield + finally: + self._scale_loss_for_estimator = False + + # pylint: disable=line-too-long + def scope(self): + """Context manager to make the strategy current and distribute variables. + + This method returns a context manager, and is used as follows: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> # Variable created inside scope: + >>> with strategy.scope(): + ... mirrored_variable = tf.Variable(1.) + >>> mirrored_variable + MirroredVariable:{ + 0: , + 1: + } + >>> # Variable created outside scope: + >>> regular_variable = tf.Variable(1.) + >>> regular_variable + + + _What happens when Strategy.scope is entered?_ + + * `strategy` is installed in the global context as the "current" strategy. + Inside this scope, `tf.distribute.get_strategy()` will now return this + strategy. Outside this scope, it returns the default no-op strategy. + * Entering the scope also enters the "cross-replica context". See + `tf.distribute.StrategyExtended` for an explanation on cross-replica and + replica contexts. + * Variable creation inside `scope` is intercepted by the strategy. Each + strategy defines how it wants to affect the variable creation. Sync + strategies like `MirroredStrategy`, `TPUStrategy` and + `MultiWorkerMiroredStrategy` create variables replicated on each replica, + whereas `ParameterServerStrategy` creates variables on the parameter + servers. This is done using a custom `tf.variable_creator_scope`. + * In some strategies, a default device scope may also be entered: in + `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is + entered on each worker. + + Note: Entering a scope does not automatically distribute a computation, except + in the case of high level training framework like keras `model.fit`. If + you're not using `model.fit`, you + need to use `strategy.run` API to explicitly distribute that computation. + See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training). + + + _What should be in scope and what should be outside?_ + + There are a number of requirements on what needs to happen inside the scope. + However, in places where we have information about which strategy is in use, + we often enter the scope for the user, so they don't have to do it + explicitly (i.e. calling those either inside or outside the scope is OK). + + * Anything that creates variables that should be distributed variables + must be called in a `strategy.scope`. This can be accomplished either by + directly calling the variable creating function within the scope context, + or by relying on another API like `strategy.run` or `keras.Model.fit` to + automatically enter it for you. Any variable that is created outside scope + will not be distributed and may have performance implications. Some common + objects that create variables in TF are Models, Optimizers, Metrics. Such + objects should always be initialized in the scope, and any functions + that may lazily create variables (e.g., `Model.__call__()`, tracing a + `tf.function`, etc.) should similarly be called within scope. Another + source of variable creation can be a checkpoint restore - when variables + are created lazily. Note that any variable created inside a strategy + captures the strategy information. So reading and writing to these + variables outside the `strategy.scope` can also work seamlessly, without + the user having to enter the scope. + * Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which + require to be in a strategy's scope, enter the scope automatically, which + means when using those APIs you don't need to explicitly enter the scope + yourself. + * When a `tf.keras.Model` is created inside a `strategy.scope`, the Model + object captures the scope information. When high level training framework + methods such as `model.compile`, `model.fit`, etc. are then called, the + captured scope will be automatically entered, and the associated strategy + will be used to distribute the training etc. See a detailed example in + [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). + WARNING: Simply calling `model(..)` does not automatically enter the + captured scope -- only high level training framework APIs support this + behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` + and `model.save` can all be called inside or outside the scope. + * The following can be either inside or outside the scope: + * Creating the input datasets + * Defining `tf.function`s that represent your training step + * Saving APIs such as `tf.saved_model.save`. Loading creates variables, + so that should go inside the scope if you want to train the model in a + distributed way. + * Checkpoint saving. As mentioned above - `checkpoint.restore` may + sometimes need to be inside scope if it creates variables. + + Returns: + A context manager. + """ + return self._extended._scope(self) # pylint: disable=protected-access + # pylint: enable=line-too-long + + @doc_controls.do_not_doc_inheritable # DEPRECATED, moving to `extended` + @deprecated(None, "use extended.colocate_vars_with() instead.") + def colocate_vars_with(self, colocate_with_variable): + """DEPRECATED: use extended.colocate_vars_with() instead.""" + return self._extended.colocate_vars_with(colocate_with_variable) + + @doc_controls.do_not_generate_docs # DEPRECATED: TF 1.x only + def make_dataset_iterator(self, dataset): + """DEPRECATED TF 1.x ONLY.""" + return self._extended._make_dataset_iterator(dataset) # pylint: disable=protected-access + + @doc_controls.do_not_generate_docs # DEPRECATED: TF 1.x only + def make_input_fn_iterator(self, + input_fn, + replication_mode=InputReplicationMode.PER_WORKER): + """DEPRECATED TF 1.x ONLY.""" + if replication_mode != InputReplicationMode.PER_WORKER: + raise ValueError( + "Input replication mode not supported: %r" % replication_mode) + with self.scope(): + return self.extended._make_input_fn_iterator( # pylint: disable=protected-access + input_fn, replication_mode=replication_mode) + + @doc_controls.do_not_generate_docs # DEPRECATED: TF 1.x only + @deprecated(None, "use run() instead") + def experimental_run(self, fn, input_iterator=None): + """DEPRECATED TF 1.x ONLY.""" + with self.scope(): + args = (input_iterator.get_next(),) if input_iterator is not None else () + return self.run(fn, args=args) + + def experimental_distribute_dataset(self, dataset, options=None): + # pylint: disable=line-too-long + """Creates `tf.distribute.DistributedDataset` from `tf.data.Dataset`. + + The returned `tf.distribute.DistributedDataset` can be iterated over + similar to regular datasets. + NOTE: The user cannot add any more transformations to a + `tf.distribute.DistributedDataset`. You can only create an iterator or + examine the `tf.TypeSpec` of the data generated by it. See API docs of + `tf.distribute.DistributedDataset` to learn more. + + The following is an example: + + >>> global_batch_size = 2 + >>> # Passing the devices is optional. + ... strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"]) + >>> # Create a dataset + ... dataset = tf.data.Dataset.range(4).batch(global_batch_size) + >>> # Distribute that dataset + ... dist_dataset = strategy.experimental_distribute_dataset(dataset) + >>> @tf.function + ... def replica_fn(input): + ... return input*2 + >>> result = [] + >>> # Iterate over the `tf.distribute.DistributedDataset` + ... for x in dist_dataset: + ... # process dataset elements + ... result.append(strategy.run(replica_fn, args=(x,))) + >>> print(result) + [PerReplica:{ + 0: , + 1: + }, PerReplica:{ + 0: , + 1: + }] + + + Three key actions happening under the hood of this method are batching, + sharding, and prefetching. + + In the code snippet above, `dataset` is batched by `global_batch_size`, and + calling `experimental_distribute_dataset` on it rebatches `dataset` to a + new batch size that is equal to the global batch size divided by the number + of replicas in sync. We iterate through it using a Pythonic for loop. + `x` is a `tf.distribute.DistributedValues` containing data for all replicas, + and each replica gets data of the new batch size. + `tf.distribute.Strategy.run` will take care of feeding the right per-replica + data in `x` to the right `replica_fn` executed on each replica. + + Sharding contains autosharding across multiple workers and within every + worker. First, in multi-worker distributed training (i.e. when you use + `tf.distribute.experimental.MultiWorkerMirroredStrategy` + or `tf.distribute.TPUStrategy`), autosharding a dataset over a set of + workers means that each worker is assigned a subset of the entire dataset + (if the right `tf.data.experimental.AutoShardPolicy` is set). This is to + ensure that at each step, a global batch size of non-overlapping dataset + elements will be processed by each worker. Autosharding has a couple of + different options that can be specified using + `tf.data.experimental.DistributeOptions`. Then, sharding within each worker + means the method will split the data among all the worker devices (if more + than one a present). This will happen regardless of multi-worker + autosharding. + + Note: for autosharding across multiple workers, the default mode is + `tf.data.experimental.AutoShardPolicy.AUTO`. This mode + will attempt to shard the input dataset by files if the dataset is + being created out of reader datasets (e.g. `tf.data.TFRecordDataset`, + `tf.data.TextLineDataset`, etc.) or otherwise shard the dataset by data, + where each of the workers will read the entire dataset and only process the + shard assigned to it. However, if you have less than one input file per + worker, we suggest that you disable dataset autosharding across workers by + setting the `tf.data.experimental.DistributeOptions.auto_shard_policy` to be + `tf.data.experimental.AutoShardPolicy.OFF`. + + By default, this method adds a prefetch transformation at the end of the + user provided `tf.data.Dataset` instance. The argument to the prefetch + transformation which is `buffer_size` is equal to the number of replicas in + sync. + + If the above batch splitting and dataset sharding logic is undesirable, + please use + `tf.distribute.Strategy.distribute_datasets_from_function` + instead, which does not do any automatic batching or sharding for you. + + Note: If you are using TPUStrategy, the order in which the data is processed + by the workers when using + `tf.distribute.Strategy.experimental_distribute_dataset` or + `tf.distribute.Strategy.distribute_datasets_from_function` is + not guaranteed. This is typically required if you are using + `tf.distribute` to scale prediction. You can however insert an index for + each element in the batch and order outputs accordingly. Refer to [this + snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) + for an example of how to order outputs. + + Note: Stateful dataset transformations are currently not supported with + `tf.distribute.experimental_distribute_dataset` or + `tf.distribute.distribute_datasets_from_function`. Any stateful + ops that the dataset may have are currently ignored. For example, if your + dataset has a `map_fn` that uses `tf.random.uniform` to rotate an image, + then you have a dataset graph that depends on state (i.e the random seed) on + the local machine where the python process is being executed. + + For a tutorial on more usage and properties of this method, refer to the + [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). + If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches). + + Args: + dataset: `tf.data.Dataset` that will be sharded across all replicas using + the rules stated above. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + + Returns: + A `tf.distribute.DistributedDataset`. + """ + distribution_strategy_input_api_counter.get_cell( + self.__class__.__name__, "distribute_dataset").increase_by(1) + # pylint: enable=line-too-long + return self._extended._experimental_distribute_dataset(dataset, options) # pylint: disable=protected-access + + def distribute_datasets_from_function(self, dataset_fn, options=None): + # pylint: disable=line-too-long + """Distributes `tf.data.Dataset` instances created by calls to `dataset_fn`. + + The argument `dataset_fn` that users pass in is an input function that has a + `tf.distribute.InputContext` argument and returns a `tf.data.Dataset` + instance. It is expected that the returned dataset from `dataset_fn` is + already batched by per-replica batch size (i.e. global batch size divided by + the number of replicas in sync) and sharded. + `tf.distribute.Strategy.distribute_datasets_from_function` does + not batch or shard the `tf.data.Dataset` instance + returned from the input function. `dataset_fn` will be called on the CPU + device of each of the workers and each generates a dataset where every + replica on that worker will dequeue one batch of inputs (i.e. if a worker + has two replicas, two batches will be dequeued from the `Dataset` every + step). + + This method can be used for several purposes. First, it allows you to + specify your own batching and sharding logic. (In contrast, + `tf.distribute.experimental_distribute_dataset` does batching and sharding + for you.) For example, where + `experimental_distribute_dataset` is unable to shard the input files, this + method might be used to manually shard the dataset (avoiding the slow + fallback behavior in `experimental_distribute_dataset`). In cases where the + dataset is infinite, this sharding can be done by creating dataset replicas + that differ only in their random seed. + + The `dataset_fn` should take an `tf.distribute.InputContext` instance where + information about batching and input replication can be accessed. + + You can use `element_spec` property of the + `tf.distribute.DistributedDataset` returned by this API to query the + `tf.TypeSpec` of the elements returned by the iterator. This can be used to + set the `input_signature` property of a `tf.function`. Follow + `tf.distribute.DistributedDataset.element_spec` to see an example. + + IMPORTANT: The `tf.data.Dataset` returned by `dataset_fn` should have a + per-replica batch size, unlike `experimental_distribute_dataset`, which uses + the global batch size. This may be computed using + `input_context.get_per_replica_batch_size`. + + Note: If you are using TPUStrategy, the order in which the data is processed + by the workers when using + `tf.distribute.Strategy.experimental_distribute_dataset` or + `tf.distribute.Strategy.distribute_datasets_from_function` is + not guaranteed. This is typically required if you are using + `tf.distribute` to scale prediction. You can however insert an index for + each element in the batch and order outputs accordingly. Refer to [this + snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) + for an example of how to order outputs. + + Note: Stateful dataset transformations are currently not supported with + `tf.distribute.experimental_distribute_dataset` or + `tf.distribute.distribute_datasets_from_function`. Any stateful + ops that the dataset may have are currently ignored. For example, if your + dataset has a `map_fn` that uses `tf.random.uniform` to rotate an image, + then you have a dataset graph that depends on state (i.e the random seed) on + the local machine where the python process is being executed. + + For a tutorial on more usage and properties of this method, refer to the + [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). + If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches). + + Args: + dataset_fn: A function taking a `tf.distribute.InputContext` instance and + returning a `tf.data.Dataset`. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + + Returns: + A `tf.distribute.DistributedDataset`. + """ + distribution_strategy_input_api_counter.get_cell( + self.__class__.__name__, + "distribute_datasets_from_function").increase_by(1) + # pylint: enable=line-too-long + return self._extended._distribute_datasets_from_function( # pylint: disable=protected-access + dataset_fn, options) + + # TODO(b/162776748): Remove deprecated symbol. + @doc_controls.do_not_doc_inheritable + @deprecation.deprecated(None, "rename to distribute_datasets_from_function") + def experimental_distribute_datasets_from_function(self, + dataset_fn, + options=None): + return self.distribute_datasets_from_function(dataset_fn, options) + + def run(self, fn, args=(), kwargs=None, options=None): + """Invokes `fn` on each replica, with the given arguments. + + This method is the primary way to distribute your computation with a + tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` + have `tf.distribute.DistributedValues`, such as those produced by a + `tf.distribute.DistributedDataset` from + `tf.distribute.Strategy.experimental_distribute_dataset` or + `tf.distribute.Strategy.distribute_datasets_from_function`, + when `fn` is executed on a particular replica, it will be executed with the + component of `tf.distribute.DistributedValues` that correspond to that + replica. + + `fn` is invoked under a replica context. `fn` may call + `tf.distribute.get_replica_context()` to access members such as + `all_reduce`. Please see the module-level docstring of tf.distribute for the + concept of replica context. + + All arguments in `args` or `kwargs` can be a nested structure of tensors, + e.g. a list of tensors, in which case `args` and `kwargs` will be passed to + the `fn` invoked on each replica. Or `args` or `kwargs` can be + `tf.distribute.DistributedValues` containing tensors or composite tensors, + i.e. `tf.compat.v1.TensorInfo.CompositeTensor`, in which case each `fn` call + will get the component of a `tf.distribute.DistributedValues` corresponding + to its replica. Note that arbitrary Python values that are not of the types + above are not supported. + + IMPORTANT: Depending on the implementation of `tf.distribute.Strategy` and + whether eager execution is enabled, `fn` may be called one or more times. If + `fn` is annotated with `tf.function` or `tf.distribute.Strategy.run` is + called inside a `tf.function` (eager execution is disabled inside a + `tf.function` by default), `fn` is called once per replica to generate a + Tensorflow graph, which will then be reused for execution with new inputs. + Otherwise, if eager execution is enabled, `fn` will be called once per + replica every step just like regular python code. + + Example usage: + + 1. Constant tensor input. + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> tensor_input = tf.constant(3.0) + >>> @tf.function + ... def replica_fn(input): + ... return input*2.0 + >>> result = strategy.run(replica_fn, args=(tensor_input,)) + >>> result + PerReplica:{ + 0: , + 1: + } + + 2. DistributedValues input. {: value=2} + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> @tf.function + ... def run(): + ... def value_fn(value_context): + ... return value_context.num_replicas_in_sync + ... distributed_values = ( + ... strategy.experimental_distribute_values_from_function( + ... value_fn)) + ... def replica_fn2(input): + ... return input*2 + ... return strategy.run(replica_fn2, args=(distributed_values,)) + >>> result = run() + >>> result + + + 3. Use `tf.distribute.ReplicaContext` to allreduce values. {: value=3} + + >>> strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"]) + >>> @tf.function + ... def run(): + ... def value_fn(value_context): + ... return tf.constant(value_context.replica_id_in_sync_group) + ... distributed_values = ( + ... strategy.experimental_distribute_values_from_function( + ... value_fn)) + ... def replica_fn(input): + ... return tf.distribute.get_replica_context().all_reduce( + ... "sum", input) + ... return strategy.run(replica_fn, args=(distributed_values,)) + >>> result = run() + >>> result + PerReplica:{ + 0: , + 1: + } + + Args: + fn: The function to run on each replica. + args: Optional positional arguments to `fn`. Its element can be a tensor, + a nested structure of tensors or a `tf.distribute.DistributedValues`. + kwargs: Optional keyword arguments to `fn`. Its element can be a tensor, + a nested structure of tensors or a `tf.distribute.DistributedValues`. + options: An optional instance of `tf.distribute.RunOptions` specifying + the options to run `fn`. + + Returns: + Merged return value of `fn` across replicas. The structure of the return + value is the same as the return value from `fn`. Each element in the + structure can either be `tf.distribute.DistributedValues`, `Tensor` + objects, or `Tensor`s (for example, if running on a single replica). + """ + del options + + if not isinstance(args, (list, tuple)): + raise ValueError( + "positional args must be a list or tuple, got {}".format(type(args))) + + with self.scope(): + # tf.distribute supports Eager functions, so AutoGraph should not be + # applied when the caller is also in Eager mode. + fn = autograph.tf_convert( + fn, autograph_ctx.control_status_ctx(), convert_by_default=False) + return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs) + + def reduce(self, reduce_op, value, axis): + """Reduce `value` across replicas and return result on current device. + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> def step_fn(): + ... i = tf.distribute.get_replica_context().replica_id_in_sync_group + ... return tf.identity(i) + >>> + >>> per_replica_result = strategy.run(step_fn) + >>> total = strategy.reduce("SUM", per_replica_result, axis=None) + >>> total + + + To see how this would look with multiple replicas, consider the same + example with MirroredStrategy with 2 GPUs: + + ```python + strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"]) + def step_fn(): + i = tf.distribute.get_replica_context().replica_id_in_sync_group + return tf.identity(i) + + per_replica_result = strategy.run(step_fn) + # Check devices on which per replica result is: + strategy.experimental_local_results(per_replica_result)[0].device + # /job:localhost/replica:0/task:0/device:GPU:0 + strategy.experimental_local_results(per_replica_result)[1].device + # /job:localhost/replica:0/task:0/device:GPU:1 + + total = strategy.reduce("SUM", per_replica_result, axis=None) + # Check device on which reduced result is: + total.device + # /job:localhost/replica:0/task:0/device:CPU:0 + + ``` + + This API is typically used for aggregating the results returned from + different replicas, for reporting etc. For example, loss computed from + different replicas can be averaged using this API before printing. + + Note: The result is copied to the "current" device - which would typically + be the CPU of the worker on which the program is running. For `TPUStrategy`, + it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, + this is CPU of each worker. + + There are a number of different tf.distribute APIs for reducing values + across replicas: + * `tf.distribute.ReplicaContext.all_reduce`: This differs from + `Strategy.reduce` in that it is for replica context and does + not copy the results to the host device. `all_reduce` should be typically + used for reductions inside the training step such as gradients. + * `tf.distribute.StrategyExtended.reduce_to` and + `tf.distribute.StrategyExtended.batch_reduce_to`: These APIs are more + advanced versions of `Strategy.reduce` as they allow customizing the + destination of the result. They are also called in cross replica context. + + _What should axis be?_ + + Given a per-replica value returned by `run`, say a + per-example loss, the batch will be divided across all the replicas. This + function allows you to aggregate across replicas and optionally also across + batch elements by specifying the axis parameter accordingly. + + For example, if you have a global batch size of 8 and 2 + replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and + `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will + aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. + This is useful when each replica is computing a scalar or some other value + that doesn't have a "batch" dimension (like a gradient or loss). + ``` + strategy.reduce("sum", per_replica_result, axis=None) + ``` + + Sometimes, you will want to aggregate across both the global batch _and_ + all replicas. You can get this behavior by specifying the batch + dimension as the `axis`, typically `axis=0`. In this case it would return a + scalar `0+1+2+3+4+5+6+7`. + ``` + strategy.reduce("sum", per_replica_result, axis=0) + ``` + + If there is a last partial batch, you will need to specify an axis so + that the resulting shape is consistent across replicas. So if the last + batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you + would get a shape mismatch unless you specify `axis=0`. If you specify + `tf.distribute.ReduceOp.MEAN`, using `axis=0` will use the correct + denominator of 6. Contrast this with computing `reduce_mean` to get a + scalar value on each replica and this function to average those means, + which will weigh some values `1/8` and others `1/4`. + + Args: + reduce_op: a `tf.distribute.ReduceOp` value specifying how values should + be combined. Allows using string representation of the enum such as + "SUM", "MEAN". + value: a `tf.distribute.DistributedValues` instance, e.g. returned by + `Strategy.run`, to be combined into a single tensor. It can also be a + regular tensor when used with `OneDeviceStrategy` or default strategy. + axis: specifies the dimension to reduce along within each + replica's tensor. Should typically be set to the batch dimension, or + `None` to only reduce across replicas (e.g. if the tensor has no batch + dimension). + + Returns: + A `Tensor`. + """ + # TODO(josh11b): support `value` being a nest. + _require_cross_replica_or_default_context_extended(self._extended) + if isinstance(reduce_op, six.string_types): + reduce_op = reduce_util.ReduceOp(reduce_op.upper()) + if axis is None: + return self._extended._reduce(reduce_op, value) # pylint: disable=protected-access + if reduce_op == reduce_util.ReduceOp.SUM: + + def reduce_sum(v): + return math_ops.reduce_sum(v, axis=axis) + + if eager_context.executing_eagerly(): + # As some strategies (e.g. TPUStrategy) doesn't support pure eager + # execution, wrap the `reduce_sum_fn` with a `tf.function` so it can be + # run from eager mode. Cache the tf.function by `axis` to avoid the + # same function to be traced again. + if axis not in self._reduce_sum_fns: + self._reduce_sum_fns[axis] = def_function.function(reduce_sum) + value = self.run(self._reduce_sum_fns[axis], args=(value,)) + else: + value = self.run(reduce_sum, args=(value,)) + + return self._extended._reduce(reduce_op, value) # pylint: disable=protected-access + if reduce_op != reduce_util.ReduceOp.MEAN: + raise TypeError("Expected `reduce_op` to be a `tf.distribute.ReduceOp`, " + "not: %r" % reduce_op) + + def mean_reduce_helper(v, axes=axis): + """Computes the numerator and denominator on each replica.""" + numer = math_ops.reduce_sum(v, axis=axes) + def dimension(axis): + if v.shape.rank is not None: + # Note(joshl): We support axis < 0 to be consistent with the + # tf.math.reduce_* operations. + if axis < 0: + if axis + v.shape.rank < 0: + raise ValueError( + "`axis` = %r out of range for `value` with rank %d" % + (axis, v.shape.rank)) + axis += v.shape.rank + elif axis >= v.shape.rank: + raise ValueError( + "`axis` = %r out of range for `value` with rank %d" % + (axis, v.shape.rank)) + # TF v2 returns `None` for unknown dimensions and an integer for + # known dimension, whereas TF v1 returns tensor_shape.Dimension(None) + # or tensor_shape.Dimension(integer). `dimension_value` hides this + # difference, always returning `None` or an integer. + dim = tensor_shape.dimension_value(v.shape[axis]) + if dim is not None: + # By returning a python value in the static shape case, we can + # maybe get a fast path for reducing the denominator. + # TODO(b/151871486): Remove array_ops.identity after we fallback to + # simple reduction if inputs are all on CPU. + return array_ops.identity( + constant_op.constant(dim, dtype=dtypes.int64)) + elif axis < 0: + axis = axis + array_ops.rank(v) + # TODO(b/151871486): Remove array_ops.identity after we fallback to + # simple reduction if inputs are all on CPU. + return array_ops.identity( + array_ops.shape_v2(v, out_type=dtypes.int64)[axis]) + if isinstance(axis, six.integer_types): + denom = dimension(axis) + elif isinstance(axis, (tuple, list)): + denom = math_ops.reduce_prod([dimension(a) for a in axes]) + else: + raise TypeError( + "Expected `axis` to be an integer, tuple or list not: %r" % axis) + # TODO(josh11b): Should we cast denom to v.dtype here instead of after the + # reduce is complete? + return numer, denom + + if eager_context.executing_eagerly(): + # As some strategies (e.g. TPUStrategy) doesn't support pure eager + # execution, wrap the `mean_reduce_helper` with a `tf.function` so it can + # be run from eager mode. Cache the tf.function by `axis` to avoid the + # same function to be traced again. + if axis not in self._mean_reduce_helper_fns: + self._mean_reduce_helper_fns[axis] = def_function.function( + mean_reduce_helper) + numer, denom = self.run(self._mean_reduce_helper_fns[axis], args=(value,)) + else: + numer, denom = self.run(mean_reduce_helper, args=(value,)) + + # TODO(josh11b): Should batch reduce here instead of doing two. + numer = self._extended._reduce(reduce_util.ReduceOp.SUM, numer) # pylint: disable=protected-access + denom = self._extended._reduce(reduce_util.ReduceOp.SUM, denom) # pylint: disable=protected-access + denom = math_ops.cast(denom, numer.dtype) + return math_ops.truediv(numer, denom) + + @doc_controls.do_not_doc_inheritable # DEPRECATED + @deprecated(None, "use `experimental_local_results` instead.") + def unwrap(self, value): + """Returns the list of all local per-replica values contained in `value`. + + DEPRECATED: Please use `experimental_local_results` instead. + + Note: This only returns values on the workers initiated by this client. + When using a `tf.distribute.Strategy` like + `tf.distribute.experimental.MultiWorkerMirroredStrategy`, each worker + will be its own client, and this function will only return values + computed on that worker. + + Args: + value: A value returned by `experimental_run()`, + `extended.call_for_each_replica()`, or a variable created in `scope`. + + Returns: + A tuple of values contained in `value`. If `value` represents a single + value, this returns `(value,).` + """ + return self._extended._local_results(value) # pylint: disable=protected-access + + def experimental_local_results(self, value): + """Returns the list of all local per-replica values contained in `value`. + + Note: This only returns values on the worker initiated by this client. + When using a `tf.distribute.Strategy` like + `tf.distribute.experimental.MultiWorkerMirroredStrategy`, each worker + will be its own client, and this function will only return values + computed on that worker. + + Args: + value: A value returned by `experimental_run()`, `run(), or a variable + created in `scope`. + + Returns: + A tuple of values contained in `value` where ith element corresponds to + ith replica. If `value` represents a single value, this returns + `(value,).` + """ + return self._extended._local_results(value) # pylint: disable=protected-access + + @doc_controls.do_not_doc_inheritable # DEPRECATED: TF v1.x only + def group(self, value, name=None): + """Shortcut for `tf.group(self.experimental_local_results(value))`.""" + return self._extended._group(value, name) # pylint: disable=protected-access + + @property + def num_replicas_in_sync(self): + """Returns number of replicas over which gradients are aggregated.""" + return self._extended._num_replicas_in_sync # pylint: disable=protected-access + + @doc_controls.do_not_doc_inheritable # DEPRECATED: see doc string + @deprecated(None, "use `update_config_proto` instead.") + def configure(self, + session_config=None, + cluster_spec=None, + task_type=None, + task_id=None): + # pylint: disable=g-doc-return-or-yield,g-doc-args + """DEPRECATED: use `update_config_proto` instead. + + Configures the strategy class. + + DEPRECATED: This method's functionality has been split into the strategy + constructor and `update_config_proto`. In the future, we will allow passing + cluster and config_proto to the constructor to configure the strategy. And + `update_config_proto` can be used to update the config_proto based on the + specific strategy. + """ + return self._extended._configure( # pylint: disable=protected-access + session_config, cluster_spec, task_type, task_id) + + @doc_controls.do_not_generate_docs # DEPRECATED + def update_config_proto(self, config_proto): + """DEPRECATED TF 1.x ONLY.""" + return self._extended._update_config_proto(config_proto) # pylint: disable=protected-access + + def __deepcopy__(self, memo): + # First do a regular deepcopy of `self`. + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + setattr(result, k, copy.deepcopy(v, memo)) + # One little fix-up: we want `result._extended` to reference `result` + # instead of `self`. + result._extended._container_strategy_weakref = weakref.ref(result) # pylint: disable=protected-access + return result + + def __copy__(self): + raise RuntimeError("Must only deepcopy DistributionStrategy.") + + @property + def cluster_resolver(self): + """Returns the cluster resolver associated with this strategy. + + In general, when using a multi-worker `tf.distribute` strategy such as + `tf.distribute.experimental.MultiWorkerMirroredStrategy` or + `tf.distribute.TPUStrategy()`, there is a + `tf.distribute.cluster_resolver.ClusterResolver` associated with the + strategy used, and such an instance is returned by this property. + + Strategies that intend to have an associated + `tf.distribute.cluster_resolver.ClusterResolver` must set the + relevant attribute, or override this property; otherwise, `None` is returned + by default. Those strategies should also provide information regarding what + is returned by this property. + + Single-worker strategies usually do not have a + `tf.distribute.cluster_resolver.ClusterResolver`, and in those cases this + property will return `None`. + + The `tf.distribute.cluster_resolver.ClusterResolver` may be useful when the + user needs to access information such as the cluster spec, task type or task + id. For example, + + ```python + + os.environ['TF_CONFIG'] = json.dumps({ + 'cluster': { + 'worker': ["localhost:12345", "localhost:23456"], + 'ps': ["localhost:34567"] + }, + 'task': {'type': 'worker', 'index': 0} + }) + + # This implicitly uses TF_CONFIG for the cluster and current task info. + strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() + + ... + + if strategy.cluster_resolver.task_type == 'worker': + # Perform something that's only applicable on workers. Since we set this + # as a worker above, this block will run on this particular instance. + elif strategy.cluster_resolver.task_type == 'ps': + # Perform something that's only applicable on parameter servers. Since we + # set this as a worker above, this block will not run on this particular + # instance. + ``` + + For more information, please see + `tf.distribute.cluster_resolver.ClusterResolver`'s API docstring. + + Returns: + The cluster resolver associated with this strategy. Returns `None` if a + cluster resolver is not applicable or available in this strategy. + """ + if hasattr(self.extended, "_cluster_resolver"): + return self.extended._cluster_resolver # pylint: disable=protected-access + return None + + +@tf_export("distribute.Strategy", v1=[]) # pylint: disable=g-missing-docstring +class Strategy(StrategyBase): + + __doc__ = StrategyBase.__doc__ + + def experimental_distribute_values_from_function(self, value_fn): + """Generates `tf.distribute.DistributedValues` from `value_fn`. + + This function is to generate `tf.distribute.DistributedValues` to pass + into `run`, `reduce`, or other methods that take + distributed values when not using datasets. + + Args: + value_fn: The function to run to generate values. It is called for + each replica with `tf.distribute.ValueContext` as the sole argument. It + must return a Tensor or a type that can be converted to a Tensor. + Returns: + A `tf.distribute.DistributedValues` containing a value for each replica. + + Example usage: + + 1. Return constant value per replica: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> def value_fn(ctx): + ... return tf.constant(1.) + >>> distributed_values = ( + ... strategy.experimental_distribute_values_from_function( + ... value_fn)) + >>> local_result = strategy.experimental_local_results( + ... distributed_values) + >>> local_result + (, + ) + + 2. Distribute values in array based on replica_id: {: value=2} + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> array_value = np.array([3., 2., 1.]) + >>> def value_fn(ctx): + ... return array_value[ctx.replica_id_in_sync_group] + >>> distributed_values = ( + ... strategy.experimental_distribute_values_from_function( + ... value_fn)) + >>> local_result = strategy.experimental_local_results( + ... distributed_values) + >>> local_result + (3.0, 2.0) + + 3. Specify values using num_replicas_in_sync: {: value=3} + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> def value_fn(ctx): + ... return ctx.num_replicas_in_sync + >>> distributed_values = ( + ... strategy.experimental_distribute_values_from_function( + ... value_fn)) + >>> local_result = strategy.experimental_local_results( + ... distributed_values) + >>> local_result + (2, 2) + + 4. Place values on devices and distribute: {: value=4} + + ``` + strategy = tf.distribute.TPUStrategy() + worker_devices = strategy.extended.worker_devices + multiple_values = [] + for i in range(strategy.num_replicas_in_sync): + with tf.device(worker_devices[i]): + multiple_values.append(tf.constant(1.0)) + + def value_fn(ctx): + return multiple_values[ctx.replica_id_in_sync_group] + + distributed_values = strategy. + experimental_distribute_values_from_function( + value_fn) + ``` + + """ + return self._extended._experimental_distribute_values_from_function( # pylint: disable=protected-access + value_fn) + + def gather(self, value, axis): + # pylint: disable=line-too-long, protected-access + """Gather `value` across replicas along `axis` to the current device. + + Given a `tf.distribute.DistributedValues` or `tf.Tensor`-like + object `value`, this API gathers and concatenates `value` across replicas + along the `axis`-th dimension. The result is copied to the "current" device, + which would typically be the CPU of the worker on which the program is + running. For `tf.distribute.TPUStrategy`, it is the first TPU host. For + multi-client `tf.distribute.MultiWorkerMirroredStrategy`, this is the CPU of + each worker. + + This API can only be called in the cross-replica context. For a counterpart + in the replica context, see `tf.distribute.ReplicaContext.all_gather`. + + Note: For all strategies except `tf.distribute.TPUStrategy`, the input + `value` on different replicas must have the same rank, and their shapes must + be the same in all dimensions except the `axis`-th dimension. In other + words, their shapes cannot be different in a dimension `d` where `d` does + not equal to the `axis` argument. For example, given a + `tf.distribute.DistributedValues` with component tensors of shape + `(1, 2, 3)` and `(1, 3, 3)` on two replicas, you can call + `gather(..., axis=1, ...)` on it, but not `gather(..., axis=0, ...)` or + `gather(..., axis=2, ...)`. However, for `tf.distribute.TPUStrategy.gather`, + all tensors must have exactly the same rank and same shape. + + Note: Given a `tf.distribute.DistributedValues` `value`, its component + tensors must have a non-zero rank. Otherwise, consider using + `tf.expand_dims` before gathering them. + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> # A DistributedValues with component tensor of shape (2, 1) on each replica + ... distributed_values = strategy.experimental_distribute_values_from_function(lambda _: tf.identity(tf.constant([[1], [2]]))) + >>> @tf.function + ... def run(): + ... return strategy.gather(distributed_values, axis=0) + >>> run() + + + + Consider the following example for more combinations: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1", "GPU:2", "GPU:3"]) + >>> single_tensor = tf.reshape(tf.range(6), shape=(1,2,3)) + >>> distributed_values = strategy.experimental_distribute_values_from_function(lambda _: tf.identity(single_tensor)) + >>> @tf.function + ... def run(axis): + ... return strategy.gather(distributed_values, axis=axis) + >>> axis=0 + >>> run(axis) + + >>> axis=1 + >>> run(axis) + + >>> axis=2 + >>> run(axis) + + + + Args: + value: a `tf.distribute.DistributedValues` instance, e.g. returned by + `Strategy.run`, to be combined into a single tensor. It can also be a + regular tensor when used with `tf.distribute.OneDeviceStrategy` or the + default strategy. The tensors that constitute the DistributedValues + can only be dense tensors with non-zero rank, NOT a `tf.IndexedSlices`. + axis: 0-D int32 Tensor. Dimension along which to gather. Must be in the + range [0, rank(value)). + + Returns: + A `Tensor` that's the concatenation of `value` across replicas along + `axis` dimension. + """ + # pylint: enable=line-too-long + error_message = ("tf.distribute.Strategy.gather method requires " + "cross-replica context, use " + "get_replica_context().all_gather() instead") + _require_cross_replica_or_default_context_extended(self._extended, + error_message) + dst = device_util.current( + ) or self._extended._default_device or "/device:CPU:0" + if isinstance(value, indexed_slices.IndexedSlices): + raise NotImplementedError("gather does not support IndexedSlices") + return self._extended._local_results( + self._extended._gather_to(value, dst, axis))[0] + + +# TF v1.x version has additional deprecated APIs +@tf_export(v1=["distribute.Strategy"]) +class StrategyV1(StrategyBase): + """A list of devices with a state & compute distribution policy. + + See [the guide](https://www.tensorflow.org/guide/distribute_strategy) + for overview and examples. + + Note: Not all `tf.distribute.Strategy` implementations currently support + TensorFlow's partitioned variables (where a single variable is split across + multiple devices) at this time. + """ + + def make_dataset_iterator(self, dataset): + """Makes an iterator for input provided via `dataset`. + + DEPRECATED: This method is not available in TF 2.x. + + Data from the given dataset will be distributed evenly across all the + compute replicas. We will assume that the input dataset is batched by the + global batch size. With this assumption, we will make a best effort to + divide each batch across all the replicas (one or more workers). + If this effort fails, an error will be thrown, and the user should instead + use `make_input_fn_iterator` which provides more control to the user, and + does not try to divide a batch across replicas. + + The user could also use `make_input_fn_iterator` if they want to + customize which input is fed to which replica/worker etc. + + Args: + dataset: `tf.data.Dataset` that will be distributed evenly across all + replicas. + + Returns: + An `tf.distribute.InputIterator` which returns inputs for each step of the + computation. User should call `initialize` on the returned iterator. + """ + return self._extended._make_dataset_iterator(dataset) # pylint: disable=protected-access + + def make_input_fn_iterator(self, # pylint: disable=useless-super-delegation + input_fn, + replication_mode=InputReplicationMode.PER_WORKER): + """Returns an iterator split across replicas created from an input function. + + DEPRECATED: This method is not available in TF 2.x. + + The `input_fn` should take an `tf.distribute.InputContext` object where + information about batching and input sharding can be accessed: + + ``` + def input_fn(input_context): + batch_size = input_context.get_per_replica_batch_size(global_batch_size) + d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size) + return d.shard(input_context.num_input_pipelines, + input_context.input_pipeline_id) + with strategy.scope(): + iterator = strategy.make_input_fn_iterator(input_fn) + replica_results = strategy.experimental_run(replica_fn, iterator) + ``` + + The `tf.data.Dataset` returned by `input_fn` should have a per-replica + batch size, which may be computed using + `input_context.get_per_replica_batch_size`. + + Args: + input_fn: A function taking a `tf.distribute.InputContext` object and + returning a `tf.data.Dataset`. + replication_mode: an enum value of `tf.distribute.InputReplicationMode`. + Only `PER_WORKER` is supported currently, which means there will be + a single call to `input_fn` per worker. Replicas will dequeue from the + local `tf.data.Dataset` on their worker. + + Returns: + An iterator object that should first be `.initialize()`-ed. It may then + either be passed to `strategy.experimental_run()` or you can + `iterator.get_next()` to get the next value to pass to + `strategy.extended.call_for_each_replica()`. + """ + return super(StrategyV1, self).make_input_fn_iterator( + input_fn, replication_mode) + + def experimental_make_numpy_dataset(self, numpy_input, session=None): + """Makes a tf.data.Dataset for input provided via a numpy array. + + This avoids adding `numpy_input` as a large constant in the graph, + and copies the data to the machine or machines that will be processing + the input. + + Note that you will likely need to use + tf.distribute.Strategy.experimental_distribute_dataset + with the returned dataset to further distribute it with the strategy. + + Example: + ``` + numpy_input = np.ones([10], dtype=np.float32) + dataset = strategy.experimental_make_numpy_dataset(numpy_input) + dist_dataset = strategy.experimental_distribute_dataset(dataset) + ``` + + Args: + numpy_input: A nest of NumPy input arrays that will be converted into a + dataset. Note that lists of Numpy arrays are stacked, as that is normal + `tf.data.Dataset` behavior. + session: (TensorFlow v1.x graph execution only) A session used for + initialization. + + Returns: + A `tf.data.Dataset` representing `numpy_input`. + """ + return self.extended.experimental_make_numpy_dataset( + numpy_input, session=session) + + @deprecated( + None, + "This method is not available in TF 2.x. Please switch to using `run` instead." + ) + def experimental_run(self, fn, input_iterator=None): # pylint: disable=useless-super-delegation + """Runs ops in `fn` on each replica, with inputs from `input_iterator`. + + DEPRECATED: This method is not available in TF 2.x. Please switch + to using `run` instead. + + When eager execution is enabled, executes ops specified by `fn` on each + replica. Otherwise, builds a graph to execute the ops on each replica. + + Each replica will take a single, different input from the inputs provided by + one `get_next` call on the input iterator. + + `fn` may call `tf.distribute.get_replica_context()` to access members such + as `replica_id_in_sync_group`. + + IMPORTANT: Depending on the `tf.distribute.Strategy` implementation being + used, and whether eager execution is enabled, `fn` may be called one or more + times (once for each replica). + + Args: + fn: The function to run. The inputs to the function must match the outputs + of `input_iterator.get_next()`. The output must be a `tf.nest` of + `Tensor`s. + input_iterator: (Optional) input iterator from which the inputs are taken. + + Returns: + Merged return value of `fn` across replicas. The structure of the return + value is the same as the return value from `fn`. Each element in the + structure can either be `PerReplica` (if the values are unsynchronized), + `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a + single replica). + """ + return super(StrategyV1, self).experimental_run( + fn, input_iterator) + + def reduce(self, reduce_op, value, axis=None): + return super(StrategyV1, self).reduce(reduce_op, value, axis) + + reduce.__doc__ = StrategyBase.reduce.__doc__ + + def update_config_proto(self, config_proto): + """Returns a copy of `config_proto` modified for use with this strategy. + + DEPRECATED: This method is not available in TF 2.x. + + The updated config has something needed to run a strategy, e.g. + configuration to run collective ops, or device filters to improve + distributed training performance. + + Args: + config_proto: a `tf.ConfigProto` object. + + Returns: + The updated copy of the `config_proto`. + """ + return self._extended._update_config_proto(config_proto) # pylint: disable=protected-access + + +# NOTE(josh11b): For any strategy that needs to support tf.compat.v1, +# instead descend from StrategyExtendedV1. +@tf_export("distribute.StrategyExtended", v1=[]) +class StrategyExtendedV2(object): + """Additional APIs for algorithms that need to be distribution-aware. + + Note: For most usage of `tf.distribute.Strategy`, there should be no need to + call these methods, since TensorFlow libraries (such as optimizers) already + call these methods when needed on your behalf. + + + Some common use cases of functions on this page: + + * _Locality_ + + `tf.distribute.DistributedValues` can have the same _locality_ as a + _distributed variable_, which leads to a mirrored value residing on the same + devices as the variable (as opposed to the compute devices). Such values may + be passed to a call to `tf.distribute.StrategyExtended.update` to update the + value of a variable. You may use + `tf.distribute.StrategyExtended.colocate_vars_with` to give a variable the + same locality as another variable. You may convert a "PerReplica" value to a + variable's locality by using `tf.distribute.StrategyExtended.reduce_to` or + `tf.distribute.StrategyExtended.batch_reduce_to`. + + * _How to update a distributed variable_ + + A distributed variable is variables created on multiple devices. As discussed + in the [glossary](https://www.tensorflow.org/api_docs/python/tf/distribute), + mirrored variable and SyncOnRead variable are two examples. The standard + pattern for updating distributed variables is to: + + 1. In your function passed to `tf.distribute.Strategy.run`, + compute a list of (update, variable) pairs. For example, the update might + be a gradient of the loss with respect to the variable. + 2. Switch to cross-replica mode by calling + `tf.distribute.get_replica_context().merge_call()` with the updates and + variables as arguments. + 3. Call + `tf.distribute.StrategyExtended.reduce_to(VariableAggregation.SUM, t, v)` + (for one variable) or `tf.distribute.StrategyExtended.batch_reduce_to` + (for a list of variables) to sum the updates. + 4. Call `tf.distribute.StrategyExtended.update(v)` for each variable to update + its value. + + Steps 2 through 4 are done automatically by class + `tf.keras.optimizers.Optimizer` if you call its + `tf.keras.optimizers.Optimizer.apply_gradients` method in a replica context. + + In fact, a higher-level solution to update a distributed variable is by + calling `assign` on the variable as you would do to a regular `tf.Variable`. + You can call the method in both _replica context_ and _cross-replica context_. + For a _mirrored variable_, calling `assign` in _replica context_ requires you + to specify the `aggregation` type in the variable constructor. In that case, + the context switching and sync described in steps 2 through 4 are handled for + you. If you call `assign` on _mirrored variable_ in _cross-replica context_, + you can only assign a single value or assign values from another mirrored + variable or a mirrored `tf.distribute.DistributedValues`. For a _SyncOnRead + variable_, in _replica context_, you can simply call `assign` on it and no + aggregation happens under the hood. In _cross-replica context_, you can only + assign a single value to a SyncOnRead variable. One example case is restoring + from a checkpoint: if the `aggregation` type of the variable is + `tf.VariableAggregation.SUM`, it is assumed that replica values were added + before checkpointing, so at the time of restoring, the value is divided by + the number of replicas and then assigned to each replica; if the `aggregation` + type is `tf.VariableAggregation.MEAN`, the value is assigned to each replica + directly. + + """ + + def __init__(self, container_strategy): + self._container_strategy_weakref = weakref.ref(container_strategy) + self._default_device = None + # This property is used to determine if we should set drop_remainder=True + # when creating Datasets from numpy array inputs. + self._require_static_shapes = False + + def _resource_creator_scope(self): + """Returns one or a list of ops.resource_creator_scope for some Strategy.""" + return None + + def _default_device_scope(self): + if self._default_device: + return ops.device(self._default_device) + return None + + def _container_strategy(self): + """Get the containing `tf.distribute.Strategy`. + + This should not generally be needed except when creating a new + `ReplicaContext` and to validate that the caller is in the correct + `scope()`. + + Returns: + The `tf.distribute.Strategy` such that `strategy.extended` is `self`. + """ + container_strategy = self._container_strategy_weakref() + assert container_strategy is not None + return container_strategy + + def _scope(self, strategy): + """Implementation of tf.distribute.Strategy.scope().""" + + def creator_with_resource_vars(next_creator, **kwargs): + """Variable creator to use in `_CurrentDistributionContext`.""" + if ops.inside_function(): + if_graph_building = "graph_building" + else: + if_graph_building = "not_graph_building" + + with monitoring.MonitoredTimer(distributed_variable_creation_time_counter.get_cell(strategy.__class__.__name__, if_graph_building)): + _require_strategy_scope_extended(self) + kwargs["use_resource"] = True + kwargs["distribute_strategy"] = strategy + + # Unwrap `initial_value` if it is a `CheckpointInitialValue` to avoid + # dereferencing a `Tensor` that is without a `name`. We still need to + # propagate the metadata it's holding. + if isinstance(kwargs["initial_value"], trackable.CheckpointInitialValue): + checkpoint_restore_uid = kwargs[ + "initial_value"].checkpoint_position.restore_uid + kwargs["initial_value"] = kwargs["initial_value"].wrapped_value + elif isinstance(kwargs["initial_value"], + trackable.CheckpointInitialValueCallable): + checkpoint_restore_uid = kwargs[ + "initial_value"].checkpoint_position.restore_uid + elif (isinstance(kwargs["initial_value"], functools.partial) and + isinstance(kwargs["initial_value"].func, + trackable.CheckpointInitialValueCallable)): + # Some libraries (e.g., Keras) create partial function out of + # initializer to bind shape/dtype, for example: + # initial_val = functools.partial(initializer, shape, dtype=dtype) + # Therefore to get the restore_uid we need to examine the "func" of + # the partial function. + checkpoint_restore_uid = kwargs[ + "initial_value"].func.checkpoint_position.restore_uid + else: + checkpoint_restore_uid = None + + created = self._create_variable(next_creator, **kwargs) + + if checkpoint_restore_uid is not None: + # pylint: disable=protected-access + # Let the checkpointing infrastructure know that the variable was + # already restored so it doesn't waste memory loading the value again. + # In this case of CheckpointInitialValueCallable this may already be + # done by the final variable creator, but it doesn't hurt to do it + # again. + created._maybe_initialize_trackable() + created._update_uid = checkpoint_restore_uid + # pylint: enable=protected-access + return created + + def distributed_getter(getter, *args, **kwargs): + if not self._allow_variable_partition(): + if kwargs.pop("partitioner", None) is not None: + tf_logging.log_first_n( + tf_logging.WARN, "Partitioned variables are disabled when using " + "current tf.distribute.Strategy.", 1) + return getter(*args, **kwargs) + + return _CurrentDistributionContext( + strategy, + variable_scope.variable_creator_scope(creator_with_resource_vars), + variable_scope.variable_scope( + variable_scope.get_variable_scope(), + custom_getter=distributed_getter, + ), + strategy.extended._resource_creator_scope(), # pylint: disable=protected-access + self._default_device_scope(), + ) + + def _allow_variable_partition(self): + return False + + def _create_variable(self, next_creator, **kwargs): + # Note: should support "colocate_with" argument. + raise NotImplementedError("must be implemented in descendants") + + def variable_created_in_scope(self, v): + """Tests whether `v` was created while this strategy scope was active. + + Variables created inside the strategy scope are "owned" by it: + + >>> strategy = tf.distribute.MirroredStrategy() + >>> with strategy.scope(): + ... v = tf.Variable(1.) + >>> strategy.extended.variable_created_in_scope(v) + True + + Variables created outside the strategy are not owned by it: + + >>> strategy = tf.distribute.MirroredStrategy() + >>> v = tf.Variable(1.) + >>> strategy.extended.variable_created_in_scope(v) + False + + Args: + v: A `tf.Variable` instance. + + Returns: + True if `v` was created inside the scope, False if not. + """ + return v._distribute_strategy == self._container_strategy_weakref() # pylint: disable=protected-access + + def colocate_vars_with(self, colocate_with_variable): + """Scope that controls which devices variables will be created on. + + No operations should be added to the graph inside this scope, it + should only be used when creating variables (some implementations + work by changing variable creation, others work by using a + tf.compat.v1.colocate_with() scope). + + This may only be used inside `self.scope()`. + + Example usage: + + ``` + with strategy.scope(): + var1 = tf.Variable(...) + with strategy.extended.colocate_vars_with(var1): + # var2 and var3 will be created on the same device(s) as var1 + var2 = tf.Variable(...) + var3 = tf.Variable(...) + + def fn(v1, v2, v3): + # operates on v1 from var1, v2 from var2, and v3 from var3 + + # `fn` runs on every device `var1` is on, `var2` and `var3` will be there + # too. + strategy.extended.update(var1, fn, args=(var2, var3)) + ``` + + Args: + colocate_with_variable: A variable created in this strategy's `scope()`. + Variables created while in the returned context manager will be on the + same set of devices as `colocate_with_variable`. + + Returns: + A context manager. + """ + + def create_colocated_variable(next_creator, **kwargs): + _require_strategy_scope_extended(self) + kwargs["use_resource"] = True + kwargs["colocate_with"] = colocate_with_variable + return next_creator(**kwargs) + + _require_strategy_scope_extended(self) + self._validate_colocate_with_variable(colocate_with_variable) + return variable_scope.variable_creator_scope(create_colocated_variable) + + def _validate_colocate_with_variable(self, colocate_with_variable): + """Validate `colocate_with_variable` argument to `colocate_vars_with`.""" + pass + + def _make_dataset_iterator(self, dataset): + raise NotImplementedError("must be implemented in descendants") + + def _make_input_fn_iterator(self, input_fn, replication_mode): + raise NotImplementedError("must be implemented in descendants") + + def _experimental_distribute_dataset(self, dataset, options): + raise NotImplementedError("must be implemented in descendants") + + def _distribute_datasets_from_function(self, dataset_fn, options): + raise NotImplementedError("must be implemented in descendants") + + def _experimental_distribute_values_from_function(self, value_fn): + raise NotImplementedError("must be implemented in descendants") + + def _reduce(self, reduce_op, value): + # Default implementation until we have an implementation for each strategy. + dst = device_util.current() or self._default_device or "/device:CPU:0" + return self._local_results(self.reduce_to(reduce_op, value, dst))[0] + + def reduce_to(self, reduce_op, value, destinations, options=None): + """Combine (via e.g. sum or mean) values across replicas. + + `reduce_to` aggregates `tf.distribute.DistributedValues` and distributed + variables. It supports both dense values and `tf.IndexedSlices`. + + This API currently can only be called in cross-replica context. Other + variants to reduce values across replicas are: + * `tf.distribute.StrategyExtended.batch_reduce_to`: the batch version of + this API. + * `tf.distribute.ReplicaContext.all_reduce`: the counterpart of this API + in replica context. It supports both batched and non-batched all-reduce. + * `tf.distribute.Strategy.reduce`: a more convenient method to reduce + to the host in cross-replica context. + + `destinations` specifies where to reduce the value to, e.g. "GPU:0". You can + also pass in a `Tensor`, and the destinations will be the device of that + tensor. For all-reduce, pass the same to `value` and `destinations`. + + It can be used in `tf.distribute.ReplicaContext.merge_call` to write code + that works for all `tf.distribute.Strategy`. + + @tf.function + def step_fn(var): + + def merge_fn(strategy, value, var): + # All-reduce the value. Note that `value` here is a + # `tf.distribute.DistributedValues`. + reduced = strategy.extended.reduce_to(tf.distribute.ReduceOp.SUM, + value, destinations=var) + strategy.extended.update(var, lambda var, value: var.assign(value), + args=(reduced,)) + + value = tf.identity(1.) + tf.distribute.get_replica_context().merge_call(merge_fn, + args=(value, var)) + + def run(strategy): + with strategy.scope(): + v = tf.Variable(0.) + strategy.run(step_fn, args=(v,)) + return v + + run(tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])) + MirroredVariable:{ + 0: , + 1: + } + run(tf.distribute.experimental.CentralStorageStrategy( + compute_devices=["GPU:0", "GPU:1"], parameter_device="CPU:0")) + + run(tf.distribute.OneDeviceStrategy("GPU:0")) + + + Args: + reduce_op: a `tf.distribute.ReduceOp` value specifying how values should + be combined. Allows using string representation of the enum such as + "SUM", "MEAN". + value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` like object. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to reduce to. To perform an all-reduce, pass the same to `value` and + `destinations`. Note that if it's a `tf.Variable`, the value is reduced + to the devices of that variable, and this method doesn't update the + variable. + options: a `tf.distribute.experimental.CommunicationOptions`. Options to + perform collective operations. This overrides the default options if the + `tf.distribute.Strategy` takes one in the constructor. See + `tf.distribute.experimental.CommunicationOptions` for details of the + options. + + Returns: + A tensor or value reduced to `destinations`. + """ + with monitoring.MonitoredTimer( + distributed_api_time_counter.get_cell(self.__class__.__name__, "Reduce_to_eagerly") + ) if not ops.inside_function() else contextlib.nullcontext(): + if options is None: + options = collective_util.Options() + _require_cross_replica_or_default_context_extended(self) + assert not isinstance(destinations, (list, tuple)) + assert not isinstance(reduce_op, variable_scope.VariableAggregation) + if isinstance(reduce_op, six.string_types): + reduce_op = reduce_util.ReduceOp(reduce_op.upper()) + assert (reduce_op == reduce_util.ReduceOp.SUM or + reduce_op == reduce_util.ReduceOp.MEAN) + return self._reduce_to(reduce_op, value, destinations, options) + + def _reduce_to(self, reduce_op, value, destinations, options): + raise NotImplementedError("must be implemented in descendants") + + def batch_reduce_to(self, reduce_op, value_destination_pairs, options=None): + """Combine multiple `reduce_to` calls into one for faster execution. + + Similar to `reduce_to`, but accepts a list of (value, destinations) pairs. + It's more efficient than reduce each value separately. + + This API currently can only be called in cross-replica context. Other + variants to reduce values across replicas are: + * `tf.distribute.StrategyExtended.reduce_to`: the non-batch version of + this API. + * `tf.distribute.ReplicaContext.all_reduce`: the counterpart of this API + in replica context. It supports both batched and non-batched all-reduce. + * `tf.distribute.Strategy.reduce`: a more convenient method to reduce + to the host in cross-replica context. + + See `reduce_to` for more information. + + @tf.function + def step_fn(var): + + def merge_fn(strategy, value, var): + # All-reduce the value. Note that `value` here is a + # `tf.distribute.DistributedValues`. + reduced = strategy.extended.batch_reduce_to( + tf.distribute.ReduceOp.SUM, [(value, var)])[0] + strategy.extended.update(var, lambda var, value: var.assign(value), + args=(reduced,)) + + value = tf.identity(1.) + tf.distribute.get_replica_context().merge_call(merge_fn, + args=(value, var)) + + def run(strategy): + with strategy.scope(): + v = tf.Variable(0.) + strategy.run(step_fn, args=(v,)) + return v + + run(tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])) + MirroredVariable:{ + 0: , + 1: + } + run(tf.distribute.experimental.CentralStorageStrategy( + compute_devices=["GPU:0", "GPU:1"], parameter_device="CPU:0")) + + run(tf.distribute.OneDeviceStrategy("GPU:0")) + + + Args: + reduce_op: a `tf.distribute.ReduceOp` value specifying how values should + be combined. Allows using string representation of the enum such as + "SUM", "MEAN". + value_destination_pairs: a sequence of (value, destinations) pairs. See + `tf.distribute.Strategy.reduce_to` for descriptions. + options: a `tf.distribute.experimental.CommunicationOptions`. Options to + perform collective operations. This overrides the default options if the + `tf.distribute.Strategy` takes one in the constructor. See + `tf.distribute.experimental.CommunicationOptions` for details of the + options. + + Returns: + A list of reduced values, one per pair in `value_destination_pairs`. + """ + with monitoring.MonitoredTimer( + distributed_api_time_counter.get_cell(self.__class__.__name__, "Batch_reduce_to_eagerly") + ) if not ops.inside_function() else contextlib.nullcontext(): + if options is None: + options = collective_util.Options() + _require_cross_replica_or_default_context_extended(self) + assert not isinstance(reduce_op, variable_scope.VariableAggregation) + if isinstance(reduce_op, six.string_types): + reduce_op = reduce_util.ReduceOp(reduce_op.upper()) + return self._batch_reduce_to(reduce_op, value_destination_pairs, options) + + def _batch_reduce_to(self, reduce_op, value_destination_pairs, options): + return [ + self.reduce_to(reduce_op, t, destinations=v, options=options) + for t, v in value_destination_pairs + ] + + def _replica_ctx_all_reduce(self, reduce_op, value, options=None): + """All-reduce `value` across all replicas so that all get the final result. + + If `value` is a nested structure of tensors, all-reduces of these tensors + will be batched when possible. `options` can be set to hint the batching + behavior. + + This API must be called in a replica context. + + Args: + reduce_op: A `tf.distribute.ReduceOp` value specifying how values should + be combined. + value: Value to be reduced. A tensor or a nested structure of tensors. + options: A `tf.distribute.experimental.CommunicationOptions`. Options to + perform collective operations. This overrides the default options if the + `tf.distribute.Strategy` takes one in the constructor. + + Returns: + A tensor or a nested strucutre of tensors with the reduced values. The + structure is the same as `value`. + """ + if options is None: + options = collective_util.Options() + replica_context = get_replica_context() + assert replica_context, ( + "`StrategyExtended._replica_ctx_all_reduce` must be called in" + " a replica context") + + def merge_fn(_, flat_value): + return self.batch_reduce_to(reduce_op, [(v, v) for v in flat_value], + options) + + reduced = replica_context.merge_call(merge_fn, args=(nest.flatten(value),)) + return nest.pack_sequence_as(value, reduced) + + def _replica_ctx_update(self, var, fn, args=(), kwargs=None, group=True): + """Run `fn` with `args` and `kwargs` to update `var`.""" + # This method is called by ReplicaContext.update. Strategies who'd like to + # remove merge_call in this path should override this method. + replica_context = get_replica_context() + if not replica_context: + raise ValueError("`StrategyExtended._replica_ctx_update` must be called " + "in a replica context.") + + def merge_fn(_, *merged_args, **merged_kwargs): + return self.update(var, fn, merged_args, merged_kwargs, group=group) + + return replica_context.merge_call(merge_fn, args=args, kwargs=kwargs) + + def _gather_to(self, value, destinations, axis, options=None): + """Gather `value` across replicas along axis-th dimension to `destinations`. + + `gather_to` gathers `tf.distribute.DistributedValues` or `tf.Tensor`-like + object, along `axis`-th dimension. It supports only dense tensors but NOT + sparse tensor. This API can only be called in cross-replica context. + + Args: + value: a `tf.distribute.DistributedValues`, or a `tf.Tensor` like object. + destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a + `tf.Tensor` alike object, or a device string. It specifies the devices + to reduce to. To perform an all-gather, pass the same to `value` and + `destinations`. Note that if it's a `tf.Variable`, the value is reduced + to the devices of that variable, and this method doesn't update the + variable. + axis: 0-D int32 Tensor. Dimension along which to gather. Must be in the + range [0, rank(value)). + options: a `tf.distribute.experimental.CommunicationOptions`. Options to + perform collective operations. This overrides the default options if the + `tf.distribute.Strategy` takes one in the constructor. See + `tf.distribute.experimental.CommunicationOptions` for details of the + options. + + Returns: + A tensor or value gathered to `destinations`. + """ + _require_cross_replica_or_default_context_extended(self) + assert not isinstance(destinations, (list, tuple)) + if options is None: + options = collective_util.Options() + return self._gather_to_implementation(value, destinations, axis, options) + + def _gather_to_implementation(self, value, destinations, axis, options): + raise NotImplementedError("_gather_to must be implemented in descendants") + + def _batch_gather_to(self, value_destination_pairs, axis, options=None): + _require_cross_replica_or_default_context_extended(self) + if options is None: + options = collective_util.Options() + return [ + self._gather_to(t, destinations=v, axis=axis, options=options) + for t, v in value_destination_pairs + ] + + def update(self, var, fn, args=(), kwargs=None, group=True): + """Run `fn` to update `var` using inputs mirrored to the same devices. + + `tf.distribute.StrategyExtended.update` takes a distributed variable `var` + to be updated, an update function `fn`, and `args` and `kwargs` for `fn`. It + applies `fn` to each component variable of `var` and passes corresponding + values from `args` and `kwargs`. Neither `args` nor `kwargs` may contain + per-replica values. If they contain mirrored values, they will be unwrapped + before calling `fn`. For example, `fn` can be `assign_add` and `args` can be + a mirrored DistributedValues where each component contains the value to be + added to this mirrored variable `var`. Calling `update` will call + `assign_add` on each component variable of `var` with the corresponding + tensor value on that device. + + Example usage: + + ```python + strategy = tf.distribute.MirroredStrategy(['GPU:0', 'GPU:1']) # With 2 + devices + with strategy.scope(): + v = tf.Variable(5.0, aggregation=tf.VariableAggregation.SUM) + def update_fn(v): + return v.assign(1.0) + result = strategy.extended.update(v, update_fn) + # result is + # Mirrored:{ + # 0: tf.Tensor(1.0, shape=(), dtype=float32), + # 1: tf.Tensor(1.0, shape=(), dtype=float32) + # } + ``` + + If `var` is mirrored across multiple devices, then this method implements + logic as following: + + ```python + results = {} + for device, v in var: + with tf.device(device): + # args and kwargs will be unwrapped if they are mirrored. + results[device] = fn(v, *args, **kwargs) + return merged(results) + ``` + + Otherwise, this method returns `fn(var, *args, **kwargs)` colocated with + `var`. + + Args: + var: Variable, possibly mirrored to multiple devices, to operate on. + fn: Function to call. Should take the variable as the first argument. + args: Tuple or list. Additional positional arguments to pass to `fn()`. + kwargs: Dict with keyword arguments to pass to `fn()`. + group: Boolean. Defaults to True. If False, the return value will be + unwrapped. + + Returns: + By default, the merged return value of `fn` across all replicas. The + merged result has dependencies to make sure that if it is evaluated at + all, the side effects (updates) will happen on every replica. If instead + "group=False" is specified, this function will return a nest of lists + where each list has an element per replica, and the caller is responsible + for ensuring all elements are executed. + """ + # TODO(b/178944108): Update the documentation to relfect the fact that + # `update` can be called in a replica context. + if kwargs is None: + kwargs = {} + replica_context = get_replica_context() + # pylint: disable=protected-access + if (replica_context is None or replica_context is + _get_default_replica_context()): + fn = autograph.tf_convert( + fn, autograph_ctx.control_status_ctx(), convert_by_default=False) + with self._container_strategy().scope(): + return self._update(var, fn, args, kwargs, group) + else: + return self._replica_ctx_update( + var, fn, args=args, kwargs=kwargs, group=group) + + def _update(self, var, fn, args, kwargs, group): + raise NotImplementedError("must be implemented in descendants") + + def _local_results(self, val): + """Returns local results per replica as a tuple.""" + if isinstance(val, ds_types.DistributedValues): + return val._values # pylint: disable=protected-access + + if nest.is_nested(val): + replica_values = [] + + def get_values(x, index): + if isinstance(x, ds_types.DistributedValues): + return x._values[index] # pylint: disable=protected-access + return x + + for i in range(len(self.worker_devices)): + replica_values.append( + nest.map_structure( + lambda x: get_values(x, i), # pylint: disable=cell-var-from-loop + val)) + return tuple(replica_values) + return (val,) + + def value_container(self, value): + """Returns the container that this per-replica `value` belongs to. + + Args: + value: A value returned by `run()` or a variable created in `scope()`. + + Returns: + A container that `value` belongs to. + If value does not belong to any container (including the case of + container having been destroyed), returns the value itself. + `value in experimental_local_results(value_container(value))` will + always be true. + """ + raise NotImplementedError("must be implemented in descendants") + + def _group(self, value, name=None): + """Implementation of `group`.""" + value = nest.flatten(self._local_results(value)) + + if len(value) != 1 or name is not None: + return control_flow_ops.group(value, name=name) + # Special handling for the common case of one op. + v, = value + if hasattr(v, "op"): + v = v.op + return v + + @property + def experimental_require_static_shapes(self): + """Returns `True` if static shape is required; `False` otherwise.""" + return self._require_static_shapes + + @property + def _num_replicas_in_sync(self): + """Returns number of replicas over which gradients are aggregated.""" + raise NotImplementedError("must be implemented in descendants") + + @property + def worker_devices(self): + """Returns the tuple of all devices used to for compute replica execution. + """ + # TODO(josh11b): More docstring + raise NotImplementedError("must be implemented in descendants") + + @property + def parameter_devices(self): + """Returns the tuple of all devices used to place variables.""" + # TODO(josh11b): More docstring + raise NotImplementedError("must be implemented in descendants") + + def _configure(self, + session_config=None, + cluster_spec=None, + task_type=None, + task_id=None): + """Configures the strategy class.""" + del session_config, cluster_spec, task_type, task_id + + def _update_config_proto(self, config_proto): + return copy.deepcopy(config_proto) + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings. + + Multi-worker training refers to the setup where the training is + distributed across multiple workers, as opposed to the case where + only a local process performs the training. This function is + used by higher-level APIs such as Keras' `model.fit()` to infer + for example whether or not a distribute coordinator should be run, + and thus TensorFlow servers should be started for communication + with other servers in the cluster, or whether or not saving/restoring + checkpoints is relevant for preemption fault tolerance. + + Subclasses should override this to provide whether the strategy is + currently in multi-worker setup. + + Experimental. Signature and implementation are subject to change. + """ + raise NotImplementedError("must be implemented in descendants") + + +@tf_export(v1=["distribute.StrategyExtended"]) # pylint: disable=missing-docstring +class StrategyExtendedV1(StrategyExtendedV2): + + __doc__ = StrategyExtendedV2.__doc__ + + def experimental_make_numpy_dataset(self, numpy_input, session=None): + """Makes a dataset for input provided via a numpy array. + + This avoids adding `numpy_input` as a large constant in the graph, + and copies the data to the machine or machines that will be processing + the input. + + Args: + numpy_input: A nest of NumPy input arrays that will be distributed evenly + across all replicas. Note that lists of Numpy arrays are stacked, as + that is normal `tf.data.Dataset` behavior. + session: (TensorFlow v1.x graph execution only) A session used for + initialization. + + Returns: + A `tf.data.Dataset` representing `numpy_input`. + """ + _require_cross_replica_or_default_context_extended(self) + return self._experimental_make_numpy_dataset(numpy_input, session=session) + + def _experimental_make_numpy_dataset(self, numpy_input, session): + raise NotImplementedError("must be implemented in descendants") + + def broadcast_to(self, tensor, destinations): + """Mirror a tensor on one device to all worker devices. + + Args: + tensor: A Tensor value to broadcast. + destinations: A mirrored variable or device string specifying the + destination devices to copy `tensor` to. + + Returns: + A value mirrored to `destinations` devices. + """ + assert destinations is not None # from old strategy.broadcast() + # TODO(josh11b): More docstring + _require_cross_replica_or_default_context_extended(self) + assert not isinstance(destinations, (list, tuple)) + return self._broadcast_to(tensor, destinations) + + def _broadcast_to(self, tensor, destinations): + raise NotImplementedError("must be implemented in descendants") + + @deprecated(None, "please use `run` instead.") + def experimental_run_steps_on_iterator(self, + fn, + iterator, + iterations=1, + initial_loop_values=None): + """DEPRECATED: please use `run` instead. + + Run `fn` with input from `iterator` for `iterations` times. + + This method can be used to run a step function for training a number of + times using input from a dataset. + + Args: + fn: function to run using this distribution strategy. The function must + have the following signature: `def fn(context, inputs)`. `context` is an + instance of `MultiStepContext` that will be passed when `fn` is run. + `context` can be used to specify the outputs to be returned from `fn` + by calling `context.set_last_step_output`. It can also be used to + capture non tensor outputs by `context.set_non_tensor_output`. See + `MultiStepContext` documentation for more information. `inputs` will + have same type/structure as `iterator.get_next()`. Typically, `fn` + will use `call_for_each_replica` method of the strategy to distribute + the computation over multiple replicas. + iterator: Iterator of a dataset that represents the input for `fn`. The + caller is responsible for initializing the iterator as needed. + iterations: (Optional) Number of iterations that `fn` should be run. + Defaults to 1. + initial_loop_values: (Optional) Initial values to be passed into the + loop that runs `fn`. Defaults to `None`. # TODO(priyag): Remove + initial_loop_values argument when we have a mechanism to infer the + outputs of `fn`. + + Returns: + Returns the `MultiStepContext` object which has the following properties, + among other things: + - run_op: An op that runs `fn` `iterations` times. + - last_step_outputs: A dictionary containing tensors set using + `context.set_last_step_output`. Evaluating this returns the value of + the tensors after the last iteration. + - non_tensor_outputs: A dictionary containing anything that was set by + `fn` by calling `context.set_non_tensor_output`. + """ + _require_cross_replica_or_default_context_extended(self) + with self._container_strategy().scope(): + return self._experimental_run_steps_on_iterator(fn, iterator, iterations, + initial_loop_values) + + def _experimental_run_steps_on_iterator(self, fn, iterator, iterations, + initial_loop_values): + raise NotImplementedError("must be implemented in descendants") + + def call_for_each_replica(self, fn, args=(), kwargs=None): + """Run `fn` once per replica. + + `fn` may call `tf.get_replica_context()` to access methods such as + `replica_id_in_sync_group` and `merge_call()`. + + `merge_call()` is used to communicate between the replicas and + re-enter the cross-replica context. All replicas pause their execution + having encountered a `merge_call()` call. After that the + `merge_fn`-function is executed. Its results are then unwrapped and + given back to each replica call. After that execution resumes until + `fn` is complete or encounters another `merge_call()`. Example: + + ```python + # Called once in "cross-replica" context. + def merge_fn(distribution, three_plus_replica_id): + # sum the values across replicas + return sum(distribution.experimental_local_results(three_plus_replica_id)) + + # Called once per replica in `distribution`, in a "replica" context. + def fn(three): + replica_ctx = tf.get_replica_context() + v = three + replica_ctx.replica_id_in_sync_group + # Computes the sum of the `v` values across all replicas. + s = replica_ctx.merge_call(merge_fn, args=(v,)) + return s + v + + with distribution.scope(): + # in "cross-replica" context + ... + merged_results = distribution.run(fn, args=[3]) + # merged_results has the values from every replica execution of `fn`. + # This statement prints a list: + print(distribution.experimental_local_results(merged_results)) + ``` + + Args: + fn: function to run (will be run once per replica). + args: Tuple or list with positional arguments for `fn`. + kwargs: Dict with keyword arguments for `fn`. + + Returns: + Merged return value of `fn` across all replicas. + """ + _require_cross_replica_or_default_context_extended(self) + if kwargs is None: + kwargs = {} + with self._container_strategy().scope(): + return self._call_for_each_replica(fn, args, kwargs) + + def _call_for_each_replica(self, fn, args, kwargs): + raise NotImplementedError("must be implemented in descendants") + + def read_var(self, v): + """Reads the value of a variable. + + Returns the aggregate value of a replica-local variable, or the + (read-only) value of any other variable. + + Args: + v: A variable allocated within the scope of this `tf.distribute.Strategy`. + + Returns: + A tensor representing the value of `v`, aggregated across replicas if + necessary. + """ + raise NotImplementedError("must be implemented in descendants") + + def update_non_slot( + self, colocate_with, fn, args=(), kwargs=None, group=True): + """Runs `fn(*args, **kwargs)` on `colocate_with` devices. + + Used to update non-slot variables. + + DEPRECATED: TF 1.x ONLY. + + Args: + colocate_with: Devices returned by `non_slot_devices()`. + fn: Function to execute. + args: Tuple or list. Positional arguments to pass to `fn()`. + kwargs: Dict with keyword arguments to pass to `fn()`. + group: Boolean. Defaults to True. If False, the return value will be + unwrapped. + + Returns: + Return value of `fn`, possibly merged across devices. + """ + _require_cross_replica_or_default_context_extended(self) + if kwargs is None: + kwargs = {} + fn = autograph.tf_convert( + fn, autograph_ctx.control_status_ctx(), convert_by_default=False) + with self._container_strategy().scope(): + return self._update_non_slot(colocate_with, fn, args, kwargs, group) + + def _update_non_slot(self, colocate_with, fn, args, kwargs, group): + raise NotImplementedError("must be implemented in descendants") + + def non_slot_devices(self, var_list): + """Device(s) for non-slot variables. + + DEPRECATED: TF 1.x ONLY. + + This method returns non-slot devices where non-slot variables are placed. + Users can create non-slot variables on these devices by using a block: + + ```python + with tf.distribute.StrategyExtended.colocate_vars_with(tf.distribute.StrategyExtended.non_slot_devices(...)): + ... + ``` + + Args: + var_list: The list of variables being optimized, needed with the + default `tf.distribute.Strategy`. + Returns: + A sequence of devices for non-slot variables. + """ + raise NotImplementedError("must be implemented in descendants") + + def _use_merge_call(self): + """Whether to use merge-calls inside the distributed strategy.""" + return True + + @property + def experimental_between_graph(self): + """Whether the strategy uses between-graph replication or not. + + This is expected to return a constant value that will not be changed + throughout its life cycle. + """ + raise NotImplementedError("must be implemented in descendants") + + @property + def experimental_should_init(self): + """Whether initialization is needed.""" + raise NotImplementedError("must be implemented in descendants") + + @property + def should_checkpoint(self): + """Whether checkpointing is needed.""" + raise NotImplementedError("must be implemented in descendants") + + @property + def should_save_summary(self): + """Whether saving summaries is needed.""" + raise NotImplementedError("must be implemented in descendants") + + +# A note about the difference between the context managers +# `ReplicaContext` (defined here) and `_CurrentDistributionContext` +# (defined above) used by `tf.distribute.Strategy.scope()`: +# +# * a ReplicaContext is only present during a `run()` +# call (except during a `merge_run` call) and in such a scope it +# will be returned by calls to `get_replica_context()`. Implementers of new +# Strategy descendants will frequently also need to +# define a descendant of ReplicaContext, and are responsible for +# entering and exiting this context. +# +# * Strategy.scope() sets up a variable_creator scope that +# changes variable creation calls (e.g. to make mirrored +# variables). This is intended as an outer scope that users enter once +# around their model creation and graph definition. There is no +# anticipated need to define descendants of _CurrentDistributionContext. +# It sets the current Strategy for purposes of +# `get_strategy()` and `has_strategy()` +# and switches the thread mode to a "cross-replica context". +class ReplicaContextBase(object): + """A class with a collection of APIs that can be called in a replica context. + + You can use `tf.distribute.get_replica_context` to get an instance of + `ReplicaContext`, which can only be called inside the function passed to + `tf.distribute.Strategy.run`. + + >>> strategy = tf.distribute.MirroredStrategy(['GPU:0', 'GPU:1']) + >>> def func(): + ... replica_context = tf.distribute.get_replica_context() + ... return replica_context.replica_id_in_sync_group + >>> strategy.run(func) + PerReplica:{ + 0: , + 1: + } + """ + + def __init__(self, strategy, replica_id_in_sync_group): + """Creates a ReplicaContext. + + Args: + strategy: A `tf.distribute.Strategy`. + replica_id_in_sync_group: An integer, a `Tensor` or None. Prefer an + integer whenever possible to avoid issues with nested `tf.function`. It + accepts a `Tensor` only to be compatible with `tpu.replicate`. + """ + self._strategy = strategy + self._thread_context = _InReplicaThreadMode( # pylint: disable=protected-access + self) + if not (replica_id_in_sync_group is None or + tensor_util.is_tf_type(replica_id_in_sync_group) or + isinstance(replica_id_in_sync_group, int)): + raise ValueError( + "replica_id_in_sync_group can only be an integer, a Tensor or None.") + self._replica_id_in_sync_group = replica_id_in_sync_group + # We need this check because TPUContext extends from ReplicaContext and + # does not pass a strategy object since it is used by TPUEstimator. + if strategy: + self._local_replica_id = strategy.extended._get_local_replica_id( + replica_id_in_sync_group) + self._summary_recording_distribution_strategy = None + + @doc_controls.do_not_generate_docs + def __enter__(self): + _push_per_thread_mode(self._thread_context) + + def replica_id_is_zero(): + return math_ops.equal(self.replica_id_in_sync_group, + constant_op.constant(0)) + + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + self._summary_recording_distribution_strategy = ( + summary_state.is_recording_distribution_strategy) + summary_state.is_recording_distribution_strategy = replica_id_is_zero + + @doc_controls.do_not_generate_docs + def __exit__(self, exception_type, exception_value, traceback): + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + summary_state.is_recording_distribution_strategy = ( + self._summary_recording_distribution_strategy) + _pop_per_thread_mode() + + def merge_call(self, merge_fn, args=(), kwargs=None): + """Merge args across replicas and run `merge_fn` in a cross-replica context. + + This allows communication and coordination when there are multiple calls + to the step_fn triggered by a call to `strategy.run(step_fn, ...)`. + + See `tf.distribute.Strategy.run` for an explanation. + + If not inside a distributed scope, this is equivalent to: + + ``` + strategy = tf.distribute.get_strategy() + with cross-replica-context(strategy): + return merge_fn(strategy, *args, **kwargs) + ``` + + Args: + merge_fn: Function that joins arguments from threads that are given as + PerReplica. It accepts `tf.distribute.Strategy` object as + the first argument. + args: List or tuple with positional per-thread arguments for `merge_fn`. + kwargs: Dict with keyword per-thread arguments for `merge_fn`. + + Returns: + The return value of `merge_fn`, except for `PerReplica` values which are + unpacked. + """ + require_replica_context(self) + if kwargs is None: + kwargs = {} + + merge_fn = autograph.tf_convert( + merge_fn, autograph_ctx.control_status_ctx(), convert_by_default=False) + return self._merge_call(merge_fn, args, kwargs) + + def _merge_call(self, merge_fn, args, kwargs): + """Default implementation for single replica.""" + _push_per_thread_mode( # thread-local, so not needed with multiple threads + _CrossReplicaThreadMode(self._strategy)) # pylint: disable=protected-access + try: + return merge_fn(self._strategy, *args, **kwargs) + finally: + _pop_per_thread_mode() + + @property + def num_replicas_in_sync(self): + """Returns number of replicas that are kept in sync.""" + return self._strategy.num_replicas_in_sync + + @property + def replica_id_in_sync_group(self): + """Returns the id of the replica. + + This identifies the replica among all replicas that are kept in sync. The + value of the replica id can range from 0 to + `tf.distribute.ReplicaContext.num_replicas_in_sync` - 1. + + NOTE: This is not guaranteed to be the same ID as the XLA replica ID use + for low-level operations such as collective_permute. + + Returns: + a `Tensor`. + """ + # It's important to prefer making the Tensor at call time whenever possible. + # Keeping Tensors in global states doesn't work well with nested + # tf.function, since it's possible that the tensor is generated in one func + # graph, and gets captured by another, which will result in a subtle "An op + # outside of the function building code is being passed a Graph tensor" + # error. Making the tensor at call time to ensure it is the same graph where + # it's used. However to be compatible with tpu.replicate(), + # self._replica_id_in_sync_group can also be a Tensor. + if tensor_util.is_tf_type(self._replica_id_in_sync_group): + return self._replica_id_in_sync_group + return constant_op.constant( + self._replica_id_in_sync_group, + dtypes.int32, + name="replica_id_in_sync_group") + + @property + def _replica_id(self): + """This is the local replica id in a given sync group.""" + return self._local_replica_id + + @property + def strategy(self): + """The current `tf.distribute.Strategy` object.""" + return self._strategy + + @property + @deprecation.deprecated(None, "Please avoid relying on devices property.") + def devices(self): + """Returns the devices this replica is to be executed on, as a tuple of strings. + + NOTE: For `tf.distribute.MirroredStrategy` and + `tf.distribute.experimental.MultiWorkerMirroredStrategy`, this returns a + nested + list of device strings, e.g., [["GPU:0"]]. + """ + require_replica_context(self) + return (device_util.current(),) + + def all_reduce(self, reduce_op, value, options=None): + """All-reduces `value` across all replicas. + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> def step_fn(): + ... ctx = tf.distribute.get_replica_context() + ... value = tf.identity(1.) + ... return ctx.all_reduce(tf.distribute.ReduceOp.SUM, value) + >>> strategy.experimental_local_results(strategy.run(step_fn)) + (, + ) + + It supports batched operations. You can pass a list of values and it + attempts to batch them when possible. You can also specify `options` + to indicate the desired batching behavior, e.g. batch the values into + multiple packs so that they can better overlap with computations. + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> def step_fn(): + ... ctx = tf.distribute.get_replica_context() + ... value1 = tf.identity(1.) + ... value2 = tf.identity(2.) + ... return ctx.all_reduce(tf.distribute.ReduceOp.SUM, [value1, value2]) + >>> strategy.experimental_local_results(strategy.run(step_fn)) + ([, + ], + [, + ]) + + Note that all replicas need to participate in the all-reduce, otherwise this + operation hangs. Note that if there're multiple all-reduces, they need to + execute in the same order on all replicas. Dispatching all-reduce based on + conditions is usually error-prone. + + Known limitation: if `value` contains `tf.IndexedSlices`, attempting to + compute gradient w.r.t `value` would result in an error. + + This API currently can only be called in the replica context. Other + variants to reduce values across replicas are: + * `tf.distribute.StrategyExtended.reduce_to`: the reduce and all-reduce API + in the cross-replica context. + * `tf.distribute.StrategyExtended.batch_reduce_to`: the batched reduce and + all-reduce API in the cross-replica context. + * `tf.distribute.Strategy.reduce`: a more convenient method to reduce + to the host in cross-replica context. + + Args: + reduce_op: a `tf.distribute.ReduceOp` value specifying how values should + be combined. Allows using string representation of the enum such as + "SUM", "MEAN". + value: a potentially nested structure of `tf.Tensor` or `tf.IndexedSlices` which + `tf.nest.flatten` accepts. The structure and the shapes of `value` need to be + same on all replicas. + options: a `tf.distribute.experimental.CommunicationOptions`. Options to + perform collective operations. This overrides the default options if the + `tf.distribute.Strategy` takes one in the constructor. See + `tf.distribute.experimental.CommunicationOptions` for details of the + options. + + Returns: + A nested structure of `tf.Tensor` with the reduced values. The structure + is the same as `value`. + """ + flattened_value = nest.flatten(value) + has_indexed_slices = False + + for v in flattened_value: + if isinstance(v, indexed_slices.IndexedSlices): + has_indexed_slices = True + + if isinstance(reduce_op, six.string_types): + reduce_op = reduce_util.ReduceOp(reduce_op.upper()) + if options is None: + options = collective_util.Options() + + def batch_all_reduce(strategy, *value_flat): + return strategy.extended.batch_reduce_to( + reduce_op, [(v, _batch_reduce_destination(v)) for v in value_flat], + options) + + # Due to the use of `capture_call_time_value` in collective ops, we have + # to maintain two branches: one w/ merge_call and one w/o. Details can be + # found in b/184009754. + if self._strategy.extended._use_merge_call(): # pylint: disable=protected-access + # TODO(cjfj): Work out why `batch_reduce` doesn't return the correct grad. + if has_indexed_slices: + return nest.pack_sequence_as( + value, + self.merge_call(batch_all_reduce, args=flattened_value)) + + @custom_gradient.custom_gradient + def grad_wrapper(*xs): + ys = self.merge_call(batch_all_reduce, args=xs) + # The gradient of an all-sum is itself an all-sum (all-mean, likewise). + return ys, lambda *dy_s: self.all_reduce(reduce_op, dy_s) + return nest.pack_sequence_as(value, grad_wrapper(*flattened_value)) + else: + if has_indexed_slices: + return nest.pack_sequence_as( + value, + self._strategy.extended._replica_ctx_all_reduce( # pylint: disable=protected-access + reduce_op, flattened_value, options)) + + @custom_gradient.custom_gradient + def grad_wrapper(*xs): + ys = self._strategy.extended._replica_ctx_all_reduce( # pylint: disable=protected-access + reduce_op, xs, options) + # The gradient of an all-sum is itself an all-sum (all-mean, likewise). + return ys, lambda *dy_s: self.all_reduce(reduce_op, dy_s) + + return nest.pack_sequence_as(value, grad_wrapper(*flattened_value)) + + # TODO(josh11b): Implement `start_all_reduce(method, t)` for efficient + # all-reduce. It would return a function returning the result of reducing `t` + # across all replicas. The caller would wait to call this function until they + # needed the reduce result, allowing an efficient implementation: + # * With eager execution, the reduction could be performed asynchronously + # in the background, not blocking until the result was needed. + # * When constructing a graph, it could batch up all reduction requests up + # to that point that the first result is needed. Most likely this can be + # implemented in terms of `merge_call()` and `batch_reduce_to()`. + + +@tf_export("distribute.ReplicaContext", v1=[]) +class ReplicaContext(ReplicaContextBase): + + __doc__ = ReplicaContextBase.__doc__ + + def all_gather(self, value, axis, options=None): + """All-gathers `value` across all replicas along `axis`. + + Note: An `all_gather` method can only be called in replica context. For + a cross-replica context counterpart, see `tf.distribute.Strategy.gather`. + All replicas need to participate in the all-gather, otherwise this + operation hangs. So if `all_gather` is called in any replica, it must be + called in all replicas. + + Note: If there are multiple `all_gather` calls, they need to be executed in + the same order on all replicas. Dispatching `all_gather` based on conditions + is usually error-prone. + + For all strategies except `tf.distribute.TPUStrategy`, the input + `value` on different replicas must have the same rank, and their shapes must + be the same in all dimensions except the `axis`-th dimension. In other + words, their shapes cannot be different in a dimension `d` where `d` does + not equal to the `axis` argument. For example, given a + `tf.distribute.DistributedValues` with component tensors of shape + `(1, 2, 3)` and `(1, 3, 3)` on two replicas, you can call + `all_gather(..., axis=1, ...)` on it, but not `all_gather(..., axis=0, ...)` + or `all_gather(..., axis=2, ...)`. However, with + `tf.distribute.TPUStrategy`, all tensors must have exactly the same rank and + same shape. + + Note: The input `value` must have a non-zero rank. Otherwise, consider using + `tf.expand_dims` before gathering them. + + You can pass in a single tensor to all-gather: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> @tf.function + ... def gather_value(): + ... ctx = tf.distribute.get_replica_context() + ... local_value = tf.constant([1, 2, 3]) + ... return ctx.all_gather(local_value, axis=0) + >>> result = strategy.run(gather_value) + >>> result + PerReplica:{ + 0: , + 1: + } + >>> strategy.experimental_local_results(result) + (, + ) + + + You can also pass in a nested structure of tensors to all-gather, say, a + list: + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> @tf.function + ... def gather_nest(): + ... ctx = tf.distribute.get_replica_context() + ... value_1 = tf.constant([1, 2, 3]) + ... value_2 = tf.constant([[1, 2], [3, 4]]) + ... # all_gather a nest of `tf.distribute.DistributedValues` + ... return ctx.all_gather([value_1, value_2], axis=0) + >>> result = strategy.run(gather_nest) + >>> result + [PerReplica:{ + 0: , + 1: + }, PerReplica:{ + 0: , + 1: + }] + >>> strategy.experimental_local_results(result) + ([, + ], + [, + ]) + + + What if you are all-gathering tensors with different shapes on different + replicas? Consider the following example with two replicas, where you have + `value` as a nested structure consisting of two items to all-gather, `a` and + `b`. + + * On Replica 0, `value` is `{'a': [0], 'b': [[0, 1]]}`. + * On Replica 1, `value` is `{'a': [1], 'b': [[2, 3], [4, 5]]}`. + * Result for `all_gather` with `axis=0` (on each of the replicas) is: + + ``` + {'a': [1, 2], 'b': [[0, 1], [2, 3], [4, 5]]} + ``` + + Args: + value: a nested structure of `tf.Tensor` which `tf.nest.flatten` accepts, + or a `tf.distribute.DistributedValues` instance. The structure of the + `tf.Tensor` need to be same on all replicas. The underlying tensor + constructs can only be dense tensors with non-zero rank, NOT + `tf.IndexedSlices`. + axis: 0-D int32 Tensor. Dimension along which to gather. + options: a `tf.distribute.experimental.CommunicationOptions`. Options to + perform collective operations. This overrides the default options if the + `tf.distribute.Strategy` takes one in the constructor. See + `tf.distribute.experimental.CommunicationOptions` for details of the + options. + + Returns: + A nested structure of `tf.Tensor` with the gathered values. The structure + is the same as `value`. + """ + for v in nest.flatten(value): + if isinstance(v, indexed_slices.IndexedSlices): + raise NotImplementedError("all_gather does not support IndexedSlices") + + if options is None: + options = collective_util.Options() + + def batch_all_gather(strategy, *value_flat): + return strategy.extended._batch_gather_to( # pylint: disable=protected-access + [(v, _batch_reduce_destination(v)) for v in value_flat], axis, + options) + + @custom_gradient.custom_gradient + def grad_wrapper(*xs): + ys = self.merge_call(batch_all_gather, args=xs) + + def grad(*dy_s): + grads = self.all_reduce(reduce_util.ReduceOp.SUM, dy_s) + new_grads = [] + for i, grad in enumerate(grads): + input_shape = array_ops.shape(xs[i]) + axis_dim = array_ops.reshape(input_shape[axis], [1]) + with ops.control_dependencies([array_ops.identity(grads)]): + d = self.all_gather(axis_dim, axis=0) + begin_dim = math_ops.reduce_sum(d[:self.replica_id_in_sync_group]) + end_dim = begin_dim + array_ops.shape(xs[i])[axis] + new_grad = array_ops.gather( + grad, axis=axis, indices=math_ops.range(begin_dim, end_dim)) + new_grads.append(new_grad) + return new_grads + + return ys, grad + + return nest.pack_sequence_as(value, grad_wrapper(*nest.flatten(value))) + + def _update(self, var, fn, args=(), kwargs=None, group=True): + """Run `fn` to update `var` with `args` and `kwargs` in replica context. + + `tf.distribute.ReplicaContext.update` takes a (distributed) variable `var` + to be updated, an update function `fn`, and `args` and `kwargs` for `fn`. + `fn` applies to each component variable of `var` with corresponding input + values from `args` and `kwargs`. + + Example usage: + + >>> strategy = tf.distribute.MirroredStrategy(['GPU:0', 'GPU:1']) # 2 replicas + >>> with strategy.scope(): + ... distributed_variable = tf.Variable(5.0) + >>> distributed_variable + MirroredVariable:{ + 0: , + 1: + } + >>> def replica_fn(v): + ... value = tf.identity(1.0) + ... replica_context = tf.distribute.get_replica_context() + ... update_fn = lambda var, value: var.assign(value) + ... replica_context._update(v, update_fn, args=(value,)) + >>> strategy.run(replica_fn, args=(distributed_variable,)) + >>> distributed_variable + MirroredVariable:{ + 0: , + 1: + } + + This API must be called in a replica context. + + Note that if `var` is a MirroredVariable (i.e., the type of variable created + under the scope of a synchronous strategy, and is synchronized on-write, see + `tf.VariableSynchronization` for more information) and `args`/`kwargs` + contains different values for different replicas, `var` will be dangerously + out of synchronization. Thus we recommend using `variable.assign(value)` as + long as you can, which under the hood aggregates the updates and guarantees + the synchronization. The case where you actually want this API instead of + `variable.assign(value)` is that before assigning `value` to the `variable`, + you'd like to conduct some pre-`assign` computation colocated with the + variable devices (i.e. where variables reside, for MirroredStrategy they are + the same as the compute device, for ParameterServerStrategy they refer to + parameter servers). E.g., + + ```python + strategy = tf.distribute.MirroredStrategy(['GPU:0', 'GPU:1']) # 2 replicas + with strategy.scope(): + v = tf.Variable(5.0, aggregation=tf.VariableAggregation.SUM) + def replica_fn(inputs): + value = computation(inputs) + replica_context = tf.distribute.get_replica_context() + reduced_value = replica_context.all_reduce(value) + + def update_fn(var, value): + # this computation will colocate with `var`'s device + updated_value = post_reduce_pre_update_computation(value) + var.assign(value) + + replica_context._update(v, update_fn, args=(reduced_value,)) + + strategy.run(replica_fn, args=(inputs,)) + ``` + + This code snippet is consistent across all strategies. If you directly + compute and use `assign` in the replica context instead of wrapping it with + `update`, for strategies with fewer variable devices than compute devices + (e.g., parameter server strategy, usually), the + `post_reduce_pre_update_computation` will happen + N==number_of_compute_devices times which is less performant. + + + Args: + var: Variable, possibly distributed to multiple devices, to operate on. + fn: Function to call. Should take the variable as the first argument. + args: Tuple or list. Additional positional arguments to pass to `fn()`. + kwargs: Dict with keyword arguments to pass to `fn()`. + group: Boolean. Defaults to True. Most strategies enter a merge_call to + conduct update in cross-replica context, and group=True guarantees updates + on all replicas is executed. + + Returns: + The return value of `fn` for the local replica. + """ + if kwargs is None: + kwargs = {} + return self._strategy.extended._replica_ctx_update(var, fn, args=args, kwargs=kwargs, group=group) # pylint: disable=protected-access + + +@tf_export(v1=["distribute.ReplicaContext"]) +class ReplicaContextV1(ReplicaContextBase): + __doc__ = ReplicaContextBase.__doc__ + + +def _batch_reduce_destination(x): + """Returns the destinations for batch all-reduce.""" + if isinstance(x, tensor_lib.Tensor): + # If this is a one device strategy. + return x.device + else: + return x +# ------------------------------------------------------------------------------ + + +class _DefaultDistributionStrategyV1(StrategyV1): + """Default `tf.distribute.Strategy` if none is explicitly selected.""" + + def __init__(self): + if not _creating_default_strategy_singleton: + raise RuntimeError("Should only create a single instance of " + "_DefaultDistributionStrategy") + super(_DefaultDistributionStrategyV1, + self).__init__(_DefaultDistributionExtended(self)) + + def __deepcopy__(self, memo): + del memo + raise RuntimeError("Should only create a single instance of " + "_DefaultDistributionStrategy") + + +class _DefaultDistributionStrategy(Strategy): + """Default `tf.distribute.Strategy` if none is explicitly selected.""" + + def __init__(self): + if not _creating_default_strategy_singleton: + raise RuntimeError("Should only create a single instance of " + "_DefaultDistributionStrategy") + super(_DefaultDistributionStrategy, self).__init__( + _DefaultDistributionExtended(self)) + + def __deepcopy__(self, memo): + del memo + raise RuntimeError("Should only create a single instance of " + "_DefaultDistributionStrategy") + + +class _DefaultDistributionContext(object): + """Context manager setting the default `tf.distribute.Strategy`.""" + + __slots__ = ["_var_creator_scope", "_strategy", "_nested_count"] + + def __init__(self, strategy): + + def creator(next_creator, **kwargs): + _require_strategy_scope_strategy(strategy) + return next_creator(**kwargs) + + self._var_creator_scope = variable_scope.variable_creator_scope(creator) + self._strategy = strategy + self._nested_count = 0 + + def __enter__(self): + # Allow this scope to be entered if this strategy is already in scope. + if has_strategy(): + raise RuntimeError("Must not nest tf.distribute.Strategy scopes.") + if self._nested_count == 0: + self._var_creator_scope.__enter__() + self._nested_count += 1 + return self._strategy + + def __exit__(self, exception_type, exception_value, traceback): + self._nested_count -= 1 + if self._nested_count == 0: + try: + self._var_creator_scope.__exit__( + exception_type, exception_value, traceback) + except RuntimeError as e: + six.raise_from( + RuntimeError("Variable creator scope nesting error: move call to " + "tf.distribute.set_strategy() out of `with` scope."), + e) + + +class _DefaultDistributionExtended(StrategyExtendedV1): + """Implementation of _DefaultDistributionStrategy.""" + + def __init__(self, container_strategy): + super(_DefaultDistributionExtended, self).__init__(container_strategy) + self._retrace_functions_for_each_device = False + + def _scope(self, strategy): + """Context manager setting a variable creator and `self` as current.""" + return _DefaultDistributionContext(strategy) + + def colocate_vars_with(self, colocate_with_variable): + """Does not require `self.scope`.""" + _require_strategy_scope_extended(self) + return ops.colocate_with(colocate_with_variable) + + def variable_created_in_scope(self, v): + return v._distribute_strategy is None # pylint: disable=protected-access + + def _experimental_distribute_dataset(self, dataset, options): + return dataset + + def _distribute_datasets_from_function(self, dataset_fn, options): + return dataset_fn(InputContext()) + + def _experimental_distribute_values_from_function(self, value_fn): + return value_fn(ValueContext()) + + def _make_dataset_iterator(self, dataset): + return _DefaultDistributionExtended.DefaultInputIterator(dataset) + + def _make_input_fn_iterator(self, + input_fn, + replication_mode=InputReplicationMode.PER_WORKER): + dataset = input_fn(InputContext()) + return _DefaultDistributionExtended.DefaultInputIterator(dataset) + + def _experimental_make_numpy_dataset(self, numpy_input, session): + numpy_flat = nest.flatten(numpy_input) + vars_flat = tuple( + variable_v1.VariableV1(array_ops.zeros(i.shape, i.dtype), + trainable=False, use_resource=True) + for i in numpy_flat + ) + for v, i in zip(vars_flat, numpy_flat): + numpy_dataset.init_var_from_numpy(v, i, session) + vars_nested = nest.pack_sequence_as(numpy_input, vars_flat) + return dataset_ops.Dataset.from_tensor_slices(vars_nested) + + def _broadcast_to(self, tensor, destinations): + if destinations is None: + return tensor + else: + raise NotImplementedError("TODO") + + def _call_for_each_replica(self, fn, args, kwargs): + with ReplicaContext(self._container_strategy(), replica_id_in_sync_group=0): + return fn(*args, **kwargs) + + def _reduce_to(self, reduce_op, value, destinations, options): + # TODO(josh11b): Use destinations? + del reduce_op, destinations, options + return value + + def _gather_to_implementation(self, value, destinations, axis, options): + del destinations, axis, options + return value + + def _update(self, var, fn, args, kwargs, group): + # The implementations of _update() and _update_non_slot() are identical + # except _update() passes `var` as the first argument to `fn()`. + return self._update_non_slot(var, fn, (var,) + tuple(args), kwargs, group) + + def _update_non_slot(self, colocate_with, fn, args, kwargs, should_group): + # TODO(josh11b): Figure out what we should be passing to UpdateContext() + # once that value is used for something. + with UpdateContext(colocate_with): + result = fn(*args, **kwargs) + if should_group: + return result + else: + return nest.map_structure(self._local_results, result) + + def read_var(self, replica_local_var): + return array_ops.identity(replica_local_var) + + def _local_results(self, distributed_value): + return (distributed_value,) + + def value_container(self, value): + return value + + @property + def _num_replicas_in_sync(self): + return 1 + + @property + def worker_devices(self): + raise RuntimeError("worker_devices() method unsupported by default " + "tf.distribute.Strategy.") + + @property + def parameter_devices(self): + raise RuntimeError("parameter_devices() method unsupported by default " + "tf.distribute.Strategy.") + + def non_slot_devices(self, var_list): + return min(var_list, key=lambda x: x.name) + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings.""" + # Default strategy doesn't indicate multi-worker training. + return False + + @property + def should_checkpoint(self): + return True + + @property + def should_save_summary(self): + return True + + def _get_local_replica_id(self, replica_id_in_sync_group): + return replica_id_in_sync_group + + def _get_replica_id_in_sync_group(self, replica_id): + return replica_id + + # TODO(priyag): This should inherit from `InputIterator`, once dependency + # issues have been resolved. + class DefaultInputIterator(object): + """Default implementation of `InputIterator` for default strategy.""" + + def __init__(self, dataset): + self._dataset = dataset + if eager_context.executing_eagerly(): + self._iterator = dataset_ops.make_one_shot_iterator(dataset) + else: + self._iterator = dataset_ops.make_initializable_iterator(dataset) + + def get_next(self): + return self._iterator.get_next() + + def get_next_as_optional(self): + return self._iterator.get_next_as_optional() + + @deprecated(None, "Use the iterator's `initializer` property instead.") + def initialize(self): + """Initialize underlying iterators. + + Returns: + A list of any initializer ops that should be run. + """ + if eager_context.executing_eagerly(): + self._iterator = self._dataset.make_one_shot_iterator() + return [] + else: + return [self._iterator.initializer] + + @property + def initializer(self): + """Returns a list of ops that initialize the iterator.""" + return self.initialize() + + # TODO(priyag): Delete this once all strategies use global batch size. + @property + def _global_batch_size(self): + """Global and per-replica batching are equivalent for this strategy.""" + return True + + +class _DefaultReplicaContext(ReplicaContext): + """ReplicaContext for _DefaultDistributionStrategy.""" + + @property + def replica_id_in_sync_group(self): + # Return 0 instead of a constant tensor to avoid creating a new node for + # users who don't use distribution strategy. + return 0 + + +# ------------------------------------------------------------------------------ +# We haven't yet implemented deserialization for DistributedVariables. +# So here we catch any attempts to deserialize variables +# when using distribution strategies. +# pylint: disable=protected-access +_original_from_proto = ref_variable._from_proto_fn + + +def _from_proto_fn(v, import_scope=None): + if has_strategy(): + raise NotImplementedError( + "Deserialization of variables is not yet supported when using a " + "tf.distribute.Strategy.") + else: + return _original_from_proto(v, import_scope=import_scope) + +ref_variable._from_proto_fn = _from_proto_fn +# pylint: enable=protected-access + + +def get_local_results_or_value_container(variable): + strategy, context = get_strategy_and_replica_context() + if context: + return [strategy.extended.value_container(variable)] + else: + return strategy.experimental_local_results(variable) + + +tape.register_watched_variable_resolver(get_local_results_or_value_container) + + +# ------------------------------------------------------------------------------ +# Metrics to track which distribution strategy is being called +distribution_strategy_gauge = monitoring.StringGauge( + "/tensorflow/api/distribution_strategy", + "Gauge to track the type of distribution strategy used.", "TFVersion") +distribution_strategy_replica_gauge = monitoring.IntGauge( + "/tensorflow/api/distribution_strategy/replica", + "Gauge to track the number of replica each distribution strategy used.", + "CountType") +distribution_strategy_input_api_counter = monitoring.Counter( + "/tensorflow/api/distribution_strategy/input_api", + "Counter to track the usage of the input APIs", "strategy", "api") +distributed_variable_creation_time_counter = monitoring.Counter( + "/tensorflow/api/distribution_strategy/distributed_variable_creation_time_usecs", + "Time to create distributed variables (us).", "strategy", "if_graph_building") +distributed_api_time_counter = monitoring.Counter( + "/tensorflow/api/distribution_strategy/distributed_variable_api_time_usecs", + "Time spent on an API (us).", "strategy", "api") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..185eec3b6e0fb073b2e0192883c2a1614e2bd643 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/distribute_utils.py @@ -0,0 +1,499 @@ +# 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. +# ============================================================================== +"""Class implementing utilities used by tf.distribute.Strategy.""" + +from collections import abc +import contextlib +import threading + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import tpu_values as tpu_values_lib +from tensorflow.python.distribute import values as values_lib +from tensorflow.python.distribute.reduce_util import ReduceOp +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops.losses import losses_impl +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export(v1=["distribute.get_loss_reduction"]) +def get_loss_reduction(): + """`tf.distribute.ReduceOp` corresponding to the last loss reduction. + + This is used to decide whether loss should be scaled in optimizer (used only + for estimator + v1 optimizer use case). + + Returns: + `tf.distribute.ReduceOp` corresponding to the last loss reduction for + estimator and v1 optimizer use case. `tf.distribute.ReduceOp.SUM` otherwise. + """ + if not distribute_lib.get_strategy()._scale_loss_for_estimator: # pylint: disable=protected-access + # If we are not in Estimator context then return 'SUM'. We do not need to + # scale loss in the optimizer. + return ReduceOp.SUM + last_reduction = ops.get_default_graph()._last_loss_reduction # pylint: disable=protected-access + if (last_reduction == losses_impl.Reduction.SUM or + last_reduction == "sum"): # Check for tf.keras.losses.Reduction.SUM + return ReduceOp.SUM + return ReduceOp.MEAN + + +def regroup(values, wrap_class=values_lib.PerReplica, always_wrap=False): + """Makes a nest per-replica into a nest of PerReplica/Mirrored values. + + Args: + values: Values to regroup + wrap_class: Class that `values` be wrapped in. + always_wrap: Always wrap the `values` in `wrap_class` even if the values + are the same except for DistributeVariable. + Returns: + Wrapped `values`. + """ + v0 = values[0] + + if isinstance(v0, list): + for v in values[1:]: + assert isinstance(v, list) + assert len(v) == len(v0), ("len(v) == %d, len(v0) == %d, v: %s, v0: %s" % + (len(v), len(v0), v, v0)) + return [ + regroup(tuple(v[i] for v in values), wrap_class, always_wrap) + for i in range(len(v0)) + ] + + if isinstance(v0, tuple): + for v in values[1:]: + assert isinstance(v, tuple) + assert len(v) == len(v0), ("Values to regroup had different lengths: " + f"len(v) == {len(v)}, len(v0) == {len(v0)}, " + f"v: {v}, v0: {v0}") + regrouped_tuple = tuple( + regroup(tuple(v[i] for v in values), wrap_class, always_wrap) + for i in range(len(v0))) + if hasattr(v0, "_fields"): + # This tuple is in fact a namedtuple! Create a new namedtuple instance + # and initialize it with the regrouped values: + assert hasattr(v0, "_make") + return v0._make(regrouped_tuple) + else: + return regrouped_tuple + + if isinstance(v0, abc.Mapping): + v0keys = v0.keys() + for v in values[1:]: + assert isinstance(v, abc.Mapping), ("v[0]: %r v[i]: %r" % (v0, v)) + assert set(v.keys()) == set(v0keys), ("v[0].keys: %s v[i].keys: %s" % + (set(v0keys), set(v.keys()))) + # Use the actual type in case it is a class inherited from a dict. + return type(v0)({ + key: regroup(tuple(v[key] for v in values), + wrap_class, always_wrap) + for key in v0keys + }) + + # If exactly the same object across all devices, return it unwrapped. + same_id = True + for v in values[1:]: + if v is not v0: + same_id = False + break + # Consider three cases where same_id is true: + # * If v0 is a DistributedVariable (a MirroredVariable or + # SyncOnReadVariable, and same_id means it is the same across all + # devices), we want to return it. We check DistributedVariable + # specifically since it can look like it has a + # _distributed_container member since its members do. + if same_id and isinstance(v0, values_lib.DistributedVariable): + return v0 + # * If v0 is a member of a distributed variable, in which case + # value_container(v0) is not v0 itself, we want to + # return the DistributedVariable that contains it using the + # _distributed_container logic below. This case can trigger + # same_id when there is only one device. + # * In any other situation, same_id means we return v0 unless `always_wrap` is + # true. + if same_id and not always_wrap and value_container(v0) is v0: + return v0 + + # Detect the case where each device has a parallel component of the + # same MirroredVariable (or SyncOnReadVariable). In this case we + # want to return the containing MirroredVariable, after a bunch of + # sanity checking. In particular, each component should have the + # same container, and the devices of the variables should match the + # keys of the per-replica dictionary. For _UnreadVariables, use the wrap_class + # path, which calls tf.identity on them. + if (not isinstance(v0, resource_variable_ops._UnreadVariable) and # pylint: disable=protected-access + value_container(v0) is not v0): + # pylint: disable=protected-access + assert not isinstance(v0, values_lib.MirroredVariable), ( + "ids = %s, values = %s" % ([id(v) for v in values], values)) + distributed_container = value_container(v0) + assert distributed_container is not None + for v in values[1:]: + assert distributed_container is value_container(v) + return distributed_container + # pylint: enable=protected-access + + return wrap_class(values) + + +def select_replica(replica_id, structured): + """Specialize a nest of regular & per-replica values for one replica.""" + + def _get(x): + # `DistributedValues` would be sliced according to replica unless it is a + # `DistributedVariable` because `DistributedVariable` can be handled + # directly in the replica context. + if (isinstance(x, values_lib.DistributedVariable) or + not isinstance(x, values_lib.DistributedValues)): + return x + else: + return x.values[replica_id] + + return nest.map_structure(_get, structured) + + +def select_replica_mirrored(replica_id, structured): + """Specialize a nest of regular & mirrored values for one replica.""" + assert_mirrored(structured) + return select_replica(replica_id, structured) + + +def assert_mirrored(structured): + """Raises if the structured is not composed of mirrored or regular values.""" + + def _assert_mirrored(x): + if isinstance(x, values_lib.DistributedValues) and not is_mirrored(x): + raise TypeError( + "Expected value to be mirrored across replicas: %s in %s." % + (x, structured)) + + nest.map_structure(_assert_mirrored, structured) + + +def update_regroup(extended, updates, group): + """Regroup for an update, with dependencies to ensure all updates execute.""" + if not group: + regrouped = regroup(updates, values_lib.Mirrored) + return nest.map_structure(extended._local_results, regrouped) # pylint: disable=protected-access + + def _make_grouped_mirrored(values): + """Convert per-replica list `values` into Mirrored type with grouping.""" + if len(values) == 1: + return values_lib.Mirrored(values) + + # Make sure we run all updates. Without this, something like + # session.run(extended.update(...)) may only update one replica. + g = control_flow_ops.group(values) + + # If values is just ops, the grouping is enough. Everything in values + # should have the same type, since we expect every replica to be performing + # the same computation. + if not all(tensor_util.is_tf_type(v) for v in values): + return g + + # Otherwise we need tensors with the same values as `values`, but + # that have a dependency on `g`. + with_dep = [] + for v in values: + with ops.device(v.device), ops.control_dependencies([g]): + with_dep.append(array_ops.identity(v)) + + return values_lib.Mirrored(with_dep) + + return regroup(updates, _make_grouped_mirrored) + + +def value_container(val): + """Returns the container that this per-replica `value` belongs to. + + Args: + val: A value returned by `call_for_each_replica()` or a variable created in + `scope()`. + + Returns: + A container that `value` belongs to. + If value does not belong to any container (including the case of + container having been destroyed), returns the value itself. + """ + # DistributedVariable has _distributed_container defined but we don't want to + # return it. + container = None + if not isinstance(val, values_lib.DistributedVariable): + if hasattr(val, "_distributed_container"): + container = val._distributed_container() # pylint: disable=protected-access + elif (isinstance(val, composite_tensor.CompositeTensor) and + hasattr(val, "handle") and + hasattr(val.handle, "_distributed_container")): + # For ResourceVariables, the _distributed_container attribute + # is added to their handle tensors. + container = val.handle._distributed_container() # pylint: disable=protected-access + return container if container is not None else val + + +def is_distributed_variable(v): + """Determine if a variable is ds variable or TPU mirrored variable.""" + return getattr(v, "is_distributed_variable", False) + + +def is_distributed_table(v): + """Determine if an object is a DistributedTable.""" + return getattr(v, "is_distributed_table", False) + + +def _validate_colocate_extended(v, extended): + variable_strategy = v._distribute_strategy # pylint: disable=protected-access + if variable_strategy.extended is not extended: + raise ValueError( + "`colocate_vars_with` must only be passed a variable created in this " + "tf.distribute.Strategy.scope(), not %s created in scope: %s" % + (v, variable_strategy)) + + +def validate_colocate_distributed_variable(v, extended): + if not isinstance(v, values_lib.DistributedVariable): + raise ValueError( + "`colocate_vars_with` must only be passed a variable created in this " + "tf.distribute.Strategy.scope(), not: %r" % (v,)) + _validate_colocate_extended(v, extended) + + +def validate_colocate(v, extended): + if not hasattr(v, "_distribute_strategy"): + raise ValueError( + "`colocate_vars_with` must only be passed a variable created in this " + "tf.distribute.Strategy.scope(), not: %r" % (v,)) + _validate_colocate_extended(v, extended) + + +# Variable creation function for sync strategies. +def _validate_synchronization(kwargs): + """Validate that given synchronization value is valid.""" + synchronization = kwargs.get("synchronization", + vs.VariableSynchronization.AUTO) + if synchronization == vs.VariableSynchronization.NONE: + raise ValueError( + "`NONE` variable synchronization mode is not supported with " + "tf.distribute strategy. Please change the `synchronization` for " + "variable: " + str(kwargs["name"])) + if synchronization not in (vs.VariableSynchronization.ON_READ, + vs.VariableSynchronization.ON_WRITE, + vs.VariableSynchronization.AUTO): + raise ValueError( + "Invalid variable synchronization mode: %s for variable: %s" % + (synchronization, kwargs["name"])) + if synchronization == vs.VariableSynchronization.AUTO: + return vs.VariableSynchronization.ON_WRITE + return synchronization + + +def _validate_aggregation(kwargs): + aggregation = kwargs.get("aggregation", vs.VariableAggregation.NONE) + + if aggregation not in (vs.VariableAggregation.NONE, + vs.VariableAggregation.SUM, + vs.VariableAggregation.MEAN, + vs.VariableAggregation.ONLY_FIRST_REPLICA): + raise ValueError("Invalid variable aggregation mode: %s for variable: %s" % + (aggregation, kwargs["name"])) + return aggregation + + +def create_mirrored_variable(strategy, real_mirrored_creator, class_mapping, + policy_mapping, **kwargs): + """Create distributed variables with given synchronization and aggregation.""" + # Figure out what collections this variable should be added to. + # We'll add the MirroredVariable to those collections instead. + + if kwargs.pop("experimental_batch_initialization", None): + variable_class_key = "LazyVariableClass" + else: + variable_class_key = "VariableClass" + + var_collections = kwargs.pop("collections", None) + if var_collections is None: + var_collections = [ops.GraphKeys.GLOBAL_VARIABLES] + kwargs["collections"] = [] + + synchronization = _validate_synchronization(kwargs) + # Update synchronization in kwargs in case it's AUTO, which is converted to + # ON_WRITE. + kwargs["synchronization"] = synchronization + aggregation = _validate_aggregation(kwargs) + use_var_policy = getattr(strategy.extended, "_use_var_policy", False) + + # Ignore user-specified caching device, not needed for mirrored variables. + kwargs.pop("caching_device", None) + + # TODO(josh11b,apassos): It would be better if variable initialization + # was never recorded on the tape instead of having to do this manually + # here. + with record.stop_recording(): + value_list = real_mirrored_creator(**kwargs) + # MirroredVariable is recreated during saved_model loading, and its + # component variables (value_list) will have None initializer. We + # set their initializers to no_op so that consumer like + # `global_variables_initializer` wouldn't complain, as it groups all + # variables' initializers thus all variables have to have initializers. + for v in value_list: + # pylint:disable=protected-access + if hasattr(v, "_initializer_op") and v._initializer_op is None: + v._initializer_op = control_flow_ops.no_op() + # pylint:enable=protected-access + if use_var_policy: + var_policy_cls = policy_mapping.get(synchronization) + var_policy = var_policy_cls(aggregation=aggregation) + var_cls = class_mapping.get(variable_class_key) + result = var_cls(strategy, value_list, aggregation, var_policy=var_policy) + else: + var_cls = class_mapping.get(synchronization) + result = var_cls(strategy, value_list, aggregation) + + # Add the wrapped variable to the requested collections. + # The handling of eager mode and the global step matches + # ResourceVariable._init_from_args(). + if not context.executing_eagerly(): + g = ops.get_default_graph() + # If "trainable" is True, next_creator() will add the member variables + # to the TRAINABLE_VARIABLES collection, so we manually remove + # them and replace with the MirroredVariable. We can't set + # "trainable" to False for next_creator() since that causes functions + # like implicit_gradients to skip those variables. + if kwargs.get("trainable", True): + var_collections.append(ops.GraphKeys.TRAINABLE_VARIABLES) + l = g.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES) + for value in value_list: + for i, trainable_variable in enumerate(l): + if value is trainable_variable: + del l[i] + break + + g.add_to_collections(var_collections, result) + elif ops.GraphKeys.GLOBAL_STEP in var_collections: + ops.add_to_collections(ops.GraphKeys.GLOBAL_STEP, result) + + return result + + +# Utility functions +# Return True if the Value is Mirrored or the Variable is replicated and kept in +# sync. +def is_mirrored(val): + return (getattr(val, "_is_mirrored", lambda: False))() + + +def is_sync_on_read(val): + return not is_mirrored(val) + + +class CachingScopeLocal(threading.local): + """Class for maintaining thread local state for caching scope.""" + + def __init__(self): + super(CachingScopeLocal, self).__init__() + self.new_cache_scope_count = 0 + self.cache_scope_exited_count = 0 + + def enter_scope(self): + self.new_cache_scope_count += 1 + + def exit_scope(self): + self.cache_scope_exited_count += 1 + + def in_caching_scope(self): + return self.new_cache_scope_count > self.cache_scope_exited_count + + +caching_scope_local = CachingScopeLocal() + + +@contextlib.contextmanager +def cache_variable_reads(): + """Scope for caching variable reads for AggregatingVariable. + + The variable reads for AggregatingVariable inside this scope are cached. i.e. + the first read of variable reads the value from possibly remote handle, but + subsequent reads are returned using local cached value. + + For example: + strategy = ParameterServerStrategy... + with strategy.scope(): + # Variable v is of AggregatingVariable type with actual variable residing + # on PS. + v = tf.Variable(1.0) + + with distribute_utils.cache_variable_reads(): + v.read_value() # Reads value 1.0 + v.assign(constant_op.constant(5.0)) # v changes to 5.0 + t1 = v.read_value() + t2 = v.read_value() # Both t1 & t2 return cached value 1.0 from local CPU. + + Notes about cache_variable_reads scope: + 1. Nesting of scope cache_variable_reads() is not supported + 2. And when caching scope is enabled, the thread enabling the cache and + mirrored_run._MirroredReplicaThread threads spawned from it will have + caching enabled. + + Yields: + A context for caching variables. + """ + + try: + if caching_scope_local.in_caching_scope(): + # There is nested cache scope, which is not supported. + raise ValueError("cache_variable_reads scope cannot be nested") + caching_scope_local.enter_scope() + yield + finally: + caching_scope_local.exit_scope() + + +# The following mapping indicates the policy that you must use for a given +# variable `synchronization` and `aggregation` pair. +# OnWritePolicy is used for: +# (synchronization=Auto, aggregation=NONE,SUM,MEAN,ONLY_FIRST_REPLICA) +# (synchronization=ON_WRITE, aggregation=NONE,SUM,MEAN,ONLY_FIRST_REPLICA) +# OnReadPolicy is used for: +# (synchronization=ON_READ, aggregation=NONE,SUM,MEAN,ONLY_FIRST_REPLICA) +VARIABLE_POLICY_MAPPING = { + vs.VariableSynchronization.ON_WRITE: values_lib.OnWritePolicy, + vs.VariableSynchronization.ON_READ: values_lib.OnReadPolicy, +} + +VARIABLE_CLASS_MAPPING = { + "VariableClass": values_lib.DistributedVariable, + vs.VariableSynchronization.ON_WRITE: values_lib.MirroredVariable, + vs.VariableSynchronization.ON_READ: values_lib.SyncOnReadVariable, +} + +TPU_VARIABLE_POLICY_MAPPING = { + vs.VariableSynchronization.ON_WRITE: tpu_values_lib.TPUOnWritePolicy, + vs.VariableSynchronization.ON_READ: tpu_values_lib.TPUOnReadPolicy, +} + +TPU_VARIABLE_CLASS_MAPPING = { + "VariableClass": tpu_values_lib.TPUDistributedVariable, + "LazyVariableClass": tpu_values_lib.TPULazyDistributedVariable, + vs.VariableSynchronization.ON_WRITE: tpu_values_lib.TPUMirroredVariable, + vs.VariableSynchronization.ON_READ: tpu_values_lib.TPUSyncOnReadVariable, +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/estimator_training.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/estimator_training.py new file mode 100644 index 0000000000000000000000000000000000000000..c5367e0e7c0de699e5d48afbde82bd78c581b74a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/estimator_training.py @@ -0,0 +1,387 @@ +# 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. +# ============================================================================== +"""Training utilities for Estimator to use Distribute Coordinator.""" + +import copy + +import six + +from tensorflow.python.distribute import distribute_coordinator as dc +from tensorflow.python.distribute import distribute_coordinator_context as dc_context +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import server_lib + +# pylint: disable=protected-access +CHIEF = dc._TaskType.CHIEF +EVALUATOR = dc._TaskType.EVALUATOR +PS = dc._TaskType.PS +WORKER = dc._TaskType.WORKER + +# pylint: enable=protected-access + + +def _count_ps(cluster_spec): + """Counts the number of parameter servers in cluster_spec.""" + if not cluster_spec: + raise RuntimeError( + 'Internal error: `_count_ps` does not expect empty cluster_spec.') + + return len(cluster_spec.as_dict().get(PS, [])) + + +def _count_worker(cluster_spec, chief_task_type): + """Counts the number of workers (including chief) in cluster_spec.""" + if not cluster_spec: + raise RuntimeError( + 'Internal error: `_count_worker` does not expect empty cluster_spec.') + + return (len(cluster_spec.as_dict().get(WORKER, [])) + len( + cluster_spec.as_dict().get(chief_task_type, []))) + + +def _get_global_id(cluster_spec, task_type, task_id, chief_task_type): + """Returns the global id of the given task type in a cluster.""" + if not task_type: + return 0 + + # Sort task names in cluster by "chief"/"master", "evaluator", "worker" + # and "ps". More details can be found at the documentation of + # `tf.estimator.RunConfig.global_id_in_cluster`. + task_type_ordered_list = [] + if chief_task_type in cluster_spec.jobs: + task_type_ordered_list = [chief_task_type] + task_type_ordered_list.extend([ + t for t in sorted(cluster_spec.jobs) if t != chief_task_type and t != PS + ]) + if PS in cluster_spec.jobs: + task_type_ordered_list.append(PS) + + # Find the right global_id for current task. + next_global_id = 0 + for t in task_type_ordered_list: + if t == task_type: + return next_global_id + task_id + # `cluster_spec.job_tasks` returns all task addresses of type `t`. + next_global_id += len(cluster_spec.job_tasks(t)) + + # It is unexpected that it passes through all task_types in + # `task_type_ordered_list`. + raise RuntimeError('Internal Error: `task_type` ({}) is not in ' + 'cluster_spec ({}).'.format(task_type, cluster_spec)) + + +def _init_run_config_from_worker_context(config, worker_context): + """Initializes run config from distribute coordinator's worker context.""" + + # pylint: disable=protected-access + config._service = None + config._cluster_spec = worker_context.cluster_spec + config._task_type = worker_context.task_type + config._task_id = worker_context.task_id + config._evaluation_master = worker_context.master_target + config._master = worker_context.master_target + config._is_chief = worker_context.is_chief + + if config._cluster_spec: + # Distributed mode. + if config._task_type != EVALUATOR: + + config._num_ps_replicas = _count_ps(config._cluster_spec) + config._num_worker_replicas = _count_worker( + config._cluster_spec, chief_task_type=CHIEF) + config._global_id_in_cluster = _get_global_id( + config._cluster_spec, + config._task_type, + config._task_id, + chief_task_type=CHIEF) + else: + # Evaluator task should not be aware of the other tasks. + config._cluster_spec = server_lib.ClusterSpec({}) + config._num_ps_replicas = 0 + config._num_worker_replicas = 0 + config._global_id_in_cluster = None # undefined + else: + # Local mode. + config._global_id_in_cluster = 0 + config._num_ps_replicas = 0 + config._num_worker_replicas = 1 + + +def init_run_config(config, tf_config): + """Initializes RunConfig for distribution strategies.""" + # pylint: disable=protected-access + if (config._experimental_distribute and + config._experimental_distribute.train_distribute): + if config._train_distribute: + raise ValueError('Either `train_distribute` or' + '`experimental_distribute.train_distribute` can be set.') + config._train_distribute = config._experimental_distribute.train_distribute + + if (config._experimental_distribute and + config._experimental_distribute.eval_distribute): + if config._eval_distribute: + raise ValueError('Either `eval_distribute` or' + '`experimental_distribute.eval_distribute` can be set.') + config._eval_distribute = config._experimental_distribute.eval_distribute + + cluster_spec = server_lib.ClusterSpec(tf_config.get('cluster', {})) + config._init_distributed_setting_from_environment_var({}) + + # Use distribute coordinator with STANDALONE_CLIENT mode if + # `experimental_distribute.remote_cluster` is set. + if (config._train_distribute and config._experimental_distribute and + config._experimental_distribute.remote_cluster): + if cluster_spec: + raise ValueError('Cannot set both "cluster_spec" of TF_CONFIG and ' + '`experimental_distribute.remote_cluster`') + config._distribute_coordinator_mode = dc.CoordinatorMode.STANDALONE_CLIENT + config._cluster_spec = config._experimental_distribute.remote_cluster + logging.info('RunConfig initialized for Distribute Coordinator with ' + 'STANDALONE_CLIENT mode') + return + + # Don't use distribute coordinator if it is local training or cluster has a + # MASTER job or `train_distribute` is not specified. + if (not cluster_spec or 'master' in cluster_spec.jobs or + not config._train_distribute): + config._distribute_coordinator_mode = None + config._init_distributed_setting_from_environment_var(tf_config) + config._maybe_overwrite_session_config_for_distributed_training() + logging.info('Not using Distribute Coordinator.') + return + + # Use distribute coordinator with INDEPENDENT_WORKER mode otherwise. + assert tf_config + + # Set the cluster_spec only since the distributed setting will come from + # distribute coordinator. + config._cluster_spec = cluster_spec + config._distribute_coordinator_mode = dc.CoordinatorMode.INDEPENDENT_WORKER + logging.info('RunConfig initialized for Distribute Coordinator with ' + 'INDEPENDENT_WORKER mode') + + +def should_run_distribute_coordinator(config): + """Checks the config to see whether to run distribute coordinator.""" + # pylint: disable=protected-access + if (not hasattr(config, '_distribute_coordinator_mode') or + config._distribute_coordinator_mode is None): + logging.info('Not using Distribute Coordinator.') + return False + if (not isinstance(config._distribute_coordinator_mode, six.string_types) or + config._distribute_coordinator_mode not in [ + dc.CoordinatorMode.STANDALONE_CLIENT, + dc.CoordinatorMode.INDEPENDENT_WORKER + ]): + logging.warning('Unexpected distribute_coordinator_mode: %r', + config._distribute_coordinator_mode) + return False + if not config.cluster_spec: + logging.warning('Running `train_and_evaluate` locally, ignoring ' + '`experimental_distribute_coordinator_mode`.') + return False + return True + + +def train_and_evaluate(estimator, train_spec, eval_spec, executor_cls): + """Run distribute coordinator for Estimator's `train_and_evaluate`. + + Args: + estimator: An `Estimator` instance to train and evaluate. + train_spec: A `TrainSpec` instance to specify the training specification. + eval_spec: A `EvalSpec` instance to specify the evaluation and export + specification. + executor_cls: the evaluation executor class of Estimator. + + Raises: + ValueError: if `distribute_coordinator_mode` is None in RunConfig. + """ + run_config = estimator.config + if not run_config._distribute_coordinator_mode: # pylint: disable=protected-access + raise ValueError( + 'Distribute coordinator mode is not specified in `RunConfig`.') + + def _worker_fn(strategy): + """Function for worker task.""" + local_estimator = copy.deepcopy(estimator) + # pylint: disable=protected-access + local_estimator._config._train_distribute = strategy + context = dc_context.get_current_worker_context() + _init_run_config_from_worker_context(local_estimator._config, context) + logging.info('Updated config: %s', str(vars(local_estimator._config))) + local_estimator._train_distribution = strategy + # pylint: enable=protected-access + + # In the standalone client, we don't need to run hooks on all threads + # because logging hooks on all threads may be too much on the screen; also + # tensor passed to one hook can only be fetched with the graph where the + # tensor is defined. Other hooks such as checkpointing hooks will added by + # MonitoredTrainingSession. + # TODO(yuefengz): Is there a hook that does need to run on all threads in + # standalone client mode? + if (run_config._distribute_coordinator_mode == # pylint: disable=protected-access + dc.CoordinatorMode.INDEPENDENT_WORKER or context.is_chief): + hooks = list(train_spec.hooks) + else: + hooks = [] + + # Prevent estimator.train from calling distribute coordinator again. This + # function calls estimator.train which will use distribute coordinator path + # again if `_distribute_coordinator_mode` is set. + local_estimator._config._distribute_coordinator_mode = None # pylint: disable=protected-access + local_estimator.train( + input_fn=train_spec.input_fn, + max_steps=train_spec.max_steps, + hooks=hooks) + + def _eval_fn(strategy): + """Function for evaluator task.""" + local_estimator = copy.deepcopy(estimator) + # pylint: disable=protected-access + local_estimator._config._eval_distribute = strategy + _init_run_config_from_worker_context( + local_estimator._config, dc_context.get_current_worker_context()) + logging.info('Updated config: %s', str(vars(local_estimator._config))) + local_estimator._eval_distribution = strategy + + # Prevent estimator.evaluate from calling distribute coordinator again. This + # function calls estimator.evaluate which will use distribute coordinator + # path again if `_distribute_coordinator_mode` is set. + local_estimator._config._distribute_coordinator_mode = None # pylint: disable=protected-access + + executor = executor_cls(local_estimator, train_spec, eval_spec) + executor._start_continuous_evaluation() + # pylint: enable=protected-access + + # pylint: disable=protected-access + if (run_config._distribute_coordinator_mode == + dc.CoordinatorMode.STANDALONE_CLIENT): + cluster_spec = run_config.cluster_spec + assert cluster_spec + else: + # The cluster_spec comes from TF_CONFIG environment variable if it is + # INDEPENDENT_WORKER mode. + cluster_spec = None + + dc.run_distribute_coordinator( + _worker_fn, + run_config.train_distribute, + _eval_fn, + run_config.eval_distribute, + mode=run_config._distribute_coordinator_mode, + cluster_spec=cluster_spec, + session_config=run_config.session_config) + + +# TODO(yuefengz): maybe merge the following two functions? +# pylint: disable=protected-access +def estimator_train(estimator, train_distributed_fn, hooks): + """Run distribute coordinator for Estimator's `train` method.""" + assert estimator._config._distribute_coordinator_mode + run_config = estimator._config + assert estimator._config.cluster_spec + cluster_spec = multi_worker_util.normalize_cluster_spec( + estimator._config.cluster_spec) + assert estimator._config._train_distribute + + if 'evaluator' in cluster_spec.jobs: + raise ValueError("'evaluator' job is not supported if you don't use " + '`train_and_evaluate`') + + if (estimator._config._distribute_coordinator_mode != # pylint: disable=protected-access + dc.CoordinatorMode.STANDALONE_CLIENT): + raise ValueError('Only `STANDALONE_CLIENT` mode is supported when you call ' + '`estimator.train`') + + if estimator._config._train_distribute.extended.experimental_between_graph: + # TODO(yuefengz): remove this limitation once we figure out how to merge + # return values from `_worker_fn`s. + raise ValueError('`Estimator.train` API is not supported for %s with ' + '`STANDALONE_CLIENT` mode.' % + estimator._config._train_distribute.__class__.__name__) + + def _worker_fn(strategy): + """Function for worker task.""" + local_estimator = copy.deepcopy(estimator) + local_estimator._config._train_distribute = strategy + context = dc_context.get_current_worker_context() + _init_run_config_from_worker_context(local_estimator._config, context) + logging.info('Updated config: %s', str(vars(local_estimator._config))) + local_estimator._train_distribution = strategy + + if context.is_chief: + chief_hooks = hooks + else: + chief_hooks = [] + train_distributed_fn(local_estimator, strategy, chief_hooks) + return local_estimator + + return dc.run_distribute_coordinator( + _worker_fn, + estimator._config.train_distribute, + mode=run_config._distribute_coordinator_mode, + cluster_spec=cluster_spec, + session_config=run_config.session_config) + + +def estimator_evaluate(estimator, evaluate_distributed_fn, hooks): + """Run distribute coordinator for Estimator's `evaluate` method.""" + assert estimator._config._distribute_coordinator_mode + run_config = estimator._config + assert estimator._config.cluster_spec + cluster_spec = multi_worker_util.normalize_cluster_spec( + estimator._config.cluster_spec) + assert estimator._config._eval_distribute + + if 'evaluator' in cluster_spec.jobs: + raise ValueError("'evaluator' job is not supported if you don't use " + '`train_and_evaluate`') + + if (estimator._config._distribute_coordinator_mode != + dc.CoordinatorMode.STANDALONE_CLIENT): + raise ValueError('Only `STANDALONE_CLIENT` mode is supported when you call ' + '`Estimator.evaluate`') + + if estimator._config._eval_distribute.extended.experimental_between_graph: + # TODO(yuefengz): remove this limitation once we figure out how to merge + # return values from `_worker_fn`s. + raise ValueError('`Estimator.evaluate` API is not supported for %s with ' + '`STANDALONE_CLIENT` mode.' % + estimator._config._eval_distribute.__class__.__name__) + + def _worker_fn(strategy): + """Function for evaluation.""" + local_estimator = copy.deepcopy(estimator) + local_estimator._config._eval_distribute = strategy + context = dc_context.get_current_worker_context() + _init_run_config_from_worker_context(local_estimator._config, context) + logging.info('Updated config: %s', str(vars(local_estimator._config))) + local_estimator._eval_distribution = strategy + + if context.is_chief: + chief_hooks = hooks + else: + chief_hooks = [] + return evaluate_distributed_fn(local_estimator, strategy, chief_hooks) + + return dc.run_distribute_coordinator( + _worker_fn, + estimator._config.eval_distribute, + mode=run_config._distribute_coordinator_mode, + cluster_spec=cluster_spec, + session_config=run_config.session_config) + +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..db9c1fe80bfab725d2560d20f52df3eda7ca94ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/__init__.py @@ -0,0 +1,20 @@ +# 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. +# ============================================================================== +"""Experimental Distribution Strategy library.""" + +# pylint: disable=unused-import +from tensorflow.python.distribute.experimental import mirrored_strategy +from tensorflow.python.distribute.experimental import multi_worker_mirrored_strategy +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/dtensor_strategy_extended.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/dtensor_strategy_extended.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7f15089e2a0d6d7c159d4948f190437e2c13ff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/dtensor_strategy_extended.py @@ -0,0 +1,278 @@ +# 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. +# ============================================================================== +"""Implement a StrategyExtended based on the DTensor low level API.""" + +import functools + +from tensorflow.dtensor.python import api as d_api +from tensorflow.dtensor.python import config as d_config +from tensorflow.dtensor.python import d_variable +from tensorflow.dtensor.python import input_util +from tensorflow.dtensor.python import layout +from tensorflow.python.data.experimental.ops import distribute +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute.experimental import dtensor_util +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.util import nest + + +class DTensorStrategyExtended(distribute_lib.StrategyExtendedV2): + """Strategy extension that support both single and multi worker strategy.""" + # Note that the unit test for this class is via the strategy interface. + + def __init__(self, container_strategy, mesh): + super().__init__(container_strategy) + self._mesh = mesh + self._num_clients = d_config.num_clients() + self._client_id = d_config.client_id() + + def _create_variable(self, next_creator, **kwargs): + # Make sure the pop the `use_resource` which is not supported by the + # base tf.Variable. The `use_resource` is added by + # creator_with_resource_vars in distribute_lib.py + kwargs.pop('use_resource', None) + + # Ignore the colocate_with for the mirrored strategy. Each of the device + # will get same copy of variable in the DTensor's case. + # `colocate_with` is added when user call: + # strategy.extended.colocate_vars_with(variable) + kwargs.pop('colocate_with', None) + + # Ignore expected_shape, which is from the v1 Variable. Keras was somehow + # using the v1 Variable, but didn't specify that value particularly. + kwargs.pop('expected_shape', None) + + # Make sure to call DVariable initializer under the scope so that it will + # have the proper replicated layout. The initial_value is multi-typed, + # eg it can be a tensor, or a python/numpy type, or a callable that + # produce tensor/python/numpy types. In all those cases, we need to wrap + # them invoke convert_to_tensor() under the scope so that the proper + # layout can be assigned. + + # TODO(scottzhu): The layout information should be injected via kwargs, or + # lazily set later. + initial_value = kwargs.pop('initial_value') + dtype = kwargs.get('dtype', None) + def new_initial_value(): + if callable(initial_value): + init_var = ops.convert_to_tensor(initial_value(), dtype=dtype) + else: + init_var = ops.convert_to_tensor(initial_value, dtype=dtype) + rank = init_var.shape.rank + return d_api.copy_to_mesh( + init_var, layout.Layout.replicated(self._mesh, rank)) + + return d_variable.DVariable(new_initial_value, **kwargs) + + @property + def _num_replicas_in_sync(self): + # The mesh should be 1D with batch sharding only. + # In the model parallel case, it should only return the size of + # batch dimension. + return self._mesh.size + + def value_container(self, value): + return value + + @property + def worker_devices(self): + # Note that in either single worker (MirroredStrategy) or multi worker ( + # MultiWorkerMirroredStrategy), worker_devices refers to the local worker + # devices. + return tuple(self._mesh.local_devices()) + + @property + def parameter_devices(self): + # Same as the worker_devices. + return self.worker_devices + + def _in_multi_worker_mode(self): + return d_config.num_clients() > 1 + + def _get_local_replica_id(self, replica_id_in_sync_group): + return replica_id_in_sync_group + + def _default_device_scope(self): + return d_api.default_mesh(self._mesh) + + def _experimental_distribute_dataset(self, dataset, options): + # Strategy always assume the user input data is a batched dataset for + # experimental_distribute_dataset(). + # TODO(yuefengz): Add check for whether a dataset is batched for all + # strategies. + + # TODO(b/265198795): Support dataset already batched to global batch size. + # Since DTensorDataset doesn't support batched dataset that is already + # batched global batch size, it only supports dataset that is batched to + # local batch size, we need to infer the batch size, and unbatch the dataset + # until the b/265198795 is resolved. + batch_size = distribute.compute_batch_size(dataset) + + # There are multiple case that the batch is not static, eg partial batch, + # or uneven batch, in all those case, it will return -1. + if batch_size.numpy() < 0: + # When we don't have a static batch size. + raise ValueError('DTensor strategy requires a static batch size for now.' + 'The dynamic batch size will be supported in future') + # Unbatch the dataset for now since the DTensorDataset has some limitation + # about the local batch size as well as the mesh size. + dataset = dataset.unbatch() + + def _create_batch_layout(tensor_spec): + # For unbatched dataset, the new layout need to have +1 rank for + # the batched result. + rank = len(tensor_spec.shape) + 1 + return layout.Layout.batch_sharded( + self._mesh, batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, + rank=rank) + + layouts = nest.map_structure(_create_batch_layout, dataset.element_spec) + + return input_util.DTensorDataset( + dataset=dataset, + mesh=self._mesh, + layouts=layouts, + global_batch_size=batch_size, + dataset_already_batched=False, + batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, + # TODO(scottzhu): Add prefetch support by inspecting the input dataset. + prefetch=None, + tf_data_service_config=None + ) + + def _make_dataset_iterator(self, dataset): + raise NotImplementedError( + 'Strategy.make_dataset_iterator() is deprecated, and only available ' + 'in the V1 API.') + + def _make_input_fn_iterator(self, input_fn, replication_mode): + raise NotImplementedError( + 'Strategy.make_input_fn_iterator() is deprecated, and only available ' + 'in the V1 API.') + + def _distribute_datasets_from_function(self, dataset_fn, options): + # TODO(scottzhu): Implement the logic for options in future + del options + input_context = distribute_lib.InputContext( + num_input_pipelines=self._num_clients, + input_pipeline_id=self._client_id, + num_replicas_in_sync=self._num_replicas_in_sync + ) + dataset = dataset_fn(input_context) + + # Note that the dataset should already batched to local per-relica batch + def _create_batch_layout(tensor_spec): + rank = len(tensor_spec.shape) + return layout.Layout.batch_sharded( + self._mesh, batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, + rank=rank) + + layouts = nest.map_structure(_create_batch_layout, dataset.element_spec) + + batch_size = distribute.compute_batch_size(dataset) + # There are multiple case that the batch is not static, eg partial batch, + # or uneven batch, in all those case, it will return -1. + if batch_size.numpy() < 0: + # When we don't have a static batch size. + raise ValueError('DTensor strategy requires a static batch size for now.' + 'The dynamic batch size will be supported in future') + global_batch_size = batch_size.numpy() * self._num_replicas_in_sync + + return input_util.DTensorDataset( + dataset=dataset, + mesh=self._mesh, + layouts=layouts, + global_batch_size=global_batch_size, + dataset_already_batched=True, + batch_dim=dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, + # TODO(scottzhu): Add prefetch support by inspecting the input dataset. + prefetch=None, + tf_data_service_config=None + ) + + def _experimental_distribute_values_from_function(self, value_fn): + per_replica_values = [] + # Note that in the multi-worker setting, this function only return the + # slide of DistributedValue for the current worker. + for i in range(self._mesh.num_local_devices()): + # In the case of 2 worker with 2 local devices on each worker, + # worker 0 will get 0 and 1 for replica_id. + # worker 1 will get 2 and 3 for replica_id. + replica_id = d_config.client_id() * self._mesh.num_local_devices() + i + per_replica_values.append(value_fn( + distribute_lib.ValueContext(replica_id, + self._num_replicas_in_sync))) + # Instead of using the DistributeVariable, return a DTensor instead since + # the run() will expect a DTensor instance. + result = distribute_utils.regroup(per_replica_values, always_wrap=True) + map_fn = functools.partial(dtensor_util.convert_per_replica_to_dtensor, + mesh=self._mesh) + return nest.map_structure(map_fn, result) + + def call_for_each_replica(self, fn, args=(), kwargs=None): + """Run `fn` once per replica. + + This is a method that expected by the strategy base class in its `run()`. + + Args: + fn: function to run (will be run once per replica). + args: Tuple or list with positional arguments for `fn`. + kwargs: Dict with keyword arguments for `fn`. + + Returns: + Merged return value of `fn` across all replicas. + """ + # Comparing to the existing MirroredStrategy, which will run the fn on + # each of the replica with individual thread, the DTensor will just run + # the fn once with the DTensor inputs, and the distribution will be handled + # by the DTensor. + + distribute_lib._require_cross_replica_or_default_context_extended(self) # pylint: disable=protected-access + if kwargs is None: + kwargs = {} + + # For any value that is not DTensor, eg normal tf.Tensor or + # DistributedValues, we need to convert them into DTensor. + map_fn = functools.partial(dtensor_util.convert_inputs_to_dtensor, + mesh=self._mesh) + d_args = nest.map_structure(map_fn, args) + d_kwargs = nest.map_structure(map_fn, kwargs) + + with self._container_strategy().scope(): + with dtensor_util.DTensorReplicaContext(self._container_strategy()): + dtensor_result = fn(*d_args, **d_kwargs) + + return nest.map_structure( + dtensor_util.DTensorDistributedValue, + dtensor_result) + + def _gather_to_implementation(self, value, destinations, axis, options): + if isinstance(value, dtensor_util.DTensorDistributedValue): + value = value.get_dtensor() + if not d_api.is_dtensor(value): + # This is the current behavior for mirrored strategy, should we raise an + # error for unsupported types? + return value + + # Unpack the dtensor components and gather the tensors on the axis + components = d_api.unpack(value) + return array_ops.concat(components, axis=axis) + + def _use_merge_call(self): + # This is method for V1 StrategyExtended by still used by + # tf.__internal__.distribute.strategy_supports_no_merge_call + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/dtensor_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/dtensor_util.py new file mode 100644 index 0000000000000000000000000000000000000000..eef41aa456923d2050153c8e1720698e8a251a4f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/dtensor_util.py @@ -0,0 +1,299 @@ +# 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. +# ============================================================================== +"""Utilities for strategies that are backed by DTensor.""" + +from tensorflow.dtensor.python import accelerator_util +from tensorflow.dtensor.python import api as d_api +from tensorflow.dtensor.python import input_util +from tensorflow.dtensor.python import layout +from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import values as values_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import summary_ops_v2 + + +# Default dimension name used for the mesh created when user provide a list +# of devices. For mirrored strategy, it should be a 1D mesh with batch dim only. +DEFAULT_BATCH_MESH_DIM_NAME = "batch" + + +class DTensorDistributedValue(values_lib.DistributedValues): + """DistributedValue backed by a DTensor instance. + + This class is useful to align the interface between DTensor and tf.distribute. + Most of the tf.distribute API will accept/return DistributedValue, whereas + DTensor low level API will only accept DTensor instance. In order to avoid + the conversion back and forth between DistributedValue and DTensor, we + introduce this class so that it can work with both side. + """ + + def __init__(self, dtensor): + if context.executing_eagerly(): + if not d_api.is_dtensor(dtensor): + raise ValueError("The DTensorDistributedValue can only be built with " + f"DTensor instance, got {type(dtensor)}") + super().__init__(d_api.unpack(dtensor)) + else: + # We can't unpack the dtensor instance for now due to graph context. + # We will treat the dtensor instance as one global instance and let it + # return as a global replica instance. + # TODO(feyu): Support unpack in the graph context. + super().__init__([dtensor,]) + self._dtensor = dtensor + + def get_dtensor(self): + return self._dtensor + + @property + def values(self): + # Note that this method exists so that it match the interface for PerReplica + # The public API in `tf.types.experimental.distributed.PerReplica` doesn't + # define any methods. + return self._values + + +def _dtensor_distributed_value_to_tensor( + var, dtype=None, name=None, as_ref=False): + del name + dtensor = var.get_dtensor() + if dtype is not None and not dtype.is_compatible_with(dtensor.dtype): + raise ValueError( + "Incompatible type conversion requested to type {!r} for variable " + "of type {!r}".format(dtype.name, dtensor.dtype.name)) + if as_ref: + raise NotImplementedError( + "PerReplica doesn't support being used as a reference.") + return dtensor + + +# Register a conversion function to provide a useful error message when users +# try to use PerReplica values in the wrong contexts +tensor_conversion_registry.register_tensor_conversion_function( + DTensorDistributedValue, _dtensor_distributed_value_to_tensor) + + +class DTensorReplicaContext(distribute_lib.ReplicaContext): + """ReplicaContext for strategy that is backed by DTensor. + + Since the DTensor is operated in the global context, most of the methods from + existing strategy ReplicaContext is not applicable since they need to access + local values. For now most of the methods in this class will raise explicit + error to user, and we will add more support for local values in future. + """ + _UNSUPPORTED_ERROR_MSG = ( + "Strategy that is backed by DTensor is run with a global context, and " + "doesn't support operations for local context, like any call to merge/" + "gather/reduce or local replica ID. Please use any strategy that is not " + "backed by DTensor") + + def __init__(self, strategy): + # Since DTensor strategy only runs in a global context, and we can't have + # a local replica ID in the sync group. For now we pass None to parent, and + # raise an explicit error when it is accessed. + super().__init__(strategy, replica_id_in_sync_group=None) + + def __enter__(self): + # This is a copy of parent class, without any check about whether the + # current replica is the first one (since DTensor only has one). + distribute_lib._push_per_thread_mode(self._thread_context) # # pylint: disable=protected-access + + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + self._summary_recording_distribution_strategy = ( + summary_state.is_recording_distribution_strategy) + summary_state.is_recording_distribution_strategy = True + + @property + def replica_id_in_sync_group(self): + # Since there is only one global context for DTensor, we always return a + # constant value here. This value is needed by the RNG which try to generate + # different seed for different replica. + return 0 + + @property + def _replica_id(self): + raise NotImplementedError(self._UNSUPPORTED_ERROR_MSG) + + def merge_call(self, merge_fn, args=(), kwargs=None): + raise NotImplementedError(self._UNSUPPORTED_ERROR_MSG) + + def all_reduce(self, reduce_op, value, options=None): + raise NotImplementedError(self._UNSUPPORTED_ERROR_MSG) + + def all_gather(self, value, axis, options=None): + raise NotImplementedError(self._UNSUPPORTED_ERROR_MSG) + + def _update(self, var, fn, args=(), kwargs=None, group=True): + raise NotImplementedError(self._UNSUPPORTED_ERROR_MSG) + + +def initialize_accelerator_system_once(device_type): + # Initialize the GPU/TPU before creating the mesh. + # Note that this method will also trigger the creation of the pairing + # virtual host CPUs, which is needed by dataset and checkpoint. + if not accelerator_util.is_initialized(): + # TODO(feyu): Add a method in accelerator_util to check the initialized + # mesh device types. + accelerator_util.initialize_accelerator_system( + device_type, + experimental_reset_context=True) + + +def convert_inputs_to_dtensor(inputs, mesh): + """Convert any input types to DTensor instance.""" + if isinstance(inputs, DTensorDistributedValue): + return inputs.get_dtensor() + elif isinstance(inputs, values_lib.DistributedValues): + return convert_per_replica_to_dtensor(inputs, mesh) + elif isinstance(inputs, input_util._DTensorIterator): # pylint: disable=protected-access + return inputs + elif tensor_util.is_tensor(inputs): + if context.executing_eagerly(): + if d_api.is_dtensor(inputs): + return inputs + else: + # For a non-dtensor input in eager context, we could choose to replica + # them into per-replica and then pack them into dtensor. However, this + # will cause an eager/graph discrepancy since we can't do this check in + # the graph context. For now, we will ask user to provide a distributed + # value for inputs. + _raise_unsupported_input_type_error(inputs) + else: + # For graph context, since we can't check if they are dtensor or not. We + # will assume the value is already distributed. This is a critical use + # case for keras, where all the inputs are pre-distributed via strategy, + # and the train function execute within graph context. + return inputs + else: + # For any other types. + _raise_unsupported_input_type_error(inputs) + + +def _raise_unsupported_input_type_error(inputs): + raise ValueError("Unsupported input types for MirroredStrategy. " + "Please use `strategy.distribute_dataset` or " + "`strategy.distribute_values_from_function` to " + f"distribute inputs. Received input type: {type(inputs)}") + + +def is_distributed_value(value): + return isinstance( + value, values_lib.DistributedValues) or d_api.is_dtensor(value) + + +def convert_per_replica_to_dtensor(per_replica_value, mesh): + """Convert a PerReplica result to a DTensor instance. + + Args: + per_replica_value: A PerReplica instance whose value will be converted + to DTensor. + mesh: The mesh used for layout creation. + + Returns: + A DTensor instance that packed from per_replica_value with batch sharded + layout. + """ + values = per_replica_value.values + if isinstance(values[0], (float, int)): + rank = 0 + else: + rank = len(values[0].shape) + + if rank == 0: + result = [] + # dtensor.pack requires each component to have same rank as the packed + # result. When the individual value is scalar, it needs to be expanded into + # 1D tensor. + for v in values: + result.append(array_ops.expand_dims_v2(v, axis=0)) + rank += 1 + else: + result = list(values) # dtensor.pack requires a list as input. + + # TODO(scottzhu): Note that the result tensor could be a partial value and + # not always batch shard or fully replicaed. See + # http://screenshot/6ERkXyX95KqftCw as an example. + batch_layout = layout.Layout.batch_sharded( + mesh, batch_dim=DEFAULT_BATCH_MESH_DIM_NAME, rank=rank) + + return d_api.pack(result, batch_layout) + + +def dtensor_reduce(strategy, reduce_op, value, axis): + """Implement dtensor based strategy.reduce().""" + # Due to the limitation of using scalar in DTensor (e.g. the rank 0 tensor + # loss the batch shard information), we need to override the default + # reduce in addition to the strategy.extend._reduce_to() + # Most of the logic here is a mimic of the parent class, except for how + # mean and sum are calculated in a global context. + distribute_lib._require_cross_replica_or_default_context_extended( # pylint: disable=protected-access + strategy.extended) + if isinstance(reduce_op, str): + reduce_op = reduce_util.ReduceOp(reduce_op.upper()) + + distributed_input = is_distributed_value(value) + if not distributed_input and axis is None: + # For any value that isn't distributed and doesn't need a reduction within + # the replica. + destinations = (device_util.current() or + strategy.extended._default_device or # pylint: disable=protected-access + "/device:CPU:0") + devices = cross_device_ops_lib.get_devices_from(destinations) + with ops.device(devices[0]): + return array_ops.identity( + cross_device_ops_lib.reduce_non_distributed_value( + reduce_op, value, destinations, strategy.num_replicas_in_sync)) + + value = convert_inputs_to_dtensor(value, strategy._mesh) # pylint: disable=protected-access + # At this point, the value is a DTensor instance now. + # There will be a final reduction step cross replica. In order to maintain + # the shape of each local replica, we need to add a new dim to the front. + # E.g. 2 replica with local shape as (4, 5, 6), the global tensor shape + # should be (8, 5, 6), we will reshape into (2, 4, 5, 6) and then do a + # reduction on axis 0. + if reduce_op == reduce_util.ReduceOp.MEAN: + reduce_op = math_ops.reduce_mean + else: + reduce_op = math_ops.reduce_sum + + # TODO(scottzhu): Make sure we handle dynamic/uneven shape in future. + if d_api.fetch_layout(value).is_fully_replicated(): + # In case of fully mirrored dtensor, we only need to do one reduce, and + # don't need to care about any per-replica logic. + if axis is not None: + value = reduce_op(value, axis=axis) + else: + new_shape = [strategy.num_replicas_in_sync, -1] + if len(value.shape) > 1: + new_shape.extend(array_ops.shape(value)[1:]) + value = array_ops.reshape(value, new_shape) + if axis is not None: + # we do a reduce_sum/mean within each of the replica when axis is not + # None. Add 1 to the axis since there is a new dim added by reshape in + # front. + value = reduce_op(value, axis=axis + 1) + value = reduce_op(value, axis=0) + + # Note that we return a DTensor instance here, which should have the same + # value as the original MirroredStrategy, but with a different type. User + # might want a tf.Tensor for the status quo. + return value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/mirrored_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/mirrored_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff42798f87277620166ae41179e0de482f49862 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/mirrored_strategy.py @@ -0,0 +1,99 @@ +# 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. +# ============================================================================== +"""Implement a MirroredStrategy based on the DTensor low level API. + +This is an experiment to validate the viability of the DTensor API, and expose +any potential feature gaps between the current API and the need. +""" + +from tensorflow.dtensor.python import config as d_config +from tensorflow.dtensor.python import mesh_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute.experimental import dtensor_strategy_extended +from tensorflow.python.distribute.experimental import dtensor_util +from tensorflow.python.framework import device as tf_device + + +class MirroredStrategy(distribute_lib.Strategy): + """Synchronous training across multiple replicas on one machine. + + This strategy is typically used for training on one machine with multiple + accelerators (GPUs/TPUs). + + For example, a variable created under a `MirroredStrategy` is a distributed + variable with layout replicated on each dimension. The variables will be + placed on the `mesh` that is specified in the __init__. + """ + + def __init__(self, devices=None, cross_device_ops=None, *, mesh=None): + """Synchronous training across multiple replicas on one machine. + + Args: + devices: a list of device strings, such as ['/gpu:0', '/gpu:1']. If both + `mesh` and `devices` are None, all the available GPU/TPU will be used. + If no accelerators are found, CPU is used. + cross_device_ops: optional, a descendant of `CrossDeviceOps`. The value is + ignored at the moment, and support will be added later. + mesh: optional DTensor mesh for the computation. Note that either `mesh` + or `devices` should be provided, and not both. The mesh should be 1D, + and will be used to split the input data among that dimension. + """ + self._validate_init_args(mesh, devices) + if not mesh: + mesh = self._build_mesh_from_device_list(devices) + + extended = dtensor_strategy_extended.DTensorStrategyExtended( + container_strategy=self, mesh=mesh) + super().__init__(extended) + self._mesh = mesh + self._devices = devices + + @classmethod + def _validate_init_args(cls, mesh, devices): + if mesh and devices: + raise ValueError('Mesh and devices can not be provided at the same time. ' + f'received mesh = {mesh}, devices = {devices}') + + # For mirrored strategy, the mesh should be 1D, and only contains a batch + # dimension, we will use that dimension to shard the inputs. + if mesh and len(mesh.shape()) != 1: + raise ValueError('The mesh for MirroredStrategy must be 1D, received: ' + f'{len(mesh.shape())}D') + + @classmethod + def _build_mesh_from_device_list(cls, devices): + if devices: + device_type = tf_device.DeviceSpec.from_string(devices[0]).device_type + dtensor_util.initialize_accelerator_system_once(device_type) + mesh = mesh_util.create_mesh( + mesh_dims=[(dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, len(devices))], + devices=devices) + else: + # Trying to detect if there is any GPU/TPUs attached. + device_type = d_config.preferred_device_type() + devices = d_config.local_devices(device_type) + dtensor_util.initialize_accelerator_system_once(device_type) + mesh = mesh_util.create_mesh( + mesh_dims=[(dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME, len(devices))], + device_type=device_type) + return mesh + + def reduce(self, reduce_op, value, axis): + return dtensor_util.dtensor_reduce(self, reduce_op, value, axis) + + @property + def mesh(self): + """Returns the mesh used by the strategy.""" + return self._mesh diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..d7fe5d748304a08aa0ab8a2e6a852208b0a14f86 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/multi_worker_mirrored_strategy.py @@ -0,0 +1,156 @@ +# 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. +# ============================================================================== +"""Implement a MultiMirroredStrategy based on the DTensor low level API. + +This is an experiment to validate the viability of the DTensor API, and expose +any potential feature gaps between the current API and the need. +""" + +import os + +from tensorflow.dtensor.python import config as d_config +from tensorflow.dtensor.python import mesh_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute.cluster_resolver import tfconfig_cluster_resolver +from tensorflow.python.distribute.experimental import dtensor_strategy_extended +from tensorflow.python.distribute.experimental import dtensor_util + + +class MultiWorkerMirroredStrategy(distribute_lib.Strategy): + """A distribution strategy for synchronous training on multiple workers. + + This strategy implements synchronous distributed training across multiple + workers, each with potentially multiple GPUs. Similar to + `tf.distribute.MirroredStrategy`, it replicates all variables and computations + to each local device. The difference is that it uses a distributed collective + implementation (e.g. all-reduce), so that multiple workers can work together. + """ + + def __init__(self, cluster_resolver=None, communication_options=None, *, + mesh=None): + """Creates the strategy. + + Args: + cluster_resolver: optional + `tf.distribute.cluster_resolver.ClusterResolver`. In case neither `mesh` + nor `cluster_resolver` are provided, + `tf.distribute.cluster_resolver.TFConfigClusterResolver` is used. + communication_options: currently ignore. + mesh: optional Dtensor global mesh for the computation. Note that either + `mesh` or the `cluster_resolver` should be provided. and not both. + """ + self._validate_init_args(mesh, cluster_resolver) + if not mesh: + if not cluster_resolver: + # Use the TFConfigClusterResolver as default + cluster_resolver = tfconfig_cluster_resolver.TFConfigClusterResolver() + dtensor_env_var = _parse_dtensor_env_var_from_cluster_resolver( + cluster_resolver) + _config_dtensor_env_var(dtensor_env_var) + mesh = _build_distributed_mesh(dtensor_util.DEFAULT_BATCH_MESH_DIM_NAME) + extended = dtensor_strategy_extended.DTensorStrategyExtended( + container_strategy=self, mesh=mesh) + super().__init__(extended) + self._mesh = mesh + self._cluster_resolver = cluster_resolver + + @classmethod + def _validate_init_args(cls, mesh, cluster_resolver): + if mesh and cluster_resolver: + raise ValueError('Mesh and cluster_resolver can not be provided at the ' + f'same time. Received mesh = {mesh}, cluster_resolver = ' + f'{cluster_resolver}') + if mesh and len(mesh.shape()) != 1: + raise ValueError('The mesh for MultiWorkerMirroredStrategy must be 1D, ' + f'received: {len(mesh.shape())}D') + + def reduce(self, reduce_op, value, axis): + return dtensor_util.dtensor_reduce(self, reduce_op, value, axis) + + @property + def mesh(self): + """Returns the mesh used by the strategy.""" + return self._mesh + + +def _parse_dtensor_env_var_from_cluster_resolver(cluster_resolver): + """Parse the env vars for Dtensor based on the cluster resolver. + + In the multi-client setting, each of the DTensor jobs need to aware of each + other, and the interface to setup those values are via the envvars. The + value used by dtensor are different from the existing + `MultiWorkerMirroredStrategy`. This function will parse the value from + cluster resolver, and populate the corresponding value for DTensor jobs in the + `os.environ`. + + Args: + cluster_resolver: A `tf.distribute.cluster_resolver.ClusterResolver` + instance. + + Returns: + A dict of {Str:Str} which contains all the env vars needed by DTensor jobs. + The value is for verification purpose. + + Raises: + The value parsed from existing cluster spec is not valid. + """ + result = {} + + # Retrieve the number of host, cluster config from the resolver. + cluster_spec = multi_worker_util.normalize_cluster_spec( + cluster_resolver.cluster_spec()) + # Export all the necessary envvars for dtensor + # Get all the jobs from the cluster spec. Note that the in the normal + # setting, it could be multiple worker devices without chief, and the + # worker 0 will be the chief, or an explicit chief with multiple worker job. + dtensor_jobs = [] + if 'chief' in cluster_spec.jobs: + dtensor_jobs.extend(cluster_spec.job_tasks('chief')) + if 'worker' in cluster_spec.jobs: + dtensor_jobs.extend(cluster_spec.job_tasks('worker')) + + if None in dtensor_jobs: + raise ValueError('Unexpected dtensor job address from cluster spec: ' + f'{cluster_spec}') + result['DTENSOR_JOBS'] = ','.join(dtensor_jobs) + result['DTENSOR_NUM_CLIENTS'] = str(len(dtensor_jobs)) + + if cluster_resolver.task_type == 'chief': + dtensor_client_id = 0 + elif cluster_resolver.task_type == 'worker': + dtensor_client_id = cluster_resolver.task_id + if 'chief' in cluster_spec.jobs: + dtensor_client_id += 1 + result['DTENSOR_CLIENT_ID'] = str(dtensor_client_id) + result['DTENSOR_JOB_NAME'] = 'worker' + + return result + + +def _config_dtensor_env_var(dtensor_env_vars): + for k, v in dtensor_env_vars.items(): + os.environ[k] = v + + +def _build_distributed_mesh(batch_dim_name): + device_type = d_config.preferred_device_type() + local_devices = d_config.local_devices(device_type) + number_clients = d_config.num_clients() + dtensor_util.initialize_accelerator_system_once(device_type) + # This assumes each client has same number of devices. + mesh_dims = [(batch_dim_name, len(local_devices) * number_clients)] + return mesh_util.create_distributed_mesh( + mesh_dims, device_type=device_type) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/rpc/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/rpc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/rpc/rpc_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/rpc/rpc_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..98529d4077d0bc901414a4c4b06d08604ecff117 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/experimental/rpc/rpc_ops.py @@ -0,0 +1,505 @@ +# 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. +# ============================================================================== +"""Module to expose RPC APIs in tensorflow.""" + +from typing import Optional, Sequence, Union + +import tensorflow.distribute.experimental.rpc.kernels.gen_rpc_ops as gen_rpc_ops +from tensorflow.distribute.experimental.rpc.proto import tf_rpc_service_pb2 as rpc_pb2 +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function as tf_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import none_tensor +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import core as core_tf_types +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +def get_output_specs_from_function(func: tf_function.ConcreteFunction): + output_specs = nest.map_structure(type_spec.type_spec_from_value, + func.structured_outputs) + output_specs_proto = nested_structure_coder.encode_structure(output_specs) + return output_specs_proto.SerializeToString() + + +def get_input_specs_from_function(func: tf_function.ConcreteFunction): + arg_specs, _ = func.structured_input_signature + arg_specs_proto = nested_structure_coder.encode_structure(arg_specs) + return arg_specs_proto.SerializeToString() + + +@tf_export("distribute.experimental.rpc.Server", v1=[]) +class Server(object): + """A Server base class for accepting RPCs for registered tf.functions. + + Functions can be registered on the server and are exposed via RPCs. + """ + + @staticmethod + def create(rpc_layer, address): + """Create TF RPC server at given address. + + Args: + rpc_layer: Communication layer between client and server. Only "grpc" rpc + layer is supported at the moment. + address: Address where RPC server is hosted. + + Returns: + An instance of `tf.distribute.experimental.rpc.Server` class. + + Raises: + A ValueError if rpc_layer other than "grpc" is used. Only GRPC + is supported at the moment. + + Example usage: + + >>> import portpicker + >>> @tf.function(input_signature=[ + ... tf.TensorSpec([], tf.int32), + ... tf.TensorSpec([], tf.int32)]) + ... def remote_fn(a, b): + ... return tf.add(a, b) + + >>> port = portpicker.pick_unused_port() + >>> address = "localhost:{}".format(port) + >>> server = tf.distribute.experimental.rpc.Server.create("grpc", address) + >>> server.register("addition", remote_fn) + >>> server.start() + + """ + if rpc_layer != "grpc": + raise ValueError("Only GRPC backend is supported at the moment.") + return GrpcServer(address=address) + + def register(self, method_name: str, + func: Union[def_function.Function, + tf_function.ConcreteFunction]): + """Method for registering tf.function on server. + + Registered methods can be invoked remotely from clients. + + Args: + method_name: Name of the tf.function. Clients use this method_name to make + RPCs. + func: A `tf.function` or ConcreteFunction to register. + """ + raise NotImplementedError("Please use create_server method to create a" + "concrete subclass of Server.") + + def start(self): + """Starts the RPC server on provided address. + + Server listens for new requests from client, once it is started. + """ + raise NotImplementedError("Please use create_server method to create a" + "concrete subclass of Server.") + + +@tf_export("distribute.experimental.rpc.Client", v1=[]) +class Client(object): + """Client class for invoking RPCs to the server.""" + + @staticmethod + def create(rpc_layer, address, name="", timeout_in_ms=0): + """Create TF RPC client to connect to the given address. + + Args: + rpc_layer: Communication layer between client and server. Only "grpc" rpc + layer is supported at the moment. + address: Address of the server to connect the RPC client to. + name: Name of the RPC Client. You can create multiple clients connecting + to same server and distinguish them using different names. + timeout_in_ms: The default timeout to use for outgoing RPCs from client. 0 + indicates no timeout. Exceeding timeout during RPC will raise + DeadlineExceeded error. + + Returns: + An instance of `tf.distribute.experimental.rpc.Client` with the following + dynamically added methods for eagerly created clients: + * `Registered methods` e.g. multiply(**args): + If Client is created when executing eagerly, client will request the + list of registered methods from server during client creation. + The convenience methods for RPCs will be dynamically added to the + created Client instance. + + For example, when a server has method "multiply" registered, the + client object created in eager mode will have 'multiply' method + available. Users can use client.multiply(..) to make RPC, instead of + client.call("multiply", ...) + + Both "call" and "multiply" methods are non-blocking i.e. they return + a StatusOrResult object which should be used to wait for getting + value or error. + + Along with the above, blocking versions of the registered + methods are also dynamically added to client instance. + e.g. multiply_blocking(**args). These methods block till the RPC is + finished and return response for successful RPC. Otherwise raise + exception. + + These methods are not available when Client is created inside a + tf.function. + + Raises: + A ValueError if rpc_layer other than "grpc" is used. Only GRPC + is supported at the moment. + A DeadlineExceeded exception in eager mode if timeout exceeds while + creating and listing client methods. + + Example usage: + >>> # Have server already started. + >>> import portpicker + >>> @tf.function(input_signature=[ + ... tf.TensorSpec([], tf.int32), + ... tf.TensorSpec([], tf.int32)]) + ... def remote_fn(a, b): + ... return tf.add(a, b) + + >>> port = portpicker.pick_unused_port() + >>> address = "localhost:{}".format(port) + >>> server = tf.distribute.experimental.rpc.Server.create("grpc", address) + >>> server.register("addition", remote_fn) + >>> server.start() + + >>> # Start client + >>> client = tf.distribute.experimental.rpc.Client.create("grpc", + ... address=address, name="test_client") + + >>> a = tf.constant(2, dtype=tf.int32) + >>> b = tf.constant(3, dtype=tf.int32) + + >>> result = client.call( + ... args=[a, b], + ... method_name="addition", + ... output_specs=tf.TensorSpec((), tf.int32)) + + >>> if result.is_ok(): + ... result.get_value() + + >>> result = client.addition(a, b) + + >>> if result.is_ok(): + ... result.get_value() + + >>> value = client.addition_blocking(a, b) + """ + if rpc_layer != "grpc": + raise ValueError("Only GRPC backend is supported at the moment.") + if context.executing_eagerly(): + list_registered_methods = True + else: + list_registered_methods = False + return GrpcClient( + address=address, + name=name, + list_registered_methods=list_registered_methods, + timeout_in_ms=timeout_in_ms) + + def call(self, + method_name: str, + args: Optional[Sequence[core_tf_types.Tensor]] = None, + output_specs=None, + timeout_in_ms=0): + """Method for making RPC calls to remote server. + + This invokes RPC to the server, executing the registered method_name + remotely. + Args: + method_name: Remote registered method to invoke + args: List of arguments for the registered method. + output_specs: Output specs for the output from method. + For example, if tf.function is: @tf.function(input_signature=[ + tf.TensorSpec([], tf.int32), tf.TensorSpec([], tf.int32) ]) + def multiply_fn(a, b): return tf.math.multiply(a, b) + output_spec is: tf.TensorSpec((), tf.int32) If you have access to TF + Function, the output specs can be generated + from tf.function by calling: output_specs = + tf.nest.map_structure(tf.type_spec_from_value, + tf_function.get_concrete_function().structured_outputs If output_specs + are not provided, flattened list of tensors will be returned in + response. + timeout_in_ms: Timeout for this call. If 0, default client timeout will be + used. + + Returns: + An instance of `StatusOrResult` class with the following available + methods. + * `is_ok()`: + Returns True of RPC was successful. + * `get_error()`: + Returns TF error_code and error message for the RPC. + * `get_value()`: + Returns the returned value from remote TF function execution + when RPC is successful. + + Calling any of the above methods will block till RPC is completed and + result is available. + """ + raise NotImplementedError("Must be implemented in inherited classes.") + + +class GrpcServer(Server): + """GrpcServer object encapsulates a resource with GRPC server. + + Functions can be registered locally and are exposed via RPCs. + Example: + ``` + server = rpc_ops.GrpcServer("host:port") + @tf.function + def add(a, b): + return a + b + + server.register("add", add) + server.start() + ``` + """ + + def __init__(self, address: str): + self._server_handle = gen_rpc_ops.rpc_server(address) + if context.executing_eagerly(): + self._handle_deleter = resource_variable_ops.EagerResourceDeleter( + handle=self._server_handle, handle_device=self._server_handle.device) + else: + raise NotImplementedError("Please create the server outside tf.function.") + + def register(self, method_name: str, + func: Union[def_function.Function, + tf_function.ConcreteFunction]): + """Method for registering functions.""" + + if isinstance(func, def_function.Function): + if func.function_spec.arg_names: + if func.input_signature is None: + raise ValueError("Input signature not specified for the function.") + concrete_fn = func.get_concrete_function() + gen_rpc_ops.rpc_server_register( + self._server_handle, + method_name=method_name, + captured_inputs=concrete_fn.captured_inputs, + input_specs=get_input_specs_from_function(concrete_fn), + output_specs=get_output_specs_from_function(concrete_fn), + f=concrete_fn) + elif isinstance(func, tf_function.ConcreteFunction): + gen_rpc_ops.rpc_server_register( + self._server_handle, + method_name=method_name, + captured_inputs=func.captured_inputs, + input_specs=get_input_specs_from_function(func), + output_specs=get_output_specs_from_function(func), + f=func) + else: + # Python functions + # TODO(b/186762191): Add an implementation to support python functions. + raise ValueError("Only TF functions are supported with Register method") + + def start(self): + """Starts GRPC server.""" + gen_rpc_ops.rpc_server_start(self._server_handle) + + +class GrpcClient(Client): + """Client wrapper to connect to remote RPC server using GRPC. + + If Client is created with (list_registered_methods=True): + 1. Input and output specs for the methods till this point will be fetched from + Server. + 2. convenience methods are added to invoke registered methods directly from + client. + For example: + For call a server method `add` + client.add(a, b) or client.add_async(a, b) can be used instead of + client.call(args=[a,b], output_specs=[..]) + + Prerequiste for using list_registered_methods=True: + 1. Server should be already started with the registered methods. + 2. Client must be created in Eager mode. + """ + + def __init__(self, + address: str, + name: str = "", + list_registered_methods=False, + timeout_in_ms=0): + self._client_handle, methods = gen_rpc_ops.rpc_client( + shared_name=name, + server_address=address, + list_registered_methods=list_registered_methods, + timeout_in_ms=timeout_in_ms) + if context.executing_eagerly(): + self._handle_deleter = resource_variable_ops.EagerResourceDeleter( + handle=self._client_handle, handle_device=self._client_handle.device) + else: + raise NotImplementedError( + "Client creation is supported only in eager mode.") + self._server_address = address + self._method_registry = {} + for method in methods.numpy(): + m = rpc_pb2.RegisteredMethod() + m.ParseFromString(method) + output_specs = nested_structure_coder.decode_proto(m.output_specs) + input_specs = nested_structure_coder.decode_proto(m.input_specs) + self._method_registry[m.method] = output_specs + # TODO(ishark): Perhaps doc string can also be taken as input during + # function registration. + doc_string = "RPC Call for " + m.method + " method to server " + address + self._add_method(m.method, output_specs, input_specs, self._client_handle, + doc_string) + + def _add_method(self, method_name, output_specs, input_specs, client_handle, + doc_string): + """Method to add RPC methods to the client object.""" + + def validate_and_get_flat_inputs(*args): + if args is None: + args = [] + if input_specs: + nest.assert_same_structure(args, input_specs) + flat_inputs = nest.flatten(args) + return flat_inputs + + def call_wrapper(*args, timeout_in_ms=0): + status_or, deleter = gen_rpc_ops.rpc_call( + client_handle, + args=validate_and_get_flat_inputs(*args), + method_name=method_name, + timeout_in_ms=timeout_in_ms) + return StatusOrResult(status_or, deleter, output_specs) + + def call_blocking_wrapper(*args, timeout_in_ms=0): + status_or, deleter = gen_rpc_ops.rpc_call( + client_handle, + args=validate_and_get_flat_inputs(*args), + method_name=method_name, + timeout_in_ms=timeout_in_ms) + status_or = StatusOrResult(status_or, deleter, output_specs) + if status_or.is_ok(): + return status_or.get_value() + else: + error_code, error_msg = status_or.get_error() + raise errors.exception_type_from_error_code(error_code.numpy())( + None, None, error_msg.numpy()) + + setattr(self, method_name, call_wrapper) + call_wrapper.__doc__ = doc_string + + blocking_method_name = method_name + "_blocking" + setattr(self, blocking_method_name, call_blocking_wrapper) + call_blocking_wrapper.__doc__ = doc_string + + def call(self, + method_name: str, + args: Optional[Sequence[core_tf_types.Tensor]] = None, + output_specs=None, + timeout_in_ms=0): + """Method to invoke remote registered functions on the connected server. + + Server should be started before making an RPC Call. + + Args: + method_name: Registered method to invoke on Server. + args: Input arguments for the method. + output_specs: Output specs for the output from method. + timeout_in_ms: Timeout for this call. If 0, default client timeout will be + used. + + Returns: + StatusOrResult object. This function issues the RPC call to server, it + does not block for the duration of RPC. Please call is_ok, get_error or + get_value methods on the returned object to blocked till RPC finishes. + """ + if args is None: + args = [] + status_or, deleter = gen_rpc_ops.rpc_call( + self._client_handle, + args=nest.flatten(args), + method_name=method_name, + timeout_in_ms=timeout_in_ms) + return StatusOrResult(status_or, deleter, output_specs) + + +class StatusOrResult(object): + """Class representing result and status from RPC Call.""" + + def __init__(self, status_or, deleter, output_specs=None): + self._status_or = status_or + self._output_specs = output_specs + self._deleter = deleter + self._error_code: dtypes.int64 = None + self._error_message: dtypes.string = None + + def _check_status(self): + if self._error_code is None: + self._error_code, self._error_message = gen_rpc_ops.rpc_check_status( + self._status_or) + + def __del__(self): + # Make sure the resource is deleted in the same mode as it was created in. + if context.executing_eagerly(): + with context.eager_mode(): + gen_rpc_ops.delete_rpc_future_resource( + handle=self._status_or, deleter=self._deleter) + else: + with context.graph_mode(): + gen_rpc_ops.delete_rpc_future_resource( + handle=self._status_or, deleter=self._deleter) + + def is_ok(self): + """Returns True if RPC is successful, otherwise returns False. + + This call will block for RPC result. + """ + self._check_status() + return math_ops.equal(self._error_code, + constant_op.constant(0, dtype=dtypes.int64)) + + def get_error(self): + """Returns (TF Error Code, Error Message) from RPC Response. + + This call will block for RPC result. + """ + self._check_status() + return self._error_code, self._error_message + + def get_value(self): + """Returns the returned response value from RPC Call when RPC is successful. + + The returned value is tensors in the output_specs format as returned from + the RPC call + + + This call will block for RPC result. + """ + + self._check_status() + if self._output_specs is None or isinstance(self._output_specs, + none_tensor.NoneTensorSpec): + flat_output_dtypes = [] + return_none = True + else: + return_none = False + flat_output_dtypes = [s.dtype for s in nest.flatten(self._output_specs)] + + result = gen_rpc_ops.rpc_get_value(self._status_or, Tout=flat_output_dtypes) + if return_none: + return None + else: + return nest.pack_sequence_as(self._output_specs, result) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/failure_handling.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/failure_handling.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb6256cc6da1fe807f40e813ed961d8c2301fc0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/failure_handling.py @@ -0,0 +1,1268 @@ +# 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. +# ============================================================================== +"""Module for `PreemptionCheckpointHandler`. + +This is currently under development and the API is subject to change. + +PreemptionCheckpointHandler reduces loss of training progress caused by +termination (preemption or maintenance) of workers in multi-worker synchronous +training and avoid surfacing an error indistinguishable from application errors +to the job scheduler or users. +""" +import os +import signal +import sys +import threading +import time + +from tensorflow.core.distributed_runtime.preemption import gen_check_preemption_op +from tensorflow.python.checkpoint import checkpoint as checkpoint_lib +from tensorflow.python.checkpoint import checkpoint_context +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute.failure_handling import failure_handling_util +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + + +_INITIAL_RUN_COUNT_KEY = 'RUN_TO_CHECKPOINT' +_FINAL_RUN_COUNT_KEY = 'LAST_RUN_TO_CHECKPOINT' +# This key is used to guarantee that only one worker (and it's the earliest +# one that receives a preemption signal) sets _received_own_sigterm, +# leads the step resolution, and controls the grace period timeline. +_PREEMPTION_WORKER_KEY = 'TERMINATED_WORKER' +_ACKNOWLEDGE_KEY = 'RECEIVED_SIGNAL' +_ITERATION_VARIABLE = 'checkpointed_runs' +_STOP_WATCHING_CLUSTER_VALUE = 'STOP_WATCHER' +PREEMPTION_KEY = 'TF_DEFAULT_PREEMPTION_NOTICE_KEY' + + +# TODO(wxinyi): add type annotations. +def _non_chief_checkpoint_dir(checkpoint_dir, task_id): + """Returns a directory for non-chief worker to save checkpoint.""" + dirpath = os.path.dirname(checkpoint_dir) + base = os.path.basename(checkpoint_dir) + base_dirpath = 'workertemp_' + str(task_id) + dirpath = os.path.join(dirpath, base_dirpath) + file_io.recursive_create_dir_v2(dirpath) + return os.path.join(dirpath, base) + + +@tf_export('distribute.experimental.TerminationConfig', v1=[]) +class TerminationConfig(object): + """Customization of `PreemptionCheckpointHandler` for various platforms. + + A `TerminationConfig` can be created and passed to a + `tf.distribute.experimental.PreemptionCheckpointHandler` to provide + customization based on the platform. It can deliver three pieces of + information: + + * How to decide if there is a termination event soon + + The form of termination notification and how to fetch it vary across + platforms. Thus `PreemptionCheckpointHandler` may take a user-defined + function, `termination_watcher_fn`, and execute it repeatedly to check for + termination notification. `termination_watcher_fn` should be a function + that returns `True` if a termination notification is available and + `False` otherwise. The function should be lightweight and non-blocking so that + resources can be cleaned up properly if no termination signal is ever raised + until training finishes. + + * How to exit the program + + A user can configure this through the `exit_fn`, which + `PreemptionCheckpointHandler` executes after saving the checkpoint to exit the + training program gracefully. For `tf.distribute.MultiWorkerMirroredStrategy`, + a restart is necessary to reset the program's state. However, having a + customized `exit_fn` may facilitate the restart and smoothen the training + experience. How so? Maybe the platform has an agreement to a `RESTART_CODE` + recognized as a program auto-restart signal, or maybe the user has a + coordinating script that starts up the training, in which they can configure + the program to auto-restart if it ever exits with this `RESTART_CODE`. In both + cases, configuring the `exit_fn` to be `sys.exit(RESTART_CODE)` makes the + training seamless. + + * How long does `PreemptionCheckpointHandler` have from receiving a + termination event notice till the actual termination + + Some platforms have a gap time as long as one hour or so. In these cases, + there is the option to utilize this gap time for training as much as possible + before saving a checkpoint and exiting. This can be achieved by passing the + `grace_period` argument a nonzero value. Note, for a user with a grace period + that is not multiple times longer than their checkpoint writing time (e.g., + three times or more), we advise not to configure this argument, in which case + `PreemptionCheckpointHandler` will directly save a checkpoint and exit. + + + **The default behavior**: + + * For Google Borg Platform: + * Automatically know how to detect preemption signal + * Exit with a platform-recognized restart code + * Save a checkpoint and exit immediately + + * For Google Cloud Platform: + * Automatically know how to detect maintenance signal. + * Exit with a code (User may configure this) + * Automatically utilized the extended training period before save and exit + + * For Other platform: + * If `termination_watcher_fn` is `None`, we will treat `signal.SIGTERM` as + a termination signal. + * If `exit_fn` is not configured, we exit the program with an arbitrary + code. + * If `grace_period` is not configured, we will wrap up the current + training step, save a checkpoint, and exit the program as soon as we + receive the termination signal. + """ + + def __init__(self, + termination_watcher_fn=None, + exit_fn=None, + grace_period=None, + save_fn=None): + """Creates a `TerminationConfig` object. + + Args: + termination_watcher_fn: a function to execute repeatedly that returns + `True` if a preemption signal is available and False otherwise. The + function cannot block until a preemption signal is available, which + prevents proper cleanup of the program. A change is **NOT** recommended + for users on Google Borg or Google Cloud Platform. + exit_fn: a function to execute after a checkpoint is saved and before the + preemption happens. Usually, it should be in the form of + `lambda: sys.exit(RESTART_CODE)`, where `RESTART_CODE` varies by + platform. A change is **NOT** recommended for users on Google Borg. + Users on Google Cloud Platform may configure it to use a customized + `RESTART_CODE`. + grace_period: the length of time between receiving a preemption signal and + the actual preemption. A change is **NOT** recommended for users on + Google Borg, Google Cloud Platform, or users with a short grace period. + save_fn: an optional function letting you configure how to save a + checkpoint. This is useful if you'd like to pass extra argument to + `tf.train.CheckpointManager.save` or `tf.train.Checkpoint.save`. By + default, if not configured, the API will save checkpoint without extra + arguments. + """ + self.termination_watcher_fn = termination_watcher_fn + self.exit_fn = exit_fn + self.grace_period = grace_period + self.save_fn = save_fn + + +# TODO(wxinyi): add some tests for TerminationConfig. +# TODO(wxinyi): configure the exit function based on device type (GPU or TPU). +class GcpGpuTerminationConfig(TerminationConfig): + """Configurations for GCP GPU VM.""" + + def __init__( # pylint: disable=super-init-not-called + self, + termination_watcher_fn=None, + exit_fn=None, + grace_period=None, + save_fn=None, + ): + self.termination_watcher_fn = ( + termination_watcher_fn + or failure_handling_util.termination_watcher_function_gce + ) + self.exit_fn = exit_fn or failure_handling_util.gce_exit_fn + self.grace_period = ( + grace_period if grace_period or grace_period == 0 else + failure_handling_util.GRACE_PERIOD_GCE) + self.save_fn = save_fn + + +class GcpCpuTerminationConfig(TerminationConfig): + """Configurations for GCP CPU VM.""" + + def __init__( # pylint: disable=super-init-not-called + self, + termination_watcher_fn=None, + exit_fn=None, + grace_period=None, + save_fn=None): + self.termination_watcher_fn = termination_watcher_fn or failure_handling_util.termination_watcher_function_gce + self.exit_fn = exit_fn or failure_handling_util.gce_exit_fn + self.grace_period = grace_period or 0 + self.save_fn = save_fn + + +class BorgTerminationConfig(TerminationConfig): + """Configurations for Borg.""" + + def __init__( # pylint: disable=super-init-not-called + self, + termination_watcher_fn=None, + exit_fn=None, + grace_period=None, + save_fn=None): + self.termination_watcher_fn = termination_watcher_fn + default_exit_fn = lambda: sys.exit(42) + self.exit_fn = exit_fn or default_exit_fn + self.grace_period = grace_period or 0 + self.save_fn = save_fn + + +class BorgTPUTerminationConfig(TerminationConfig): + """Configurations for Borg.""" + + def __init__( # pylint: disable=super-init-not-called + self, + termination_watcher_fn=None, + exit_fn=None, + grace_period=None, + save_fn=None): + self.termination_watcher_fn = termination_watcher_fn + self.exit_fn = exit_fn or failure_handling_util.default_tpu_exit_fn + self.grace_period = grace_period or 0 + self.save_fn = save_fn + + +def _complete_config_for_environment(platform_device, termination_config): + """Complete un-filled fields of TerminationConfig based on platform.""" + if not termination_config: + termination_config = TerminationConfig() + + if platform_device is failure_handling_util.PlatformDevice.GCE_GPU: + return GcpGpuTerminationConfig(termination_config.termination_watcher_fn, + termination_config.exit_fn, + termination_config.grace_period, + termination_config.save_fn) + + elif platform_device is failure_handling_util.PlatformDevice.GCE_CPU: + return GcpCpuTerminationConfig(termination_config.termination_watcher_fn, + termination_config.exit_fn, + termination_config.grace_period, + termination_config.save_fn) + + elif platform_device is failure_handling_util.PlatformDevice.INTERNAL_TPU: + return BorgTPUTerminationConfig(termination_config.termination_watcher_fn, + termination_config.exit_fn, + termination_config.grace_period, + termination_config.save_fn) + + else: + # The default we chose are the same as the ones used by Borg. So we just + # return this. + return BorgTerminationConfig( + termination_config.termination_watcher_fn, + termination_config.exit_fn, termination_config.grace_period, + termination_config.save_fn) + + +# TODO(wxinyi): add release updates. +# Implementation: +# Each worker will create its own PreemptionCheckpointHandler instance, and the +# instances communicate through coordination services. Each +# PreemptionCheckpointHandler conduct three tasks in parallel: +# - Watches out for its own preemption signal. (_poll_termination_signal_thread) +# - Watches out for a step key from the coordination service made available +# by any member in the cluster (_cluster_wise_termination_watcher_thread) +# - The main thread for training. +# +# The life cycle of a PreemptionCheckpointHandler is as below: +# +# It starts two threads as two watcher as described above. And it starts +# training. Each time before it starts a training step, it will check if any +# information has been made available by the two watchers: The +# _poll_termination_signal_thread will be in charge of the _received_own_sigterm +# event, the _cluster_wise_termination_watcher_thread will be in charge of the +# _received_checkpoint_step event. +# +# If at any point the local worker receives a preemption signal, +# _poll_termination_signal_thread will set _received_own_sigterm. +# Next time before it attempts to run a training step, it will deal with the +# event, by setting its current finished step + 1 as the step after which a +# checkpoint should be saved and make it available to all the workers through +# the coordination service. It will then continue training. +# +# This step key will be picked up by the other watcher, +# _cluster_wise_termination_watcher_thread, both on the worker to be preempted +# and other workers. And it will set the _received_checkpoint_step event. +# Now, if there is a long grace period before the training +# has to terminate (e.g., an hour), we would like to keep training and save a +# checkpoint again right before the termination. Thus this watcher thread will +# move on to watch out for a final step-to-save key. Otherwise, +# it has finished all the task to do. +# +# Back to the main training thread. Again, before the next training step, the +# PreemptionCheckpointHandler found that _received_checkpoint_step is set. If +# the local worker has not finished the required step after which to save a +# checkpoint, it will not do anything. Continue training and it will revisit +# after another step. If the step is met, then it will save a checkpoint, +# which requires participation of all workers. +# +# After this checkpoint is saved, if there is NO long grace period, all workers +# will just exit. If there is, all workers will enter a grace period countdown +# phase (_final_checkpoint_countdown) and clear the _received_checkpoint_step +# event. They will then continue training. +# +# For the worker to be preempted, during this countdown period, it will check +# whether the grace period is almost ending before its every step. If not, +# nothing needs to be done. If so, it will again set a step-to-save key and made +# it available to all workers. This is still watched by +# _cluster_wise_termination_watcher_thread and gestured by +# _received_checkpoint_step. A similar process is repeated: all workers save +# a checkpoint at an agreed step. And after they finish saving, they recognize +# that they have finished a countdown period for an extended grace period, and +# they all exit. +# +# When the program restarts and PreemptionCheckpointHandler object is created, +# it will restore the checkpoint. +@tf_export('distribute.experimental.PreemptionCheckpointHandler', v1=[]) +class PreemptionCheckpointHandler(object): + # pylint: disable=line-too-long + """Preemption and error handler for synchronous training. + + Note: This API only supports use with + `tf.distribute.MultiWorkerMirroredStrategy` and `tf.distribute.TPUStrategy`. + + A `PreemptionCheckpointHandler` coordinates all workers to save a checkpoint + upon receiving a preemption signal. It also helps disseminate application + error messages accurately among the cluster. When a + `PreemptionCheckpointHandler` object is created, it restores values from + the latest checkpoint file if any exists. + + Right after the initialization, the object starts to watch out for termination + signal for any member in the cluster. If receiving a signal, the next time the + worker executes `PreemptionCheckpointHandler.run`, the + `PreemptionCheckpointHandler` will align all workers to save a checkpoint. + Then, if an `exit_fn` is configured via + `tf.distribute.experimental.TerminationConfig`, it will be invoked. Otherwise, + the process will simply exit and later the platform should restart it. + + Note: We advise users of `tf.distribute.MultiWorkerMirroredStrategy` who + choose to configure their + own `exit_fn` in `tf.distribute.experimental.TerminationConfig` to include a + `sys.exit(CODE_OR_MESSAGE)` in the `exit_fn` so that after the restart, all + workers can initialize communication services correctly. For users of + `tf.distribute.TPUStrategy`, if they do not wish to do a cluster restart but + would like an in-process restart (i.e., keep the coordinator alive and re-do + the steps to connect to cluster, initialize TPU system, and make the + `TPUStrategy` object), they could configure the `exit_fn` to a no-op. + + For users of `tf.distribute.MultiWorkerMirroredStrategy`, the core API is + `PreemptionCheckpointHandler.run`: + + ```python + strategy = tf.distribute.MultiWorkerMirroredStrategy() + + trained_epoch = tf.Variable(initial_value=tf.constant(0, dtype=tf.dtypes.int64), name='epoch') + step_in_epoch = tf.Variable(initial_value=tf.constant(0, dtype=tf.dtypes.int64), name='step_in_epoch') + + with strategy.scope(): + dataset, model, optimizer = ... + + checkpoint = tf.train.Checkpoint(optimizer=optimizer, + model=model, + trained_epoch=trained_epoch, + step_in_epoch=step_in_epoch) + + preemption_checkpoint_handler = tf.distribute.experimental.PreemptionCheckpointHandler(cluster_resolver, checkpoint, checkpoint_dir) + + while trained_epoch.numpy() < NUM_EPOCH: + + while step_in_epoch.numpy() < STEPS_PER_EPOCH: + + # distributed_train_function contains a call to strategy.run. + loss += preemption_checkpoint_handler.run(distributed_train_function, args=(next(iterator),)) + # For users of MultiWorkerMirroredStrategy, usually + # STEPS_PER_TRAIN_FUNCTION = 1. + step_in_epoch.assign_add(STEPS_PER_TRAIN_FUNCTION) + ... + + epoch.assign_add(1) + step_in_epoch.assign(0) + ``` + + For users of `tf.distribute.TPUStrategy`, the core APIs are + `PreemptionCheckpointHandler.run` and + `PreemptionCheckpointHandler.watch_preemption_scope`: + + ```python + + strategy = tf.distribute.TPUStrategy(tpu_cluster_resolver) + + # Rest of TPU init omitted, see documentation for TPUSTrategy. + + with preemption_checkpoint_handler.watch_preemption_scope(): + while trained_epoch.numpy() < NUM_EPOCH: + + while step_in_epoch.numpy() < STEPS_PER_EPOCH: + + # distributed_train_function contains a call to strategy.run. + loss += preemption_checkpoint_handler.run(distributed_train_function, args=(next(iterator),)) + + # For users of TPUStrategy, usually STEPS_PER_TRAIN_FUNCTION >> 1 since + # clustering multiple steps within a tf.function amortizes the overhead + # of launching a multi-device function on TPU Pod. + step_in_epoch.assign_add(STEPS_PER_TRAIN_FUNCTION) + ... + + epoch.assign_add(1) + step_in_epoch.assign(0) + ``` + + Not all interruptions come with advance notice so that the + `PreemptionCheckpointHandler` can handle them, e.g., those caused by hardware + failure. For a user who saves checkpoints for these cases themselves outside + the `PreemptionCheckpointHandler`, if they are using a + `tf.train.CheckpointManager`, pass it as the + `checkpoint_or_checkpoint_manager` argument to the + `PreemptionCheckpointHandler`. If they do not have a + `tf.train.CheckpointManager` but are directly working with + `tf.train.Checkpoint`, we advise saving the checkpoints in the directory + that's passed as the `checkpoint_dir` argument. In this way, at the program + beginning, `PreemptionCheckpointHandler` can restore the latest checkpoint + from the directory, no matter it's saved by the user themselves or saved by + the `PreemptionCheckpointHandler` before preemption happens. + + **A note on the platform:** + + `PreemptionCheckpointHandler` can only handle the kind of termination with + advance notice. For now, the API recognizes the termination signal for CPU, + GPU, and TPU on Google Borg and CPU and GPU on the Google Cloud Platform. In + these cases, `PreemptionCheckpointHandler` will automatically adopt the + correct preemption/maintenance notification detection mechanism. Users of + other platforms can configure a detection monitoring behavior through the + `tf.distribute.experimental.TerminationConfig`. Customization for the exit + behavior and grace period length could also be done here. + """ + # pylint: enable=line-too-long + + def __init__(self, + cluster_resolver, + checkpoint_or_checkpoint_manager, + checkpoint_dir=None, + termination_config=None): + """Creates the `PreemptionCheckpointHandler`. + + Args: + cluster_resolver: a `tf.distribute.cluster_resolver.ClusterResolver` + object. You may also obtain it through the `cluster_resolver` attribute + of the distribution strategy in use. + checkpoint_or_checkpoint_manager: a `tf.train.CheckpointManager` or a + `tf.train.Checkpoint`. If you are using a `tf.train.CheckpointManager` + to manage checkpoints outside the `PreemptionCheckpointHandler` for + backup purpose as well, pass it as `checkpoint_or_checkpoint_manager` + argument. Otherwise, pass a `tf.train.Checkpoint` and the + `PreemptionCheckpointHandler` will create + a `tf.train.CheckpointManager` to manage it in the `checkpoint_dir`. + checkpoint_dir: a directory where the `PreemptionCheckpointHandler` saves + and restores checkpoints. When a `PreemptionCheckpointHandler` is + created, the latest checkpoint in the `checkpoint_dir` will be restored. + (This is not needed if a `tf.train.CheckpointManager` instead of a + `tf.train.Checkpoint` is passed as the + `checkpoint_or_checkpoint_manager` argument.) + termination_config: optional, a + `tf.distribute.experimental.TerminationConfig` object to configure for a + platform other than Google Borg or GCP. + """ + # TODO(wxinyi): Maybe make checkpoint_or_checkpoint_manager optional if + # save_fn is passed. For now it's still useful for restore. + if isinstance(checkpoint_or_checkpoint_manager, + checkpoint_lib.Checkpoint) and not checkpoint_dir: + raise errors.InvalidArgumentError('When a checkpoint is passed, a ' + 'checkpoint_dir must be passed as well' + '.') + + self._cluster_resolver = cluster_resolver + self._termination_config = termination_config + self._checkpoint_or_checkpoint_manager = checkpoint_or_checkpoint_manager + self._checkpoint_dir = checkpoint_dir + + self._platform_device = failure_handling_util.detect_platform() + + completed_termination_config = _complete_config_for_environment( + self._platform_device, self._termination_config + ) + self._termination_watcher_fn = ( + completed_termination_config.termination_watcher_fn + ) + self._exit_fn = completed_termination_config.exit_fn + self._grace_period = completed_termination_config.grace_period + self._save_fn = completed_termination_config.save_fn + + self._local_mode = True + if self._platform_device in ( + failure_handling_util.PlatformDevice.GCE_TPU, + failure_handling_util.PlatformDevice.GCE_CPU, + ): + # While running MultiWorkerMirroredStrategy training with GPUs and CPUs + # are the same on Borg, GCE CPU VM and GPU VM are different in terms + # of live migration, grace period, etc. We can make it work upon request. + logging.warning( + 'PreemptionCheckpointHandler does not support usage with ' + 'TPU or CPU device on GCP.' + ) + + elif ( + self._platform_device + == failure_handling_util.PlatformDevice.INTERNAL_TPU + ): + self._initialize_for_tpu_strategy() + + else: + if cluster_resolver and 'ps' in cluster_resolver.cluster_spec().as_dict(): + raise NotImplementedError( + 'PreemptionCheckpointHandler does not support' + 'usage with tf.distribute.experimental.ParameterServerStrategy.' + ) + + self._initialize_for_mirrored_and_multi_worker_mirrored() + + logging.info('PreemptionCheckpointHandler initialized or restored.') + + def _initialize_for_tpu_strategy(self): + """Makes configurations for using the handler with TPUStrategy.""" + self._is_chief = True + self._poll_termination_signal_thread = None + self._cluster_wise_termination_watcher_thread = None + self._maybe_create_checkpoint_manager() + self._read_checkpoint_manager.restore_or_initialize() + self._run_counter = 0 + + def _initialize_for_mirrored_and_multi_worker_mirrored(self): + """Makes configurations and start watchers for MS, MWMS, or OneDevice.""" + if ( + not self._cluster_resolver + or not self._cluster_resolver.cluster_spec().jobs + ): + # For MirroredStrategy, OneDeviceStrategy, and local-mode + # MultiWorkerMirroredStrategy, an empty cluster spec is passed, and + # coordination service is not enabled nor is it needed (since + # it's used for cross-worker communication). Thus we will directly name + # the worker id and is_chief properties and also skip the + # uploading/reading from coordination service logic. + self._local_mode = True + self._id_in_cluster = 'single_worker' + self._is_chief = True + else: + self._local_mode = False + self._id_in_cluster = str( + multi_worker_util.id_in_cluster( + self._cluster_resolver.cluster_spec(), + self._cluster_resolver.task_type, + self._cluster_resolver.task_id)) + self._is_chief = multi_worker_util.is_chief( + cluster_spec=self._cluster_resolver.cluster_spec(), + task_type=self._cluster_resolver.task_type, + task_id=self._cluster_resolver.task_id) + # The number of calls to `PreemptionCheckpointHandler.run` when the latest + # checkpoint was saved. + self._checkpointed_runs = variables.Variable( + initial_value=constant_op.constant(0, dtype=dtypes.int64), + trainable=False, + name=_ITERATION_VARIABLE) + + self._maybe_create_checkpoint_manager() + + if not hasattr(self._write_checkpoint_manager._checkpoint, # pylint: disable=protected-access + _ITERATION_VARIABLE): + setattr(self._write_checkpoint_manager._checkpoint, _ITERATION_VARIABLE, # pylint: disable=protected-access + self._checkpointed_runs) + + if not hasattr(self._read_checkpoint_manager._checkpoint, # pylint: disable=protected-access + _ITERATION_VARIABLE): + setattr(self._read_checkpoint_manager._checkpoint, _ITERATION_VARIABLE, # pylint: disable=protected-access + self._checkpointed_runs) + + self._read_checkpoint_manager.restore_or_initialize() + + # grace period countdown. Set to True for all workers once they finish + # timing saving a checkpoint. Once entering this phase, new + # preemption/maintenance notice will not be handled, since the whole cluster + # goes down as the worker who first initiates the grace period goes down. + self._final_checkpoint_countdown = False + + self._estimated_run_time = 0 + + # An internal step counter that's restored to checkpointed_iterations when + # training is restored. It increments by one every time + # `PreemptionCheckpointHandler.run` is called. Note that in this case, the + # user must pass a single-step training function to + # `PreemptionCheckpointHandler.run` instead of a multiple-step one. + self._run_counter = self._checkpointed_runs.numpy() + + # The worker itself has received preeption signal. + self._received_own_sigterm = threading.Event() + + # Some member (could be oneself) has received preemption signal, and the + # step number to save a checkpoint has been aligned. + self._received_checkpoint_step = threading.Event() + + distribute_lib.distribution_strategy_input_api_counter.get_cell( + self._platform_device.name, + 'PreemptionCheckpointHandler').increase_by(1) + + if not self._local_mode: + # When training is interrupted, we explicitly call the cleanup methods for + # the thread watching for local worker's termination signal and the thread + # watching for clusterwise information before we save a checkpoint and + # exit. In the final chapter of the training where no interruption is + # encountered, we rely on __del__ to clean up. However, there is no + # guarantee when or whether __del__ is executed, thus we make the threads + # daemon to avoid it preventing program from exit. + self._cluster_wise_termination_watcher_thread = threading.Thread( + target=self._watch_step_to_save_key, + name='PeerTerminationWatcher-%s' % self._id_in_cluster, + daemon=True) + logging.info('Start watcher for peer\'s signal.') + self._cluster_wise_termination_watcher_thread.start() + + else: + self._cluster_wise_termination_watcher_thread = None + + self._poll_termination_signal_thread = None + + if self._termination_watcher_fn: + self._start_polling_for_termination_signal() + else: + self._start_watching_for_signal() + + def _maybe_create_checkpoint_manager(self): + """Create CheckpointManager(s) if a checkpoint is passed else take it.""" + if isinstance(self._checkpoint_or_checkpoint_manager, + checkpoint_management.CheckpointManager): + self._read_checkpoint_manager = self._checkpoint_or_checkpoint_manager + self._write_checkpoint_manager = self._checkpoint_or_checkpoint_manager + self._api_made_checkpoint_manager = False + else: + self._api_made_checkpoint_manager = True + # Make CheckpointManagers. MultiWorkerMirroredStrategy requires different + # setup on chief and on other workers. + self._read_checkpoint_manager = checkpoint_management.CheckpointManager( + self._checkpoint_or_checkpoint_manager, + directory=self._checkpoint_dir, + max_to_keep=1) + + if self._is_chief: + self._write_checkpoint_manager = self._read_checkpoint_manager + else: + self._write_checkpoint_manager = ( + checkpoint_management.CheckpointManager( + self._checkpoint_or_checkpoint_manager, + _non_chief_checkpoint_dir(self._checkpoint_dir, + self._cluster_resolver.task_id), + max_to_keep=1)) + + def _start_watching_for_signal(self): + logging.info('Start watcher for local signal.') + signal.signal(signal.SIGTERM, self._sigterm_handler_fn) + + def _start_polling_for_termination_signal(self): + self._poll_termination_signal_thread_should_stop = threading.Event() + self._poll_termination_signal_thread = threading.Thread( + target=self._poll_termination_signal, + name='WorkerTerminationSignalWatcher-%s' % self._id_in_cluster, + daemon=True) + logging.info('Start polling for termination signal.') + self._poll_termination_signal_thread.start() + + def _poll_termination_signal(self): + """Poll maintenance notice and notify peers if receiving one.""" + while True: + if self._poll_termination_signal_thread_should_stop.is_set( + ) or self._final_checkpoint_countdown: + return + if self._termination_watcher_fn(): + break + time.sleep(1) + + self._maybe_set_received_own_sigterm() + + def _maybe_set_received_own_sigterm(self): + """Claim earliest preemption if no one else has done it before.""" + if self._local_mode: + logging.info('Member %s has received termination notice.', + self._id_in_cluster) + self._received_own_sigterm_time = time.time() + self._received_own_sigterm.set() + return + + try: + context.context().set_config_key_value(_PREEMPTION_WORKER_KEY, + self._id_in_cluster) + logging.info('Member %s has received termination notice.', + self._id_in_cluster) + self._received_own_sigterm_time = time.time() + self._received_own_sigterm.set() + + # This is to handle the case that a worker has received termination + # notice but hasn't come to the next step to set the step key. Other + # workers might receive a termination notice too, and attempt to set the + # config key again, which causes this error. This can be safely ignored + # since checkpoint should be saved as early as the earliest call is made. + except errors.AlreadyExistsError: + logging.info( + ( + 'Member %s has received termination notice. But some other ' + 'worker has received it as well! Leaving' + ' it to them to decide when to checkpoint. ' + ), + self._id_in_cluster, + ) + return + + def _stop_poll_termination_signal_thread(self): + if getattr(self, '_poll_termination_signal_thread', None): + self._poll_termination_signal_thread_should_stop.set() + self._poll_termination_signal_thread.join() + + self._poll_termination_signal_thread = None + logging.info("Shut down watcher for one's own termination signal") + + def _stop_cluster_wise_termination_watcher_thread(self): + """Stop the thread that is _watch_step_to_save_key.""" + if getattr(self, '_cluster_wise_termination_watcher_thread', None): + try: + context.context().set_config_key_value( + _INITIAL_RUN_COUNT_KEY, _STOP_WATCHING_CLUSTER_VALUE + ) + except (errors.AlreadyExistsError, errors.UnavailableError): + # We'll ignore any error in the process of setting this key. There + # certainly will be a AlreadyExistError since all workers are trying to + # push this key. Or some worker might have exited already, leading to a + # errors.UnavailableError or errors.AbortedError. + pass + except Exception as e: # pylint: disable=broad-except + # We'll also ignore other errors since they are not important to the + # process. + logging.info('Ignoring error when shutting down ' + '_stop_cluster_wise_termination_watcher_thread: ' + str(e)) + + try: + context.context().set_config_key_value(_FINAL_RUN_COUNT_KEY, + _STOP_WATCHING_CLUSTER_VALUE) + except (errors.AlreadyExistsError, errors.UnavailableError): + pass + + except Exception as e: # pylint: disable=broad-except + logging.info('Ignoring error when shutting down ' + '_stop_cluster_wise_termination_watcher_thread: ' + str(e)) + + finally: + self._cluster_wise_termination_watcher_thread.join() + self._cluster_wise_termination_watcher_thread = None + logging.info('Shut down watcher for peer\'s termination signal.') + + def __del__(self): + self._stop_cluster_wise_termination_watcher_thread() + self._stop_poll_termination_signal_thread() + + @property + @deprecated(None, + 'Track steps using a tf.Variable saved in checkpoint instead.') + @doc_controls.do_not_generate_docs + def total_run_calls(self): + """Returns the number of times `PreemptionCheckpointHandler.run` is called. + + DEPRECATED: user should track total steps themselves, as this API provides + little expressivity gain but could easily be misused and incurs extra + synchronization cost for TPUStrategy users. + + This value tracks the number of all calls to + `PreemptionCheckpointHandler.run` including those before the program is + restarted and the training is restored, by saving and reading the value in + the checkpoint. A user can compute their total number of iterations + by `PreemptionCheckpointHandler.total_run_calls * + number_of_steps_in_train_function`, + while `number_of_steps_in_train_function` should be one for + `tf.distribute.MultiWorkerMirroredStrategy` users. They can also use this + value to infer the starting epoch and step after training restores, as shown + in the example above. + """ + if (self._platform_device == + failure_handling_util.PlatformDevice.INTERNAL_TPU): + raise NotImplementedError('Please create variables saved in checkpoint ' + 'to keep track of steps and epochs.') + return self._run_counter + + def run(self, + distributed_train_function, + *args, + **kwargs): + """Runs a training function with error and preemption handling. + + This function handles the preemption signal from any peer in the cluster by + saving the training progress and exiting gracefully. It will + also broadcase any program error encountered during the execution of + `distributed_train_function` to all workers so that they can raise the same + error. + + The `distributed_train_function` argument should be a distributed train + function (i.e., containing a call to `tf.distribute.Strategy.run`). For + `tf.distribute.MultiWorkerMirroredStrategy` users, we recommend passing in a + single-step `distributed_train_function` to + `PreemptionCheckpointHandler.run` so that the checkpoint can be saved in + time in case a preemption signal or maintenance notice is sent. + + Besides the preemption and error handling part, + `PreemptionCheckpointHandler.run(distributed_train_function, *args, + **kwargs)` has the same effect and output as + `distributed_train_function(*args, **kwargs)`. `distributed_train_function` + can return either some or no result. The following is a shortened example: + + ```python + + @tf.function + def distributed_train_step(iterator): + # A distributed single-step training function. + + def step_fn(inputs): + # A per-replica single-step training function. + x, y = inputs + ... + return loss + + per_replica_losses = strategy.run(step_fn, args=(next(iterator),)) + return strategy.reduce( + tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None) + + for epoch in range(preemption_handler.total_run_calls // STEPS_PER_EPOCH, + EPOCHS_TO_RUN): + iterator = iter(multi_worker_dataset) + total_loss = 0.0 + num_batches = 0 + + for step in range(preemption_handler.total_run_calls % STEPS_PER_EPOCH, + STEPS_PER_EPOCH): + total_loss += preemption_handler.run(distributed_train_step) + num_batches += 1 + + train_loss = total_loss / num_batches + print('Epoch: %d, train_loss: %f.' %(epoch.numpy(), train_loss)) + + train_accuracy.reset_states() + ``` + + Args: + distributed_train_function: A (single-step) distributed training function. + *args: args for `distributed_train_function`. + **kwargs: kwargs for `distributed_train_function`. + + Raises: + Program error encountered by any member in the cluster while executing the + `distributed_train_function`, or any error from the program error + propagation process. + + Returns: + Result of running the `distributed_train_function`. + """ + # TODO(wxinyi): after we support use with TPUStrategy, we should expand the + # API doc to state that `distributed_train_function` does not need to be a + # single-step training function, since a multi-step host-training loop is + # the dominant use case for TPU user. Besides, passing in a multi-step + # `distributed_train_function` will require the user to track their own + # training steps. + if ( + self._platform_device + == failure_handling_util.PlatformDevice.INTERNAL_TPU + ): + return self._run_for_tpu(distributed_train_function, *args, **kwargs) + elif self._platform_device in ( + failure_handling_util.PlatformDevice.GCE_TPU, + failure_handling_util.PlatformDevice.GCE_CPU, + ): + return distributed_train_function(*args, **kwargs) + else: + return self._run_for_multi_worker_mirrored( + distributed_train_function, *args, **kwargs + ) + + def _run_for_tpu(self, distributed_train_function, *args, **kwargs): + """PreemptionCheckpointHandler.run implementation for TPUStrategy.""" + gen_check_preemption_op.check_preemption(preemption_key=PREEMPTION_KEY) + return distributed_train_function(*args, **kwargs) + + def _run_for_multi_worker_mirrored( + self, distributed_train_function, *args, **kwargs + ): + """PreemptionCheckpointHandler.run implementation for MWMS.""" + try: + self._check_preemption_and_maybe_checkpoint() + run_begin_time = time.time() + result = distributed_train_function(*args, **kwargs) + new_run_time = time.time() - run_begin_time + self._run_counter += 1 + # Update the average run time with the new run. + self._estimated_run_time = self._estimated_run_time + ( + new_run_time - self._estimated_run_time) / self._run_counter + + except errors.OpError as e: + if not self._local_mode: + logging.info('Propagating error to cluster: %r: %s', e, e) + try: + context.context().report_error_to_cluster(e.error_code, e.message) + except Exception as ex: # pylint: disable=broad-except + logging.info('Ignoring error during error propagation: %r:%s', ex, ex) + raise + + return result + + # Disabling line-too-long check since we do not want to break the line when + # converted to public documentation. + # pylint: disable=line-too-long + def save_checkpoint_if_preempted(self, *args, **kwargs): + """Saves a checkpoint if a preemption signal has been made available. + + This is an alternative API for `PreemptionCheckpointHandler.run` and + `PreemptionCheckpointHandler.watch_preemption_scope`. This method works for + both `tf.distribute.MultiWorkerMirroredStrategy` and + `tf.distribute.TPUStrategy`. However, **for TPUStrategy, this method will + add a synchronization point between workers and the coordinator** and thus + may have performance implication. If this is a concern, use the combination + of `PreemptionCheckpointHandler.watch_preemption_scope` and + `PreemptionCheckpointHandler.run` instead. + + ```python + strategy = tf.distribute.TPUStrategy(tpu_cluster_resolver) + # initialization omitted + + with strategy.scope(): + # Save in the checkpoint. + trained_step = tf.Variable(initial_value=tf.constant(0, dtype=tf.dtypes.int64), name='trained_step', aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA) + + checkpoint_manager = tf.train.CheckpointManager(checkpoint, directory, max_to_keep=1) + preemption_handler = tf.distribute.experimental.PreemptionCheckpointHandler(cluster_resolver, checkpoint_manager) + + while trained_step.numpy() < NUM_STEPS: + # Train STEPS_IN_FUNCTION steps at once. + train_multi_step_function() + trained_step.assign_add(STEPS_IN_FUNCTION) + preemption_handler.save_checkpoint_if_preempted() + ``` + + Args: + *args: args for `tf.train.CheckpointManager.save()` to save checkpoint. + **kwargs: kwargs for `tf.train.CheckpointManager.save()` to save. + """ + # pylint: enable=line-too-long + if (self._platform_device == + failure_handling_util.PlatformDevice.INTERNAL_TPU): + + try: + with context.async_scope(): + gen_check_preemption_op.check_preemption( + preemption_key=PREEMPTION_KEY) + except errors.AbortedError as abort_error: + if abort_error.experimental_payloads.get( + b'type.googleapis.com/tensorflow.distributed_runtime.WorkerPreemption' + ): + logging.info('Clearing preemption error to save checkpoint...') + + context.async_clear_error() + self._save_checkpoint(*args, **kwargs) + + # For TPU training, the default behavior is that it will block until + # workers are down and returns with error. + self._exit_fn() + + else: + raise + + elif self._platform_device in ( + failure_handling_util.PlatformDevice.GCE_TPU, + failure_handling_util.PlatformDevice.GCE_CPU, + ): + return + + else: + self._check_preemption_and_maybe_checkpoint(*args, **kwargs) + self._run_counter += 1 + self._estimated_run_time = 0 + + @tf_contextlib.contextmanager + def watch_preemption_scope(self): + """Syncs error and maybe save checkpoint for usage with TPUStrategy. + + Note: Usage with `tf.distribute.MultiWorkerMirroredStrategy` does not need + this API. + + Example usage: + + ```python + with preemption_checkpoint_handler.watch_preemption_scope(): + while trained_step.numpy() < NUM_STEPS: + + # distributed_train_function contains a call to strategy.run. + loss += preemption_checkpoint_handler.run(distributed_train_function, args=(next(iterator),)) + trained_step.assign_add(STEPS_PER_TRAIN_FUNCTION) + ``` + + In this workflow, `PreemptionCheckpointHandler.run` will flag preemption + signal received, and `watch_preemption_scope` will handle the preemption + signal by saving a checkpoint and then either exit to restart or execute a + user-passed `exit_fn` in `tf.distribute.experimental.TerminationConfig`. If + no preemption signal is received during execution of ops and function inside + the scope, `watch_preemption_scope` ensures the completion of all async op + and function execution when exiting and will raises exceptions if async + execution results in an error state. + + Yields: + None + """ + if self._platform_device == failure_handling_util.PlatformDevice.INTERNAL_TPU: + try: + with context.async_scope(): + yield + except errors.AbortedError as abort_error: + if abort_error.experimental_payloads.get( + b'type.googleapis.com/tensorflow.distributed_runtime.WorkerPreemption' + ): + logging.info('Clearing preemption error to save checkpoint...') + + context.async_clear_error() + self._save_checkpoint() + + self._exit_fn() + + else: + raise + else: + try: + yield + except errors.OpError as e: + if not self._local_mode: + logging.info('Propagating error to cluster: %r: %s', e, e) + try: + context.context().report_error_to_cluster(e.error_code, e.message) + except Exception as ex: # pylint: disable=broad-except + logging.info('Ignoring error during error propagation: %r:%s', ex, ex) + raise + + def _save_checkpoint(self, *args, **kwargs): + """Saves the checkpoint and exit program.""" + distribute_lib.distribution_strategy_input_api_counter.get_cell( + self._platform_device.name, + 'PreemptionCheckpointHandler Saving Checkpoint').increase_by(1) + logging.info('PreemptionCheckpointHandler: Starting saving a checkpoint.') + + if self._platform_device != failure_handling_util.PlatformDevice.INTERNAL_TPU: + self._checkpointed_runs.assign(self.total_run_calls) + + start_time = time.monotonic() + + with checkpoint_context.preemption_save_context(): + if self._save_fn: + self._save_fn(*args, **kwargs) + else: + self._write_checkpoint_manager.save(*args, **kwargs) + + end_time = time.monotonic() + + logging.info('Checkpoint finished at path %s', + self._write_checkpoint_manager.directory) + self._checkpoint_time = end_time - start_time + + def _check_preemption_and_maybe_checkpoint(self, *args, **kwargs): + """Checkpoint if any worker has received a preemption signal. + + This function handles preemption signal reported by any worker in the + cluster. The current implementation relies on the fact that all workers in a + MultiWorkerMirroredStrategy training cluster have a step number difference + maximum of 1. + - If the signal comes from the worker itself (i.e., where this failure + handler sits), the worker will notify all peers to checkpoint after they + finish CURRENT_STEP+1 steps, where CURRENT_STEP is the step this worker has + just finished. And the worker will wait for all peers to acknowledge that + they have received its preemption signal and the final-step number before + the worker proceeds on training the final step. + - If the signal comes from another member in the cluster but NO final-step + info is available, proceed on training, because it will be available after + finishing the next step. + - If the signal comes from some other member in the cluster, and final-step + info is available, if the worker has not finished these steps yet, keep + training; otherwise, checkpoint and exit with a cluster-recognized restart + code. + + Args: + *args: args for `tf.train.CheckpointManager.save()` to save checkpoint. + **kwargs: kwargs for `tf.train.CheckpointManager.save()` to save. + """ + if self._platform_device == failure_handling_util.PlatformDevice.INTERNAL_TPU: + gen_check_preemption_op.check_preemption(preemption_key=PREEMPTION_KEY) + return + + if self._final_checkpoint_countdown: + run_count_config_key = _FINAL_RUN_COUNT_KEY + + else: + run_count_config_key = _INITIAL_RUN_COUNT_KEY + + if self._received_checkpoint_step.is_set(): + + if self._step_to_checkpoint == str(self._run_counter): + self._save_checkpoint(*args, **kwargs) + + if self._time_to_exit(): + self._stop_poll_termination_signal_thread() + self._stop_cluster_wise_termination_watcher_thread() + if self._api_made_checkpoint_manager and not self._is_chief: + gfile.DeleteRecursively( + os.path.dirname(self._write_checkpoint_manager.directory)) + logging.info( + 'PreemptionCheckpointHandler: checkpoint saved. Exiting.') + + self._exit_fn() + + else: + logging.info('Continue training for the grace period.') + self._final_checkpoint_countdown = True + self._received_checkpoint_step.clear() + + elif self._received_own_sigterm.is_set(): + # Only the worker who gets termination signal first among the cluster + # will enter this branch. The following will happen in chronological + # order: + # 1. The worker just receives a preemption signal and enters this branch + # for the first time. It will set a step-to-checkpoint and let the cluster + # know. + # 2. If there is a long grace period, it will also set + # _final_checkpoint_countdown, so that during this grace period, it will + # re-enter this branch to check if grace period is ending. + # 3. If it is, set a step-to-checkpoint key again. + + if self._final_checkpoint_countdown: + if self._target_time_for_termination < time.time(): + logging.info( + 'Grace period almost ended. Final call to save a checkpoint!') + else: + return + + step_to_save_at = str(self._run_counter + 1) + + logging.info('Termination caught in main thread on preempted worker') + + if self._local_mode: + self._step_to_checkpoint = step_to_save_at + self._received_checkpoint_step.set() + + else: + context.context().set_config_key_value(run_count_config_key, + step_to_save_at) + logging.info('%s set to %s', run_count_config_key, step_to_save_at) + + if not self._local_mode: + worker_count = multi_worker_util.worker_count( + self._cluster_resolver.cluster_spec(), + self._cluster_resolver.task_type) + for i in range(worker_count): + context.context().get_config_key_value( + f'{_ACKNOWLEDGE_KEY}_{run_count_config_key}_{i}') + logging.info('Sigterm acknowledgement from replica %d received', i) + + self._setup_countdown_if_has_grace_period_and_not_already_counting_down() + + def _time_to_exit(self): + """Return whether to exit: exit if no grace period or grace period ends.""" + # we should directly exit in either of the two cases: + # 1. if no grace period is provided; + # 2. if there is a grace period, and we're in countdown period. This, + # together with the fact that _received_checkpoint_step is set (again), + # means it's time to exit: when there is a grace period, a worker + # receives preemption signal and sets the step key. Then all workers + # receive the step key and set their local _received_checkpoint_step + # event, enters this branch in _check_preemption_and_maybe_checkpoint, make + # a checkpoint. Then they set _final_checkpoint_countdown to True, clear + # _received_checkpoint_step, and continue training. New preemption + # signals anywhere in the cluster will not be handled, because + # _PREEMPTION_WORKER_KEY is occupied. The only chance that + # _received_checkpoint_step gets set again is when the worker who has + # received the preemption signal earlier decide it's time to do a final + # checkpoint (by checking if it already passes + # _target_time_for_termination). It will upload a final step key. All + # workers receive this key and again set _received_checkpoint_step. So, + # if we found out that _received_checkpoint_step is set, and also + # _final_checkpoint_countdown is true, it's checkpoint and exit time. + return (self._grace_period <= 0) or self._final_checkpoint_countdown + + def _setup_countdown_if_has_grace_period_and_not_already_counting_down(self): + """Set up at the beginning of a countdown period for long grace period.""" + if self._grace_period > 0 and not self._final_checkpoint_countdown: + # A factor to provide more buffer / inaccuracy. + # TODO(wxinyi): update buffer_factor as needed. Maybe deduct a constant. + buffer_factor = 3 + # Timing by 2 since while the preempted worker needs to do 1 extra step + # when time_till_final_call <=0, other workers might need to do x step + # where 0 0: + # Continue to wait until a final call is made. + final_step_value = context.context().get_config_key_value( + _FINAL_RUN_COUNT_KEY) + if final_step_value != _STOP_WATCHING_CLUSTER_VALUE: + ack_key = f'{_ACKNOWLEDGE_KEY}_{_FINAL_RUN_COUNT_KEY}_{self._id_in_cluster}' + context.context().set_config_key_value(ack_key, '1') + logging.info( + 'PreemptionCheckpointHandler: %s acknowledged, final ' + 'checkpoint timing received.', ack_key) + self._received_checkpoint_step.set() + self._step_to_checkpoint = final_step_value + +# TODO(wxinyi): remove this line after we move the Keras callback prototype and +# change gce test usage. +WorkerPreemptionHandler = PreemptionCheckpointHandler diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/failure_handling_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/failure_handling_util.py new file mode 100644 index 0000000000000000000000000000000000000000..5151fd6fa02724a83bf0c57d95879f9ea0ac275c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/failure_handling_util.py @@ -0,0 +1,119 @@ +# 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. +# ============================================================================== +"""Util of GCE specifics to ingegrate with WorkerPreemptionHandler.""" +import enum +import os +import sys +import requests + +from six.moves.urllib import request +from tensorflow.python.eager import context +from tensorflow.python.platform import tf_logging as logging + + +GCP_METADATA_HEADER = {'Metadata-Flavor': 'Google'} +_GCE_METADATA_URL_ENV_VARIABLE = 'GCE_METADATA_IP' +_RESTARTABLE_EXIT_CODE = 143 +GRACE_PERIOD_GCE = 3600 + + +def gce_exit_fn(): + sys.exit(_RESTARTABLE_EXIT_CODE) + + +def default_tpu_exit_fn(): + """Default exit function to run after saving checkpoint for TPUStrategy. + + For TPUStrategy, we want the coordinator to exit after workers are down so + that restarted coordinator would not connect to workers scheduled to be + preempted. This function achieves so by attempting to get a key-value store + from coordination service, which will block until workers are done and then + returns with error. Then we have the coordinator sys.exit(42) to re-schedule + the job. + """ + logging.info('Waiting for workers to exit...') + try: + context.context().get_config_key_value('BLOCK_TILL_EXIT') + except: # pylint: disable=bare-except + logging.info('Restarting cluster due to preemption.') + sys.exit(42) + + +def request_compute_metadata(path): + """Returns GCE VM compute metadata.""" + gce_metadata_endpoint = 'http://' + os.environ.get( + _GCE_METADATA_URL_ENV_VARIABLE, 'metadata.google.internal') + req = request.Request( + '%s/computeMetadata/v1/%s' % (gce_metadata_endpoint, path), + headers={'Metadata-Flavor': 'Google'}) + info = request.urlopen(req).read() + if isinstance(info, bytes): + return info.decode('utf-8') + else: + return info + + +def termination_watcher_function_gce(): + result = request_compute_metadata( + 'instance/maintenance-event') == 'TERMINATE_ON_HOST_MAINTENANCE' + return result + + +def on_gcp(): + """Detect whether the current running environment is on GCP.""" + gce_metadata_endpoint = 'http://' + os.environ.get( + _GCE_METADATA_URL_ENV_VARIABLE, 'metadata.google.internal') + + try: + # Timeout in 5 seconds, in case the test environment has connectivity issue. + # There is not default timeout, which means it might block forever. + response = requests.get( + '%s/computeMetadata/v1/%s' % + (gce_metadata_endpoint, 'instance/hostname'), + headers=GCP_METADATA_HEADER, + timeout=5) + return response.status_code == 200 + except requests.exceptions.RequestException: + return False + + +@enum.unique +class PlatformDevice(enum.Enum): + INTERNAL_CPU = 'internal_CPU' + INTERNAL_GPU = 'internal_GPU' + INTERNAL_TPU = 'internal_TPU' + GCE_GPU = 'GCE_GPU' + GCE_TPU = 'GCE_TPU' + GCE_CPU = 'GCE_CPU' + UNSUPPORTED = 'unsupported' + + +def detect_platform(): + """Returns the platform and device information.""" + if on_gcp(): + if context.context().list_logical_devices('GPU'): + return PlatformDevice.GCE_GPU + elif context.context().list_logical_devices('TPU'): + return PlatformDevice.GCE_TPU + else: + return PlatformDevice.GCE_CPU + + else: + if context.context().list_logical_devices('GPU'): + return PlatformDevice.INTERNAL_GPU + elif context.context().list_logical_devices('TPU'): + return PlatformDevice.INTERNAL_TPU + else: + return PlatformDevice.INTERNAL_CPU diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/preemption_watcher.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/preemption_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d8435baa992fdabb00f2405bb241ae17340009a0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/failure_handling/preemption_watcher.py @@ -0,0 +1,137 @@ +# 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. +# ============================================================================== +"""Provides a utility class for preemption detection and recovery.""" + +import threading + +from absl import logging + +from tensorflow.python.distribute.failure_handling.failure_handling_util import detect_platform +from tensorflow.python.distribute.failure_handling.failure_handling_util import PlatformDevice +from tensorflow.python.eager import context +from tensorflow.python.eager import monitoring +from tensorflow.python.framework.errors import AbortedError +from tensorflow.python.framework.errors import CancelledError +from tensorflow.python.framework.errors import InternalError +from tensorflow.python.framework.errors import UnavailableError +from tensorflow.python.util.tf_export import tf_export + + +_preemption_watcher_initialization_counter = monitoring.Counter( + "/tensorflow/api/distribution_strategy/preemption_watcher_initialized", + "Counter for usages of PreemptionWatcher", +) +_preemption_handling_counter = monitoring.Counter( + "/tensorflow/api/distribution_strategy/preemption_watcher_handled", + "Counter for number of preempions catched and handled by PreemptionWatcher", +) + +_PREEMPTION_KEY = "TF_DEFAULT_PREEMPTION_NOTICE_KEY" + + +@tf_export("distribute.experimental.PreemptionWatcher", v1=[]) +class PreemptionWatcher: + """Watch preemption signal and store it. + + Notice: Currently only support Borg TPU environment with TPUClusterResolver. + + This class provides a way to monitor the preemption signal during training on + TPU. It will start a background thread to watch the training process, trying + to fetch preemption message from the coordination service. When preemption + happens, the preempted worker will write the preemption message to the + coordination service. Thus getting a non-empty preemption message means there + is a preemption happened. + + User can use the preemption message as a reliable preemption indicator, and + then set the coordinator to reconnect to the TPU worker instead of a fully + restart triggered by Borg. For example, a training process with + preemption recovery will be like: + + ```python + keep_running = True + preemption_watcher = None + while keep_running: + try: + # Initialize TPU cluster and stratygy. + resolver = tf.distribute.cluster_resolver.TPUClusterResolver() + tf.config.experimental_connect_to_cluster(resolver) + tf.tpu.experimental.initialize_tpu_system(resolver) + strategy = tf.distribute.TPUStrategy(resolver) + + # PreemptionWatcher must be created after connected to cluster. + preemption_watcher = tf.distribute.experimental.PreemptionWatcher() + train_model(strategy) + keep_running = False + except Exception as e: + if preemption_watcher and preemption_watcher.preemption_message: + preemption_watcher.block_until_worker_exit() + keep_running = True + else: + raise e + ``` + + Attributes: + preemption_message: A variable to store the preemption message fetched from + the coordination service. If it is not None, then there is a preemption + happened. + platform: A PlatformDevice to indicate the current job's platform. Refer to + failure_handling_util.py for the definition of enum class PlatformDevice. + """ + + def __init__(self): + # TODO(b/254321514): Integrate with GPU and cloud enviornmenmt. + self._preemption_message = None + self._platform = detect_platform() + if self._platform != PlatformDevice.INTERNAL_TPU: + logging.warning( + "Preemption watcher does not support environment: %s", self._platform + ) + else: + _preemption_watcher_initialization_counter.get_cell().increase_by(1) + threading.Thread(target=self._watch_preemption_key, daemon=True).start() + + @property + def preemption_message(self): + """Returns the preemption message.""" + return self._preemption_message + + def _watch_preemption_key(self): + logging.info("Watching preemption signal.") + message = context.context().get_config_key_value(_PREEMPTION_KEY) + _preemption_handling_counter.get_cell().increase_by(1) + logging.info("Preemption signal received.") + self._preemption_message = message + + def block_until_worker_exit(self): + """Block coordinator until workers exit. + + In some rare cases, another error could be raised during the + preemption grace period. This will cause the coordinator to reconnect to the + same TPU workers, which will be killed later. It prevents the coordinator to + reconnect to new TPU workers, and falls back to a hard restart. To avoid + this situation, this method will block the coordinator to reconnect until + workers exit. This method will be a no-op for non-TPU platform. + """ + if self._platform != PlatformDevice.INTERNAL_TPU: + return + try: + context.context().get_config_key_value("BLOCK_TILL_EXIT") + except InternalError as e: + # Ensure that internal error is related to coordination service. + if "Coordination service is not enabled." not in e.message: + raise + logging.info("Workers exited.") + except (AbortedError, CancelledError, UnavailableError): + logging.info("Workers exited.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..2313fefc522bd78c74a3ce69cb61323092f889a9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py @@ -0,0 +1,1994 @@ +# 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. +# ============================================================================== +"""Various classes representing distributed inputs.""" + +import functools +import sys +import time + +import six + +from tensorflow.python.autograph.operators import py_builtins +from tensorflow.python.data.experimental.ops import batching +from tensorflow.python.data.experimental.ops import cardinality as cardinality_lib +from tensorflow.python.data.experimental.ops import distribute +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.data.ops import multi_device_iterator_ops +from tensorflow.python.data.ops import optional_ops +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import input_ops +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import values +from tensorflow.python.distribute.distribute_lib import InputReplicationMode +from tensorflow.python.eager import context +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond as tf_cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.types import distribute as distribute_types +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc + + +_distributed_dataset_initialization_time_milliseconds = monitoring.Sampler( + "/tensorflow/api/distribution_strategy/" + "distributed_dataset_initialization_time_milliseconds", + monitoring.ExponentialBuckets(scale=1, growth_factor=2, bucket_count=26), + "Track the time (in milliseconds) to initialize distributed datasets.", + "strategy", "workers") + +_distributed_dataset_from_function_initialization_time_milliseconds = ( + monitoring.Sampler( + "/tensorflow/api/distribution_strategy/" + "distributed_dataset_from_function_initialization_time_milliseconds", + monitoring.ExponentialBuckets( + scale=1, growth_factor=2, bucket_count=26), + "Track the time (in milliseconds) to initialize distributed datasets " + "from function.", + "strategy", "workers")) + + +def get_iterator_spec_from_dataset(strategy, dataset): + """Returns an iterator spec from dataset function. + + This function constructs type spec for iterator obtained from + iter(dataset). + + Args: + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + dataset: A tf.data.Dataset instance. If using a function that returns a + tf.data.Dataset instance, pass dataset_fn.structured_outputs. + + Returns: + A type_spec for iterator for dataset instance. + + """ + # pylint: disable=protected-access + output_element_spec = dataset.element_spec + if isinstance(dataset._type_spec, + (DistributedDatasetSpec, + DistributedDatasetsFromFunctionSpec)): + iterator_type_spec = DistributedIteratorSpec( + strategy.extended._input_workers_with_options(), + output_element_spec, + strategy.extended._container_strategy(), + options=None, + cardinality=dataset.cardinality, + enable_get_next_as_optional=True) + else: + if strategy.extended._num_gpus_per_worker: + logging.warning( + f"{strategy.extended._num_gpus_per_worker} GPUs " + "are allocated per worker. Please use DistributedDataset by " + "calling strategy.experimental_distribute_dataset or strategy." + "distribute_datasets_from_function to make best use of GPU " + "resources" + ) + iterator_type_spec = iterator_ops.IteratorSpec(output_element_spec) + return iterator_type_spec + # pylint: enable=protected-access + + +class InputWorkers(object): + """A 1-to-many mapping from input worker devices to compute devices.""" + + # TODO(ishark): Remove option canonicalize_devices and make all the callers + # pass canonicalized or raw device strings as relevant from strategy. + def __init__(self, + worker_device_pairs, + canonicalize_devices=True): + """Initialize an `InputWorkers` object. + + Args: + worker_device_pairs: A sequence of pairs: `(input device, a tuple of + compute devices fed by that input device)`. + canonicalize_devices: Whether to canonicalize devices for workers fully or + partially. If False, it will partially canonicalize devices by removing + job and task. + """ + self._worker_device_pairs = worker_device_pairs + self._input_worker_devices = tuple(d for d, _ in self._worker_device_pairs) + self._canonicalize_devices = canonicalize_devices + if canonicalize_devices: + self._fed_devices = tuple( + tuple(device_util.canonicalize(d) + for d in f) + for _, f in self._worker_device_pairs) + else: + self._fed_devices = tuple( + tuple(device_util.canonicalize_without_job_and_task(d) + for d in f) + for _, f in self._worker_device_pairs) + + @property + def num_workers(self): + return len(self._input_worker_devices) + + @property + def worker_devices(self): + return self._input_worker_devices + + def compute_devices_for_worker(self, worker_index): + return self._fed_devices[worker_index] + + def __repr__(self): + devices = self.worker_devices + debug_repr = ",\n".join(" %d %s: %s" % + (i, devices[i], self._fed_devices[i]) + for i in range(len(devices))) + return "%s:{\n%s}" % (self.__class__.__name__, debug_repr) + + def serialize(self): + return (self._worker_device_pairs, self._canonicalize_devices) + + def deserialize(self, serialized): + return InputWorkers(serialized) + + +def _calculate_replicas_with_values(strategy, input_workers, optional_list): + """Calcualates the number of replicas that have values. + + Args: + strategy: the `tf.distribute.Strategy`. + input_workers: the `InputWorkers`. + optional_list: a list of lists `tf.experimental.Optional`. The values from + each compute device grouped by the input device. + + Returns: + A scalar Tensor. + """ + worker_has_values = [] + for worker, optionals in zip(input_workers.worker_devices, optional_list): + with ops.device(worker): + device_has_values = [ + math_ops.cast(v.has_value(), dtypes.int64) for v in optionals + ] + worker_has_values.append( + math_ops.reduce_sum(device_has_values, keepdims=True)) + client_has_values = math_ops.reduce_sum(worker_has_values, keepdims=True) + if strategy.extended._in_multi_worker_mode(): # pylint: disable=protected-access + global_has_values = strategy.reduce( + reduce_util.ReduceOp.SUM, client_has_values, axis=None) + return array_ops.reshape(global_has_values, []) + else: + return array_ops.reshape(client_has_values, []) + + +def _is_statically_shaped(element_spec): + """Test if an iterator output is statically shaped. + + For sparse and ragged tensors this only tests the batch dimension. + + Args: + element_spec: a nest structure of `tf.TypeSpec`. The element spec of the + dataset of the iterator. + + Returns: + True if the shape is static, false otherwise. + """ + + for spec in nest.flatten(element_spec): + if isinstance( + spec, (sparse_tensor.SparseTensorSpec, ragged_tensor.RaggedTensorSpec)): + # For sparse or ragged tensor, we should only check the first + # dimension in order to get_next_as_optional. This is because + # when these tensors get batched by dataset only the batch dimension + # is set. + if spec.shape.rank > 0 and spec.shape.as_list()[0] is None: + return False + else: + for component in spec._flat_tensor_specs: # pylint: disable=protected-access + if not component.shape.is_fully_defined(): + return False + return True + + +class DistributedIteratorBase(collections_abc.Iterator, + distribute_types.DistributedIteratorInterface): + """Common implementation for all input iterators.""" + + # pylint: disable=super-init-not-called + def __init__( + self, + input_workers, + iterators, + strategy, + cardinality, + enable_get_next_as_optional, + replica_order=None, + ): + assert isinstance(input_workers, InputWorkers) + if not input_workers.worker_devices: + raise ValueError("Should have at least one worker for input iterator.") + + self._iterators = iterators + self._input_workers = input_workers + self._strategy = strategy + self._cardinality = cardinality + self._enable_get_next_as_optional = enable_get_next_as_optional + self._replica_order = replica_order + + def next(self): + return self.__next__() + + def __next__(self): + try: + return self.get_next() + except errors.OutOfRangeError: + raise StopIteration + + def __iter__(self): + return self + + def get_next_as_optional(self): + # Ideally get_next_as_optional() should be consistent with get_next(), but + # we used to always do partial batch handling in get_next_as_optional(). We + # are keeping this behavior for now until we understantd the impact. + + # Skip partial batch handling when the dataset is infinite or empty, as + # there won't be any partial batches in those cases. This gives the user + # more static shapes as it avoids the tf.cond. Note that for empty datasets, + # we can only skip in single client mode, as the dataset can be non-empty on + # other workers. + if self._cardinality == cardinality_lib.INFINITE: + return optional_ops.Optional.from_value( + self._get_next_no_partial_batch_handling()) + if (self._cardinality == 0 and + not self._strategy.extended._in_multi_worker_mode()): # pylint: disable=protected-access + return optional_ops.Optional.empty(self._element_spec) + + optional_list = [] + for i, worker in enumerate(self._input_workers.worker_devices): + with ops.device(worker): + optional_list.append(self._iterators[i].get_next_as_optional_list()) + + def _create_optional_with_dummy(): + value_list = _get_value_or_dummy( + self._input_workers, optional_list, produce_dummy=True) + + if self._replica_order is not None: + value_list = self._reorder_replicas(value_list) + + per_replica = _create_per_replica(value_list, self._strategy) + return optional_ops.Optional.from_value(per_replica) + + def _create_empty_optional(): + return optional_ops.Optional.empty(self._element_spec) + + num_replicas_with_values = _calculate_replicas_with_values( + self._strategy, self._input_workers, optional_list) + + return tf_cond.cond( + num_replicas_with_values > 0, + _create_optional_with_dummy, + _create_empty_optional, + strict=True) + + def get_next(self, name=None): + """Returns the next input from the iterator for all replicas.""" + with distribute_lib.enter_or_assert_strategy( + self._strategy): + if distribute_lib.get_replica_context() is not None: + raise ValueError("next(iterator) should be called from outside of " + "replica_fn. e.g. strategy.run(replica_fn, " + "args=(next(iterator),))") + + if not self._enable_get_next_as_optional: + return self._get_next_no_partial_batch_handling(name) + + optional_list = [] + for i, worker in enumerate(self._input_workers.worker_devices): + with ops.device(worker): + optional_list.append(self._iterators[i].get_next_as_optional_list()) + num_replicas_with_values = _calculate_replicas_with_values( + self._strategy, self._input_workers, optional_list) + + def _value_or_dummy(): + value_list = _get_value_or_dummy( + self._input_workers, optional_list, produce_dummy=True) + + if self._replica_order is not None: + value_list = self._reorder_replicas(value_list) + + return _create_per_replica(value_list, self._strategy) + + def _eof(): + # Optional.get_value raises InvalidArgumentError when there's no value, + # so we need to call GetNext to raise EOFError. + return self._get_next_no_partial_batch_handling() + + return tf_cond.cond( + num_replicas_with_values > 0, _value_or_dummy, _eof, strict=True) + + def _get_next_no_partial_batch_handling(self, name=None): + replicas = [] + for i, worker in enumerate(self._input_workers.worker_devices): + if name is not None: + d = tf_device.DeviceSpec.from_string(worker) + new_name = "%s_%s_%d" % (name, d.job, d.task) + else: + new_name = None + with ops.device(worker): + # Make `replicas` a flat list of values across all replicas. + replicas.extend(self._iterators[i].get_next_as_list(new_name)) + + if self._replica_order is not None: + replicas = self._reorder_replicas(replicas) + + return _create_per_replica(replicas, self._strategy) + + def _reorder_replicas(self, replicas): + assert len(self._replica_order) == len( + replicas + ), "replica order size ({}) != replicas size ({})!".format( + len(self._replica_order), len(replicas) + ) + return [replicas[i] for i in self._replica_order] + + +class DistributedDatasetAndIteratorSpec(type_spec.TypeSpec): + """Common Type specification for `DistributedDataset and DistributedDatasetsFromFunction.""" + + __slots__ = [ + "_input_workers", "_element_spec", "_strategy", "_cardinality", + "_enable_get_next_as_optional", "_options", "_canonicalize_devices" + ] + + def __init__( + self, + input_workers, + element_spec, + strategy, + options, + cardinality=cardinality_lib.UNKNOWN, + enable_get_next_as_optional=None, + replica_order=None, + ): + # We don't want to allow deserialization of this class because we don't + # serialize the strategy object. Currently the only places where + # _deserialize is called is when we save/restore using SavedModels. + if isinstance(input_workers, tuple): + raise NotImplementedError("DistributedIteratorSpec does not have support " + "for deserialization.") + else: + self._input_workers = input_workers + self._element_spec = element_spec + self._strategy = strategy + self._cardinality = cardinality + self._enable_get_next_as_optional = enable_get_next_as_optional + self._options = options + if self._strategy: + self._canonicalize_devices = getattr(self._strategy, + "_canonicalize_devices", True) + else: + self._canonicalize_devices = True + self._replica_order = replica_order + + def _serialize(self): + # We cannot serialize the strategy object so we convert it to an id that we + # can use for comparison. + return (self._input_workers.serialize(), self._element_spec, + id(self._strategy), id(self._options)) + + def _deserialize(self): + raise ValueError( + f"Deserialization is currently unsupported for {type(self)}.") + + def sanity_check_type(self, other): + """Returns the most specific TypeSpec compatible with `self` and `other`. + + Args: + other: A `TypeSpec`. + + Raises: + ValueError: If there is no TypeSpec that is compatible with both `self` + and `other`. + """ + # pylint: disable=protected-access + if type(self) is not type(other): + raise ValueError("No TypeSpec is compatible with both %s and %s" % + (self, other)) + if self._input_workers.serialize() != other._input_workers.serialize(): + raise ValueError("_input_workers is not compatible with both %s " + "and %s" % (self, other)) + if self._strategy is not other._strategy: + raise ValueError("tf.distribute strategy is not compatible with both %s " + "and %s" % (self, other)) + + def is_subtype_of(self, other): + """Returns True if `self` is subtype of `other`. + + Args: + other: A `TypeSpec`. + """ + try: + self.sanity_check_type(other) + nest.assert_same_structure(self._element_spec, other._element_spec) # pylint: disable=protected-access + except (TypeError, ValueError): + return False + + self_elements = nest.flatten(self._element_spec) + other_elements = nest.flatten(other._element_spec) # pylint: disable=protected-access + + return all( + self_element.is_subtype_of(other_element) + for (self_element, other_element) in zip(self_elements, other_elements)) + + def most_specific_common_supertype(self, others): + """Returns the most specific supertype of `self` and `others`. + + Args: + others: A Sequence of `TypeSpec`. + + Returns `None` if a supertype does not exist. + """ + try: + for other in others: + self.sanity_check_type(other) + nest.assert_same_structure(self._element_spec, other._element_spec) # pylint: disable=protected-access + except (TypeError, ValueError): + return None + + self_elements = nest.flatten(self._element_spec) + others_elements = [nest.flatten(other._element_spec) for other in others] # pylint: disable=protected-access + common_elements = [None] * len(self_elements) + + for i, self_element in enumerate(self_elements): + common_elements[i] = self_element.most_specific_common_supertype( + [other_elements[i] for other_elements in others_elements]) + if common_elements[i] is None: + return None + common_element_spec = nest.pack_sequence_as(self._element_spec, + common_elements) + return type(self)( + self._input_workers, + common_element_spec, + self._strategy, + self._options, + cardinality=self._cardinality, + enable_get_next_as_optional=self._enable_get_next_as_optional) + + def _with_tensor_ranks_only(self): + element_spec = nest.map_structure( + lambda s: s._with_tensor_ranks_only(), # pylint: disable=protected-access + self._element_spec) + return type(self)( + self._input_workers, + element_spec, + self._strategy, + self._options, + cardinality=self._cardinality, + enable_get_next_as_optional=self._enable_get_next_as_optional) + + # TODO(b/206014848): Remove once names are not used. + def _without_tensor_names(self): + element_spec = nest.map_structure( + lambda s: s._without_tensor_names(), # pylint: disable=protected-access + self._element_spec) + return type(self)( + self._input_workers, + element_spec, + self._strategy, + self._options, + cardinality=self._cardinality, + enable_get_next_as_optional=self._enable_get_next_as_optional) + + +class DistributedIteratorSpec(DistributedDatasetAndIteratorSpec): + """Type specification for `DistributedIterator`.""" + + @property + def value_type(self): + return DistributedIterator + + @property + def _component_specs(self): + specs = [] + worker_device_pairs = self._input_workers._worker_device_pairs # pylint: disable=protected-access + + for i, (input_device, compute_devices) in enumerate(worker_device_pairs): + element_spec = nest.map_structure( + functools.partial(_replace_per_replica_spec, i=i), self._element_spec) + specs.append( + _SingleWorkerDatasetIteratorSpec(input_device, compute_devices, + element_spec, self._options, + self._canonicalize_devices)) + return specs + + def _to_components(self, value): + return value._iterators # pylint: disable=protected-access + + def _from_components(self, components): + return DistributedIterator( + input_workers=self._input_workers, + iterators=None, + components=components, + element_spec=self._element_spec, + strategy=self._strategy, + cardinality=self._cardinality, + enable_get_next_as_optional=self._enable_get_next_as_optional, + options=self._options, + replica_order=self._replica_order, + ) + + @staticmethod + def from_value(value): + # pylint: disable=protected-access + return DistributedIteratorSpec( + value._input_workers, + value._element_spec, + value._strategy, + value._options, + cardinality=value._cardinality, + enable_get_next_as_optional=value._enable_get_next_as_optional) + + +class DistributedIterator(DistributedIteratorBase, + composite_tensor.CompositeTensor): + """Input Iterator for a distributed dataset.""" + + def __init__( + self, + input_workers=None, + iterators=None, + strategy=None, + components=None, + element_spec=None, + cardinality=cardinality_lib.UNKNOWN, + enable_get_next_as_optional=False, + options=None, + replica_order=None, + ): + if input_workers is None: + raise ValueError("`input_workers` should be " + "provided.") + + error_message = ("Either `input_workers` or " + "both `components` and `element_spec` need to be " + "provided.") + self._options = options + + if iterators is None: + if (components is None or element_spec is None): + raise ValueError(error_message) + self._element_spec = element_spec + self._input_workers = input_workers + self._iterators = components + self._strategy = strategy + self._cardinality = cardinality + self._enable_get_next_as_optional = enable_get_next_as_optional + self._replica_order = replica_order + else: + if (components is not None and element_spec is not None): + raise ValueError(error_message) + + super(DistributedIterator, self).__init__( + input_workers, + iterators, + strategy, + cardinality, + enable_get_next_as_optional, + replica_order, + ) + + @property + def element_spec(self): + # When partial batch handling is enabled, always set the batch dimension to + # None, otherwise we just follow element_spec of the underlying dataset + # (whose batch dimension may also be None). This is because with partial + # batching handling we could always produce empty batches. + if (self._enable_get_next_as_optional and + self._strategy.extended._in_multi_worker_mode()): # pylint: disable=protected-access + return nest.map_structure( + _rebatch_as_dynamic, self._element_spec, expand_composites=False) + return self._element_spec + + @property + def _type_spec(self): + # Note that we use actual element_spec instead of the rebatched-as-dynamic + # one to create DistributedIteratorSpec, to be consistent with the + # underlying iterators' specs. + return DistributedIteratorSpec( + self._input_workers, + self._element_spec, + self._strategy, + self._options, + self._cardinality, + self._enable_get_next_as_optional, + self._replica_order, + ) + + +class _IterableInput(collections_abc.Iterable, + distribute_types.DistributedDatasetInterface): + """Base class for iterable inputs for distribution strategies.""" + + # pylint: disable=super-init-not-called + def __init__(self, input_workers): + assert isinstance(input_workers, InputWorkers) + self._input_workers = input_workers + + def __iter__(self): + raise NotImplementedError("must be implemented in descendants") + + def reduce(self, initial_state, reduce_fn): + """Execute a `reduce_fn` over all the elements of the input.""" + iterator = iter(self) + optional_data = iterator.get_next_as_optional() + + def cond(optional_data, state): + del state # Unused. + return optional_data.has_value() + + def loop_body(optional_data, state): + """Executes `reduce_fn` in a loop till the dataset is empty.""" + state = reduce_fn(state, optional_data.get_value()) + optional_data = iterator.get_next_as_optional() + return optional_data, state + + optional_data, final_state = while_loop.while_loop( + cond, + loop_body, [optional_data, initial_state], + parallel_iterations=1, + return_same_structure=True) + return final_state + + +class DistributedDatasetSpec(DistributedDatasetAndIteratorSpec): + """Type specification for `DistributedDataset.""" + + @property + def value_type(self): + return DistributedDataset + + @property + def _component_specs(self): + specs = [] + worker_device_pairs = self._input_workers._worker_device_pairs # pylint: disable=protected-access + + for i, _ in enumerate(worker_device_pairs): + element_spec = nest.map_structure( + functools.partial(_replace_per_replica_spec, i=i), self._element_spec) + specs.append(dataset_ops.DatasetSpec(element_spec)) + return specs + + def _to_components(self, value): + return value._cloned_datasets # pylint: disable=protected-access + + def _from_components(self, components): + return DistributedDataset( + input_workers=self._input_workers, + strategy=self._strategy, + components=components, + element_spec=self._element_spec, + enable_get_next_as_optional=self._enable_get_next_as_optional, + options=self._options, + replica_order=self._replica_order, + ) + + @staticmethod + def from_value(value): + # pylint: disable=protected-access + return DistributedDatasetSpec( + value._input_workers, + value._element_spec, + value._strategy, + value._options, + enable_get_next_as_optional=value._enable_get_next_as_optional) + # pylint: enable=protected-access + + +class DistributedDataset(_IterableInput, composite_tensor.CompositeTensor): + """Distributed dataset that supports prefetching to multiple devices.""" + + def __init__( + self, + input_workers, + strategy, + dataset=None, + num_replicas_in_sync=None, + input_context=None, + components=None, + element_spec=None, + enable_get_next_as_optional=None, + build=True, + options=None, + replica_order=None, + ): + """Distribute the dataset on all workers. + + If `num_replicas_in_sync` is not None, we split each batch of the dataset + into `num_replicas_in_sync` smaller batches, to be distributed among that + worker's replicas, so that the batch size for a global step (across all + workers and replicas) is as expected. + + Args: + input_workers: an `InputWorkers` object. + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + dataset: `tf.data.Dataset` that will be used as the input source. Either + dataset or components field should be passed when constructing + DistributedDataset. Use this when contructing DistributedDataset from a + new `tf.data.Dataset`. Use components when constructing using + DistributedDatasetSpec. + num_replicas_in_sync: Optional integer. If this is not None, the value is + used to decide how to rebatch datasets into smaller batches so that the + total batch size for each step (across all workers and replicas) adds up + to `dataset`'s batch size. + input_context: `InputContext` for sharding. Only pass this in for between + graph multi-worker cases where there is only one `input_worker`. In + these cases, we will shard based on the `input_pipeline_id` and + `num_input_pipelines` in the `InputContext`. + components: datasets when DistributedDataset is constructed from + DistributedDatasetSpec. Either field dataset or components should be + passed. + element_spec: element spec for DistributedDataset when constructing from + DistributedDatasetSpec. This will be used to set the element_spec for + DistributedDataset and verified against element_spec from components. + enable_get_next_as_optional: this is required when components is passed + instead of dataset. + build: whether to build underlying datasets when this object is created. + This is only useful for `ParameterServerStrategy` now. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + replica_order: the order of the replicas, which will be used to reorder + the iterators to match the device order. + """ + super(DistributedDataset, self).__init__(input_workers=input_workers) + if input_workers is None or strategy is None: + raise ValueError("input_workers and strategy are required arguments") + if dataset is not None and components is not None: + raise ValueError("Only one of dataset or components should be present") + if dataset is None and components is None: + raise ValueError("At least one of dataset or components should be passed") + + self._input_workers = input_workers + self._strategy = strategy + self._options = options + self._input_context = input_context + self._num_replicas_in_sync = num_replicas_in_sync + self._replica_order = replica_order + + if dataset is not None: + self._original_dataset = dataset + self._built = False + if build: + self.build() + else: + if not build: + raise ValueError( + "When constructing DistributedDataset with components, build " + "should not be False. This is an internal error. Please file a " + "bug.") + if enable_get_next_as_optional is None: + raise ValueError( + "When constructing DistributedDataset with components, " + + "enable_get_next_as_optional should also be passed") + self._cloned_datasets = components + self._cardinality = _cardinality(self._cloned_datasets[0]) + self._enable_get_next_as_optional = enable_get_next_as_optional + + assert element_spec is not None + if element_spec != _create_distributed_tensor_spec( + self._strategy, self._cloned_datasets[0].element_spec): + raise ValueError("Mismatched element_spec from the passed components") + self._element_spec = element_spec + + self._built = True + + def build(self, dataset_to_replace=None): + assert not self._built + dataset = dataset_to_replace or self._original_dataset + self._cardinality = _cardinality(dataset) + self._enable_get_next_as_optional = _enable_get_next_as_optional( + self._strategy, dataset, self._cardinality) + distribute_start_time_ns = time.time_ns() + self._create_cloned_datasets_from_dataset(dataset, self._input_context, + self._input_workers, + self._strategy, + self._num_replicas_in_sync) + if context.executing_eagerly(): + # Records the time to initialize the distributed dataset. + context.async_wait() + distribute_duration_ms = (time.time_ns() - + distribute_start_time_ns) // 1_000_000 + _distributed_dataset_initialization_time_milliseconds.get_cell( + self._strategy.__class__.__name__, + str(self._input_workers.num_workers)).add(distribute_duration_ms) + self._element_spec = _create_distributed_tensor_spec( + self._strategy, self._cloned_datasets[0].element_spec) + self._built = True + + def auto_shard(self, num_shards, shard_ix): + assert ( + len(self._cloned_datasets) == len(self._input_workers.worker_devices) + ), ( + f"datasets: {len(self._cloned_datasets)}, " + f"input workers: {len(self._input_workers.worker_devices)}" + ) + sharded_datasets = [] + for i in range(len(self._input_workers.worker_devices)): + with ops.colocate_with(self._cloned_datasets[i]._variant_tensor): # pylint:disable=protected-access + sharded_datasets.append( + input_ops.auto_shard_dataset( + self._cloned_datasets[i], num_shards, shard_ix, + self._num_replicas_in_sync + )) + return DistributedDataset( + self._input_workers, + self._strategy, + components=sharded_datasets, + element_spec=self._element_spec, + options=self._options, + enable_get_next_as_optional=self._enable_get_next_as_optional) + + @property + def cardinality(self): + if not self._built: + raise ValueError( + "Cannot get the cardinality of a dataset that is not built") + return self._cardinality + + def _create_cloned_datasets_from_dataset(self, dataset, input_context, + input_workers, strategy, + num_replicas_in_sync): + # We clone and shard the dataset on each worker. The current setup tries to + # shard the dataset by files if possible so that each worker sees a + # different subset of files. If that is not possible, will attempt to shard + # the final input such that each worker will run the entire preprocessing + # pipeline and only receive its own shard of the dataset. + + # Additionally, we rebatch the dataset on each worker into + # `num_replicas_in_sync` smaller batches to be distributed among that + # worker's replicas, so that the batch size for a global step (across all + # workers and replicas) adds up to the original dataset's batch size. + if num_replicas_in_sync is not None and num_replicas_in_sync > 1: + num_workers = input_context.num_input_pipelines if input_context else len( + input_workers.worker_devices) + rebatch_fn = self._make_rebatch_fn(dataset, num_workers, + num_replicas_in_sync) + else: + rebatch_fn = None + self._cloned_datasets = [] + if input_context: + # Between-graph where we rely on the input_context for sharding + assert input_workers.num_workers == 1 + if rebatch_fn is not None: + dataset = rebatch_fn(dataset, input_context.input_pipeline_id) + dataset = input_ops.auto_shard_dataset(dataset, + input_context.num_input_pipelines, + input_context.input_pipeline_id, + num_replicas_in_sync) + self._cloned_datasets.append(dataset) + else: + replicated_ds = distribute.replicate(dataset, + input_workers.worker_devices) + for i, worker in enumerate(input_workers.worker_devices): + with ops.device(worker): + cloned_dataset = replicated_ds[worker] + if rebatch_fn is not None: + cloned_dataset = rebatch_fn(cloned_dataset, i) + cloned_dataset = input_ops.auto_shard_dataset( + cloned_dataset, len(input_workers.worker_devices), i, + num_replicas_in_sync) + self._cloned_datasets.append(cloned_dataset) + + def _make_rebatch_fn(self, dataset, num_workers, num_replicas_in_sync): + """Returns a callable that rebatches the input dataset. + + Args: + dataset: A `tf.data.Dataset` representing the dataset to be distributed. + num_workers: An integer representing the number of workers to distribute + `dataset` among. + num_replicas_in_sync: An integer representing the number of replicas in + sync across all workers. + """ + if num_replicas_in_sync % num_workers: + raise ValueError( + "tf.distribute expects every worker to have the same number of " + "replicas. However, encountered `num_replicas_in_sync` ({}) that " + "cannot be divided by `num_workers` ({})".format( + num_replicas_in_sync, num_workers)) + + num_replicas_per_worker = num_replicas_in_sync // num_workers + with ops.colocate_with(dataset._variant_tensor): # pylint: disable=protected-access + batch_size = distribute.compute_batch_size(dataset) + + def rebatch_fn(dataset, worker_index): + try: + + def apply_rebatch(): + batch_sizes = distribute.batch_sizes_for_worker( + batch_size, num_workers, num_replicas_per_worker, worker_index) + return dataset.rebatch(batch_sizes).prefetch(num_replicas_per_worker) + + # pylint: disable=protected-access + def apply_legacy_rebatch(): + return distribute._LegacyRebatchDataset( + dataset, num_replicas_in_sync).prefetch(num_replicas_per_worker) + + with ops.colocate_with(dataset._variant_tensor): + return tf_cond.cond( + math_ops.not_equal(batch_size, -1), + true_fn=apply_rebatch, + false_fn=apply_legacy_rebatch) + except errors.InvalidArgumentError as e: + if "without encountering a batch" in str(e): + six.reraise( + ValueError, + ValueError( + "Call the `batch` method on the input Dataset in order to be " + "able to split your input across {} replicas.\n Please see " + "the tf.distribute.Strategy guide. {}".format( + num_replicas_in_sync, e)), + sys.exc_info()[2]) + else: + raise + + return rebatch_fn + + def __iter__(self): + if not (context.executing_eagerly() or + ops.get_default_graph().building_function): + raise RuntimeError("__iter__() is only supported inside of tf.function " + "or when eager execution is enabled.") + if not self._built: + raise ValueError("To use this dataset, you need to pass this dataset to " + "ClusterCoordinator.create_per_worker_dataset.") + + canonicalize_devices = getattr(self._strategy, "_canonicalize_devices", + True) + + worker_iterators = _create_iterators_per_worker( + self._cloned_datasets, + self._input_workers, + options=self._options, + canonicalize_devices=canonicalize_devices) + iterator = DistributedIterator( + self._input_workers, + worker_iterators, + self._strategy, + cardinality=self._cardinality, + enable_get_next_as_optional=self._enable_get_next_as_optional, + options=self._options, + replica_order=self._replica_order, + ) + iterator._element_spec = self._element_spec # pylint: disable=protected-access + + # When async eager is enabled, sometimes the iterator may not finish + # initialization before passing to a multi device function, add a sync point + # here to make sure all underlying iterators are initialized. + if context.executing_eagerly(): + context.async_wait() + + return iterator + + @property + def element_spec(self): + """The type specification of an element of this dataset.""" + # When partial batch handling is enabled, always set the batch dimension to + # None, otherwise we just follow element_spec of the underlying dataset + # (whose batch dimension may also be None). This is because with partial + # batching handling we could always produce empty batches. + if (self._enable_get_next_as_optional and + self._strategy.extended._in_multi_worker_mode()): # pylint: disable=protected-access + return nest.map_structure( + _rebatch_as_dynamic, self._element_spec, expand_composites=False) + return self._element_spec + + @property + def _type_spec(self): + return DistributedDatasetSpec( + self._input_workers, + self._element_spec, + self._strategy, + self._options, + enable_get_next_as_optional=self._enable_get_next_as_optional) + + +class DistributedDatasetsFromFunctionSpec(DistributedDatasetAndIteratorSpec): + """Type specification for `DistributedDatasetsFromFunction.""" + + @property + def value_type(self): + return DistributedDatasetsFromFunction + + @property + def _component_specs(self): + specs = [] + worker_device_pairs = self._input_workers._worker_device_pairs # pylint: disable=protected-access + + for i, _ in enumerate(worker_device_pairs): + element_spec = nest.map_structure( + functools.partial(_replace_per_replica_spec, i=i), self._element_spec) + specs.append(dataset_ops.DatasetSpec(element_spec)) + return specs + + def _to_components(self, value): + return value._datasets # pylint: disable=protected-access + + def _from_components(self, components): + return DistributedDatasetsFromFunction( + input_workers=self._input_workers, + strategy=self._strategy, + components=components, + element_spec=self._element_spec, + options=self._options) + + @staticmethod + def from_value(value): + # pylint: disable=protected-access + return DistributedDatasetsFromFunctionSpec( + input_workers=value._input_workers, + element_spec=value._element_spec, + strategy=value._strategy, + options=value._options) + + +# TODO(priyag): Add other replication modes. +class DistributedDatasetsFromFunction(_IterableInput, + composite_tensor.CompositeTensor): + """Inputs created from dataset function.""" + + def __init__( + self, + input_workers, + strategy, + input_contexts=None, + dataset_fn=None, + options=None, + components=None, + element_spec=None, + build=True, + replica_order=None, + ): + """Makes an iterable from datasets created by the given function. + + Args: + input_workers: an `InputWorkers` object. + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + input_contexts: A list of `InputContext` instances to be passed to call(s) + to `dataset_fn`. Length and order should match worker order in + `worker_device_pairs`. + dataset_fn: A function that returns a `Dataset` given an `InputContext`. + Either dataset_fn or components should be passed to construct + DistributedDatasetsFromFunction. Use this when constructing + DistributedDataset using a function. Use components when constructing + using DistributedDatasetsFromFunctionSpec. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + components: datasets when DistributedDatasetsFromFunction is constructed + from DistributedDatasetsFromFunctionSpec. Only one of dataset or + components should be passed. + element_spec: element spec for DistributedDataset when constructing from + DistributedDatasetSpec. This will be used to set the element_spec for + DistributedDatasetsFromFunctionSpec and verified against element_spec + from components. + build: whether to build underlying datasets when this object is created. + This is only useful for `ParameterServerStrategy` now. + replica_order: the order of the replicas, which will be used to reorder + the iterators to match the device order. + """ + super(DistributedDatasetsFromFunction, self).__init__( + input_workers=input_workers) + self._input_workers = input_workers + self._strategy = strategy + self._options = options + self._replica_order = replica_order + if dataset_fn is not None and components is not None: + raise ValueError("Only one of dataset_fn or components should be set") + if dataset_fn is None and components is None: + raise ValueError("At least one of dataset_fn or components should be set") + + if dataset_fn is not None: + if input_workers.num_workers != len(input_contexts): + raise ValueError( + "Number of input workers (%d) is not same as number of " + "input_contexts (%d)" % + (input_workers.num_workers, len(input_contexts))) + self._input_contexts = input_contexts + self._num_replicas_in_sync = self._input_contexts[0].num_replicas_in_sync + self._dataset_fn = dataset_fn + self._built = False + if build: + self.build() + else: + if element_spec is None: + raise ValueError( + "element_spec should also be passed when passing components") + if not build: + raise ValueError( + "When constructing DistributedDatasetFromFunction with components, " + "build should not be False. This is an internal error. Please file " + "a bug.") + self._element_spec = element_spec + self._datasets = components + self._num_replicas_in_sync = None + self._built = True + self._cardinality = _cardinality(self._datasets[0]) + self._enable_get_next_as_optional = _enable_get_next_as_optional( + self._strategy, self._datasets[0], self._cardinality) + + def build(self): + assert not self._built + distribute_start_time_ns = time.time_ns() + self._datasets, element_spec = ( + _create_datasets_from_function_with_input_context( + self._input_contexts, self._input_workers, self._dataset_fn)) + if context.executing_eagerly(): + # Records the time to initialize the distributed dataset. + context.async_wait() + distribute_duration_ms = (time.time_ns() - + distribute_start_time_ns) // 1_000_000 + _distributed_dataset_from_function_initialization_time_milliseconds.get_cell( + self._strategy.__class__.__name__, + str(self._input_workers.num_workers)).add(distribute_duration_ms) + + self._element_spec = _create_distributed_tensor_spec( + self._strategy, element_spec) + self._cardinality = _cardinality(self._datasets[0]) + self._enable_get_next_as_optional = _enable_get_next_as_optional( + self._strategy, self._datasets[0], self._cardinality) + self._built = True + + def auto_shard(self, num_shards, shard_ix): + assert ( + len(self._datasets) == len(self._input_workers.worker_devices) + ), ( + f"datasets: {len(self._datasets)}, " + f"input workers: {len(self._input_workers.worker_devices)}" + ) + sharded_datasets = [] + for i in range(len(self._input_workers.worker_devices)): + with ops.colocate_with(self._datasets[i]._variant_tensor): # pylint: disable=protected-access + sharded_datasets.append( + input_ops.auto_shard_dataset( + self._datasets[i], num_shards, shard_ix, + self._num_replicas_in_sync + ) + ) + return DistributedDatasetsFromFunction(self._input_workers, self._strategy, + components=sharded_datasets, + element_spec=self._element_spec, + options=self._options) + + @property + def cardinality(self): + if not self._built: + raise ValueError( + "Cannot get the cardinality of a dataset that is not built") + return self._cardinality + + def __iter__(self): + if not (ops.executing_eagerly_outside_functions() or + ops.get_default_graph().building_function): + raise RuntimeError("__iter__() is only supported inside of tf.function " + "or when eager execution is enabled.") + + if not self._built: + raise ValueError("You need to use this dataset in " + "ClusterCoordinator.create_per_worker_dataset.") + + canonicalize_devices = getattr(self._strategy, "_canonicalize_devices", + True) + + iterators = _create_iterators_per_worker( + self._datasets, + self._input_workers, + options=self._options, + canonicalize_devices=canonicalize_devices) + iterator = DistributedIterator( + input_workers=self._input_workers, + iterators=iterators, + strategy=self._strategy, + cardinality=self._cardinality, + enable_get_next_as_optional=self._enable_get_next_as_optional, + options=self._options, + replica_order=self._replica_order, + ) + iterator._element_spec = self._element_spec # pylint: disable=protected-access + + # When async eager is enabled, sometimes the iterator may not finish + # initialization before passing to a multi device function, add a sync + # point here to make sure all underlying iterators are initialized. + if context.executing_eagerly(): + context.async_wait() + + return iterator + + @property + def element_spec(self): + """The type specification of an element of this dataset.""" + # When partial batch handling is enabled, always set the batch dimension to + # None, otherwise we just follow element_spec of the underlying dataset + # (whose batch dimension may also be None). This is because with partial + # batching handling we could always produce empty batches. + if (self._enable_get_next_as_optional and + self._strategy.extended._in_multi_worker_mode()): # pylint: disable=protected-access + return nest.map_structure( + _rebatch_as_dynamic, self._element_spec, expand_composites=False) + return self._element_spec + + @property + def _type_spec(self): + return DistributedDatasetsFromFunctionSpec(self._input_workers, + self._element_spec, + self._strategy, self._options) + + +def _dummy_tensor_fn(value_structure): + """A function to create dummy tensors from `value_structure`.""" + + def create_dummy_tensor(spec): + """Create a dummy tensor with possible batch dimensions set to 0.""" + if hasattr(spec, "_create_empty_value"): + # Type spec may overwrite default dummy values behavior by declaring the + # `_create_empty_value(self)` method. This method must return a value + # compatible with the type spec with batch dimensions set to 0 or fail if + # such a value does not exist. This allows a composite tensor to customize + # dummy values creation as, in general, its dummy value is not composed + # from dummy components (e.g. `row_splits` tensor of a RaggedTensor is + # never allowed to be empty). See b/183969859 for more discussions. + # TODO(b/186079336): reconsider CompositeTensor support. + return spec._create_empty_value() # pylint: disable=protected-access + + if isinstance(spec, ragged_tensor.RaggedTensorSpec): + # Splice out the ragged dimensions. + # pylint: disable=protected-access + feature_shape = spec._shape[:1].concatenate( + spec._shape[(1 + spec._ragged_rank):]) + feature_type = spec._dtype + # pylint: enable=protected-access + else: + feature_shape = spec.shape + feature_type = spec.dtype + # Ideally we should set the batch dimension to 0, however as in + # DistributionStrategy we don't know the batch dimension, we try to + # guess it as much as possible. If the feature has unknown dimensions, we + # will set them to 0. If the feature shape is already static, we guess the + # first dimension as batch dimension and set it to 0. + dims = ([dim if dim is not None else 0 for dim in feature_shape.as_list()] + if feature_shape else []) + if dims and (isinstance(spec, ragged_tensor.RaggedTensorSpec) or + feature_shape.is_fully_defined()): + dims[0] = tensor_shape.Dimension(0) + + if isinstance(spec, sparse_tensor.SparseTensorSpec): + return sparse_tensor.SparseTensor( + values=array_ops.zeros(0, feature_type), + indices=array_ops.zeros((0, len(dims)), dtypes.int64), + dense_shape=dims) + + # Create the dummy tensor. + dummy_tensor = array_ops.zeros(tensor_shape.TensorShape(dims), feature_type) + if isinstance(spec, ragged_tensor.RaggedTensorSpec): + # Reinsert the ragged dimensions with size 0. + # pylint: disable=protected-access + row_splits = array_ops.zeros(1, spec._row_splits_dtype) + dummy_tensor = ragged_tensor.RaggedTensor.from_nested_row_splits( + dummy_tensor, (row_splits,) * spec._ragged_rank, validate=False) + # pylint: enable=protected-access + return dummy_tensor + + return nest.map_structure(create_dummy_tensor, value_structure) + + +def _get_value_or_dummy(input_workers, optional_list, produce_dummy): + """Returns the value of the optionals or dummy values. + + Args: + input_workers: the `InputWorkers`. + optional_list: a list of lists `tf.experimental.Optional`. The values from + each compute device grouped by the input device. + produce_dummy: a bool. Whether to produce dummy tensors when the optional + doesn't have a value. + + Returns: + A flatten list of Tensors. + + """ + value_list = [] + for i, worker in enumerate(input_workers.worker_devices): + with ops.device(worker): + devices = input_workers.compute_devices_for_worker(i) + for j, device in enumerate(devices): + with ops.device(device): + if produce_dummy: + # pylint: disable=cell-var-from-loop + value_list.append( + tf_cond.cond( + optional_list[i][j].has_value(), + lambda: optional_list[i][j].get_value(), # pylint: disable=unnecessary-lambda + lambda: _dummy_tensor_fn(optional_list[i][j].element_spec), + strict=True, + )) + # pylint: enable=cell-var-from-loop + else: + value_list.append(optional_list[i][j].get_value()) + return value_list + + +class _SingleWorkerDatasetIteratorBase(object): + """Iterator for a single `tf.data.Dataset`.""" + + def __init__(self, dataset, worker, devices, options=None): + """Create iterator for the `dataset` to fetch data to worker's `devices` . + + A `MultiDeviceIterator` or `OwnedMultiDeviceIterator` is used to prefetch + input to the devices on the given worker. + + Args: + dataset: A `tf.data.Dataset` instance. + worker: Worker on which ops should be created. + devices: Distribute data from `dataset` to these devices. + options: options. + """ + self._dataset = dataset + self._worker = worker + self._devices = devices + self._element_spec = dataset.element_spec + self._options = options + self._make_iterator() + + def _make_iterator(self): + raise NotImplementedError("must be implemented in descendants") + + def _format_data_list_with_options(self, data_list): + """Change the data in to a list type if required. + + The OwnedMultiDeviceIterator returns the list data type, + while the PER_REPLICA iterator (when used with prefetch disabled) + returns without the enclosed list. This is to fix the inconsistency. + Args: + data_list: data_list + Returns: + list + """ + if (self._options and self._options.experimental_replication_mode == + InputReplicationMode.PER_REPLICA and + not self._options.experimental_fetch_to_device): + return [data_list] + else: + return data_list + + def get_next(self, device, name=None): + """Get next element for the given device.""" + del name + with ops.device(self._worker): + if _should_use_multi_device_iterator(self._options): + return self._iterator.get_next(device) + else: + return self._iterator.get_next() + + def get_next_as_list(self, name=None): + """Get next element from the underlying iterator. + + Runs the iterator get_next() within a device scope. Since this doesn't use + get_next_as_optional(), it is considerably faster than get_next_as_list(), + but it raises EOFError if any of the device doesn't get any data. + + Args: + name: not used. + + Returns: + A list consisting of the next data from each device. + """ + del name + with ops.device(self._worker): + return self._format_data_list_with_options(self._iterator.get_next()) + + def get_next_as_optional_list(self): + with ops.device(self._worker): + return self._format_data_list_with_options( + self._iterator.get_next_as_optional()) + + +class _SingleWorkerDatasetIteratorSpec(type_spec.TypeSpec): + """Type specification for `_SingleWorkerOwnedDatasetIterator`.""" + + __slots__ = [ + "_worker", "_devices", "_element_spec", "_options", + "_canonicalize_devices" + ] + + def __init__(self, worker, devices, element_spec, options, + canonicalize_devices=True): + self._worker = worker + if canonicalize_devices: + self._devices = tuple(device_util.canonicalize(d) for d in devices) + else: + self._devices = tuple( + device_util.canonicalize_without_job_and_task(d) for d in devices) + self._element_spec = element_spec + # `self._options` intentionally made not `None` for proper serialization. + self._options = (options if options is not None else + distribute_lib.InputOptions()) + self._canonicalize_devices = canonicalize_devices + + @property + def value_type(self): + return _SingleWorkerOwnedDatasetIterator + + def _serialize(self): + return (self._worker, self._devices, self._element_spec, self._options, + self._canonicalize_devices) + + def _get_multi_device_iterator_spec(self, specs): + device_scope = device_util.canonicalize(self._worker, device_util.current()) + host_device = device_util.get_host_for_device(device_scope) + # source_device while creating iterator governs the worker device in + # iterator spec. + worker = host_device + specs.append( + multi_device_iterator_ops.MultiDeviceIteratorSpec( + self._devices, worker, element_spec=self._element_spec)) + + @property + def _component_specs(self): + specs = [] + if _should_use_multi_device_iterator(self._options): + self._get_multi_device_iterator_spec(specs) + else: + specs.append(iterator_ops.IteratorSpec(element_spec=self._element_spec)) + return specs + + def _to_components(self, value): + return [value._iterator] # pylint: disable=protected-access + + def _from_components(self, components): + return _SingleWorkerOwnedDatasetIterator( + dataset=None, + worker=self._worker, + devices=self._devices, + components=components, + element_spec=self._element_spec, + options=self._options, + canonicalize_devices=self._canonicalize_devices) + + @staticmethod + def from_value(value): + # pylint: disable=protected-access + return _SingleWorkerDatasetIteratorSpec(value._worker, value._devices, + value._element_spec, value._options, + value._canonicalize_devices) + + +class _SingleWorkerOwnedDatasetIterator(_SingleWorkerDatasetIteratorBase, + composite_tensor.CompositeTensor): + """Iterator for a DistributedDataset instance.""" + + def __init__(self, + dataset=None, + worker=None, + devices=None, + components=None, + element_spec=None, + options=None, + canonicalize_devices=None): + """Create iterator for the `dataset` to fetch data to worker's `devices` . + + `OwnedMultiDeviceIterator` is used to prefetch input to the devices on the + given worker. The lifetime of this iterator is tied to the encompassing + python object. Once we go out of scope of the python object or return from + a tf.function the underlying iterator resource is deleted. + + Args: + dataset: A `tf.data.Dataset` instance. + worker: Worker on which ops should be created. + devices: Distribute data from `dataset` to these devices. + components: Tensor components to construct the + _SingleWorkerOwnedDatasetIterator from. + element_spec: A nested structure of `TypeSpec` objects that represents the + type specification of elements of the iterator. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + canonicalize_devices: Whether to canonicalize devices for workers fully or + partially. If False, it will partially canonicalize devices by removing + job and task. + """ + if worker is None or devices is None: + raise ValueError("Both `worker` and `devices` should be provided") + + error_message = ("Either `dataset` or both `components` and `element_spec` " + "need to be provided.") + + self._options = options + self._canonicalize_devices = canonicalize_devices + if dataset is None: + if (components is None or element_spec is None): + raise ValueError(error_message) + self._element_spec = element_spec + self._worker = worker + self._devices = devices + self._iterator = components[0] + else: + if (components is not None or element_spec is not None): + raise ValueError(error_message) + super(_SingleWorkerOwnedDatasetIterator, + self).__init__(dataset, worker, devices, self._options) + + def _create_owned_multi_device_iterator(self): + # If the worker devices are already canonicalized, canonicalizing again + # would have no impact. + # For strategies running on remote workers such as PS Strategy, the device + # scope will be derived from current worker, if used under init_scope(). + if not ops.inside_function(): + device_scope = device_util.canonicalize(self._worker, + device_util.current()) + host_device = device_util.get_host_for_device(device_scope) + else: + # In general, iterators should not be created within tf.functions. For + # exact visitation guarantee solutions for parameter server training, + # however, we do create iterators within the tf.functions that are + # dispatched to workers. In these cases, the traced device must match the + # runtime device. Since tracing occurs on the chief, we do not want to use + # the current device scope, which would be the chief, but rather use the + # relative worker device scope explicitly. + device_scope, host_device = self._worker, self._worker + with ops.device(device_scope): + if self._options is not None: + self._iterator = multi_device_iterator_ops.OwnedMultiDeviceIterator( + self._dataset, + self._devices, + source_device=host_device, + max_buffer_size=self._options + .experimental_per_replica_buffer_size, + prefetch_buffer_size=self._options + .experimental_per_replica_buffer_size) + else: + self._iterator = multi_device_iterator_ops.OwnedMultiDeviceIterator( + self._dataset, self._devices, source_device=host_device) + + def _make_iterator(self): + """Make appropriate iterator on the dataset.""" + if not self._worker: + raise ValueError("Worker device must be specified when creating an " + "owned iterator.") + if _should_use_multi_device_iterator(self._options): + self._create_owned_multi_device_iterator() + else: + with ops.device(self._worker): + self._iterator = iter(self._dataset) + + @property + def element_spec(self): + return self._element_spec + + @property + def _type_spec(self): + return _SingleWorkerDatasetIteratorSpec(self._worker, self._devices, + self._element_spec, self._options, + self._canonicalize_devices) + + @property + def output_classes(self): + """Returns the class of each component of an element of this iterator. + + The expected values are `tf.Tensor` and `tf.SparseTensor`. + + Returns: + A nested structure of Python `type` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access + self._element_spec) + + @property + def output_shapes(self): + """Returns the shape of each component of an element of this iterator. + + Returns: + A nested structure of `tf.TensorShape` objects corresponding to each + component of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access + self._element_spec) + + @property + def output_types(self): + """Returns the type of each component of an element of this iterator. + + Returns: + A nested structure of `tf.DType` objects corresponding to each component + of an element of this dataset. + """ + return nest.map_structure( + lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access + self._element_spec) + + +def _create_iterators_per_worker(worker_datasets, + input_workers, + options=None, + canonicalize_devices=False): + """Create a multidevice iterator on each of the workers.""" + assert isinstance(input_workers, InputWorkers) + assert len(worker_datasets) == len(input_workers.worker_devices) + iterators = [] + for i, worker in enumerate(input_workers.worker_devices): + with ops.device(worker): + worker_devices = input_workers.compute_devices_for_worker(i) + iterator = _SingleWorkerOwnedDatasetIterator( + dataset=worker_datasets[i], + worker=worker, + devices=worker_devices, + options=options, + canonicalize_devices=canonicalize_devices) + iterators.append(iterator) + return iterators + + +def _create_datasets_from_function_with_input_context(input_contexts, + input_workers, + dataset_fn): + """Create device datasets per worker given a dataset function.""" + datasets = [] + for i, ctx in enumerate(input_contexts): + worker = input_workers.worker_devices[i] + with ops.device(worker): + dataset = dataset_fn(ctx) + datasets.append(dataset) + return datasets, dataset.element_spec + + +# TODO(sourabhbajaj): Remove this in lieu of distributed datasets +def _get_batched_dataset(d): + """Get the batched dataset from `d`.""" + # pylint: disable=protected-access + if isinstance(d, dataset_ops.DatasetV1Adapter): + d = d._dataset + + if isinstance(d, (dataset_ops.BatchDataset, batching._MapAndBatchDataset)): + return d + elif isinstance(d, (dataset_ops.PrefetchDataset, + dataset_ops._OptionsDataset)): + return _get_batched_dataset(d._input_dataset) + + raise ValueError( + "Unable to get batched dataset from the input dataset. `batch` " + "`map_and_batch` need to be the last operations on the dataset. " + "The batch operations can be followed by a prefetch.") + + +def _get_batched_dataset_attributes(d): + """Get `batch_size`, `drop_remainder` of dataset.""" + # pylint: disable=protected-access + assert isinstance(d, + (dataset_ops.BatchDataset, batching._MapAndBatchDataset)) + if isinstance(d, dataset_ops.BatchDataset): + batch_size = d._batch_size + drop_remainder = d._drop_remainder + elif isinstance(d, batching._MapAndBatchDataset): + batch_size = d._batch_size_t + drop_remainder = d._drop_remainder_t + # pylint: enable=protected-access + + if tensor_util.is_tf_type(batch_size): + batch_size = tensor_util.constant_value(batch_size) + + if tensor_util.is_tf_type(drop_remainder): + drop_remainder = tensor_util.constant_value(drop_remainder) + + return batch_size, drop_remainder + + +# TODO(sourabhbajaj): Remove this in lieu of distributed datasets +def _get_dataset_attributes(dataset): + """Get the underlying attributes from the dataset object.""" + # pylint: disable=protected-access + + # First, get batch_size and drop_remainder from the dataset. We need + # to walk back the dataset creation process and find the batched version in + # order to get the attributes. + batched_dataset = _get_batched_dataset(dataset) + batch_size, drop_remainder = _get_batched_dataset_attributes(batched_dataset) + + # Second, prefetch buffer should be get from the original dataset. + prefetch_buffer = None + if isinstance(dataset, dataset_ops.PrefetchDataset): + prefetch_buffer = dataset._buffer_size + elif (isinstance(dataset, dataset_ops.DatasetV1Adapter) + and isinstance(dataset._dataset, dataset_ops.PrefetchDataset)): + prefetch_buffer = dataset._dataset._buffer_size + + return batch_size, drop_remainder, prefetch_buffer + + +def _should_use_multi_device_iterator(options): + """Determine whether to use multi_device_iterator_ops.""" + if (options is None or + options.experimental_replication_mode == InputReplicationMode.PER_WORKER + or + (options.experimental_replication_mode == InputReplicationMode.PER_REPLICA + and options.experimental_fetch_to_device)): + return True + return False + + +class MultiStepContext(object): + """A context object that can be used to capture things when running steps. + + This context object is useful when running multiple steps at a time using the + `experimental_run_steps_on_iterator` API. For e.g. it allows the user's step + function to specify which outputs to emit at what frequency. Currently it + supports capturing output from the last step, as well as capturing non tensor + outputs. In the future it will be augmented to support other use cases such + as output each N steps. + """ + + def __init__(self): + """Initialize an output context. + + Returns: + A context object. + """ + self._last_step_outputs = {} + self._last_step_outputs_reduce_ops = {} + self._non_tensor_outputs = {} + + @property + def last_step_outputs(self): + """A dictionary consisting of outputs to be captured on last step. + + Keys in the dictionary are names of tensors to be captured, as specified + when `set_last_step_output` is called. + Values in the dictionary are the tensors themselves. If + `set_last_step_output` was called with a `reduce_op` for this output, + then the value is the reduced value. + + Returns: + A dictionary with last step outputs. + """ + return self._last_step_outputs + + def _set_last_step_outputs(self, outputs): + """Replace the entire dictionary of last step outputs.""" + if not isinstance(outputs, dict): + raise ValueError("Need a dictionary to set last_step_outputs.") + self._last_step_outputs = outputs + + def set_last_step_output(self, name, output, reduce_op=None): + """Set `output` with `name` to be outputted from the last step. + + Args: + name: String, name to identify the output. Doesn't need to match tensor + name. + output: The tensors that should be outputted with `name`. See below for + actual types supported. + reduce_op: Reduction method to use to reduce outputs from multiple + replicas. Required if `set_last_step_output` is called in a replica + context. Optional in cross_replica_context. + When present, the outputs from all the replicas are reduced using the + current distribution strategy's `reduce` method. Hence, the type of + `output` must be what's supported by the corresponding `reduce` method. + For e.g. if using MirroredStrategy and reduction is set, output + must be a `PerReplica` value. + The reduce method is also recorded in a dictionary + `_last_step_outputs_reduce_ops` for later interpreting of the + outputs as already reduced or not. + """ + if distribute_lib.in_cross_replica_context(): + self._last_step_outputs_reduce_ops[name] = reduce_op + if reduce_op is None: + self._last_step_outputs[name] = output + else: + distribution = distribute_lib.get_strategy() + self._last_step_outputs[name] = distribution.reduce(reduce_op, output, + axis=None) + else: + assert reduce_op is not None + def merge_fn(distribution, value): + self._last_step_outputs[name] = distribution.reduce(reduce_op, value, + axis=None) + # Setting this inside the `merge_fn` because all replicas share the same + # context object, so it's more robust to set it only once (even if all + # the replicas are trying to set the same value). + self._last_step_outputs_reduce_ops[name] = reduce_op + + distribute_lib.get_replica_context().merge_call( + merge_fn, args=(output,)) + + @property + def non_tensor_outputs(self): + """A dictionary consisting of any non tensor outputs to be captured.""" + return self._non_tensor_outputs + + def set_non_tensor_output(self, name, output): + """Set `output` with `name` to be captured as a non tensor output.""" + if distribute_lib.in_cross_replica_context(): + self._non_tensor_outputs[name] = output + else: + def merge_fn(distribution, value): + # NOTE(priyag): For non tensor outputs, we simply return all the values + # in a list as reduction doesn't make sense on non tensors. + self._non_tensor_outputs[name] = ( + distribution.experimental_local_results(value)) + distribute_lib.get_replica_context().merge_call( + merge_fn, args=(output,)) + + +def _create_distributed_tensor_spec(strategy, tensor_spec): + """Create a `tf.TypeSpec` for a given strategy and input `tensor_spec`. + + Args: + strategy: The given `tf.distribute` strategy. + tensor_spec: `tf.TensorSpec` of a given value. The batch dimension of the + shape should be None if you have partial batches. + + Returns: + A `tf.TypeSpec` that matches the values produced by a given strategy. This + can be a `tf.TensorSpec` or a `PerRelicaSpec`. + """ + num_replicas = len(strategy.extended.worker_devices) + + # For one device strategy that is not MultiWorkerMirroredStrategy, return the + # tensor_spec as is, since we don't wrap the output with PerReplica in this + # case. + # TODO(b/166464552): remove after we always wrap for all strategies. + if not _always_wrap(strategy): + return tensor_spec + + # For other cases we assume the input to tf.function is a per replica type. + def _get_value_per_replica(tensor_spec_per_input): + value_specs = [tensor_spec_per_input for _ in range(num_replicas)] + return values.PerReplicaSpec(*value_specs) + + return nest.map_structure(_get_value_per_replica, tensor_spec) + + +def _replace_per_replica_spec(spec, i): + """If `spec` is a `PerReplicaSpec`, then return its `i`th value_spec.""" + if isinstance(spec, values.PerReplicaSpec): + return spec._value_specs[i] # pylint: disable=protected-access + else: + return spec + + +def _cardinality(dataset): + """Returns the cardinality of the dataset.""" + if context.executing_eagerly(): + with ops.device(dataset._variant_tensor.device): # pylint: disable=protected-access + return dataset.cardinality().numpy() + return cardinality_lib.UNKNOWN + + +def _enable_get_next_as_optional(strategy, dataset, cardinality): + """Returns whether to enable using partial batch handling.""" + # TODO(b/133073708): we currently need a flag to control the usage because + # there is a performance difference between get_next() and + # get_next_as_optional(). And we only enable get_next_as_optional when the + # output shapes are not static. + # + # TODO(rxsang): We want to always enable the get_next_as_optional behavior + # when user passed input_fn instead of dataset. + if not getattr( + strategy.extended, "enable_partial_batch_handling", + getattr(strategy.extended, "experimental_enable_get_next_as_optional", + False)): + return False + + # If the dataset is infinite, we don't need to enable last partial batch + # support. Note that we can only evaluate the cardinality of the dataset in + # eager. + if cardinality == cardinality_lib.INFINITE: + return False + + return not _is_statically_shaped( + dataset.element_spec) or strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access + + +def _create_per_replica(value_list, strategy): + """Creates a PerReplica. + + For strategies other than OneDeviceStrategy, it creates a PerReplica whose + type spec is set to the element spec of the dataset. This helps avoid + retracing for partial batches. Retracing is problematic for multi client when + different client retraces different time, since retracing changes the + collective keys in the tf.function, and causes mismatches among clients. + + For single client strategies, this simply calls distribute_utils.regroup(). + + Args: + value_list: a list of values, one for each replica. + strategy: the `tf.distribute.Strategy`. + + Returns: + a structure of PerReplica. + + """ + # TODO(b/166464552): always wrap for all one device strategies as well. + always_wrap = _always_wrap(strategy) + per_replicas = distribute_utils.regroup(value_list, always_wrap=always_wrap) + return per_replicas + + +def _always_wrap(strategy): + """Returns whether to always wrap the values in a DistributedValues.""" + return strategy.extended._in_multi_worker_mode() or len( # pylint: disable=protected-access + strategy.extended.worker_devices) > 1 + + +def _rebatch_as_dynamic(per_replica_spec): + """Rebatch the spec to have a dynamic batch dimension.""" + assert isinstance(per_replica_spec, values.PerReplicaSpec), per_replica_spec + + # pylint: disable=protected-access + def _rebatch(spec): + # Rebatch if possible. + try: + return spec._unbatch()._batch(None) + except ValueError: + pass + return spec + + return values.PerReplicaSpec( + *nest.map_structure(_rebatch, per_replica_spec._value_specs)) + # pylint: enable=protected-access + + +def _ag_enumerate_not_implemented(s, unused_start): + msg = ( + f"enumerate not supported with {s.__class__.__name__} types within " + "tf.functions. Use a for loop over the dataset and keep a separate " + "counter instead." + ) + raise NotImplementedError(msg) + + +py_builtins.enumerate_registry.register( + DistributedIterator, _ag_enumerate_not_implemented +) +py_builtins.enumerate_registry.register( + DistributedDataset, _ag_enumerate_not_implemented +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..df066b65d873d72bfe4ba8f67a9741fd6ff060f2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_ops.py @@ -0,0 +1,107 @@ +# 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. +# ============================================================================== +"""Input-pipeline utilities for Distribution strategies.""" + +from tensorflow.python.data.experimental.ops import distribute +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops.options import AutoShardPolicy +from tensorflow.python.data.util import traverse +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.types import data as data_types +from tensorflow.python.types import distribute as distribute_types + + +# pylint: disable=protected-access +def auto_shard_dataset(dataset, num_shards, index, num_replicas_in_sync=None): + """Shard the input pipeline by sharding the underlying list of files. + + Args: + dataset: A `tf.data.Dataset` instance, typically the result of a bunch of + dataset transformations. + num_shards: A `tf.int64` scalar `tf.Tensor`, representing the number of + shards operating in parallel. Same usage as in `tf.data.Dataset.shard`. + index: A `tf.int64` scalar `tf.Tensor`, representing the worker index. + Same usage as in `tf.data.Dataset.shard`. + num_replicas_in_sync: An integer representing the total number of replicas + across all workers. This is used in the rewrite when sharding by data. + + Returns: + A modified `Dataset` obtained by updating the pipeline sharded by the + files. The input dataset will be returned if we cannot automatically + determine a good way to shard the input dataset. + """ + if isinstance(dataset, distribute_types.DistributedDatasetInterface): + return dataset.auto_shard(num_shards, index) + if (dataset.options().experimental_distribute.auto_shard_policy != + AutoShardPolicy.OFF): + if num_replicas_in_sync is None: + num_replicas_in_sync = 1 + if isinstance(dataset, data_types.DatasetV1): + return distribute._AutoShardDatasetV1(dataset, num_shards, index, + num_replicas_in_sync) + else: + return distribute._AutoShardDataset(dataset, num_shards, index, + num_replicas_in_sync) + else: + return dataset + + +def _clone_dataset(dataset): + """Returns a cloned version of `dataset`.""" + variant_tensor_ops = traverse.obtain_all_variant_tensor_ops(dataset) + remap_dict = _clone_helper(dataset._variant_tensor.op, variant_tensor_ops) + new_variant_tensor = remap_dict[dataset._variant_tensor.op].outputs[0] + return dataset_ops._VariantDataset(new_variant_tensor, dataset.element_spec) + + +def _get_op_def(op): + return op.op_def or op_def_registry.get(op.type) + + +def _clone_helper(op_to_clone, variant_tensor_ops): + """Helper method that recursively clones `op_to_clone`. + + Args: + op_to_clone: The op we want to clone. + variant_tensor_ops: A list of ops that we have to clone along the way. + + Returns: + A dictionary mapping old_ops to new_ops created. Includes op_to_clone + as a key. + """ + remap_dict = {} + for input_tensor in op_to_clone.inputs: + input_tensor_op = input_tensor.op + if input_tensor_op in variant_tensor_ops: + recursive_map = _clone_helper(input_tensor_op, variant_tensor_ops) + remap_dict.update(recursive_map) + inputs_list = [] + for input_tensor in op_to_clone.inputs: + input_tensor_op = input_tensor.op + if input_tensor_op in remap_dict: + remapped_input = remap_dict[input_tensor_op].outputs[0] + inputs_list.append(remapped_input) + else: + inputs_list.append(input_tensor_op.outputs[input_tensor.value_index]) + g = ops.get_default_graph() + new_op = g.create_op( + op_to_clone.type, + inputs_list, [o.dtype for o in op_to_clone.outputs], + name=op_to_clone.name, + attrs=op_to_clone.node_def.attr, + op_def=_get_op_def(op_to_clone)) + remap_dict[op_to_clone] = new_op + return remap_dict diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_util.py new file mode 100644 index 0000000000000000000000000000000000000000..1dda2a5fd81adddd4d1ffb707aa8aaf09a01a48e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/input_util.py @@ -0,0 +1,155 @@ +# 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. +# ============================================================================== +"""Utils to create distributed datasets based on TF version.""" + +from tensorflow.python import tf2 +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute.v1 import input_lib as input_lib_v1 + + +def get_distributed_dataset( + dataset, + input_workers, + strategy, + num_replicas_in_sync=None, + input_context=None, + options=None, + build=True, + replica_order=None, +): + """Returns a distributed dataset from the given tf.data.Dataset instance. + + This is a common function that is used by all strategies to return a + distributed dataset. The distributed dataset instance returned is different + depending on if we are in a TF 1 or TF 2 context. The distributed dataset + instances returned differ from each other in the APIs supported by each of + them. + + Args: + dataset: a tf.data.Dataset instance. + input_workers: an InputWorkers object which specifies devices on which + iterators should be created. + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + num_replicas_in_sync: Optional integer. If this is not None, the value is + used to decide how to rebatch datasets into smaller batches so that the + total batch size for each step (across all workers and replicas) adds up + to `dataset`'s batch size. + input_context: `InputContext` for sharding. Only pass this in for between + graph multi-worker cases where there is only one `input_worker`. In these + cases, we will shard based on the `input_pipeline_id` and + `num_input_pipelines` in the `InputContext`. + options: Default is None. `tf.distribute.InputOptions` used to control + options on how this dataset is distributed. + build: whether to build underlying datasets when a DistributedDataset is + created. This is only useful for `ParameterServerStrategy` now. + replica_order: the order of the replicas, which will be used to reorder the + iterators to match the device order. + + Returns: + A distributed dataset instance. + """ + if tf2.enabled(): + return input_lib.DistributedDataset( + input_workers, + strategy, + dataset, + num_replicas_in_sync=num_replicas_in_sync, + input_context=input_context, + build=build, + options=options, + replica_order=replica_order, + ) + else: + return input_lib_v1.DistributedDatasetV1( + dataset, + input_workers, + strategy, + num_replicas_in_sync=num_replicas_in_sync, + input_context=input_context, + options=options) + + +def get_distributed_datasets_from_function( + dataset_fn, + input_workers, + input_contexts, + strategy, + options=None, + build=True, + replica_order=None, +): + """Returns a distributed dataset from the given input function. + + This is a common function that is used by all strategies to return a + distributed dataset. The distributed dataset instance returned is different + depending on if we are in a TF 1 or TF 2 context. The distributed dataset + instances returned differ from each other in the APIs supported by each of + them. + + Args: + dataset_fn: a function that returns a tf.data.Dataset instance. + input_workers: an InputWorkers object which specifies devices on which + iterators should be created. + input_contexts: A list of `InputContext` instances to be passed to call(s) + to `dataset_fn`. Length and order should match worker order in + `worker_device_pairs`. + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + options: Default is None. `tf.distribute.InputOptions` used to control + options on how this dataset is distributed. + build: whether to build underlying datasets when a + `DistributedDatasetFromFunction` is created. This is only useful for + `ParameterServerStrategy` now. + replica_order: the order of the replicas, which will be used to reorder the + iterators to match the device order. + + Returns: + A distributed dataset instance. + + Raises: + ValueError: if `options.experimental_replication_mode` and + `options.experimental_place_dataset_on_device` are not consistent + """ + if (options is not None and options.experimental_replication_mode != + input_lib.InputReplicationMode.PER_REPLICA and + options.experimental_place_dataset_on_device): + raise ValueError( + "When `experimental_place_dataset_on_device` is set for dataset " + "placement, you must also specify `PER_REPLICA` for the " + "replication mode") + + if (options is not None and options.experimental_replication_mode + == input_lib.InputReplicationMode.PER_REPLICA and + options.experimental_fetch_to_device and + options.experimental_place_dataset_on_device): + raise ValueError( + "`experimental_place_dataset_on_device` can not be set to True " + "when experimental_fetch_to_device is True and " + "replication mode is set to `PER_REPLICA`") + + if tf2.enabled(): + return input_lib.DistributedDatasetsFromFunction( + input_workers, + strategy, + input_contexts=input_contexts, + dataset_fn=dataset_fn, + options=options, + build=build, + replica_order=replica_order, + ) + else: + return input_lib_v1.DistributedDatasetsFromFunctionV1( + input_workers, strategy, input_contexts, dataset_fn, options) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/merge_call_interim.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/merge_call_interim.py new file mode 100644 index 0000000000000000000000000000000000000000..23337f4739cfe677e849e8573a2d0fca07c8aa1d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/merge_call_interim.py @@ -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. +# ============================================================================== +"""A module for interm merge-call related internal APIs.""" +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.distribute.strategy_supports_no_merge_call", v1=[]) +def strategy_supports_no_merge_call(): + """Returns if the current `Strategy` can operate in pure replica context.""" + if not distribute_lib.has_strategy(): + return True + strategy = distribute_lib.get_strategy() + return not strategy.extended._use_merge_call() # pylint: disable=protected-access + + +@tf_export("__internal__.distribute.interim.maybe_merge_call", v1=[]) +def maybe_merge_call(fn, strategy, *args, **kwargs): + """Maybe invoke `fn` via `merge_call` which may or may not be fulfilled. + + The caller of this utility function requests to invoke `fn` via `merge_call` + at `tf.distribute.Strategy`'s best efforts. It is `tf.distribute`'s internal + whether the request is honored, depending on the `Strategy`. See + `tf.distribute.ReplicaContext.merge_call()` for more information. + + This is an interim API which is subject to removal and does not guarantee + backward-compatibility. + + Args: + fn: the function to be invoked. + strategy: the `tf.distribute.Strategy` to call `fn` with. + *args: the positional arguments to be passed in to `fn`. + **kwargs: the keyword arguments to be passed in to `fn`. + + Returns: + The return value of the `fn` call. + """ + if strategy_supports_no_merge_call(): + return fn(strategy, *args, **kwargs) + else: + return distribute_lib.get_replica_context().merge_call( + fn, args=args, kwargs=kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/mirrored_run.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/mirrored_run.py new file mode 100644 index 0000000000000000000000000000000000000000..be58c82cf18b8ed8c3f085f1f151120fa333c91b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/mirrored_run.py @@ -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. +# ============================================================================== +"""Class MirroredStrategy implementing tf.distribute.Strategy.""" + +import contextlib +import threading +import weakref + +from tensorflow.python import pywrap_tfe +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import shared_variable_creator +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import ops +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import coordinator +from tensorflow.python.util import traceback_utils + + +def _is_gpu_device(device): + return tf_device.DeviceSpec.from_string(device).device_type == "GPU" + + +def call_for_each_replica(strategy, fn, args=None, kwargs=None): + """Call `fn` on each worker devices(replica). + + It's highly recommended to wrap the call to this function inside a + `tf.function`, otherwise the performance is poor. + + Args: + strategy: `tf.distribute.Strategy`. + fn: function to call on each worker devices. + args: positional arguments to `fn`. + kwargs: keyword arguments to `fn`. + + Returns: + Wrapped returned value of `fn` from all replicas. + """ + if args is None: + args = () + if kwargs is None: + kwargs = {} + + if isinstance(fn, def_function.Function): + # Don't lift up the tf.function decoration if `fn` is compiled with XLA + # and all devices are GPU. In this case we will use collectives to do + # cross-device communication, thus no merge_call is in the path. + if fn._jit_compile and all( # pylint: disable=protected-access + [_is_gpu_device(d) for d in strategy.extended.worker_devices]): + return _call_for_each_replica(strategy, fn, args, kwargs) + + if strategy not in _cfer_fn_cache: + _cfer_fn_cache[strategy] = weakref.WeakKeyDictionary() + wrapped = _cfer_fn_cache[strategy].get(fn) + if wrapped is None: + # We need to wrap fn such that it triggers _call_for_each_replica inside + # the tf.function. We use _clone() instead of @tf.function wrapped + # call_for_each_replica() because we would like to retain the arguments to + # the @tf.function decorator of fn. + def wrapped_fn(*args, **kwargs): + return call_for_each_replica(strategy, fn.python_function, args, kwargs) + + wrapped = fn._clone( # pylint: disable=protected-access + python_function=wrapped_fn) + _cfer_fn_cache[strategy][fn] = wrapped + return wrapped(*args, **kwargs) + + if context.executing_eagerly(): + logging.log_first_n( + logging.WARN, "Using %s eagerly has significant " + "overhead currently. We will be working on improving " + "this in the future, but for now please wrap " + "`call_for_each_replica` or `experimental_run` or " + "`run` inside a tf.function to get " + "the best performance." % strategy.__class__.__name__, 5) + else: + # When a tf.function is wrapped to trigger _call_for_each_replica (see + # the other branch above), AutoGraph stops conversion at + # _call_for_each_replica itself (TF library functions are allowlisted). + # This makes sure that the Python function that originally passed to + # the tf.function is still converted. + fn = autograph.tf_convert(fn, autograph_ctx.control_status_ctx()) + + return _call_for_each_replica(strategy, fn, args, kwargs) + + +# Per strategy cache for call_for_each_replica def_function.Function objects. +_cfer_fn_cache = weakref.WeakKeyDictionary() + + +@contextlib.contextmanager +def _enter_graph(g, eager, creator_stack=None): + """Context manager for selecting a graph and maybe eager mode.""" + if eager: + with g.as_default(), context.eager_mode(): + if creator_stack is not None: + g._variable_creator_stack = creator_stack # pylint: disable=protected-access + yield + else: + with g.as_default(): + if creator_stack is not None: + g._variable_creator_stack = creator_stack # pylint: disable=protected-access + yield + + +@contextlib.contextmanager +def _maybe_enter_eager_mode(eager): + if eager: + with context.eager_mode(): + yield + else: + yield + + +def _cpu_device(device): + cpu_device = tf_device.DeviceSpec.from_string(device) + cpu_device = cpu_device.replace(device_type="CPU", device_index=0) + return cpu_device.to_string() + + +class _RequestedStop(Exception): # pylint: disable=g-bad-exception-name + pass + + +def _get_thread_local_configuration_callable(): + if traceback_utils.is_traceback_filtering_enabled(): + thread_local_callables = {traceback_utils.enable_traceback_filtering} + else: + thread_local_callables = {traceback_utils.disable_traceback_filtering} + return thread_local_callables + + +def _call_for_each_replica(distribution, fn, args, kwargs): + """Run `fn` in separate threads, once per replica/worker device. + + Args: + distribution: the DistributionStrategy object. + fn: function to run (will be run once per replica, each in its own thread). + args: positional arguments for `fn` + kwargs: keyword arguments for `fn`. + + Returns: + Merged return value of `fn` across all replicas. + + Raises: + RuntimeError: If fn() calls get_replica_context().merge_call() a different + number of times from the available devices. + """ + # TODO(josh11b): Add this option once we add synchronization to variable + # creation. Until then, this is pretty unsafe to use. + run_concurrently = False + if not context.executing_eagerly(): + # Needed for per-thread device, etc. contexts in graph mode. + ops.get_default_graph().switch_to_thread_local() + + coord = coordinator.Coordinator(clean_stop_exception_types=(_RequestedStop,)) + + shared_variable_store = {} + devices = distribution.extended.worker_devices + + thread_local_callables = _get_thread_local_configuration_callable() + + # TODO(isaprykin): Create these threads once instead of during every call. + threads = [] + for index in range(len(devices)): + variable_creator_fn = shared_variable_creator.make_fn( + shared_variable_store, index) + t = _MirroredReplicaThread(distribution, coord, index, devices, + variable_creator_fn, fn, + distribute_utils.caching_scope_local, + distribute_utils.select_replica(index, args), + distribute_utils.select_replica(index, kwargs), + thread_local_callables) + threads.append(t) + + for t in threads: + t.start() + + # When `fn` starts `should_run` event is set on _MirroredReplicaThread + # (`MRT`) threads. The execution waits until + # `MRT.has_paused` is set, which indicates that either `fn` is + # complete or a `get_replica_context().merge_call()` is called. If `fn` is + # complete, then `MRT.done` is set to True. Otherwise, arguments + # of `get_replica_context().merge_call` from all paused threads are grouped + # and the `merge_fn` is performed. Results of the + # `get_replica_context().merge_call` are then set to `MRT.merge_result`. + # Each such `get_replica_context().merge_call` call returns the + # `MRT.merge_result` for that thread when `MRT.should_run` event + # is reset again. Execution of `fn` resumes. + + try: + with coord.stop_on_exception(): + all_done = False + while not all_done and not coord.should_stop(): + done = [] + if run_concurrently: + for t in threads: + t.should_run.set() + for t in threads: + t.has_paused.wait() + t.has_paused.clear() + if coord.should_stop(): + return None + done.append(t.done) + else: + for t in threads: + t.should_run.set() + t.has_paused.wait() + t.has_paused.clear() + if coord.should_stop(): + return None + done.append(t.done) + if coord.should_stop(): + return None + all_done = all(done) + if not all_done: + if any(done): + raise RuntimeError("Some replicas made a different number of " + "replica_context().merge_call() calls.") + # get_replica_context().merge_call() case + merge_args = distribute_utils.regroup( + tuple(t.merge_args for t in threads)) + merge_kwargs = distribute_utils.regroup( + tuple(t.merge_kwargs for t in threads)) + # We capture the name_scope of the MRT when we call merge_fn + # to ensure that if we have opened a name scope in the MRT, + # it will be respected when executing the merge function. We only + # capture the name_scope from the first MRT and assume it is + # the same for all other MRTs. + mtt_captured_name_scope = threads[0].captured_name_scope + mtt_captured_var_scope = threads[0].captured_var_scope + # Capture and merge the control dependencies from all the threads. + mtt_captured_control_deps = set() + for t in threads: + mtt_captured_control_deps.update(t.captured_control_deps) + + # Control is transfered from _MirroredReplicaThread (MRT) to the main + # thread, i.e., here, to perform `merge_fn`, and thus we preserve the + # name scope, control dependencies, etc. from MRT at the time + # `merge_call` is made. + # One special case is that the `merge_call` is made under an + # `tf.init_scope` in the MRT. `tf.init_scope` will clear control + # dependencies, pause gradient tape, and enter the lowest context on + # the `context_stack` that is not building a graph function. Entering + # the lowest context could be one of the two things: installation of a + # graph as the default graph or switch into eager mode. If the former + # is done and causes `merge_call` to be called in a different graph + # from the one in which `call_for_each_replica` is called, we do not + # allow this case (see comment in `_merge_call`) and we would not have + # arrived here due to the assertion in `_merge_call`. However, if the + # latter is done, we want to make sure the main thread enter an eager + # mode scope as well so that `merge_fn` does not have trouble + # accessing resources defined in MRT under the same context. + with ops.name_scope( + mtt_captured_name_scope), ops.control_dependencies( + mtt_captured_control_deps), variable_scope.variable_scope( + mtt_captured_var_scope), _maybe_enter_eager_mode( + threads[0].merge_call_entered_in_eager): + merge_result = threads[0].merge_fn(distribution, *merge_args, + **merge_kwargs) + for r, t in enumerate(threads): + t.merge_result = distribute_utils.select_replica(r, merge_result) + finally: + for t in threads: + t.should_run.set() + coord.join(threads) + + return distribute_utils.regroup(tuple(t.main_result for t in threads)) + + +class _MirroredReplicaThread(threading.Thread): + """A thread that runs() a function on a device.""" + + def __init__(self, dist, coord, replica_id, devices, variable_creator_fn, fn, + caching_scope, args, kwargs, thread_local_callables=None): + super(_MirroredReplicaThread, self).__init__() + self.coord = coord + self.distribution = dist + self.devices = devices + self.replica_id = replica_id + self.replica_id_in_sync_group = ( + dist.extended._get_replica_id_in_sync_group(replica_id)) # pylint: disable=protected-access + + self.variable_creator_fn = variable_creator_fn + # State needed to run and return the results of `fn`. + self.main_fn = fn + self.main_args = args + self.main_kwargs = kwargs + self.main_result = None + self.done = False + # State needed to run the next merge_call() (if any) requested via + # ReplicaContext. + self.merge_fn = None + self.merge_args = None + self.merge_kwargs = None + self.merge_result = None + self.captured_name_scope = None + self.captured_var_scope = None + try: + self.caching_scope_entered = caching_scope.new_cache_scope_count + self.caching_scope_exited = caching_scope.cache_scope_exited_count + except AttributeError: + self.caching_scope_entered = None + self.caching_scope_exited = None + + # We use a thread.Event for the main thread to signal when this + # thread should start running (`should_run`), and another for + # this thread to transfer control back to the main thread + # (`has_paused`, either when it gets to a + # `get_replica_context().merge_call` or when `fn` returns). In + # either case the event starts cleared, is signaled by calling + # set(). The receiving thread waits for the signal by calling + # wait() and then immediately clearing the event using clear(). + self.should_run = threading.Event() + self.has_paused = threading.Event() + # These fields have to do with inheriting various contexts from the + # parent thread: + context.ensure_initialized() + ctx = context.context() + self.in_eager = ctx.executing_eagerly() + self.record_thread_local_summary_state() + self.record_thread_local_eager_context_state() + self.context_device_policy = ( + pywrap_tfe.TFE_ContextGetDevicePlacementPolicy( + ctx._context_handle)) # pylint: disable=protected-access + self.graph = ops.get_default_graph() + with ops.init_scope(): + self._init_in_eager = context.executing_eagerly() + self._init_graph = ops.get_default_graph() + self._variable_creator_stack = self.graph._variable_creator_stack[:] # pylint: disable=protected-access + self._var_scope = variable_scope.get_variable_scope() + # Adding a "/" at end lets us re-enter this scope later. + self._name_scope = self.graph.get_name_scope() + if self._name_scope: + self._name_scope += "/" + if self.replica_id > 0: + if not self._name_scope: + self._name_scope = "" + self._name_scope += "replica_%d/" % self.replica_id + + self._thread_local_callables = thread_local_callables + + def run(self): + self.should_run.wait() + self.should_run.clear() + try: + if self.coord.should_stop(): + return + self.restore_thread_local_summary_state() + self.restore_thread_local_callable() + self.restore_thread_local_eager_context_state() + if (self.caching_scope_entered is not None and + self.caching_scope_exited is not None): + distribute_utils.caching_scope_local.new_cache_scope_count = self.caching_scope_entered + distribute_utils.caching_scope_local.cache_scope_exited_count = self.caching_scope_exited + # TODO(josh11b): Use current logical device instead of 0 here. + with self.coord.stop_on_exception(), \ + _enter_graph(self._init_graph, self._init_in_eager), \ + _enter_graph(self.graph, self.in_eager, + self._variable_creator_stack), \ + context.device_policy(self.context_device_policy), \ + _MirroredReplicaContext(self.distribution, + self.replica_id_in_sync_group), \ + ops.device(self.devices[self.replica_id]), \ + ops.name_scope(self._name_scope), \ + variable_scope.variable_scope( + self._var_scope, reuse=self.replica_id > 0), \ + variable_scope.variable_creator_scope(self.variable_creator_fn): + self.main_result = self.main_fn(*self.main_args, **self.main_kwargs) + self.done = True + finally: + self.has_paused.set() + + def record_thread_local_summary_state(self): + """Record the thread local summary state in self.""" + # TODO(slebedev): is this still relevant? the referenced bug is closed. + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + self._summary_step = summary_state.step + self._summary_writer = summary_state.writer + self._summary_recording = summary_state.is_recording + self._summary_recording_distribution_strategy = ( + summary_state.is_recording_distribution_strategy) + + def restore_thread_local_summary_state(self): + """Restore thread local summary state from self.""" + # TODO(slebedev): is this still relevant? the referenced bug is closed. + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + summary_state.step = self._summary_step + summary_state.writer = self._summary_writer + summary_state.is_recording = self._summary_recording + summary_state.is_recording_distribution_strategy = ( + self._summary_recording_distribution_strategy) + + def record_thread_local_eager_context_state(self): + ctx = context.context() + eager_context_state = ctx._thread_local_data # pylint: disable=protected-access + self._eager_context_op_callbacks = eager_context_state.op_callbacks + # TODO(b/125892694): record other fields in EagerContext. + + def restore_thread_local_eager_context_state(self): + ctx = context.context() + eager_context_state = ctx._thread_local_data # pylint: disable=protected-access + eager_context_state.op_callbacks = self._eager_context_op_callbacks + # TODO(b/125892694): record other fields in EagerContext. + + def restore_thread_local_callable(self): + if self._thread_local_callables: + for fn in self._thread_local_callables: + fn() + + +class _MirroredReplicaContext(distribute_lib.ReplicaContext): + """ReplicaContext for synchronized replica.""" + + def _merge_call(self, fn, args, kwargs): + """`merge_call()` implementation for synchronized replica. + + This pauses the current replica thread and passes `fn` and its arguments to + the main thread. The main thread will wait until all replicas pause, then + invoke `fn` with grouped arguments. The current replica thread will continue + after `fn` completes. + + See `_call_for_each_replica` for the logic in the main thread. + + Args: + fn: a function that is called in cross replica context with grouped + arguments from each replica. `fn` should returns grouped values. + args: positional arguments to `fn`. + kwargs: keyward arguments to `fn`. + + Returns: + Return value of `fn` for the current replica. + + Raises: + RuntimeError: when merge_call happens in a different graph, e.g. in a + different tf.function, which is not supported now. + _RequestedStop: when stop is requested. + + """ + t = threading.current_thread() + assert isinstance(t, _MirroredReplicaThread) + t.merge_fn = fn + t.merge_args = args + t.merge_kwargs = kwargs + t.captured_name_scope = t.graph.get_name_scope() + # Adding a "/" at end lets us re-enter this scope later. + if t.captured_name_scope: + t.captured_name_scope += "/" + + t.captured_var_scope = variable_scope.get_variable_scope() + t.captured_control_deps = t.graph._current_control_dependencies() # pylint: disable=protected-access + + t.merge_call_entered_in_eager = context.context().executing_eagerly() + + # It is problematic if `merge_call` is called under a different graph other + # than the one that `_call_for_each_replica` is called under, there are + # 3 cases this can happen: + # + # 1. The `fn` passed to `_call_for_each_replica` is decorated with + # `tf.function` and there is a `merge_call` in `fn`. Since + # MirroredStrategy traces a separate function per thread (per device), + # and each trace takes a shared lock, the lock is never released by the + # first thread and subsequent replica threads cannot proceed to trace + # their own functions. This issue is addressed by always converting + # `_call_for_each_replica(tf.function(f))` to + # ``tf.function(_call_for_each_replica(f))`.` in + # `MirroredStrategy._call_for_each_replica`. + # + # 2. The `fn` passed to `_call_for_each_replica` contains a nested + # `tf.function`, and there is a `merge_call` in the nested `tf.function`. + # In this case each thread can successfully trace its own function, but + # since the `merge_fn` passed to `merge_call` is executed in the main + # thread (where `_call_for_each_replica` is executed), it can't access + # the tensors that come from different graphs. + # + # 3. The `fn` passed to `_call_for_each_replica` contains a control-flow + # statement, and there is a `merge_call` inside the control-flow body, + # `fn` or `_call_for_each_replica` is decorated with `tf.function`. + # Control flow statement creates a separate graph for its body, similar + # to #2, `merge_fn` executed in the main thread can't access the + # tensors that come from different graphs. + # + # We raise an error for #2 and #3. + if ops.get_default_graph() != t.graph: + raise RuntimeError( + "`merge_call` called while defining a new graph or a tf.function." + " This can often happen if the function `fn` passed to" + " `strategy.run()` contains a nested `@tf.function`, and the nested " + "`@tf.function` contains a synchronization point, such as aggregating" + " gradients (e.g, optimizer.apply_gradients), or if the function `fn`" + " uses a control flow statement which contains a synchronization" + " point in the body. Such behaviors are not yet supported. Instead," + " please avoid nested `tf.function`s or control flow statements that" + " may potentially cross a synchronization boundary, for example," + " wrap the `fn` passed to `strategy.run` or the entire `strategy.run`" + " inside a `tf.function` or move the control flow out of `fn`. If" + " you are subclassing a `tf.keras.Model`, please avoid decorating" + " overridden methods `test_step` and `train_step` in `tf.function`.") + + t.has_paused.set() + t.should_run.wait() + t.should_run.clear() + if t.coord.should_stop(): + raise _RequestedStop() + t.merge_call_entered_in_eager = None + return t.merge_result + + @property + def devices(self): + distribute_lib.require_replica_context(self) + return [ + self._strategy.extended.worker_devices_by_replica[ + self._replica_id_in_sync_group] + ] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/mirrored_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/mirrored_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..3be22ea30837e05c5bd3015d9c416b06a6457b76 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/mirrored_strategy.py @@ -0,0 +1,941 @@ +# 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. +# ============================================================================== +"""Class MirroredStrategy implementing tf.distribute.Strategy.""" + +import copy + +from tensorflow.python import tf2 +from tensorflow.python.distribute import collective_util +from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib +from tensorflow.python.distribute import cross_device_utils +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import input_util +from tensorflow.python.distribute import mirrored_run +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute import numpy_dataset +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import values +from tensorflow.python.distribute import values_util +from tensorflow.python.distribute.cluster_resolver import tfconfig_cluster_resolver +from tensorflow.python.distribute.v1 import input_lib as input_lib_v1 +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import while_loop +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +# TODO(josh11b): Replace asserts in this file with if ...: raise ... + + +def _is_device_list_single_worker(devices): + """Checks whether the devices list is for single or multi-worker. + + Args: + devices: a list of device strings or tf.config.LogicalDevice objects, for + either local or for remote devices. + + Returns: + a boolean indicating whether these device strings are for local or for + remote. + + Raises: + ValueError: if device strings are not consistent. + """ + specs = [] + for d in devices: + name = d.name if isinstance(d, context.LogicalDevice) else d + specs.append(tf_device.DeviceSpec.from_string(name)) + num_workers = len({(d.job, d.task, d.replica) for d in specs}) + all_local = all(d.job in (None, "localhost") for d in specs) + any_local = any(d.job in (None, "localhost") for d in specs) + + if any_local and not all_local: + raise ValueError("Local device should have only 'localhost' in the job " + "field in device string. " + "E.g. 'job:localhost' in " + "/job:localhost/replica:0/task:0/device:CPU:0" + "Devices cannot have mixed list of device strings " + "containing both localhost and other job types such as " + "worker, ps etc. ") + + if num_workers == 1 and not all_local: + if any(d.task is None for d in specs): + raise ValueError("Remote device string must have task specified." + "E.g. 'task:0' in " + "/job:worker/replica:0/task:0/device:CPU:0") + + return num_workers == 1 + + +def _cluster_spec_to_device_list(cluster_spec, num_gpus_per_worker): + """Returns a device list given a cluster spec.""" + cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec) + devices = [] + for task_type in ("chief", "worker"): + for task_id in range(len(cluster_spec.as_dict().get(task_type, []))): + if num_gpus_per_worker == 0: + devices.append("/job:%s/task:%d/device:CPU:0" % (task_type, task_id)) + else: + devices.extend([ + "/job:%s/task:%d/device:GPU:%i" % (task_type, task_id, gpu_id) + for gpu_id in range(num_gpus_per_worker) + ]) + return devices + + +def _group_device_list(devices): + """Groups the devices list by task_type and task_id. + + Args: + devices: a list of device strings for remote devices. + + Returns: + a dict of list of device strings mapping from task_type to a list of devices + for the task_type in the ascending order of task_id. + """ + assert not _is_device_list_single_worker(devices) + device_dict = {} + + for d in devices: + d_spec = tf_device.DeviceSpec.from_string(d) + + # Create an entry for the task_type. + if d_spec.job not in device_dict: + device_dict[d_spec.job] = [] + + # Fill the device list for task_type until it covers the task_id. + while len(device_dict[d_spec.job]) <= d_spec.task: + device_dict[d_spec.job].append([]) + + device_dict[d_spec.job][d_spec.task].append(d) + + return device_dict + + +def _is_gpu_device(device): + return tf_device.DeviceSpec.from_string(device).device_type == "GPU" + + +def _infer_num_gpus_per_worker(devices): + """Infers the number of GPUs on each worker. + + Currently to make multi-worker cross device ops work, we need all workers to + have the same number of GPUs. + + Args: + devices: a list of device strings, can be either local devices or remote + devices. + + Returns: + number of GPUs per worker. + + Raises: + ValueError if workers have different number of GPUs or GPU indices are not + consecutive and starting from 0. + """ + if _is_device_list_single_worker(devices): + return sum(1 for d in devices if _is_gpu_device(d)) + else: + device_dict = _group_device_list(devices) + num_gpus = None + for _, devices_in_task in device_dict.items(): + for device_in_task in devices_in_task: + if num_gpus is None: + num_gpus = sum(1 for d in device_in_task if _is_gpu_device(d)) + + # Verify other workers have the same number of GPUs. + elif num_gpus != sum(1 for d in device_in_task if _is_gpu_device(d)): + raise ValueError("All workers should have the same number of GPUs.") + + for d in device_in_task: + d_spec = tf_device.DeviceSpec.from_string(d) + if (d_spec.device_type == "GPU" and + d_spec.device_index >= num_gpus): + raise ValueError("GPU `device_index` on a worker should be " + "consecutive and start from 0.") + return num_gpus + + +def all_local_devices(num_gpus=None): + devices = config.list_logical_devices("GPU") + if num_gpus is not None: + devices = devices[:num_gpus] + return devices or config.list_logical_devices("CPU") + + +def all_devices(): + devices = [] + tfconfig = tfconfig_cluster_resolver.TFConfigClusterResolver() + if tfconfig.cluster_spec().as_dict(): + devices = _cluster_spec_to_device_list(tfconfig.cluster_spec(), + context.num_gpus()) + return devices if devices else all_local_devices() + + +@tf_export("distribute.MirroredStrategy", v1=[]) # pylint: disable=g-classes-have-attributes +class MirroredStrategy(distribute_lib.Strategy): + """Synchronous training across multiple replicas on one machine. + + This strategy is typically used for training on one + machine with multiple GPUs. For TPUs, use + `tf.distribute.TPUStrategy`. To use `MirroredStrategy` with multiple workers, + please refer to `tf.distribute.experimental.MultiWorkerMirroredStrategy`. + + For example, a variable created under a `MirroredStrategy` is a + `MirroredVariable`. If no devices are specified in the constructor argument of + the strategy then it will use all the available GPUs. If no GPUs are found, it + will use the available CPUs. Note that TensorFlow treats all CPUs on a + machine as a single device, and uses threads internally for parallelism. + + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> with strategy.scope(): + ... x = tf.Variable(1.) + >>> x + MirroredVariable:{ + 0: , + 1: + } + + While using distribution strategies, all the variable creation should be done + within the strategy's scope. This will replicate the variables across all the + replicas and keep them in sync using an all-reduce algorithm. + + Variables created inside a `MirroredStrategy` which is wrapped with a + `tf.function` are still `MirroredVariables`. + + >>> x = [] + >>> @tf.function # Wrap the function with tf.function. + ... def create_variable(): + ... if not x: + ... x.append(tf.Variable(1.)) + ... return x[0] + >>> strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]) + >>> with strategy.scope(): + ... _ = create_variable() + ... print(x[0]) + MirroredVariable:{ + 0: , + 1: + } + + `experimental_distribute_dataset` can be used to distribute the dataset across + the replicas when writing your own training loop. If you are using `.fit` and + `.compile` methods available in `tf.keras`, then `tf.keras` will handle the + distribution for you. + + For example: + + ```python + my_strategy = tf.distribute.MirroredStrategy() + with my_strategy.scope(): + @tf.function + def distribute_train_epoch(dataset): + def replica_fn(input): + # process input and return result + return result + + total_result = 0 + for x in dataset: + per_replica_result = my_strategy.run(replica_fn, args=(x,)) + total_result += my_strategy.reduce(tf.distribute.ReduceOp.SUM, + per_replica_result, axis=None) + return total_result + + dist_dataset = my_strategy.experimental_distribute_dataset(dataset) + for _ in range(EPOCHS): + train_result = distribute_train_epoch(dist_dataset) + ``` + + Args: + devices: a list of device strings such as `['/gpu:0', '/gpu:1']`. If + `None`, all available GPUs are used. If no GPUs are found, CPU is used. + cross_device_ops: optional, a descendant of `CrossDeviceOps`. If this is not + set, `NcclAllReduce()` will be used by default. One would customize this + if NCCL isn't available or if a special implementation that exploits + the particular hardware is available. + """ + + # Only set this in tests. + _collective_key_base = 0 + + def __init__(self, devices=None, cross_device_ops=None): + extended = MirroredExtended( + self, devices=devices, cross_device_ops=cross_device_ops) + super(MirroredStrategy, self).__init__(extended) + distribute_lib.distribution_strategy_gauge.get_cell("V2").set( + "MirroredStrategy") + + +@tf_export(v1=["distribute.MirroredStrategy"]) +class MirroredStrategyV1(distribute_lib.StrategyV1): # pylint: disable=g-missing-docstring + + __doc__ = MirroredStrategy.__doc__ + + # Only set this in tests. + _collective_key_base = 0 + + def __init__(self, devices=None, cross_device_ops=None): + extended = MirroredExtended( + self, devices=devices, cross_device_ops=cross_device_ops) + super(MirroredStrategyV1, self).__init__(extended) + distribute_lib.distribution_strategy_gauge.get_cell("V1").set( + "MirroredStrategy") + + +# TODO(josh11b): Switch to V2 when we no longer need to support tf.compat.v1. +class MirroredExtended(distribute_lib.StrategyExtendedV1): + """Implementation of MirroredStrategy.""" + + def __init__(self, container_strategy, devices=None, cross_device_ops=None): + super(MirroredExtended, self).__init__(container_strategy) + if context.executing_eagerly(): + if devices and not _is_device_list_single_worker(devices): + raise RuntimeError("In-graph multi-worker training with " + "`MirroredStrategy` is not supported in eager mode.") + else: + if ( + tfconfig_cluster_resolver.TFConfigClusterResolver() + .cluster_spec() + .as_dict() + ): + # if you are executing in eager mode, only the single machine code + # path is supported. + logging.info("Initializing local devices since in-graph multi-worker " + "training with `MirroredStrategy` is not supported in " + "eager mode. TF_CONFIG will be ignored when " + "when initializing `MirroredStrategy`.") + devices = devices or all_local_devices() + else: + devices = devices or all_devices() + + assert devices, ("Got an empty `devices` list and unable to recognize " + "any local devices.") + + self._collective_key_base = container_strategy._collective_key_base + self._communication_options = collective_util.Options( + implementation=collective_util.CommunicationImplementation.NCCL) + self._cross_device_ops = cross_device_ops + self._initialize_strategy(devices) + + # TODO(b/128995245): Enable last partial batch support in graph mode. + if ops.executing_eagerly_outside_functions(): + self.experimental_enable_get_next_as_optional = True + + # Flag to turn on VariablePolicy. + self._use_var_policy = False + + def _use_merge_call(self): + # We currently only disable merge_call when XLA is used to compile the `fn` + # passed to `strategy.run` and all devices are GPU. + return not control_flow_util.GraphOrParentsInXlaContext( + ops.get_default_graph()) or not all( + [_is_gpu_device(d) for d in self._devices]) + + def _initialize_strategy(self, devices): + # The _initialize_strategy method is intended to be used by distribute + # coordinator as well. + assert devices, "Must specify at least one device." + devices = tuple(device_util.resolve(d) for d in devices) + assert len(set(devices)) == len(devices), ( + "No duplicates allowed in `devices` argument: %s" % (devices,)) + + self._initialize_single_worker(devices) + + self._collective_ops = self._make_collective_ops_with_fallbacks() + # If cross_device_ops is not provided, set it to collective op by default. + if not self._cross_device_ops: + self._cross_device_ops = self._collective_ops + + def _make_collective_ops_with_fallbacks(self): + self._collective_keys = cross_device_utils.CollectiveKeys( + group_key_start=1 + self._collective_key_base) + + if not ops.executing_eagerly_outside_functions() and any( + "gpu" not in d.lower() for d in self._devices): + # In TF1/Session, fall back to ReductionToOneDevice() if there are + # non-GPU devices or virtual GPUs are used. + return cross_device_ops_lib.ReductionToOneDevice() + + # Use ReductionToOneDevice() if mixed devices are used. + if any("cpu" in d.lower() for d in self._devices) and any( + "gpu" in d.lower() for d in self._devices): + return cross_device_ops_lib.ReductionToOneDevice() + + if all("cpu" in d.lower() for d in self._devices): + # Use RING collective ops if all devices are CPU. + self._communication_options = collective_util.Options( + implementation=collective_util.CommunicationImplementation.RING) + + else: + physical_gpus = context.context().list_physical_devices(device_type="GPU") + logical_gpus = context.context().list_logical_devices(device_type="GPU") + # Use RING collective ops if virtual devices are used. + if len(physical_gpus) < len(logical_gpus): + self._communication_options = collective_util.Options( + implementation=collective_util.CommunicationImplementation.RING) + + # If all devices are physical GPU, use NCCL implementation. + return cross_device_ops_lib.CollectiveAllReduce( + devices=self._devices, + group_size=len(self._devices), + options=self._communication_options, + collective_keys=self._collective_keys) + + def _initialize_single_worker(self, devices): + """Initializes the object for single-worker training.""" + self._devices = tuple(device_util.canonicalize(d) for d in devices) + self._input_workers_devices = ( + (device_util.canonicalize("/device:CPU:0", devices[0]), devices),) + + self._host_input_device = numpy_dataset.SingleDevice( + self._input_workers_devices[0][0]) + device_spec = tf_device.DeviceSpec.from_string( + self._input_workers_devices[0][0]) + # Ensures when we enter strategy.scope() we use the correct default device + if device_spec.job is not None and device_spec.job != "localhost": + self._default_device = "/job:%s/replica:%d/task:%d" % ( + device_spec.job, device_spec.replica, device_spec.task) + + logging.info("Using MirroredStrategy with devices %r", devices) + + def _initialize_multi_worker(self, devices): + """Initializes the object for multi-worker training.""" + device_dict = _group_device_list(devices) + workers = [] + worker_devices = [] + for job in ("chief", "worker"): + for task in range(len(device_dict.get(job, []))): + worker = "/job:%s/task:%d" % (job, task) + workers.append(worker) + worker_devices.append((worker, device_dict[job][task])) + + # Setting `_default_device` will add a device scope in the + # distribution.scope. We set the default device to the first worker. When + # users specify device under distribution.scope by + # with tf.device("/cpu:0"): + # ... + # their ops will end up on the cpu device of its first worker, e.g. + # "/job:worker/task:0/device:CPU:0". Note this is not used in replica mode. + self._default_device = workers[0] + self._host_input_device = numpy_dataset.SingleDevice(workers[0]) + + self._devices = tuple(devices) + self._input_workers_devices = worker_devices + self._is_multi_worker_training = True + + if len(workers) > 1: + # Grandfather usage in the legacy tests if they're configured properly. + if (not isinstance(self._cross_device_ops, + cross_device_ops_lib.ReductionToOneDevice) or + self._cross_device_ops._num_between_graph_workers > 1): # pylint: disable=protected-access + raise ValueError( + "In-graph multi-worker training with `MirroredStrategy` is not " + "supported.") + self._inferred_cross_device_ops = self._cross_device_ops + else: + # TODO(yuefengz): make `select_cross_device_ops` work with device strings + # containing job names. + self._inferred_cross_device_ops = cross_device_ops_lib.NcclAllReduce() + + logging.info("Using MirroredStrategy with remote devices %r", devices) + + def _input_workers_with_options(self, options=None): + if not options: + return input_lib.InputWorkers(self._input_workers_devices) + if (options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + if options.experimental_place_dataset_on_device: + self._input_workers_devices = ( + tuple( + (device_util.canonicalize(d, d), (d,)) for d in self._devices)) + else: + self._input_workers_devices = ( + tuple((device_util.canonicalize("/device:CPU:0", d), (d,)) + for d in self._devices)) + return input_lib.InputWorkers(self._input_workers_devices) + else: + if not options.experimental_fetch_to_device: + return input_lib.InputWorkers([ + (host_device, (host_device,) * len(compute_devices)) + for host_device, compute_devices in self._input_workers_devices + ]) + else: + return input_lib.InputWorkers(self._input_workers_devices) + + @property + def _input_workers(self): + return self._input_workers_with_options() + + def _get_variable_creator_initial_value(self, + replica_id, + device, + primary_var, + **kwargs): + """Return the initial value for variables on a replica.""" + if replica_id == 0: + return kwargs["initial_value"] + else: + assert primary_var is not None + assert device is not None + assert kwargs is not None + + def initial_value_fn(): + if context.executing_eagerly() or ops.inside_function(): + init_value = primary_var.value() + return array_ops.identity(init_value) + else: + with ops.device(device): + init_value = primary_var.initial_value + return array_ops.identity(init_value) + + return initial_value_fn + + def _create_variable(self, next_creator, **kwargs): + """Create a mirrored variable. See `DistributionStrategy.scope`.""" + colocate_with = kwargs.pop("colocate_with", None) + if colocate_with is None: + devices = self._devices + elif isinstance(colocate_with, numpy_dataset.SingleDevice): + with ops.device(colocate_with.device): + return next_creator(**kwargs) + else: + devices = colocate_with._devices # pylint: disable=protected-access + + def _real_mirrored_creator(**kwargs): # pylint: disable=g-missing-docstring + value_list = [] + for i, d in enumerate(devices): + with ops.device(d): + kwargs["initial_value"] = self._get_variable_creator_initial_value( + replica_id=i, + device=d, + primary_var=value_list[0] if value_list else None, + **kwargs) + if i > 0: + # Give replicas meaningful distinct names: + var0name = value_list[0].name.split(":")[0] + # We append a / to variable names created on replicas with id > 0 to + # ensure that we ignore the name scope and instead use the given + # name as the absolute name of the variable. + kwargs["name"] = "%s/replica_%d/" % (var0name, i) + with context.device_policy(context.DEVICE_PLACEMENT_SILENT): + # Don't record operations (e.g. other variable reads) during + # variable creation. + with record.stop_recording(): + v = next_creator(**kwargs) + assert not isinstance(v, values.DistributedVariable) + value_list.append(v) + return value_list + + return distribute_utils.create_mirrored_variable( + self._container_strategy(), _real_mirrored_creator, + distribute_utils.VARIABLE_CLASS_MAPPING, + distribute_utils.VARIABLE_POLICY_MAPPING, **kwargs) + + def _validate_colocate_with_variable(self, colocate_with_variable): + distribute_utils.validate_colocate_distributed_variable( + colocate_with_variable, self) + + def _make_dataset_iterator(self, dataset): + return input_lib_v1.DatasetIterator( + dataset, + self._input_workers, + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync) + + def _make_input_fn_iterator( + self, + input_fn, + replication_mode=distribute_lib.InputReplicationMode.PER_WORKER): + input_contexts = [] + num_workers = self._input_workers.num_workers + for i in range(num_workers): + input_contexts.append(distribute_lib.InputContext( + num_input_pipelines=num_workers, + input_pipeline_id=i, + num_replicas_in_sync=self._num_replicas_in_sync)) + return input_lib_v1.InputFunctionIterator(input_fn, self._input_workers, + input_contexts, + self._container_strategy()) + + def _experimental_distribute_dataset(self, dataset, options): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`distribute_datasets_from_function`." + ) + return input_util.get_distributed_dataset( + dataset, + self._input_workers_with_options(options), + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync, + options=options) + + def _experimental_make_numpy_dataset(self, numpy_input, session): + return numpy_dataset.one_host_numpy_dataset( + numpy_input, self._host_input_device, session) + + def _distribute_datasets_from_function(self, dataset_fn, options): + input_workers = self._input_workers_with_options(options) + input_contexts = [] + num_workers = input_workers.num_workers + for i in range(num_workers): + input_contexts.append(distribute_lib.InputContext( + num_input_pipelines=num_workers, + input_pipeline_id=i, + num_replicas_in_sync=self._num_replicas_in_sync)) + + return input_util.get_distributed_datasets_from_function( + dataset_fn, input_workers, input_contexts, self._container_strategy(), + options) + + def _experimental_distribute_values_from_function(self, value_fn): + per_replica_values = [] + for replica_id in range(self._num_replicas_in_sync): + per_replica_values.append(value_fn( + distribute_lib.ValueContext(replica_id, + self._num_replicas_in_sync))) + return distribute_utils.regroup(per_replica_values, always_wrap=True) + + # TODO(priyag): Deal with OutOfRange errors once b/111349762 is fixed. + def _experimental_run_steps_on_iterator(self, fn, iterator, iterations, + initial_loop_values=None): + if initial_loop_values is None: + initial_loop_values = {} + initial_loop_values = nest.flatten(initial_loop_values) + + ctx = input_lib.MultiStepContext() + def body(i, *args): + """A wrapper around `fn` to create the while loop body.""" + del args + fn_result = fn(ctx, iterator.get_next()) + for (name, output) in ctx.last_step_outputs.items(): + # Convert all outputs to tensors, potentially from `DistributedValues`. + ctx.last_step_outputs[name] = self._local_results(output) + flat_last_step_outputs = nest.flatten(ctx.last_step_outputs) + with ops.control_dependencies([fn_result]): + return [i + 1] + flat_last_step_outputs + + # We capture the control_flow_context at this point, before we run `fn` + # inside a while_loop. This is useful in cases where we might need to exit + # these contexts and get back to the outer context to do some things, for + # e.g. create an op which should be evaluated only once at the end of the + # loop on the host. One such usage is in creating metrics' value op. + self._outer_control_flow_context = ( + ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access + + cond = lambda i, *args: i < iterations + i = constant_op.constant(0) + loop_result = while_loop.while_loop( + cond, + body, [i] + initial_loop_values, + name="", + parallel_iterations=1, + back_prop=False, + swap_memory=False, + return_same_structure=True) + del self._outer_control_flow_context + + ctx.run_op = control_flow_ops.group(loop_result) + + # Convert the last_step_outputs from a list to the original dict structure + # of last_step_outputs. + last_step_tensor_outputs = loop_result[1:] + last_step_tensor_outputs_dict = nest.pack_sequence_as( + ctx.last_step_outputs, last_step_tensor_outputs) + + for name, reduce_op in ctx._last_step_outputs_reduce_ops.items(): # pylint: disable=protected-access + output = last_step_tensor_outputs_dict[name] + # For outputs that have already been reduced, wrap them in a Mirrored + # container, else in a PerReplica container. + if reduce_op is None: + last_step_tensor_outputs_dict[name] = distribute_utils.regroup(output) + else: + assert len(output) == 1 + last_step_tensor_outputs_dict[name] = output[0] + + ctx._set_last_step_outputs(last_step_tensor_outputs_dict) # pylint: disable=protected-access + return ctx + + def _broadcast_to(self, tensor, destinations): + # This is both a fast path for Python constants, and a way to delay + # converting Python values to a tensor until we know what type it + # should be converted to. Otherwise we have trouble with: + # global_step.assign_add(1) + # since the `1` gets broadcast as an int32 but global_step is int64. + if isinstance(tensor, (float, int)): + return tensor + # TODO(josh11b): In eager mode, use one thread per device, or async mode. + if not destinations: + # TODO(josh11b): Use current logical device instead of 0 here. + destinations = self._devices + return self._get_cross_device_ops(tensor).broadcast(tensor, destinations) + + def _call_for_each_replica(self, fn, args, kwargs): + return mirrored_run.call_for_each_replica( + self._container_strategy(), fn, args, kwargs) + + def _configure(self, + session_config=None, + cluster_spec=None, + task_type=None, + task_id=None): + del task_type, task_id + + if session_config: + session_config.CopyFrom(self._update_config_proto(session_config)) + + if cluster_spec: + # TODO(yuefengz): remove the following code once cluster_resolver is + # added. + num_gpus_per_worker = _infer_num_gpus_per_worker(self._devices) + multi_worker_devices = _cluster_spec_to_device_list( + cluster_spec, num_gpus_per_worker) + self._initialize_multi_worker(multi_worker_devices) + + def _update_config_proto(self, config_proto): + updated_config = copy.deepcopy(config_proto) + updated_config.isolate_session_state = True + return updated_config + + def _get_cross_device_ops(self, value): + # Always use CollectiveAllReduce when XLA is enabled, since other cross + # device ops don't have as good support on XLA. + if not self._use_merge_call(): + if not isinstance(self._cross_device_ops, + cross_device_ops_lib.CollectiveAllReduce): + logging.warning( + "Under XLA context, MirroredStrategy uses CollectiveAllReduce op. " + "Although %r is provided to initialize MirroredStrategy, it is " + "ignored in XLA. Please use CollectiveAllReduce(or default option) " + "in the future, since other cross device ops are not well " + "supported on XLA.", self._cross_device_ops + ) + return self._collective_ops + + if isinstance(value, values.DistributedValues): + value_int32 = True in { + dtypes.as_dtype(v.dtype) == dtypes.int32 for v in value.values + } + else: + value_int32 = dtypes.as_dtype(value.dtype) == dtypes.int32 + + if value_int32: + return cross_device_ops_lib.ReductionToOneDevice() + else: + return self._cross_device_ops + + def _gather_to_implementation(self, value, destinations, axis, options): + if not isinstance(value, values.DistributedValues): + # ReductionToOneDevice._gather accepts DistributedValues only. + return value + return self._get_cross_device_ops(value)._gather( # pylint: disable=protected-access + value, + destinations=destinations, + axis=axis, + options=self._communication_options.merge(options)) + + def _reduce_to(self, reduce_op, value, destinations, options): + if (distribute_utils.is_mirrored(value) and + reduce_op == reduce_util.ReduceOp.MEAN): + return value + assert not distribute_utils.is_mirrored(value) + def get_values(value): + if not isinstance(value, values.DistributedValues): + # This function handles reducing values that are not PerReplica or + # Mirrored values. For example, the same value could be present on all + # replicas in which case `value` would be a single value or value could + # be 0. + return cross_device_ops_lib.reduce_non_distributed_value( + reduce_op, value, destinations, self._num_replicas_in_sync) + + if self._use_merge_call() and ( + not cross_device_ops_lib._devices_match(value, destinations) or # pylint: disable=protected-access + any("cpu" in d.lower() + for d in cross_device_ops_lib.get_devices_from(destinations))): + return cross_device_ops_lib.ReductionToOneDevice().reduce( + reduce_op, value, destinations) + return self._get_cross_device_ops(value).reduce( + reduce_op, + value, + destinations=destinations, + options=self._communication_options.merge(options)) + + return nest.map_structure(get_values, value) + + def _batch_reduce_to(self, reduce_op, value_destination_pairs, options): + cross_device_ops = None + for value, _ in value_destination_pairs: + if cross_device_ops is None: + cross_device_ops = self._get_cross_device_ops(value) + elif cross_device_ops is not self._get_cross_device_ops(value): + raise ValueError("Inputs to batch_reduce_to must be either all on " + "the host or all on the compute devices.") + return cross_device_ops.batch_reduce( + reduce_op, + value_destination_pairs, + options=self._communication_options.merge(options)) + + def _update(self, var, fn, args, kwargs, group): + # TODO(josh11b): In eager mode, use one thread per device. + assert isinstance(var, values.DistributedVariable) + updates = [] + for i, v in enumerate(var.values): + name = "update_%d" % i + with ops.device(v.device), \ + distribute_lib.UpdateContext(i), \ + ops.name_scope(name): + # If args and kwargs are not mirrored, the value is returned as is. + updates.append( + fn(v, *distribute_utils.select_replica(i, args), + **distribute_utils.select_replica(i, kwargs))) + return distribute_utils.update_regroup(self, updates, group) + + def _replica_ctx_all_reduce(self, reduce_op, value, options=None): + """Implements `StrategyExtendedV2._replica_ctx_all_reduce`.""" + # This implementation avoids using `merge_call` and just launches collective + # ops in one replica. + if options is None: + options = collective_util.Options() + + if context.executing_eagerly() or ( + not tf2.enabled()) or self._use_merge_call(): + # In eager mode, falls back to the default implementation that uses + # `merge_call`. Replica functions are running sequentially in eager mode, + # and due to the blocking nature of collective ops, execution will hang if + # collective ops are to be launched sequentially. + return super()._replica_ctx_all_reduce(reduce_op, value, options) + + replica_context = distribute_lib.get_replica_context() + assert replica_context, ( + "`StrategyExtended._replica_ctx_all_reduce` must be called in a " + "replica context") + return self._get_cross_device_ops(value)._all_reduce( # pylint: disable=protected-access + reduce_op, + value, + replica_context._replica_id, # pylint: disable=protected-access + options) + + def _replica_ctx_update(self, var, fn, args, kwargs, group): + if self._use_merge_call(): + return super()._replica_ctx_update(var, fn, args, kwargs, group) + + replica_context = distribute_lib.get_replica_context() + assert replica_context + replica_id = values_util.get_current_replica_id_as_int() + name = "update_%d" % replica_id + + if isinstance(var, values.DistributedVariable): + var = var._get_replica(replica_id) # pylint: disable=protected-access + + with ops.device(var.device), ops.name_scope(name): + result = fn(var, *args, **kwargs) + return result + + def _update_non_slot(self, colocate_with, fn, args, kwargs, group): + assert isinstance(colocate_with, tuple) + # TODO(josh11b): In eager mode, use one thread per device. + updates = [] + for i, d in enumerate(colocate_with): + name = "update_%d" % i + with ops.device(d), distribute_lib.UpdateContext(i), ops.name_scope(name): + updates.append( + fn(*distribute_utils.select_replica(i, args), + **distribute_utils.select_replica(i, kwargs))) + return distribute_utils.update_regroup(self, updates, group) + + def read_var(self, replica_local_var): + """Read the aggregate value of a replica-local variable.""" + # pylint: disable=protected-access + if distribute_utils.is_sync_on_read(replica_local_var): + return replica_local_var._get_cross_replica() + assert distribute_utils.is_mirrored(replica_local_var) + return array_ops.identity(replica_local_var._get()) + # pylint: enable=protected-access + + def value_container(self, val): + return distribute_utils.value_container(val) + + @property + def _num_replicas_in_sync(self): + return len(self._devices) + + @property + def worker_devices(self): + return self._devices + + @property + def worker_devices_by_replica(self): + return [[d] for d in self._devices] + + @property + def parameter_devices(self): + return self.worker_devices + + @property + def experimental_between_graph(self): + return False + + @property + def experimental_should_init(self): + return True + + @property + def should_checkpoint(self): + return True + + @property + def should_save_summary(self): + return True + + def non_slot_devices(self, var_list): + del var_list + # TODO(josh11b): Should this be the last logical device instead? + return self._devices + + # TODO(priyag): Delete this once all strategies use global batch size. + @property + def _global_batch_size(self): + """`make_dataset_iterator` and `make_numpy_iterator` use global batch size. + + `make_input_fn_iterator` assumes per-replica batching. + + Returns: + Boolean. + """ + return True + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings.""" + return False + + def _get_local_replica_id(self, replica_id_in_sync_group): + return replica_id_in_sync_group + + def _get_replica_id_in_sync_group(self, replica_id): + return replica_id diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_process_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_process_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..fa1e44fbf583236ec9baea4eea40cbddd01e4be2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_process_lib.py @@ -0,0 +1,172 @@ +# 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. +# ============================================================================== +"""Library for multi-process testing.""" + +import multiprocessing +import os +import platform +import sys +import unittest +from absl import app +from absl import logging + +from tensorflow.python.eager import test + + +def is_oss(): + """Returns whether the test is run under OSS.""" + return len(sys.argv) >= 1 and 'bazel' in sys.argv[0] + + +def _is_enabled(): + # Note that flags may not be parsed at this point and simply importing the + # flags module causes a variety of unusual errors. + tpu_args = [arg for arg in sys.argv if arg.startswith('--tpu')] + if is_oss() and tpu_args: + return False + if sys.version_info == (3, 8) and platform.system() == 'Linux': + return False # TODO(b/171242147) + return sys.platform != 'win32' + + +class _AbslProcess: + """A process that runs using absl.app.run.""" + + def __init__(self, *args, **kwargs): + super(_AbslProcess, self).__init__(*args, **kwargs) + # Monkey-patch that is carried over into the spawned process by pickle. + self._run_impl = getattr(self, 'run') + self.run = self._run_with_absl + + def _run_with_absl(self): + app.run(lambda _: self._run_impl()) + + +if _is_enabled(): + + class AbslForkServerProcess(_AbslProcess, + multiprocessing.context.ForkServerProcess): + """An absl-compatible Forkserver process. + + Note: Forkserver is not available in windows. + """ + + class AbslForkServerContext(multiprocessing.context.ForkServerContext): + _name = 'absl_forkserver' + Process = AbslForkServerProcess # pylint: disable=invalid-name + + multiprocessing = AbslForkServerContext() + Process = multiprocessing.Process + +else: + + class Process(object): + """A process that skips test (until windows is supported).""" + + def __init__(self, *args, **kwargs): + del args, kwargs + raise unittest.SkipTest( + 'TODO(b/150264776): Windows is not supported in MultiProcessRunner.') + + +_test_main_called = False + + +def _set_spawn_exe_path(): + """Set the path to the executable for spawned processes. + + This utility searches for the binary the parent process is using, and sets + the executable of multiprocessing's context accordingly. + + Raises: + RuntimeError: If the binary path cannot be determined. + """ + # TODO(b/150264776): This does not work with Windows. Find a solution. + if sys.argv[0].endswith('.py'): + def guess_path(package_root): + # If all we have is a python module path, we'll need to make a guess for + # the actual executable path. + if 'bazel-out' in sys.argv[0] and package_root in sys.argv[0]: + # Guess the binary path under bazel. For target + # //tensorflow/python/distribute:input_lib_test_multiworker_gpu, the + # argv[0] is in the form of + # /.../tensorflow/python/distribute/input_lib_test.py + # and the binary is + # /.../tensorflow/python/distribute/input_lib_test_multiworker_gpu + package_root_base = sys.argv[0][:sys.argv[0].rfind(package_root)] + binary = os.environ['TEST_TARGET'][2:].replace(':', '/', 1) + possible_path = os.path.join(package_root_base, package_root, + binary) + logging.info('Guessed test binary path: %s', possible_path) + if os.access(possible_path, os.X_OK): + return possible_path + return None + path = guess_path('org_tensorflow') + if not path: + path = guess_path('org_keras') + if path is None: + logging.error( + 'Cannot determine binary path. sys.argv[0]=%s os.environ=%s', + sys.argv[0], os.environ) + raise RuntimeError('Cannot determine binary path') + sys.argv[0] = path + # Note that this sets the executable for *all* contexts. + multiprocessing.get_context().set_executable(sys.argv[0]) + + +def _if_spawn_run_and_exit(): + """If spawned process, run requested spawn task and exit. Else a no-op.""" + + # `multiprocessing` module passes a script "from multiprocessing.x import y" + # to subprocess, followed by a main function call. We use this to tell if + # the process is spawned. Examples of x are "forkserver" or + # "semaphore_tracker". + is_spawned = ('-c' in sys.argv[1:] and + sys.argv[sys.argv.index('-c') + + 1].startswith('from multiprocessing.')) + + if not is_spawned: + return + cmd = sys.argv[sys.argv.index('-c') + 1] + # As a subprocess, we disregarding all other interpreter command line + # arguments. + sys.argv = sys.argv[0:1] + + # Run the specified command - this is expected to be one of: + # 1. Spawn the process for semaphore tracker. + # 2. Spawn the initial process for forkserver. + # 3. Spawn any process as requested by the "spawn" method. + exec(cmd) # pylint: disable=exec-used + sys.exit(0) # Semaphore tracker doesn't explicitly sys.exit. + + +def test_main(): + """Main function to be called within `__main__` of a test file.""" + global _test_main_called + _test_main_called = True + + os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true' + + if _is_enabled(): + _set_spawn_exe_path() + _if_spawn_run_and_exit() + + # Only runs test.main() if not spawned process. + test.main() + + +def initialized(): + """Returns whether the module is initialized.""" + return _test_main_called diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_process_runner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_process_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..69b22392903a03a02f6ba433bc8e2f9ebbe4b789 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_process_runner.py @@ -0,0 +1,1455 @@ +# 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. +# ============================================================================== +"""Multi-process runner for testing purpose.""" + +import collections +import contextlib +import json +import os +import signal +import sys +import threading +import time +import unittest +import weakref + +from absl import logging +import six +from six.moves import queue as Queue + +from tensorflow.python import tf2 +from tensorflow.python.compat import v2_compat +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute import multi_process_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import test_util +from tensorflow.python.util.tf_export import tf_export + +multiprocessing = multi_process_lib.multiprocessing + +# pylint: disable=g-import-not-at-top +try: + # `faulthandler` is not available in py2. + import faulthandler +except ImportError: + faulthandler = None + +# TODO(b/150264776): Remove after resolving CI issue. +try: + import dill +except ImportError: + dill = None + +# TODO(b/150264776): Remove after resolving CI issue. +try: + import tblib.pickling_support + # For pickling traceback objects. + tblib.pickling_support.install() +except ImportError: + pass + + +# _ProcessStatusInfo contains process status information. When is_successful +# attribute is True, the subprocess has ended successfully, or if False, the +# exception stack trace info is stored in exc_info to pass on to parent process +# to be re-raised. +_ProcessStatusInfo = collections.namedtuple( + '_ProcessStatusInfo', + ['task_type', 'task_id', 'is_successful', 'exc_info', 'return_value']) + +# Information returned from a successful MultiProcessRunner run. +MultiProcessRunnerResult = collections.namedtuple('MultiProcessRunnerResult', + ['return_value', 'stdout']) + +# visible_gpus: If not None, CUDA_VISIBLE_DEVICES is set to visible_gpus. +TestEnvironment = collections.namedtuple('TestEnvironment', [ + 'task_type', 'task_id', 'cluster_spec', 'rpc_layer', 'grpc_fail_fast', + 'v2_enabled', 'executing_eagerly', 'visible_gpus' +]) + +# Resources for communication between worker processes and the main process. +# +# `process_status_queue` is used by `multi_process_runner` internally for +# communication from subprocesses to the parent process for whether it's been +# successful, and if not what the error stack trace is. +# `parent_to_sub_queue` is used for communications from parent to subprocess. +# Currently this is only used to terminate subprocesses. +# TODO(rchao): Remove this once subprocess is terminated by SIGKILL. +# `streaming_pipe_w` is to stream stdout and stderr from subprocesses to parent +# process. +# `barrier` is a barrier for the party of all subprocesses. +Resources = collections.namedtuple('Resources', [ + 'process_status_queue', 'parent_to_sub_queue', 'streaming_pipe_w', 'barrier' +]) + +# Default time out sec is selected so that it's handled before the default +# "medium" timeout of the test runs. +_DEFAULT_TIMEOUT_SEC = 200 + +# The timeout in seconds to wait to force kill a child process. When a child +# process times out we first try to SIGTERM it so that it has a chance to dump +# stacktraces. However dumping stacktrace can take a long time. +_FORCE_KILL_WAIT_SEC = 30 + + +class MultiProcessRunner(object): + """A utility class to start multiple processes to simulate a cluster. + + We need to use multiple processes to simulate a cluster in TF 2.0 tests + because TF 2.0 has some process-global data structures that have to be + separated by processes. We also need child processes to test out our fault + tolerance because shutting down a standard TensorFlow server within its + process is not supported. + + Note: the main test program that uses this runner class must run main program + via `test_main` defined in this file. Using this runner in non-test binaries + is not supported yet. + + This class is not thread-safe. Child processes will inherit TF2 behavior flag. + """ + + def __init__(self, + fn, + cluster_spec, + rpc_layer=None, + max_run_time=None, + grpc_fail_fast=None, + stream_output=True, + return_output=False, + use_dill_for_args=True, + daemon=False, + dependence_on_chief=True, + auto_restart=False, + share_gpu=True, + args=None, + kwargs=None): + """Instantiation of a `MultiProcessRunner`. + + Args: + fn: Function to be run on child processes. This will be run on processes + for all task types. + cluster_spec: Dict for cluster spec. The utility function + `tf.__internal__.distribute.multi_process_runner.create_cluster_spec` + can be conveniently used to create such dict. The following is an + example of cluster with three workers and two ps's. + {"worker": ["worker0.example.com:2222", + "worker1.example.com:2222", + "worker2.example.com:2222"], + "ps": ["ps0.example.com:2222", + "ps1.example.com:2222"]} + rpc_layer: RPC layer to use. Default value is 'grpc'. + max_run_time: `None` or integer. If not `None`, child processes are forced + to exit at approximately this many seconds after this utility is called. + We achieve this through `signal.alarm()` api. Note that this is best + effort at Python level since Python signal handler does not get executed + when it runs lower level C/C++ code. So it can be delayed for + arbitrarily long time. If any of the child process is still running when + `max_run_time` is up, they will be force-terminated and an + `UnexpectedSubprocessExitError` may be raised. If `None`, child + processes are not forced to exit. + grpc_fail_fast: Whether GRPC connection between processes should fail + without retrying. Defaults to None, in which case the environment + variable is not explicitly set. + stream_output: True if the output/error from the subprocesses should be + streamed to be printed in parent process' log. Defaults to True. + return_output: If True, the output/error from the subprocesses should be + collected to be attached to the resulting namedtuple returned from + `join()`. The list of output can be retrieved via `stdout` attribute. + Defaults to False. + use_dill_for_args: Whether to use dill to pickle `args` and `kwargs`. dill + can pickle more objects, but doesn't work with types in + `multiprocessing` library like `Mutex`. + daemon: Whether to start processes as daemons. + dependence_on_chief: Whether to terminates the cluster if the chief exits. + If auto_restart is True, it only terminates the cluster if the chief + exits with a zero exit code. + auto_restart: Whether to automatically restart processes that exit with + non-zero exit code. + share_gpu: Whether to share GPUs among workers. If False, each worker is + assigned different GPUs in a roundrobin fashion. This should be True + whenever possible for better test execution coverage; some situations + that need it to be False are tests that runs NCCL. + args: Positional arguments to be sent to `fn` run on subprocesses. + kwargs: Keyword arguments to be sent to `fn` run on subprocesses. + + Raises: + RuntimeError: if `multi_process_runner.test_main()` is not called. + ValueError: if there are more than one chief in the `cluster_spec`. + SkipTest: if thread sanitizer is enabled (which is incompatible with MPR). + """ + if test_util.is_tsan_enabled(): + raise unittest.SkipTest( + 'ThreadSanitizer is not compatible with MultiProcessRunner.') + + assert cluster_spec is not None + if 'chief' in cluster_spec and len(cluster_spec['chief']) > 1: + raise ValueError('If chief exists in the cluster, there must be at most ' + 'one chief. Current `cluster_spec` has {} chiefs.' + .format(len(cluster_spec['chief']))) + _check_initialization() + if not callable(fn): + raise ValueError('fn is not a callable') + + self._fn = fn + self._cluster_spec = cluster_spec + self._rpc_layer = rpc_layer or 'grpc' + self._max_run_time = max_run_time + self._grpc_fail_fast = grpc_fail_fast + self._stream_output = stream_output + # TODO(rchao): Revisit return_output argument to consider other solution. + self._return_output = return_output + self._dependence_on_chief = dependence_on_chief + self._use_dill_for_args = use_dill_for_args + self._daemon = daemon + self._auto_restart = auto_restart + self._args = args or () + self._kwargs = kwargs or {} + + self._share_gpu = share_gpu + self._total_gpu = len(context.context().list_physical_devices('GPU')) + + # Child processes should have the same v2 and eager behavior. + self._v2_enabled = tf2.enabled() + self._executing_eagerly = context.executing_eagerly() + + self._joined = False + self._process_lock = threading.Lock() + # Guarded by self._process_lock. + self._processes = {} + # Record which processes are terminated. Due to a bug in Python<3.7, + # terminated processes return 255 exit code, which should cause an exception + # in join(). + # https://bugs.python.org/issue30589 + # Guarded by self._process_lock. + self._terminated = set() + self._reading_threads = [] + + self._manager = manager() + self._process_status_queue = self._manager.Queue() + self._parent_to_sub_queue = self._manager.Queue() + parties = sum(len(addresses) for addresses in self._cluster_spec.values()) + self._barrier = self._manager.Barrier(parties) + + # We use a queue to collect outputs from worker processes since it's thread + # safe. + self._streaming_queue = self._manager.Queue() + + self._watchdog_thread = None + + def set_args(self, args=None, kwargs=None): + self._args = args or self._args + self._kwargs = kwargs or self._kwargs + + def _continuously_readline_from_sub(self, pipe_r, task_type, task_id): + """Function to continuously read lines from subprocesses.""" + with os.fdopen(pipe_r.fileno(), 'r', closefd=False) as reader: + for line in reader: + task_string = '[{}-{}]:'.format(task_type, task_id) + formatted_line = '{} {}'.format(task_string.ljust(14), line) + if self._stream_output: + # TODO(rchao): Use a lock here to ensure the printed lines are not + # broken. + print(formatted_line, end='', flush=True) + if self._return_output: + self._streaming_queue.put(formatted_line) + + def _start_subprocess_and_reading_thread(self, + task_type, + task_id, + cluster_spec=None, + fn=None, + args=None, + kwargs=None): + """Start a subprocess and a thread the reads lines from the subprocess.""" + + if dill is None: + raise unittest.SkipTest( + 'TODO(b/150264776): Resolve dependency issue in CI') + + cluster_spec = cluster_spec or self._cluster_spec + visible_gpus = None + if not self._share_gpu and self._total_gpu > 0: + # Assign GPUs in a roundrobin fashion. + id_in_cluster = multi_worker_util.id_in_cluster(cluster_spec, task_type, + task_id) + worker_count = multi_worker_util.worker_count(cluster_spec, task_type) + visible_gpus = list(range(id_in_cluster, self._total_gpu, worker_count)) + + test_env = TestEnvironment( + task_type=task_type, + task_id=task_id, + cluster_spec=cluster_spec, + rpc_layer=self._rpc_layer, + grpc_fail_fast=self._grpc_fail_fast, + v2_enabled=self._v2_enabled, + executing_eagerly=self._executing_eagerly, + visible_gpus=visible_gpus, + ) + pipe_r, pipe_w = multiprocessing.Pipe(duplex=False) + resources = Resources( + process_status_queue=self._process_status_queue, + parent_to_sub_queue=self._parent_to_sub_queue, + streaming_pipe_w=pipe_w, + barrier=self._barrier, + ) + if fn is None: + fn, args, kwargs = self._fn, self._args, self._kwargs + # Always use dill to pickle fn so that we support more callable + # types, e.g. lambda. + fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL) + if self._use_dill_for_args: + args = dill.dumps(args, dill.HIGHEST_PROTOCOL) + kwargs = dill.dumps(kwargs, dill.HIGHEST_PROTOCOL) + + p = _Process( + test_env=test_env, + target=_ProcFunc(), + args=(resources, test_env, fn, args, kwargs, self._use_dill_for_args), + daemon=self._daemon) + p.start() + self._processes[(task_type, task_id)] = p + self._terminated.discard((task_type, task_id)) + + # For each subprocess, we dedicate a thread continuously reading lines + # from them. + thread = threading.Thread( # pylint: disable=unexpected-keyword-arg + target=self._continuously_readline_from_sub, + args=(pipe_r, task_type, task_id)) + thread.start() + self._reading_threads.append(thread) + + if self._watchdog_thread is None or not self._watchdog_thread.is_alive(): + self._watchdog_thread = threading.Thread(target=self._process_watchdog) + self._watchdog_thread.start() + + def start(self): + """Starts processes, one for each task in `cluster_spec`. + + Note that this is best effort by the applicable multiprocessing library, + and it may take up to seconds for a subprocess to be successfully started. + """ + with self._process_lock: + if self._processes: + raise ValueError('MultiProcessRunner already started.') + if self._joined: + raise ValueError('cannot start new processes after' + 'MultiProcessRunner.join() is called') + + for task_type, addresses in self._cluster_spec.items(): + for task_id, _ in enumerate(addresses): + self._start_subprocess_and_reading_thread(task_type, task_id) + + # TODO(rchao): Remove the need of using SIGALRM if possible. At this time, + # without this the tests become very flaky. + if self._max_run_time is not None: + + def handler(signum, frame): + del signum, frame + self.terminate_all() + + signal.signal(signal.SIGALRM, handler) + signal.alarm(self._max_run_time) + + def start_in_process_as(self, as_task_type, as_task_id): + """Start the processes, with the specified task run in main process. + + This is similar to `start()` except that the task with task_type + `as_task_type` and task_id `as_task_id` is run in the main process. + This method is particularly useful when debugging tool such as `pdb` is + needed in some specific task. Note that since this method is blocking until + that specific task exits, additional actions would need a thread to be + called: + + ```python + def fn(): + # user code to be run + import pdb; pdb.set_trace() + + def follow_ups(): + time.sleep(5) + mpr.start_single_process( + task_type='evaluator', + task_id=0) + + mpr = multi_process_runner.MultiProcessRunner( + fn, + multi_worker_test_base.create_cluster_spec( + has_chief=True, num_workers=1)) + threading.Thread(target=follow_ups).start() + mpr.start_in_process_as(as_task_type='chief', as_task_id=0) + mpr.join() + ``` + + Note that if `return_output=True`, the logs/stdout by task + run by the main process is not available in result.stdout. + + Args: + as_task_type: The task type to be run in the main process. + as_task_id: The task id to be run in the main process. + """ + if self._processes: + raise ValueError('MultiProcessRunner already started.') + with self._process_lock: + if self._joined: + raise ValueError('cannot start new processes after' + 'MultiProcessRunner.join() is called') + for task_type, addresses in self._cluster_spec.items(): + for task_id, _ in enumerate(addresses): + if not (task_type == as_task_type and task_id == as_task_id): + self._start_subprocess_and_reading_thread(task_type, task_id) + + _set_tf_config(as_task_type, as_task_id, self._cluster_spec, + self._rpc_layer) + self._fn(*self._args, **self._kwargs) + + def start_single_process(self, + task_type, + task_id, + cluster_spec=None, + fn=None, + args=None, + kwargs=None): + """Starts a single process. + + This starts a process in the cluster with the task type, task id, and the + process function (`fn`). If process function is `None`, the function + provided at `__init__` will be used. If `cluster_spec` is `None`, the + cluster spec provided at `__init__` will be used. + + TODO(rchao): It is meant that all subprocesses will be updated with the new + cluster spec, but this has yet to be implemented. At this time only the + newly started subprocess picks up this updated cluster spec. + + Args: + task_type: The task type. + task_id: The task id. + cluster_spec: The cluster spec to be used on the newly started + process. If `None`, the cluster spec provided at `__init__` will be + used. + fn: The process function to be run on the newly started + process. If specified, specify `args` and `kwargs` as well. If `None`, + the function provided at `__init__` will be used. + args: Optional positional arguments to be supplied in `fn`. + kwargs: Optional keyword arguments to be supplied in `fn`. + """ + with self._process_lock: + if self._joined: + raise ValueError('cannot start new processes after' + 'MultiProcessRunner.join() is called') + self._start_subprocess_and_reading_thread( + task_type, + task_id, + cluster_spec=cluster_spec, + fn=fn, + args=args or (), + kwargs=kwargs or {}) + + def _queue_to_list(self, queue_to_convert): + """Convert `queue.Queue` to `list`.""" + list_to_return = [] + # Calling `queue.empty()` is not reliable. + while True: + try: + list_to_return.append(queue_to_convert.get(block=False)) + except Queue.Empty: + break + return list_to_return + + def _get_process_statuses(self): + # One worker may have multiple statuses. We only keep the last one. + statuses = {} + for status in self._queue_to_list(self._process_status_queue): + statuses[(status.task_type, status.task_id)] = status + return statuses + + def get_process_id(self, task_type, task_id): + """Returns the subprocess id given the task type and task id.""" + with self._process_lock: + p = self._processes.get((task_type, task_id), None) + return p.pid if p else None + + def get_process_exit_code(self, task_type, task_id): + """Returns the subprocess exit code given the task type and task id. + + Args: + task_type: The task type. + task_id: The task id. + + Returns: + The subprocess exit code; `None` if the subprocess has not exited yet. + + Raises: + KeyError: If the corresponding subprocess is not found with `task_type` + and `task_id`. + """ + with self._process_lock: + p = self._processes[(task_type, task_id)] + return p.exitcode if p else None + + def process_exists(self, task_type, task_id): + """Returns whether the subprocess still exists given the task type and id. + + Args: + task_type: The task type. + task_id: The task id. + + Returns: + Boolean; whether the subprocess still exists. If the subprocess has + exited, this returns False. + """ + return self.get_process_exit_code(task_type, task_id) is None + + def _process_watchdog(self): + """Simulates a cluster management system. + + - If auto_restart is True, it restarts processes that exit with a non-zero + exit code. Note that when join() times out it overrides auto_restart to + False. + - If dependence_on_chief is True, it terminates all processes once the chief + exits. If auto_restart is also True, it only terminates all processes if + the chief exit with a zero exit code, otherwise it restarts the chief. + + This runs in self._watchdog_thread. + """ + while True: + time.sleep(1) + with self._process_lock: + chief = self._processes.get(('chief', 0), None) + # Terminate the cluster when _dependence_on_chief is True if either: + # - chief has exited with zero exit code. + # - chief has exited with non-zero exit code and self._auto_restart is + # False. + if chief and self._dependence_on_chief and chief.exitcode is not None: + if chief.exitcode == 0 or (not self._auto_restart): + for p in self._processes.values(): + # Give other processes a chance to exit on their own. + p.join(timeout=3) + self._terminate_all() + for p in self._processes.values(): + p.join() + return + + # Auto restart failed processes if self._auto_restart is True. + if self._auto_restart: + has_failure = False + for (task_type, task_id), p in self._processes.items(): + if p.exitcode is not None and p.exitcode != 0: + has_failure = True + logging.info('Restarting failed %s-%d', task_type, task_id) + self._start_subprocess_and_reading_thread(task_type, task_id) + if has_failure: + continue + + # Exit the thread if all processes have exited at this point. + if all(p.exitcode is not None for p in self._processes.values()): + return + + def _reraise_if_subprocess_error(self, process_statuses): + for process_status in process_statuses.values(): + assert isinstance(process_status, _ProcessStatusInfo) + if not process_status.is_successful: + process_status.exc_info[1].mpr_result = self._get_mpr_result( + process_statuses) + six.reraise(*process_status.exc_info) + + def join(self, timeout=_DEFAULT_TIMEOUT_SEC): + """Joins all the processes with timeout. + + If any of the subprocesses does not exit approximately after `timeout` + seconds has passed after `join` call, this raises a + `SubprocessTimeoutError`. + + Note: At timeout, it uses SIGTERM to terminate the subprocesses, in order to + log the stack traces of the subprocesses when they exit. However, this + results in timeout when the test runs with tsan (thread sanitizer); if tsan + is being run on the test targets that rely on timeout to assert information, + `MultiProcessRunner.terminate_all()` must be called after `join()`, before + the test exits, so the subprocesses are terminated with SIGKILL, and data + race is removed. + + Args: + timeout: optional integer or `None`. If provided as an integer, and not + all processes report status within roughly `timeout` seconds, a + `SubprocessTimeoutError` exception will be raised. If `None`, `join` never + times out. + + Returns: + A `MultiProcessRunnerResult` object, which has two attributes, + `return_value` and `stdout`. `return_value` always contains a list of + return values from the subprocesses, although the order is not meaningful. + If `return_output` argument is True at `__init__`, `stdout` is available + that contains a list of all messages from subprocesses' stdout and stderr. + + Raises: + SubprocessTimeoutError: if not all processes report status approximately + within `timeout` seconds. When this is raised, a + `MultiProcessRunnerResult` object can be retrieved by + `SubprocessTimeoutError`'s mpr_result attribute, which has the same + structure as above 'Returns' section describes. + UnexpectedSubprocessExitError: If any of the subprocesses did not exit + properly (for example, they exit on SIGTERM or SIGKILL signal). When + this is raised, a `MultiProcessRunnerResult` object can be retrieved by + `UnexpectedSubprocessExitError`'s mpr_result attribute, which has the + same structure as above 'Returns' section describes. If `max_run_time` + is not `None`, it is expected that some subprocesses may be + force-killed when `max_run_time` is up, and this is raised in those + cases. + Exception: if there is an Exception propagated from any subprocess. When + this is raised, a `MultiProcessRunnerResult` object can be retrieved by + `UnexpectedSubprocessExitError`'s mpr_result attribute, which has the + same structure as above 'Returns' section describes. + """ + if timeout and not isinstance(timeout, int): + raise ValueError('`timeout` must be an integer or `None`.') + with self._process_lock: + if self._joined: + raise ValueError("MultiProcessRunner can't be joined twice.") + self._joined = True + + self._watchdog_thread.join(timeout) + if self._watchdog_thread.is_alive(): + # Timeout. Force termination to dump worker processes stack trace. + with self._process_lock: + self._auto_restart = False + logging.error('Timeout when joining for child processes. Terminating...') + self.terminate_all(sig=signal.SIGTERM) + # Wait for the processes to terminate by themselves first, so they have a + # chance to dump stacktraces. After _FORCE_KILL_WAIT_SEC, we SIGKILL them. + self._watchdog_thread.join(_FORCE_KILL_WAIT_SEC) + if self._watchdog_thread.is_alive(): + logging.error('Timeout when waiting for child processes to ' + 'print stacktrace. Sending SIGKILL...') + self.terminate_all() + self._watchdog_thread.join() + process_statuses = self._get_process_statuses() + self._reraise_if_subprocess_error(process_statuses) + raise SubprocessTimeoutError( + 'One or more subprocesses timed out, where timeout was set to {}s. ' + 'Please change the `timeout` argument for ' + '`MultiProcessRunner.join()` or `multi_process_runner.run()` ' + 'if it should be adjusted.'.format(timeout), + self._get_mpr_result(process_statuses)) + + for (task_type, task_id), p in self._processes.items(): + logging.info('%s-%d exit code: %s', task_type, task_id, p.exitcode) + + process_statuses = self._get_process_statuses() + self._reraise_if_subprocess_error(process_statuses) + + # Checking all the processes that are expected to exit properly. + for (task_type, task_id), p in self._processes.items(): + # Successfully exiting process has exit code 0. We ignore processes that + # are terminated. + assert p.exitcode is not None + if (p.exitcode > 0 and (task_type, task_id) not in self._terminated): + raise UnexpectedSubprocessExitError( + 'Subprocess %s-%d exited with exit code %s. See logs for details.' + % (task_type, task_id, p.exitcode), + self._get_mpr_result(process_statuses)) + + logging.info('Joining log reading threads.') + for thread in self._reading_threads: + thread.join() + logging.info('Joined log reading threads.') + + # Clear the alarm. + signal.alarm(0) + + return self._get_mpr_result(process_statuses) + + def _get_mpr_result(self, process_statuses): + stdout = self._queue_to_list(self._streaming_queue) + return_values = [] + for process_status in process_statuses.values(): + if process_status.return_value is not None: + return_values.append(process_status.return_value) + return MultiProcessRunnerResult(stdout=stdout, return_value=return_values) + + def terminate(self, task_type, task_id): + """Terminates the process with `task_type` and `task_id`. + + If auto_retart=True, the terminated task will be restarted unless the chief + has already exited with zero exit code. + + Args: + task_type: the task type. + task_id: the task id. + + """ + with self._process_lock: + p = self._processes.get((task_type, task_id), None) + if p is None: + raise ValueError('{}-{} does not exist'.format(task_type, task_id)) + self._terminated.add((task_type, task_id)) + # TODO(crccw): change to use Process.terminate() as well. + self._parent_to_sub_queue.put('terminate {} {}'.format( + task_type, task_id)) + p.join() + + def _terminate_all(self, sig=None): + """Terminates all subprocesses. + + The caller is required to hold self._process_lock. + + Args: + sig: the signal used to terminate the process. The default is SIGKILL. + """ + + # Use SIGKILL as default. In systems where that's unavailable such as + # windows, use SIGTERM. + sig = sig or getattr(signal, 'SIGKILL', signal.SIGTERM) + for (task_type, task_id), p in self._processes.items(): + if p.exitcode is not None: + logging.info('%s-%d has already exited. Not terminating.', task_type, + task_id) + continue + try: + os.kill(p.pid, sig) + self._terminated.add((task_type, task_id)) + logging.info('%s-%d terminated with signal %r.', task_type, task_id, + sig) + except ProcessLookupError: + logging.info('Attempting to kill %s-%d but it does not exist.', + task_type, task_id) + + def terminate_all(self, sig=None): + """Terminates all subprocesses.""" + with self._process_lock: + self._terminate_all(sig) + + +class _Process(multi_process_lib.Process): + """A modified `multiprocessing.Process` that can set up environment variables.""" + + # TODO(crccw): consider moving other logics in _ProcFunc to _Process. + + def __init__(self, test_env, **kwargs): + super(_Process, self).__init__(**kwargs) + self._test_env = test_env + self._actual_run = getattr(self, 'run') + self.run = self._run_with_setenv + + def _run_with_setenv(self): + # We need to set environment variables before doing anything because + # setenv() is not thread-safe. + test_env = self._test_env + if test_env.grpc_fail_fast is not None: + os.environ['GRPC_FAIL_FAST'] = str(test_env.grpc_fail_fast) + if test_env.visible_gpus: + os.environ['CUDA_VISIBLE_DEVICES'] = ','.join( + [str(i) for i in test_env.visible_gpus]) + _set_tf_config(test_env.task_type, test_env.task_id, test_env.cluster_spec, + test_env.rpc_layer) + return self._actual_run() + + +class _ProcFunc(object): + """Represents a callable to run in a subprocess.""" + + @contextlib.contextmanager + def _runtime_mode(self, executing_eagerly): + if executing_eagerly: + with context.eager_mode(): + yield + else: + with context.graph_mode(): + yield + + def _message_checking_func(self, task_type, task_id): + """A function that regularly checks messages from parent process.""" + # TODO(rchao): Remove this once parent uses SIGKILL to terminate subprocess. + while True: + try: + message = self._resources.parent_to_sub_queue.get(block=False) + + # Currently the only possible message is termination. + if not message.startswith('terminate'): + raise ValueError('Unrecognized message: {}'.format(message)) + + if message == 'terminate {} {}'.format(task_type, task_id): + break + else: + # If the message is not targeting this process, put it back to the + # queue. + self._resources.parent_to_sub_queue.put(message) + time.sleep(1) + except Queue.Empty: + time.sleep(0.1) + self._resources.process_status_queue.put( + _ProcessStatusInfo( + task_type=task_type, + task_id=task_id, + is_successful=True, + exc_info=None, + return_value=None)) + # `os._exit(1)` is used to more reliably terminate a subprocess. + os._exit(1) # pylint: disable=protected-access + + def _close_streaming(self): + """Close stdout, stderr and streaming pipe. + + We need to explicitly close them since Tensorflow may take a while to exit, + so that the reading threads in the main process can exit more quickly. + """ + sys.stdout.flush() + sys.stderr.flush() + sys.stdout.close() + sys.stderr.close() + self._resources.streaming_pipe_w.close() + + def __call__(self, resources, test_env, fn, args, kwargs, use_dill_for_args): + """The wrapper function that actually gets run in child process(es).""" + + global _barrier + + self._resources = resources + _barrier = self._resources.barrier + fn = dill.loads(fn) + if use_dill_for_args: + args = dill.loads(args) + kwargs = dill.loads(kwargs) + + if faulthandler is not None: + faulthandler.enable() + faulthandler.register(signal.SIGTERM, chain=True) + + # All logging should go to stderr to be streamed to the main process. + logging.set_stderrthreshold(logging.DEBUG) + + # Assign sys.stdout and sys.stderr as duplicates of `streaming_pipe_w` so + # print() and logging.*() write directly to `streaming_pipe_w`. + # Unfortunately since we cannot prepend task_type and task_id information to + # the streamed logs we will need a thread per subprocess to distinguish + # where the piece of message is from. + os.dup2(resources.streaming_pipe_w.fileno(), sys.stdout.fileno()) + os.dup2(resources.streaming_pipe_w.fileno(), sys.stderr.fileno()) + + pid = os.getpid() + logging.info('Subprocess with PID %d (%s, %d) is now being started.', pid, + test_env.task_type, test_env.task_id) + logging.info('TF_CONFIG: %r', os.environ['TF_CONFIG']) + + # The thread will be dedicated to checking messages from the parent process. + threading.Thread( # pylint: disable=unexpected-keyword-arg + target=self._message_checking_func, + args=(test_env.task_type, test_env.task_id), + daemon=True).start() + + if test_env.v2_enabled: + v2_compat.enable_v2_behavior() + + with self._runtime_mode(test_env.executing_eagerly): + info = _run_contained(test_env.task_type, test_env.task_id, fn, args, + kwargs) + self._resources.process_status_queue.put(info) + + # Re-raise the exception in addition to reporting it to the parent + # process, so that even if `--test_timeout` flag is set and the + # error doesn't make it to be shown in parent process before bazel's + # timeout, the log would still show what happens in this subprocess, + # instead of silently suppressing the error due to early bazel + # timeout. Raising an error in the subprocess produces stack trace in + # the log, but the program continues running. + if not info.is_successful: + six.reraise(*info.exc_info) + + self._close_streaming() + + # Exit with code 0 as it's considered successful exit at this point. + sys.exit(0) + + +# Active MultiProcessPoolRunner. We need to shut them down when the program +# exits, and this is by setting the `tearDownModule` of the module containing +# `__main__`. Note this it set in both the parent process and the subprocesses. +_active_pool_runners = weakref.WeakSet() + + +def _shutdown_all_pool_runners(): + for pool in _active_pool_runners: + pool.shutdown() + + +def is_oss(): + """Returns whether the test is run under OSS.""" + return len(sys.argv) >= 1 and 'bazel' in sys.argv[0] + + +class MultiProcessPoolRunner(object): + """A utility class to start a process pool to simulate a cluster. + + It's similar to MultiProcessRunner, but uses a pool of processes to avoid the + expensive initialization cost of Tensorflow. + """ + + def __init__(self, cluster_spec, initializer=None, share_gpu=True): + """Creates a multi-process pool runner. + + Args: + cluster_spec: Dict for cluster spec. The following is an example of + cluster with three workers. + {"worker": ["worker0.example.com:2222", + "worker1.example.com:2222", + "worker2.example.com:2222"]} + initializer: a callable to called at the startup of worker processes. + share_gpu: Whether to share GPUs among workers. If False, each worker is + assigned different GPUs in a roundrobin fashion. + + Raises: + RuntimeError: if `multi_process_runner.test_main()` is not called. + ValueError: if there are more than one chief in the `cluster_spec`. + """ + _active_pool_runners.add(self) + self._cluster_spec = cluster_spec + self._initializer = initializer + self._share_gpu = share_gpu + self._conn = {} + self._runner = None + + def __del__(self): + self.shutdown() + + def shutdown(self): + """Shuts down the worker pool.""" + for conn in self._conn.values(): + conn.close() + self._conn = {} + if self._runner is not None: + try: + self._runner.join() + except Exception as e: # pylint: disable=broad-except + logging.error( + 'Ignoring exception when shutting down MultiProcessPoolRunner: %s', + e) + self._runner = None + + def _start(self): + """Starts the worker pool.""" + # We need different arguments for different processes so we're passing a + # no-op fn here and use start_single_process instead. + + if dill is None: + raise unittest.SkipTest( + 'TODO(b/150264776): Resolve dependency issue in CI') + + self._runner = MultiProcessRunner( + fn=lambda: None, + cluster_spec=self._cluster_spec, + use_dill_for_args=False, + share_gpu=self._share_gpu) + if self._initializer: + initializer = dill.dumps(self._initializer, dill.HIGHEST_PROTOCOL) + else: + initializer = None + for task_type, addresses in self._cluster_spec.items(): + for task_id, _ in enumerate(addresses): + conn1, conn2 = multiprocessing.Pipe(duplex=True) + self._conn[(task_type, task_id)] = conn1 + self._runner.start_single_process( + task_type, + task_id, + fn=_pool_runner_worker, + args=(task_type, task_id, initializer, conn2)) + + def run(self, fn, args=None, kwargs=None): + """Runs `fn` with `args` and `kwargs` on all jobs. + + Args: + fn: The function to be run. + args: Optional positional arguments to be supplied in `fn`. + kwargs: Optional keyword arguments to be supplied in `fn`. + + Returns: + A list of return values. + """ + _check_initialization() + # TODO(b/150264776): skip in OSS until it's implemented. + multi_process_lib.Process() + if self._runner is None: + self._start() + + fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL) + for conn in self._conn.values(): + conn.send((fn, args or [], kwargs or {})) + + process_statuses = [] + for (task_type, task_id), conn in self._conn.items(): + logging.info('Waiting for the result from %s-%d', task_type, task_id) + try: + process_statuses.append(conn.recv()) + except EOFError: + # This shouldn't happen due to exceptions in fn. This usually + # means bugs in the runner. + self.shutdown() + raise RuntimeError('Unexpected EOF. Worker process may have died. ' + 'Please report a bug') + + return_values = [] + for process_status in process_statuses: + assert isinstance(process_status, _ProcessStatusInfo) + if not process_status.is_successful: + six.reraise(*process_status.exc_info) + if process_status.return_value is not None: + return_values.append(process_status.return_value) + + return return_values + + +def _pool_runner_worker(task_type, task_id, initializer, conn): + """Function that runs on the workers in a pool. + + It listens for callables to run and returns the result until `conn` is closed. + It captures the exceptions during executing the callable and return it through + `conn`. + + Args: + task_type: the task type. + task_id: the task index. + initializer: a callable to execute during startup. + conn: a multiprocessing.Connection object to listen for tasks and send + results. + """ + if initializer: + initializer = dill.loads(initializer) + initializer() + while True: + try: + fn, args, kwargs = conn.recv() + except EOFError: + break + fn = dill.loads(fn) + info = _run_contained(task_type, task_id, fn, args, kwargs) + sys.stdout.flush() + sys.stderr.flush() + conn.send(info) + + +def _run_contained(task_type, task_id, fn, args, kwargs): + """Runs `fn` with `args` and `kwargs`. + + The function returns _ProcessStatusInfo which captures the return value and + the exception. + + Args: + task_type: the task type. + task_id: the task index. + fn: the function to be run. + args: optional positional arguments to be supplied in `fn`. + kwargs: optional keyword arguments to be supplied in `fn`. + + Returns: + a _ProcessStatusInfo. + + """ + is_successful = False + return_value = None + exc_info = None + try: + return_value = fn(*args, **kwargs) + is_successful = True + return _ProcessStatusInfo( + task_type=task_type, + task_id=task_id, + is_successful=is_successful, + exc_info=exc_info, + return_value=return_value) + + # If `fn` ends up exiting with `sys.exit()`, the `SystemExit` is not + # handled here. + except Exception: # pylint: disable=broad-except + exc_info = sys.exc_info() + return _ProcessStatusInfo( + task_type=task_type, + task_id=task_id, + is_successful=is_successful, + exc_info=exc_info, + return_value=return_value) + + +@tf_export('__internal__.distribute.multi_process_runner' + '.SubprocessTimeoutError', + v1=[]) +class SubprocessTimeoutError(RuntimeError): + """An error that indicates there is at least one subprocess timing out. + + When this is raised, a namedtuple object representing the multi-process run + result can be retrieved by + `tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s + `mpr_result` attribute. See + `tf.__internal__.distribute.multi_process_runner.run` for more information. + """ + + def __init__(self, msg, mpr_result): + super(SubprocessTimeoutError, self).__init__(msg) + self.mpr_result = mpr_result + + +@tf_export('__internal__.distribute.multi_process_runner' + '.UnexpectedSubprocessExitError', + v1=[]) +class UnexpectedSubprocessExitError(RuntimeError): + """An error indicating there is at least one subprocess with unexpected exit. + + When this is raised, a namedtuple object representing the multi-process run + result can be retrieved by + `tf.__internal__.distribute.multi_process_runner + .UnexpectedSubprocessExitError`'s + `mpr_result` attribute. See + `tf.__internal__.distribute.multi_process_runner.run` for more information. + """ + + def __init__(self, msg, mpr_result): + super(UnexpectedSubprocessExitError, self).__init__(msg) + self.mpr_result = mpr_result + + +@tf_export( + '__internal__.distribute.multi_process_runner.NotInitializedError', v1=[]) +class NotInitializedError(RuntimeError): + """An error indicating `multi_process_runner.run` is used without init. + + When this is raised, user is supposed to call + `tf.__internal__.distribute.multi_process_runner.test_main()` within + `if __name__ == '__main__':` block to properly initialize + `multi_process_runner.run`. + """ + pass + + +def _check_initialization(): + if not multi_process_lib.initialized(): + raise NotInitializedError( + '`multi_process_runner` is not initialized. ' + 'Please call `tf.__internal__.distribute.multi_process_runner.' + 'test_main()` within `if __name__ == \'__main__\':` block ' + 'in your python module to properly initialize ' + '`multi_process_runner`.') + + +def _set_tf_config(task_type, task_id, cluster_spec, rpc_layer=None): + """Set TF_CONFIG environment variable.""" + tf_config_dict = { + 'cluster': cluster_spec, + 'task': { + 'type': task_type, + 'index': task_id, + }, + } + if rpc_layer is not None: + tf_config_dict['rpc_layer'] = rpc_layer + os.environ['TF_CONFIG'] = json.dumps(tf_config_dict) + + +@tf_export('__internal__.distribute.multi_process_runner.run', v1=[]) +def run(fn, + cluster_spec, + rpc_layer=None, + max_run_time=None, + return_output=False, + timeout=_DEFAULT_TIMEOUT_SEC, + args=None, + kwargs=None): + """Run `fn` in multiple processes according to `cluster_spec`. + + Given a callable `fn`, `tf.__internal__.distribute.multi_process_runner.run` + launches multiple processes, each of which runs `fn`. These processes are + referred to as "subprocesses" or "child processes". Each of those subprocesses + will have their `TF_CONFIG` environment variable set, according to + `cluster_spec` and their task types. The stdout of the subprocesses are + streamed to the main process' and thus available in logs (if `stream_output` + is True), with [type-id] prefix. + + `tf.__internal__.distribute.multi_process_runner.run` will block until all + subprocesses have successfully exited, and return a namedtuple object that + represents the run result. This object has a `return_value` attribute, which + is a list that contains subprocesses `fn`'s return values, for those + subprocesses that successfully returned from `fn`. The order of `return_value` + list is not meaningful. If an optional arg `return_output` (default to False) + is set to True, the namedtuple object will have an additional attribute + `stdout`, which is a list containing the stdout of the subprocesses. If any + subprocess' `fn` ends up raising an error, that error will be reraised from + `tf.__internal__.distribute.multi_process_runner.run`, and the aforementioned + namedtuple object will be available through the exception's + `mpr_result` attribute. + + This utility is used for simulating running TensorFlow programs across + multiple task types, and each of the task type may contain more than one task + (except for "chief" where more than one task is prohibited). Test coverage of + multi-worker training is the main application of this utility, where code + written for multi-worker training can be realistically covered in unit tests. + + Any test module that uses + `tf.__internal__.distribute.multi_process_runner.run()` must call + `tf.__internal__.distribute.multi_process_runner.test_main()` instead of + regular `test.main()` inside `if __name__ == '__main__':` block for proper + initialization. + + Args: + fn: Function to be run on child processes. This will be run on processes for + all task types. + cluster_spec: Dict for cluster spec. The utility function + `tf.__internal__.distribute.multi_process_runner.create_cluster_spec` can + be conveniently used to create such dict. The following is an example of + cluster with three workers and two ps's. + {"worker": ["worker0.example.com:2222", + "worker1.example.com:2222", + "worker2.example.com:2222"], + "ps": ["ps0.example.com:2222", + "ps1.example.com:2222"]} + rpc_layer: RPC layer to use. Default value is 'grpc'. + max_run_time: `None` or integer. If not `None`, child processes are forced + to exit at approximately this many seconds after this utility is called. + We achieve this through `signal.alarm()` api. Note that this is best + effort at Python level since Python signal handler does not get executed + when it runs lower level C/C++ code. So it can be delayed for arbitrarily + long time. If any of the child process is still running when + `max_run_time` is up, they will be force-terminated and an + `tf.__internal__.distribute.multi_process_runner + .UnexpectedSubprocessExitError` + may be raised. If `None`, child processes are not forced to exit. + return_output: If True, the output/error from the subprocesses should be + collected to be attached to the resulting namedtuple returned from this + utility. The list of output can be retrieved via `stdout` attribute. + Defaults to False. + timeout: optional integer or `None`. If provided as an integer, and not all + processes report status within roughly `timeout` seconds, a + `tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError` + exception will be raised. If `None`, + `tf.__internal__.distribute.multi_process_runner.run` never times out. + Defaults to the constant `_DEFAULT_TIMEOUT_SEC` defined in + `multi_process_runner` module. + args: Positional arguments to be sent to `fn` run on subprocesses. + kwargs: Keyword arguments to be sent to `fn` run on subprocesses. + + Returns: + A namedtuple object, which has two attributes, + `return_value` and `stdout`. `return_value` always contains a list of + returnvalues from the subprocesses, although the order is not meaningful. + If `return_output` argument is True, `stdout` is available that contains a + list of all messages from subprocesses' stdout and stderr, and the order + is mostly chronological. + + Raises: + RuntimeError: if + `tf.__internal__.distribute.multi_process_runner.test_main()` is + not called in test's `if __name__ == '__main__':` block. + ValueError: if there are more than one chief in the `cluster_spec`. + tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError: if + not all processes report status approximately + within `timeout` seconds. When this is raised, a + namedtuple object can be retrieved by + `tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s + `mpr_result` attribute, which has the same + structure as above 'Returns' section describes. + tf.__internal__.distribute.multi_process_runner + .UnexpectedSubprocessExitError: + If any of the subprocesses did not exit + properly (for example, they exit on SIGTERM or SIGKILL signal). When + this is raised, a namedtuple object can be retrieved by + `tf.__internal__.distribute.multi_process_runner + .UnexpectedSubprocessExitError`'s + `mpr_result` attribute, which has the + same structure as above 'Returns' section describes. If `max_run_time` + is not `None`, it is expected that some subprocesses may be + force-killed when `max_run_time` is up, and this is raised in those + cases. + Exception: if there is an Exception propagated from any subprocess. When + this is raised, a namedtuple object can be retrieved by + `tf.__internal__.distribute.multi_process_runner + .UnexpectedSubprocessExitError` + `mpr_result` attribute, which has the + same structure as above 'Returns' section describes. + + Examples: + + ```python + class SimpleMultiProcessTest(tf.test.TestCase): + + def test_simple_printing_and_return(self): + + def fn(): + resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver() + + # This will print "[chief-0]: Task type: chief , task id: 0" + # for chief, for example. + logging.info('Task type: %s, task id: %d', + resolver.task_type, resolver.task_id) + + return resolver.task_type + + result = tf.__internal__.distribute.multi_process_runner.run( + fn=fn, + cluster_spec=( + tf.__internal__ + .distribute.multi_process_runner.create_cluster_spec( + has_chief=True, num_workers=2))) + assert sorted(result.return_value) == ['chief', 'worker', 'worker'] + + def test_error_from_fn(self): + + def fn(): + resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver() + raise ValueError('Task type {}, task id {} is errors out'.format( + resolver.task_type, resolver.task_id)) + + with self.assertRaisesRegexp(ValueError, + 'Task type worker, task id 0 is errors out'): + cluster_spec = ( + tf.__internal__.distribute.multi_process_runner.create_cluster_spec( + num_workers=1)) + tf.__internal__.distribute.multi_process_runner.run( + fn=fn, cluster_spec=cluster_spec) + + + if __name__ == '__main__': + tf.__internal__.distribute.multi_process_runner.test_main() + ``` + """ + runner = MultiProcessRunner( + fn, + cluster_spec, + rpc_layer, + max_run_time=max_run_time, + return_output=return_output, + args=args, + kwargs=kwargs) + runner.start() + return runner.join(timeout) + + +# This is set by MultiProcessRunner in worker processes. +_barrier = None + + +@tf_export('__internal__.distribute.multi_process_runner.get_barrier', v1=[]) +def get_barrier(): + """Returns a `multiprocessing.Barrier` for `multi_process_runner.run`. + + `tf.__internal__.distribute.multi_process_runner.get_barrier()` returns + a `multiprocessing.Barrier` object which can be used within `fn` of + `tf.__internal__.distribute.multi_process_runner` to wait with + `barrier.wait()` call until all other tasks have also reached the + `barrier.wait()` call, before they can proceed individually. + + Note that all tasks (subprocesses) have to reach `barrier.wait()` call to + proceed. Currently it is not supported to block on only a subset of tasks + in the cluster. + + Example: + ```python + + def fn(): + some_work_to_be_done_by_all_tasks() + + tf.__internal__.distribute.multi_process_runner.get_barrier().wait() + + # The barrier guarantees that at this point, all tasks have finished + # `some_work_to_be_done_by_all_tasks()` + some_other_work_to_be_done_by_all_tasks() + + result = tf.__internal__.distribute.multi_process_runner.run( + fn=fn, + cluster_spec=( + tf.__internal__ + .distribute.multi_process_runner.create_cluster_spec( + num_workers=2))) + ``` + + + Returns: + A `multiprocessing.Barrier` for `multi_process_runner.run`. + """ + if _barrier is None: + raise ValueError( + 'barrier is not defined. It is likely because you are calling ' + 'get_barrier() in the main process. get_barrier() can only be called ' + 'in the subprocesses.' + ) + return _barrier + + +_manager = None +_manager_lock = threading.Lock() + + +def manager(): + """Returns the multiprocessing manager object for concurrency tools. + + The manager object is useful as it controls a server process that holds + the python objects that can be shared across processes. This can be used + for parent-subprocess communication: + + ```python + manager = multi_process_runner.manager() + some_event_happening_in_subprocess = manager.Event() + mpr = multi_process_runner.MultiProcessRunner(fn, cluster_spec, + args=(some_event_happening_in_subprocess,)) + mpr.start() + some_event_happening_in_subprocess.wait() + # Do something that only should after some event happens in subprocess. + ``` + + Note that the user of multi_process_runner should not create additional + `multiprocessing.Manager()` objects; doing so can result in segfault in + some cases. + + This method should only be called after multi_process_runner.test_main() is + called. + """ + _check_initialization() + global _manager + with _manager_lock: + if _manager is None: + _manager = multiprocessing.Manager() + return _manager + + +@tf_export('__internal__.distribute.multi_process_runner.test_main', v1=[]) +def test_main(): + """Main function to be called within `__main__` of a test file. + + Any test module that uses + `tf.__internal__.distribute.multi_process_runner.run()` + must call this instead of regular `test.main()` inside + `if __name__ == '__main__':` block, or an error will be raised when + `tf.__internal__.distribute.multi_process_runner.run()` is used. This method + takes + care of needed initialization for launching multiple subprocesses. + + Example: + ```python + class MyTestClass(tf.test.TestCase): + def testSomething(self): + # Testing code making use of + # `tf.__internal__.distribute.multi_process_runner.run()`. + + if __name__ == '__main__': + tf.__internal__.distribute.multi_process_runner.test_main() + ``` + """ + # Inject tearDownModule() to shut down all pool runners. Active pool runners + # will block the program from exiting. This is necessary for global pool + # runners. We tried atexit in the past, and it doesn't work in some + # deployment. + old_tear_down_module = getattr(sys.modules['__main__'], 'tearDownModule', + None) + + def tear_down_module(): + _shutdown_all_pool_runners() + if old_tear_down_module is not None: + old_tear_down_module() + + setattr(sys.modules['__main__'], 'tearDownModule', tear_down_module) + multi_process_lib.test_main() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_worker_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_worker_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..061db2de755f05450e2ea8d8e93e27fd73fd3588 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_worker_test_base.py @@ -0,0 +1,840 @@ +# 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. +# ============================================================================== +"""Base testing class for strategies that require multiple nodes.""" + +import contextlib +import copy +import json +import os +import subprocess +import sys +import threading +import unittest + +import six + + +# pylint: disable=g-import-not-at-top +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.client import session +from tensorflow.python.distribute import distribute_coordinator as dc +from tensorflow.python.distribute import multi_process_runner +from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib +from tensorflow.python.distribute.cluster_resolver import tfconfig_cluster_resolver +from tensorflow.python.eager import context +from tensorflow.python.eager import remote +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.platform import test +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import coordinator +from tensorflow.python.training import server_lib +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +original_run_std_server = dc._run_std_server # pylint: disable=protected-access +pick_unused_port = test_util.pick_unused_port + + +def _create_cluster(num_workers, + num_ps, + has_chief=False, + has_eval=False, + protocol='grpc', + worker_config=None, + ps_config=None, + eval_config=None, + worker_name='worker', + ps_name='ps', + chief_name='chief'): + """Creates and starts local servers and returns the cluster_spec dict.""" + + worker_ports = [pick_unused_port() for _ in range(num_workers)] + ps_ports = [pick_unused_port() for _ in range(num_ps)] + + cluster_dict = {} + if num_workers > 0: + cluster_dict[worker_name] = ['localhost:%s' % port for port in worker_ports] + if num_ps > 0: + cluster_dict[ps_name] = ['localhost:%s' % port for port in ps_ports] + if has_eval: + cluster_dict['evaluator'] = ['localhost:%s' % pick_unused_port()] + if has_chief: + cluster_dict[chief_name] = ['localhost:%s' % pick_unused_port()] + + cs = server_lib.ClusterSpec(cluster_dict) + + for i in range(num_workers): + server_lib.Server( + cs, + job_name=worker_name, + protocol=protocol, + task_index=i, + config=worker_config, + start=True) + + for i in range(num_ps): + server_lib.Server( + cs, + job_name=ps_name, + protocol=protocol, + task_index=i, + config=ps_config, + start=True) + + if has_chief: + server_lib.Server( + cs, + job_name=chief_name, + protocol=protocol, + task_index=0, + config=worker_config, + start=True) + + if has_eval: + server_lib.Server( + cs, + job_name='evaluator', + protocol=protocol, + task_index=0, + config=eval_config, + start=True) + + return cluster_dict + + +def create_in_process_cluster(num_workers, + num_ps, + has_chief=False, + has_eval=False, + rpc_layer='grpc'): + """Create an in-process cluster that consists of only standard server.""" + # Leave some memory for cuda runtime. + gpu_mem_frac = 0.7 / (num_workers + int(has_chief) + int(has_eval)) + worker_config = config_pb2.ConfigProto() + worker_config.gpu_options.per_process_gpu_memory_fraction = gpu_mem_frac + + # The cluster may hang if workers don't have enough inter_op threads. See + # b/172296720 for more details. + if worker_config.inter_op_parallelism_threads < num_workers + 1: + worker_config.inter_op_parallelism_threads = num_workers + 1 + + # Enable collective ops which has no impact on non-collective ops. + # TODO(yuefengz, tucker): removing this after we move the initialization of + # collective mgr to the session level. + if has_chief: + worker_config.experimental.collective_group_leader = ( + '/job:chief/replica:0/task:0') + else: + worker_config.experimental.collective_group_leader = ( + '/job:worker/replica:0/task:0') + + ps_config = config_pb2.ConfigProto() + ps_config.device_count['GPU'] = 0 + + eval_config = config_pb2.ConfigProto() + eval_config.experimental.collective_group_leader = '' + + # Create in-process servers. Once an in-process tensorflow server is created, + # there is no way to terminate it. So we create one cluster per test process. + # We could've started the server in another process, we could then kill that + # process to terminate the server. The reasons why we don't want multiple + # processes are + # 1) it is more difficult to manage these processes; + # 2) there is something global in CUDA such that if we initialize CUDA in the + # parent process, the child process cannot initialize it again and thus cannot + # use GPUs (https://stackoverflow.com/questions/22950047). + cluster = None + try: + cluster = _create_cluster( + num_workers, + num_ps=num_ps, + has_chief=has_chief, + has_eval=has_eval, + worker_config=worker_config, + ps_config=ps_config, + eval_config=eval_config, + protocol=rpc_layer) + except errors.UnknownError as e: + if 'Could not start gRPC server' in e.message: + raise unittest.SkipTest('Cannot start std servers.') + else: + raise + return cluster + + +class MultiProcessCluster(object): + """A cluster of TensorFlow servers in separate processes. + + This class is not thread-safe. + """ + + def __init__(self, + cluster_resolver, + stream_output=False, + collective_leader=None): + self._cluster_resolver = cluster_resolver + self._cluster_spec = cluster_resolver.cluster_spec().as_dict() + self._rpc_layer = cluster_resolver.rpc_layer + self._stream_output = stream_output + self._start_events = {} + self._finish_events = {} + self._mpr_manager = multi_process_runner.manager() + + def task_function(start_events, finish_events): + cluster_resolver = tfconfig_cluster_resolver.TFConfigClusterResolver() + cluster_spec = cluster_resolver.cluster_spec() + task_type = cluster_resolver.task_type + task_id = cluster_resolver.task_id + rpc_layer = cluster_resolver.rpc_layer + + # TODO(yuefengz): support GPU clusters. + server_config = config_pb2.ConfigProto() + server_config.device_count['GPU'] = 0 + + if collective_leader: + server_config.experimental.collective_group_leader = collective_leader + server_config.experimental.collective_nccl = False + + logging.info( + 'Enabling collective ops with cluster_spec = %r, task_type = %r, ' + 'task_id = %r, rpc_layer = %r, collective_leader = %s', + cluster_spec, task_type, task_id, rpc_layer, collective_leader) + else: + logging.info( + 'Starting server with cluster_spec = %r, task_type = %r, ' + 'task_id = %r, rpc_layer = %r', cluster_spec, task_type, task_id, + rpc_layer) + + server_lib.Server( + cluster_spec, + job_name=task_type, + protocol=rpc_layer, + task_index=task_id, + config=server_config, + start=True) + + start_event = start_events[task_type][task_id] + start_event.set() + + finish_event = finish_events[task_type][task_id] + finish_event.wait() + + os._exit(0) # pylint: disable=protected-access + + self._task_function = task_function + self._mpr = None + + def start(self): + """Starts one TensorFlow server for each task in the cluster_resolver. + + It will wait until all the servers are up before returns. + """ + if self._mpr: + raise ValueError('The cluster has already been started.') + for task_type, task_addresses in self._cluster_spec.items(): + self._start_events[task_type] = [] + self._finish_events[task_type] = [] + for _ in task_addresses: + self._start_events[task_type].append(self._mpr_manager.Event()) + self._finish_events[task_type].append(self._mpr_manager.Event()) + + self._mpr = multi_process_runner.MultiProcessRunner( + self._task_function, + self._cluster_spec, + args=(self._start_events, self._finish_events), + rpc_layer=self._rpc_layer, + stream_output=self._stream_output, + return_output=False, + use_dill_for_args=False) + self._mpr.start() + for task_type, task_addresses in self._cluster_spec.items(): + for i in range(len(task_addresses)): + self._start_events[task_type][i].wait() + + def stop(self): + """Stops all the servers.""" + for task_type, task_addresses in self._cluster_spec.items(): + for i in range(len(task_addresses)): + self._finish_events[task_type][i].set() + try: + self._mpr.join() + except multi_process_runner.UnexpectedSubprocessExitError: + # TODO(yuefengz): investigate why processes exit with 255. + pass + self._mpr = None + self._start_events = {} + self._finish_events = {} + + def kill_task(self, task_type, task_id): + """Kill a server given task_type and task_id. + + Args: + task_type: the type of the task such as "worker". + task_id: the id the task such as 1. + """ + assert self._mpr + if (not self._start_events[task_type][task_id].is_set() or + self._finish_events[task_type][task_id].is_set()): + raise ValueError("The task %s:%d doesn't exist." % (task_type, task_id)) + + self._finish_events[task_type][task_id].set() + self._mpr._processes[(task_type, task_id)].join() + + def start_task(self, task_type, task_id): + """Starts a server given task_type and task_id. + + Args: + task_type: the type of the task such as "worker". + task_id: the id the task such as 1. + + Raises: + ValueError: if the server already exists. + """ + assert self._mpr + + if (not self._start_events[task_type][task_id].is_set() or + not self._finish_events[task_type][task_id].is_set()): + raise ValueError( + 'The task %s:%d is still alive. You cannot start another one.' % + (task_type, task_id)) + self._start_events[task_type][task_id] = self._mpr_manager.Event() + self._finish_events[task_type][task_id] = self._mpr_manager.Event() + self._mpr.start_single_process(task_type=task_type, task_id=task_id) + self._start_events[task_type][task_id].wait() + + @property + def cluster_resolver(self): + return copy.deepcopy(self._cluster_resolver) + + +def create_multi_process_cluster(num_workers, + num_ps, + has_chief=False, + has_eval=False, + rpc_layer='grpc', + stream_output=False, + collective_leader=None): + logging.info('Now creating a MultiProcessCluster with ' + f'num_workers={num_workers}, num_ps={num_ps}.') + cluster_spec = create_cluster_spec( + has_chief=has_chief, + num_workers=num_workers, + num_ps=num_ps, + has_eval=has_eval) + + cluster = MultiProcessCluster( + cluster_resolver_lib.SimpleClusterResolver( + server_lib.ClusterSpec(cluster_spec), rpc_layer=rpc_layer), + stream_output=stream_output, + collective_leader=collective_leader) + cluster.start() + return cluster + + +@tf_export( + '__internal__.distribute.multi_process_runner.create_cluster_spec', v1=[]) +def create_cluster_spec(has_chief=False, + num_workers=1, + num_ps=0, + has_eval=False): + """Create a cluster spec with tasks with unused local ports. + + This utility finds available ports at localhost, and returns a dict that + represents the cluster spec that utilizes those ports, according to the + arguments. The dict representing the cluster spec contains task types, and + their instances' addresses. Note that this is usually only for testing purpose + using multiple processes in the local machine, and should not be used for real + multi-worker TensorFlow programs, where the addresses need to point to the + processes at separate machines. + + This util is useful when creating the `cluster_spec` arg for + `tf.__internal__.distribute.multi_process_runner.run`. + + Args: + has_chief: Whether the generated cluster spec should contain "chief" task + type. + num_workers: Number of workers to use in the cluster spec. + num_ps: Number of parameter servers to use in the cluster spec. + has_eval: Whether this cluster spec has evaluator. + + Returns: + A dict that represents the cluster spec using localhost ports for the tasks. + + Example: + + ```python + cluster_spec = + tf.__internal__.distribute.multi_process_runner.create_cluster_spec( + has_chief=True, num_workers=2, num_ps=2) + # An example of cluster_spec is + # {'chief': ['localhost:23381'], + # 'worker': ['localhost:19197', 'localhost:22903'], + # 'ps': ['localhost:16912', 'localhost:21535']} + + cluster_spec = + tf.__internal__.distribute.multi_process_runner.create_cluster_spec( + has_chief=False, num_workers=0, num_ps=0, has_eval=True) + # An example of cluster_spec is + # {'evaluator': ['localhost:23381']} + ``` + """ + cluster_spec = {} + if has_chief: + cluster_spec['chief'] = ['localhost:%s' % pick_unused_port()] + if num_workers: + cluster_spec['worker'] = [ + 'localhost:%s' % pick_unused_port() for _ in range(num_workers) + ] + if num_ps: + cluster_spec['ps'] = [ + 'localhost:%s' % pick_unused_port() for _ in range(num_ps) + ] + if has_eval: + cluster_spec['evaluator'] = ['localhost:%s' % pick_unused_port()] + return cluster_spec + + +@contextlib.contextmanager +def skip_if_grpc_server_cant_be_started(test_obj): + try: + yield + except errors.UnknownError as e: + if 'Could not start gRPC server' in e.message: + reason = 'Cannot start std servers.' + test_obj.test_skipped_reason = reason + test_obj.skipTest(reason) + else: + raise + + +class MultiWorkerTestBase(test.TestCase): + """Base class for testing multi node strategy and dataset.""" + + @classmethod + def setUpClass(cls, num_workers=2, num_ps=1): # pylint: disable=g-missing-super-call + """Create a local cluster with 2 workers.""" + cls._cluster_spec = create_in_process_cluster(num_workers=num_workers, + num_ps=num_ps) + cls._default_target = 'grpc://' + cls._cluster_spec['worker'][0] + + def setUp(self): + # We only cache the session in one test because another test may have a + # different session config or master target. + self._thread_local = threading.local() + self._thread_local.cached_session = None + self._coord = coordinator.Coordinator() + + @contextlib.contextmanager + def session(self, graph=None, config=None, target=None): + """Create a test session with master target set to the testing cluster. + + Creates a test session that connects to the local testing cluster. + + Args: + graph: Optional graph to use during the returned session. + config: An optional config_pb2.ConfigProto to use to configure the + session. + target: the target of session to connect to. + + Yields: + A Session object that should be used as a context manager to surround + the graph building and execution code in a test case. + """ + config = self._create_config(config) + + if target is None: + target = self._default_target + with session.Session(graph=graph, config=config, target=target) as sess: + yield sess + + @contextlib.contextmanager + # TODO(b/117573461): Overwrite self.evaluate() to use this function. + def cached_session(self, graph=None, config=None, target=None): + """Create a test session with master target set to the testing cluster. + + Creates a test session that connects to the local testing cluster. + The session is only created once per test and then reused. + + Args: + graph: Optional graph to use during the returned session. + config: An optional config_pb2.ConfigProto to use to configure the + session. + target: the target of session to connect to. + + Yields: + A Session object that should be used as a context manager to surround + the graph building and execution code in a test case. Note that the + session will live until the end of the test. + """ + config = self._create_config(config) + + if target is None: + target = self._default_target + if getattr(self._thread_local, 'cached_session', None) is None: + self._thread_local.cached_session = session.Session( + graph=None, config=config, target=target) + sess = self._thread_local.cached_session + with sess.graph.as_default(), sess.as_default(): + yield sess + + def _create_config(self, config): + if config is None: + config = config_pb2.ConfigProto(allow_soft_placement=True) + else: + config = copy.deepcopy(config) + # Don't perform optimizations for tests so we don't inadvertently run + # gpu ops on cpu + config.graph_options.optimizer_options.opt_level = -1 + config.graph_options.rewrite_options.constant_folding = ( + rewriter_config_pb2.RewriterConfig.OFF) + + return config + + def _run_client(self, client_fn, task_type, task_id, num_gpus, eager_mode, + *args, **kwargs): + + def wrapped_client_fn(): + with self._coord.stop_on_exception(): + client_fn(task_type, task_id, num_gpus, *args, **kwargs) + + if eager_mode: + with context.eager_mode(): + wrapped_client_fn() + else: + with context.graph_mode(): + wrapped_client_fn() + + def _run_between_graph_clients(self, client_fn, cluster_spec, num_gpus, *args, + **kwargs): + """Runs several clients for between-graph replication. + + Args: + client_fn: a function that needs to accept `task_type`, `task_id`, + `num_gpus`. + cluster_spec: a dict specifying jobs in a cluster. + num_gpus: number of GPUs per worker. + *args: will be passed to `client_fn`. + **kwargs: will be passed to `client_fn`. + """ + threads = [] + for task_type in ['chief', 'worker']: + for task_id in range(len(cluster_spec.get(task_type, []))): + t = threading.Thread( + target=self._run_client, + args=(client_fn, task_type, task_id, num_gpus, + context.executing_eagerly()) + args, + kwargs=kwargs) + t.start() + threads.append(t) + self._coord.join(threads) + + +class SingleWorkerTestBaseGraph(MultiWorkerTestBase): + """Base class for testing remote single worker strategy graph and dataset.""" + + @classmethod + def setUpClass(cls): + super(SingleWorkerTestBaseGraph, cls).setUpClass(num_workers=1) + + +class SingleWorkerTestBaseEager(test.TestCase): + """Base class for testing remote single worker strategy eager and dataset.""" + + def setUp(self): + super(SingleWorkerTestBaseEager, self).setUp() + workers, _ = test_util.create_local_cluster(num_workers=1, num_ps=0) + remote.connect_to_remote_host(workers[0].target) + + def cached_session(self): + return DummySession() + + +class DummySession(object): + + def __enter__(self): + return + + def __exit__(self, exception_type, exception_value, traceback): + pass + + +class MockOsEnv(collections_abc.Mapping): + """A class that allows per-thread TF_CONFIG.""" + + def __init__(self, *args): + self._dict = dict() + self._thread_local = threading.local() + super(MockOsEnv, self).__init__(*args) + + def get(self, key, default=None): + if not hasattr(self._thread_local, 'dict'): + self._thread_local.dict = dict() + if key == 'TF_CONFIG': + return dict.get(self._thread_local.dict, key, default) + else: + return dict.get(self._dict, key, default) + + def __getitem__(self, key): + if not hasattr(self._thread_local, 'dict'): + self._thread_local.dict = dict() + if key == 'TF_CONFIG': + return dict.__getitem__(self._thread_local.dict, key) + else: + return dict.__getitem__(self._dict, key) + + def __setitem__(self, key, val): + if not hasattr(self._thread_local, 'dict'): + self._thread_local.dict = dict() + if key == 'TF_CONFIG': + return dict.__setitem__(self._thread_local.dict, key, val) + else: + return dict.__setitem__(self._dict, key, val) + + def __iter__(self): + if not hasattr(self._thread_local, 'dict'): + self._thread_local.dict = dict() + for x in self._thread_local.dict: + yield x + for x in self._dict: + yield x + + def __len__(self): + if not hasattr(self._thread_local, 'dict'): + self._thread_local.dict = dict() + return self._thread_local.dict.__len__() + self._dict.__len__() + + +class IndependentWorkerTestBase(test.TestCase): + """Testing infra for independent workers.""" + + def _make_mock_run_std_server(self): + + def _mock_run_std_server(*args, **kwargs): + """Returns the std server once all threads have started it.""" + with skip_if_grpc_server_cant_be_started(self): + ret = original_run_std_server(*args, **kwargs) + # Wait for all std servers to be brought up in order to reduce the chance + # of remote sessions taking local ports that have been assigned to std + # servers. Only call this barrier the first time this function is run for + # each thread. + if not getattr(self._thread_local, 'server_started', False): + self._barrier.wait() + self._thread_local.server_started = True + return ret + + return _mock_run_std_server + + def setUp(self): + self._mock_os_env = MockOsEnv() + self._mock_context = test.mock.patch.object(os, 'environ', + self._mock_os_env) + self._coord = coordinator.Coordinator() + super(IndependentWorkerTestBase, self).setUp() + self._mock_context.__enter__() + # threading local object to be shared by all threads + self._thread_local = threading.local() + + def tearDown(self): + self._mock_context.__exit__(None, None, None) + super(IndependentWorkerTestBase, self).tearDown() + + def _task_thread(self, task_fn, tf_config, executing_eagerly, *args, + **kwargs): + with self._coord.stop_on_exception(): + os.environ['TF_CONFIG'] = json.dumps(tf_config) + # Force the new thread simulating a worker to run in the same context + # mode as the parent thread does. + if executing_eagerly: + with context.eager_mode(): + task_fn(*args, **kwargs) + else: + with ops.Graph().as_default(), context.graph_mode(): + task_fn(*args, **kwargs) + + def _run_task_in_thread(self, task_fn, cluster_spec, task_type, task_id, + *args, **kwargs): + """Run tasks in a thread. + + If `tf_config` is provided, use it for the new thread; if not, construct one + from `cluster_spec`, `task_type`, and `task_id`, and provide it to the new + thread to be set as `TF_CONFIG` environment. + + Args: + task_fn: The function to run in the new thread. + cluster_spec: The cluster spec. + task_type: The task type. + task_id: The task id. + *args: Additional positional arguments to provide to the thread's task_fn. + **kwargs: Additional keyword arguments to provide to the thread's task_fn. + If `tf_config` is provided, that dict will be used for the TF_CONFIG for + the new thread. + + Returns: + The thread that has started. + """ + tf_config = kwargs.pop('tf_config', None) + if tf_config is None: + if task_type: + tf_config = { + 'cluster': cluster_spec, + 'task': { + 'type': task_type, + 'index': task_id + } + } + else: + tf_config = { + 'cluster': cluster_spec, + } + t = threading.Thread( + target=self._task_thread, + args=(task_fn, tf_config, context.executing_eagerly()) + args, + kwargs=kwargs) + t.start() + return t + + def run_multiple_tasks_in_threads(self, task_fn, cluster_spec, *args, + **kwargs): + # The task_fn should create std_server by itself. + threads = {} + for task_type in cluster_spec.keys(): + threads[task_type] = [] + for task_id in range(len(cluster_spec[task_type])): + t = self._run_task_in_thread(task_fn, cluster_spec, task_type, task_id, + *args, **kwargs) + threads[task_type].append(t) + return threads + + def join_independent_workers(self, worker_threads): + with skip_if_grpc_server_cant_be_started(self): + self._coord.join(worker_threads) + + +class MultiWorkerMultiProcessTest(test.TestCase): + """Testing infra for independent workers using multiple processes.""" + + def _run_task_in_process(self, cmd_args, cluster_spec, task_type, task_id): + env = os.environ.copy() + env['TF_CONFIG'] = json.dumps({ + 'cluster': cluster_spec, + 'task': { + 'type': task_type, + 'index': task_id + } + }) + return subprocess.Popen( + cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) + + @deprecation.deprecated( + None, '`run_multiple_tasks_in_processes` is deprecated; any new test ' + 'requiring multiple processes should use `multi_process_runner` for ' + 'better support of log printing, streaming, and more functionality.') + def run_multiple_tasks_in_processes(self, cmd_args, cluster_spec): + """Run `cmd_args` in a process for each task in `cluster_spec`.""" + processes = {} + for task_type in cluster_spec.keys(): + processes[task_type] = [] + for task_id in range(len(cluster_spec[task_type])): + p = self._run_task_in_process(cmd_args, cluster_spec, task_type, + task_id) + processes[task_type].append(p) + return processes + + @deprecation.deprecated( + None, '`join_independent_workers` is deprecated; any new test ' + 'requiring multiple processes should use `multi_process_runner` for ' + 'better support of log printing, streaming, and more functionality.') + def join_independent_workers(self, worker_processes): + return_codes = [] + for p in nest.flatten(worker_processes): + try: + # Calling p.wait() will hang if we don't consume its output. + p.communicate() + except ValueError: + # The output of the process may have been consumed, in which case + # calling `p.communicate()` will raise a ValueError. + pass + finally: + return_codes.append(p.returncode) + for return_code in return_codes: + self.assertEqual(return_code, 0) + + @deprecation.deprecated( + None, '`stream_stderr` is deprecated; any new test ' + 'requiring multiple processes should use `multi_process_runner` for ' + 'better support of log printing, streaming, and more functionality.') + def stream_stderr(self, processes, print_only_first=False): + """Consume stderr of all processes and print to stdout. + + To reduce the amount of logging, caller can set print_only_first to True. + In that case, this function only prints stderr from the first process of + each type. + + Args: + processes: A dictionary from process type string -> list of processes. + print_only_first: If true, only print output from first process of each + type. + """ + + def _stream_stderr_single_process(process, type_string, index, + print_to_stdout): + """Consume a single process's stderr and optionally print to stdout.""" + while True: + output = process.stderr.readline() + if not output and process.poll() is not None: + break + if output and print_to_stdout: + print('{}{} {}'.format(type_string, index, output.strip())) + sys.stdout.flush() + + stream_threads = [] + for process_type, process_list in six.iteritems(processes): + for i in range(len(process_list)): + print_to_stdout = (not print_only_first) or (i == 0) + thread = threading.Thread( + target=_stream_stderr_single_process, + args=(process_list[i], process_type, i, print_to_stdout)) + thread.start() + stream_threads.append(thread) + for thread in stream_threads: + thread.join() + + +def get_tf_config_task(): + return json.loads(os.environ['TF_CONFIG'])['task'] + + +def get_tf_config_cluster_spec(): + return json.loads(os.environ['TF_CONFIG'])['cluster'] + + +def get_task_type(): + return get_tf_config_task()['type'] + + +def get_task_index(): + return get_tf_config_task()['index'] + + +def is_chief(): + return ('chief' not in get_tf_config_cluster_spec() + and get_task_type() == 'worker' + and get_task_index() == 0) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_worker_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_worker_util.py new file mode 100644 index 0000000000000000000000000000000000000000..082dbdf7abb1b76ed9957329db680456c3e36332 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/multi_worker_util.py @@ -0,0 +1,306 @@ +# 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. +# ============================================================================== +"""Utilities for multi-worker distribution strategies.""" + +from tensorflow.core.protobuf import cluster_pb2 +from tensorflow.python.distribute import distribute_coordinator_context as dc_context +from tensorflow.python.training import server_lib + + +def normalize_cluster_spec(cluster_spec): + """Makes `cluster_spec` into a `ClusterSpec` object. + + Args: + cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the + cluster configurations. + + Returns: + a `ClusterSpec` object. + + Raises: + ValueError: if `cluster_spec` is not a dict or a `ClusterSpec` or a + `ClusterDef`. + """ + if isinstance(cluster_spec, (dict, cluster_pb2.ClusterDef)): + return server_lib.ClusterSpec(cluster_spec) + elif not isinstance(cluster_spec, server_lib.ClusterSpec): + raise ValueError( + "`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a " + "`tf.train.ClusterDef` object") + return cluster_spec + + +def task_count(cluster_spec, task_type): + try: + return cluster_spec.num_tasks(task_type) + except ValueError: + return 0 + + +def _validate_cluster_spec(cluster_spec, + task_type, + task_id): + """Validates `cluster_spec`. + + It checks: + 1) task type is one of "chief", "worker", "ps", "evaluator", or not provided + (None). + 2) whether there is such a task type as `task_type` in the `cluster_spec`. The + only exception is `evaluator`. In other words, it is still a valid + configuration when `task_type` is `evaluator` but it doesn't appear in + `cluster_spec`. This is to be compatible with `TF_CONFIG` in Estimator. + 3) whether there is at most one "chief" job. + 4) whether there is at most one "evaluator" job. + 5) whether the `task_id` is smaller than the number of tasks for that + particular `task_type`. + + Args: + cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object to be validated. + task_type: string indicating the type of the task. + task_id: the id of the `task_type` in this cluster. + + Raises: + ValueError: if `cluster_spec` fails any check. + """ + allowed_task_types = ("chief", "worker", "evaluator", "ps", None) + + cluster_spec = normalize_cluster_spec(cluster_spec) + + if any(job not in allowed_task_types for job in cluster_spec.jobs): + raise ValueError("Disallowed task type found in cluster spec. Allowed " + "types are {} and the cluster spec is {}.".format( + allowed_task_types, cluster_spec)) + + if task_type not in allowed_task_types: + raise ValueError( + "Unrecognized task_type: {}, valid task types are: {}".format( + task_type, allowed_task_types)) + + if (task_type and task_type not in cluster_spec.jobs and + task_type != "evaluator"): + raise ValueError("`task_type` %r not found in cluster_spec." % task_type) + + if task_count(cluster_spec, "chief") > 1: + raise ValueError("There must be at most one 'chief' job.") + + if task_count(cluster_spec, "evaluator") > 1: + raise ValueError("There must be at most one 'evaluator' job.") + + # The `evaluator` job is allowed to be missing in `cluster_spec`. + if task_type in cluster_spec.jobs and task_id >= task_count( + cluster_spec, task_type): + raise ValueError( + "The `task_id` %d exceeds the maximum id of %s." % (task_id, task_type)) + + +def is_chief(cluster_spec=None, task_type=None, task_id=None): + """Returns whether the given task is chief in the cluster. + + Since there is at most one evaluator and the evaluator itself should be + independent of the training cluster, the evaluator job is also a chief job on + its own. + + If this is currently running under a `_WorkerContext` of distribute + coordinator, the arguments can be omitted as the result is already available. + + Args: + cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object specifying the + cluster configurations. + task_type: the task type in the cluster. + task_id: the task id in the cluster. + + Returns: + a boolean indicating whether the given task is chief. + + Raises: + ValueError: if `task_type` is not in the `cluster_spec` or `task_id` exceeds + the maximum id of the `task_type`. + """ + if has_worker_context(): + # If a worker context exists, use the value provided by it. + return dc_context.get_current_worker_context().is_chief + + _validate_cluster_spec(cluster_spec, task_type, task_id) + cluster_spec = normalize_cluster_spec(cluster_spec).as_dict() + + if task_type == "chief" or task_type == "evaluator": + return True + + # If chief not in the cluster_spec, use the first worker as chief. This is + # common in CollectiveAllReduceStrategy. + if ("chief" not in cluster_spec and task_type == "worker" and task_id == 0): + return True + return False + + +def collective_leader(cluster_spec, task_type, task_id): + """Return the job name for the leader of for collective ops. + + Args: + cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object specifying the + cluster configurations. + task_type: the task type in the cluster. + task_id: the task id in the cluster. + + Returns: + a string indicating the leader job name or empty string if no need to set + leader job. + """ + cluster_spec = normalize_cluster_spec(cluster_spec) + + # No need to set collective leader for local. + if not cluster_spec.as_dict(): + return "" + + _validate_cluster_spec(cluster_spec, task_type, task_id) + + # Only one evaluator, so no need to set collective leader. + if task_type == "evaluator": + return "" + + # Use chief if chief is in the cluster. + if "chief" in cluster_spec.jobs: + return "/job:chief/replica:0/task:0" + + # Use worker 0 if no chief job. + assert "worker" in cluster_spec.jobs + return "/job:worker/replica:0/task:0" + + +def coordination_leader(cluster_spec): + """Return the task name of the coordination service leader. + + Args: + cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object sxpecifying the + cluster configurations. + + Returns: + a string indicating the task name of the coordination service leader. + """ + cluster_spec = normalize_cluster_spec(cluster_spec) + + # No need to set coordination service leader for local. + if not cluster_spec.as_dict(): + return "" + + # Use PS 0 if parameter servers are in the cluster + if "ps" in cluster_spec.jobs: + return "/job:ps/replica:0/task:0" + + # Use chief if chief is in the cluster. + if "chief" in cluster_spec.jobs: + return "/job:chief/replica:0/task:0" + + # Use worker 0 if no chief job. + assert "worker" in cluster_spec.jobs + return "/job:worker/replica:0/task:0" + + +def worker_count(cluster_spec, task_type): + """Returns the number of workers in the cluster.""" + _validate_cluster_spec(cluster_spec, task_type, task_id=0) + cluster_spec = normalize_cluster_spec(cluster_spec).as_dict() + + # Other jobs such as "ps" shouldn't call this function. + if task_type not in ["chief", "worker", "evaluator"]: + raise ValueError("Unexpected `task_type` %r" % task_type) + + if task_type == "evaluator": + # The "evaluator" is in its own cluster or its own partition of a cluster. + # So we don't have to count "chief" or "worker" if the current task is an + # "evaluator". + return len(cluster_spec["evaluator"]) + else: + # In the non-evaluator case, we return the total number of "chief" and + # "worker" tasks as the "chief" is also a worker. + return (len(cluster_spec.get("chief", [])) + len( + cluster_spec.get("worker", []))) + + +def id_in_cluster(cluster_spec, task_type, task_id): + """Returns a unique id for the task in the `task_type`'s cluster. + + It returns an id ranging from [0, `worker_count(task_type, task_id)`). + + Note: this function assumes that "evaluate" job is in its own cluster or its + own partition of a cluster. + + Args: + cluster_spec: a dict, `ClusterDef` or `ClusterSpec` object to be validated. + task_type: string indicating the type of the task. + task_id: the id of the `task_type` in this cluster. + + Returns: + an int indicating the unique id. + + Throws: + ValueError: if `task_type` is not "chief", "worker" or "evaluator". + """ + _validate_cluster_spec(cluster_spec, task_type, task_id) + cluster_spec = normalize_cluster_spec(cluster_spec).as_dict() + + # The "chief" job has always id 0 and there is at most one and "worker" jobs + # come after it. + if task_type == "chief": + return 0 + + if task_type == "worker": + return task_id + len(cluster_spec.get("chief", [])) + + # The "evaluator" is in its own cluster or its own partition of a cluster. + if task_type == "evaluator": + return task_id + + # We currently don't assign ids to other tasks. + raise ValueError("There is no id for task_type %r" % task_type) + + +def should_save_checkpoint(): + """Returns whether the current worker should save checkpoints. + + In multi-worker training, if saving checkpoint is requested by user, or needed + for fault-tolerance, the cluster should save checkpoint but not necessarily + every worker in the cluster should. + + TODO(rchao): Consider generalizing this util to be `should_save_file` as there + can be other files to save such as summary. + + Returns: + Whether this particular worker in the cluster should save checkpoints. + """ + return dc_context.get_current_worker_context().should_checkpoint + + +def should_load_checkpoint(): + """Returns whether the current worker should load checkpoints. + + In multi-worker training, if loading checkpoint is requested by user, or + needed for fault-tolerance, the cluster should load checkpoint but not + necessarily every worker in the cluster should. + + Returns: + Whether this particular worker in the cluster should load checkpoints. + """ + return dc_context.get_current_worker_context().experimental_should_init + + +def wait_for_other_workers(): + """Waits for other workers to reach the same call to this method.""" + return dc_context.get_current_worker_context().wait_for_other_workers() + + +def has_worker_context(): + """Returns whether a worker context has been entered.""" + return dc_context.get_current_worker_context() is not None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/numpy_dataset.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/numpy_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8133e21c7339595569233f8ae77a212aa3456189 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/numpy_dataset.py @@ -0,0 +1,95 @@ +# 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. +# ============================================================================== +"""Code for creating a dataset out of a NumPy array.""" + +import numpy as np + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.util import nest + + +def init_var_from_numpy(input_var, numpy_input, session): + """Initialize `input_var` to `numpy_input` using `session` in graph mode.""" + with ops.init_scope(): + if context.executing_eagerly(): + input_var.assign(numpy_input) + return + + assert session is not None + session.run(input_var.initializer) + + start_placeholder = array_ops.placeholder(dtypes.int64, ()) + end_placeholder = array_ops.placeholder(dtypes.int64, ()) + slice_placeholder = array_ops.placeholder(input_var.dtype) + assign_slice_op = input_var[start_placeholder:end_placeholder].assign( + slice_placeholder) + + # If each batch element is > 64 MB, then we copy each batch element + # individually. Otherwise, the slices will be < 128 MB. There might be + # padding which might mean that the slices are 128 MB even if the size of + # the tensor allocated is less than 128 MB. This formula gives slices with + # size: ceil(64 MB / byte size per batch element) bytes. Using ceil() + # guarantees we get a number >= 1. + + # Calculate the size of each batch element. + byte_size_per_batch_element = ( + np.prod(numpy_input.shape[1:]) * input_var.dtype.size) + + # Calculate number of elements we want to copy per slice. + batch_size_per_slice = int( + np.ceil((64 << 20) / byte_size_per_batch_element)) + + # Copy slices of the above size starting at 0, except the last slice will be + # smaller. + start = 0 + limit = numpy_input.shape[0] + while start < limit: + end = min(start + batch_size_per_slice, limit) + session.run(assign_slice_op, feed_dict={ + start_placeholder: start, + end_placeholder: end, + slice_placeholder: numpy_input[start:end]}) + start = end + + +def one_host_numpy_dataset(numpy_input, colocate_with, session): + """Create a dataset on `colocate_with` from `numpy_input`.""" + + def create_colocated_variable(next_creator, **kwargs): + kwargs["colocate_with"] = colocate_with + return next_creator(**kwargs) + + numpy_flat = nest.flatten(numpy_input) + with variable_scope.variable_creator_scope(create_colocated_variable): + vars_flat = tuple(variable_v1.VariableV1(array_ops.zeros(i.shape, i.dtype), + trainable=False) + for i in numpy_flat) + for v, i in zip(vars_flat, numpy_flat): + init_var_from_numpy(v, i, session) + vars_nested = nest.pack_sequence_as(numpy_input, vars_flat) + return dataset_ops.Dataset.from_tensor_slices(vars_nested) + + +class SingleDevice(object): + """Used with `colocate_with` to create a non-mirrored variable.""" + + def __init__(self, device): + self.device = device diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/one_device_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/one_device_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2aa3fd744ae82559a0c1e202aa04ebe75c68b0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/one_device_strategy.py @@ -0,0 +1,492 @@ +# 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. +# ============================================================================== +"""A tf.distribute.Strategy for running on a single device.""" + +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import input_util +from tensorflow.python.distribute import numpy_dataset +from tensorflow.python.distribute.v1 import input_lib as input_lib_v1 +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# TODO(josh11b): Do we wrap values in types to generate errors if you are +# doing something that won't work with other DistributionStrategy +# implementations? + + +@tf_export("distribute.OneDeviceStrategy", v1=[]) +class OneDeviceStrategy(distribute_lib.Strategy): + """A distribution strategy for running on a single device. + + Using this strategy will place any variables created in its scope on the + specified device. Input distributed through this strategy will be + prefetched to the specified device. Moreover, any functions called via + `strategy.run` will also be placed on the specified device + as well. + + Typical usage of this strategy could be testing your code with the + tf.distribute.Strategy API before switching to other strategies which + actually distribute to multiple devices/machines. + + For example: + ``` + strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0") + + with strategy.scope(): + v = tf.Variable(1.0) + print(v.device) # /job:localhost/replica:0/task:0/device:GPU:0 + + def step_fn(x): + return x * 2 + + result = 0 + for i in range(10): + result += strategy.run(step_fn, args=(i,)) + print(result) # 90 + ``` + """ + + def __init__(self, device): + """Creates a `OneDeviceStrategy`. + + Args: + device: Device string identifier for the device on which the variables + should be placed. See class docs for more details on how the device is + used. Examples: "/cpu:0", "/gpu:0", "/device:CPU:0", "/device:GPU:0" + """ + super(OneDeviceStrategy, self).__init__(OneDeviceExtended(self, device)) + distribute_lib.distribution_strategy_gauge.get_cell("V2").set( + "OneDeviceStrategy") + + def experimental_distribute_dataset(self, dataset, options=None): # pylint: disable=useless-super-delegation + """Distributes a tf.data.Dataset instance provided via dataset. + + In this case, there is only one device, so this is only a thin wrapper + around the input dataset. It will, however, prefetch the input data to the + specified device. The returned distributed dataset can be iterated over + similar to how regular datasets can. + + NOTE: Currently, the user cannot add any more transformations to a + distributed dataset. + + Example: + ``` + strategy = tf.distribute.OneDeviceStrategy() + dataset = tf.data.Dataset.range(10).batch(2) + dist_dataset = strategy.experimental_distribute_dataset(dataset) + for x in dist_dataset: + print(x) # [0, 1], [2, 3],... + ``` + Args: + dataset: `tf.data.Dataset` to be prefetched to device. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + Returns: + A "distributed `Dataset`" that the caller can iterate over. + """ + return super(OneDeviceStrategy, self).experimental_distribute_dataset( + dataset, options) + + def distribute_datasets_from_function( + self, + dataset_fn, # pylint: disable=useless-super-delegation + options=None): + """Distributes `tf.data.Dataset` instances created by calls to `dataset_fn`. + + `dataset_fn` will be called once for each worker in the strategy. In this + case, we only have one worker and one device so `dataset_fn` is called + once. + + The `dataset_fn` should take an `tf.distribute.InputContext` instance where + information about batching and input replication can be accessed: + + ``` + def dataset_fn(input_context): + batch_size = input_context.get_per_replica_batch_size(global_batch_size) + d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size) + return d.shard( + input_context.num_input_pipelines, input_context.input_pipeline_id) + + inputs = strategy.distribute_datasets_from_function(dataset_fn) + + for batch in inputs: + replica_results = strategy.run(replica_fn, args=(batch,)) + ``` + + IMPORTANT: The `tf.data.Dataset` returned by `dataset_fn` should have a + per-replica batch size, unlike `experimental_distribute_dataset`, which uses + the global batch size. This may be computed using + `input_context.get_per_replica_batch_size`. + + Args: + dataset_fn: A function taking a `tf.distribute.InputContext` instance and + returning a `tf.data.Dataset`. + options: `tf.distribute.InputOptions` used to control options on how this + dataset is distributed. + + Returns: + A "distributed `Dataset`", which the caller can iterate over like regular + datasets. + """ + return super(OneDeviceStrategy, + self).distribute_datasets_from_function(dataset_fn, options) + + def experimental_local_results(self, value): # pylint: disable=useless-super-delegation + """Returns the list of all local per-replica values contained in `value`. + + In `OneDeviceStrategy`, the `value` is always expected to be a single + value, so the result is just the value in a tuple. + + Args: + value: A value returned by `experimental_run()`, `run()`, + `extended.call_for_each_replica()`, or a variable created in `scope`. + + Returns: + A tuple of values contained in `value`. If `value` represents a single + value, this returns `(value,).` + """ + return super(OneDeviceStrategy, self).experimental_local_results(value) + + def run(self, fn, args=(), kwargs=None, options=None): # pylint: disable=useless-super-delegation + """Run `fn` on each replica, with the given arguments. + + In `OneDeviceStrategy`, `fn` is simply called within a device scope for the + given device, with the provided arguments. + + Args: + fn: The function to run. The output must be a `tf.nest` of `Tensor`s. + args: (Optional) Positional arguments to `fn`. + kwargs: (Optional) Keyword arguments to `fn`. + options: (Optional) An instance of `tf.distribute.RunOptions` specifying + the options to run `fn`. + + Returns: + Return value from running `fn`. + """ + return super(OneDeviceStrategy, self).run(fn, args, kwargs, options) + + def reduce(self, reduce_op, value, axis): # pylint: disable=useless-super-delegation + """Reduce `value` across replicas. + + In `OneDeviceStrategy`, there is only one replica, so if axis=None, value + is simply returned. If axis is specified as something other than None, + such as axis=0, value is reduced along that axis and returned. + + Example: + ``` + t = tf.range(10) + + result = strategy.reduce(tf.distribute.ReduceOp.SUM, t, axis=None).numpy() + # result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + result = strategy.reduce(tf.distribute.ReduceOp.SUM, t, axis=0).numpy() + # result: 45 + ``` + + Args: + reduce_op: A `tf.distribute.ReduceOp` value specifying how values should + be combined. + value: A "per replica" value, e.g. returned by `run` to + be combined into a single tensor. + axis: Specifies the dimension to reduce along within each + replica's tensor. Should typically be set to the batch dimension, or + `None` to only reduce across replicas (e.g. if the tensor has no batch + dimension). + + Returns: + A `Tensor`. + """ + return super(OneDeviceStrategy, self).reduce(reduce_op, value, axis) + + def scope(self): # pylint: disable=useless-super-delegation + """Returns a context manager selecting this Strategy as current. + + Inside a `with strategy.scope():` code block, this thread + will use a variable creator set by `strategy`, and will + enter its "cross-replica context". + + In `OneDeviceStrategy`, all variables created inside `strategy.scope()` + will be on `device` specified at strategy construction time. + See example in the docs for this class. + + Returns: + A context manager to use for creating variables with this strategy. + """ + return super(OneDeviceStrategy, self).scope() + + +@tf_export(v1=["distribute.OneDeviceStrategy"]) # pylint: disable=empty-docstring +class OneDeviceStrategyV1(distribute_lib.StrategyV1): + + __doc__ = OneDeviceStrategy.__doc__.replace( + "For example:\n ```", + "For example:\n ```\n tf.enable_eager_execution()") + + def __init__(self, device): + super(OneDeviceStrategyV1, self).__init__(OneDeviceExtended(self, device)) + distribute_lib.distribution_strategy_gauge.get_cell("V1").set( + "OneDeviceStrategy") + __init__.__doc__ = OneDeviceStrategy.__init__.__doc__ + + +# TODO(josh11b): Switch to V2 after callers have been updated to only V2 APIs. +class OneDeviceExtended(distribute_lib.StrategyExtendedV1): + """Implementation of OneDeviceStrategy.""" + + def __init__(self, container_strategy, device): + super(OneDeviceExtended, self).__init__(container_strategy) + self._device = device_util.resolve(device) + self._input_device = device_util.get_host_for_device(self._device) + + def _input_workers_with_options(self, options=None): + if not options or options.experimental_fetch_to_device: + return input_lib.InputWorkers([(self._input_device, (self._device,))]) + else: + return input_lib.InputWorkers([(self._input_device, + (self._input_device,))]) + + @property + def _input_workers(self): + return self._input_workers_with_options() + + def _create_variable(self, next_creator, **kwargs): + colocate_with = kwargs.pop("colocate_with", None) + if colocate_with is None: + with ops.device(self._device): + return next_creator(**kwargs) + elif isinstance(colocate_with, numpy_dataset.SingleDevice): + with ops.device(colocate_with.device): + return next_creator(**kwargs) + else: + with ops.colocate_with(colocate_with): + return next_creator(**kwargs) + + def _validate_colocate_with_variable(self, colocate_with_variable): + distribute_utils.validate_colocate(colocate_with_variable, self) + + def _make_dataset_iterator(self, dataset): + """Make iterator from dataset without splitting the batch.""" + # Note that split_batch_by argument is not passed because it is always 1 in + # this strategy, and adding it adds unnecessary overhead to the dataset. + return input_lib_v1.DatasetIterator(dataset, self._input_workers, + self._container_strategy()) + + def _make_input_fn_iterator( + self, + input_fn, + replication_mode=distribute_lib.InputReplicationMode.PER_WORKER): + return input_lib_v1.InputFunctionIterator(input_fn, self._input_workers, + [distribute_lib.InputContext()], + self._container_strategy()) + + def _experimental_make_numpy_dataset(self, numpy_input, session): + return numpy_dataset.one_host_numpy_dataset( + numpy_input, numpy_dataset.SingleDevice(self._input_device), session) + + def _broadcast_to(self, tensor, destinations): + del destinations + return tensor + + def _experimental_distribute_dataset(self, dataset, options): + # Note that split_batch_by argument is not passed because it is always 1 in + # this strategy, and adding it adds unnecessary overhead to the dataset. + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`experimental_distribute_datasets_from_function`." + ) + return input_util.get_distributed_dataset( + dataset, + self._input_workers_with_options(options), + self._container_strategy(), + options=options) + + def _distribute_datasets_from_function(self, dataset_fn, options): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`experimental_distribute_datasets_from_function` " + "of tf.distribute.MirroredStrategy") + return input_util.get_distributed_datasets_from_function( + dataset_fn, + self._input_workers_with_options(options), + [distribute_lib.InputContext()], + self._container_strategy(), + options=options) + + def _experimental_distribute_values_from_function(self, value_fn): + # TODO(b/137795644): This should return a PerReplica value but other + # methods like run in OneDeviceStrategy need to be modified + # to do the same. + return value_fn(distribute_lib.ValueContext()) + + # TODO(priyag): Deal with OutOfRange errors once b/111349762 is fixed. + def _experimental_run_steps_on_iterator(self, fn, iterator, iterations, + initial_loop_values=None): + if initial_loop_values is None: + initial_loop_values = {} + initial_loop_values = nest.flatten(initial_loop_values) + + ctx = input_lib.MultiStepContext() + def body(i, *args): + """A wrapper around `fn` to create the while loop body.""" + del args + fn_result = fn(ctx, iterator.get_next()) + flat_last_step_outputs = nest.flatten(ctx.last_step_outputs) + with ops.control_dependencies([fn_result]): + return [i + 1] + flat_last_step_outputs + + # We capture the control_flow_context at this point, before we run `fn` + # inside a while_loop. This is useful in cases where we might need to exit + # these contexts and get back to the outer context to do some things, for + # e.g. create an op which should be evaluated only once at the end of the + # loop on the host. One such usage is in creating metrics' value op. + self._outer_control_flow_context = ( + ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access + + # TODO(priyag): Use max_iterations instead of an explicit counter. + cond = lambda i, *args: i < iterations + i = constant_op.constant(0) + loop_result = while_loop.while_loop( + cond, + body, [i] + initial_loop_values, + name="", + parallel_iterations=1, + back_prop=False, + swap_memory=False, + return_same_structure=True) + del self._outer_control_flow_context + + ctx.run_op = control_flow_ops.group(loop_result) + + # Convert the last_step_outputs from a list to the original dict structure + # of last_step_outputs. + last_step_tensor_outputs = loop_result[1:] + last_step_tensor_outputs_dict = nest.pack_sequence_as( + ctx.last_step_outputs, last_step_tensor_outputs) + + ctx._set_last_step_outputs(last_step_tensor_outputs_dict) # pylint: disable=protected-access + return ctx + + def _call_for_each_replica(self, fn, args, kwargs): + strategy = self._container_strategy() + with ops.device(self._device), _OneDeviceReplicaContext(strategy): + return fn(*args, **kwargs) + + def _reduce_to(self, reduce_op, value, destinations, options): + del reduce_op, destinations, options + return value + + def _gather_to_implementation(self, value, destinations, axis, options): + del destinations, axis, options + return value + + def _update(self, var, fn, args, kwargs, group): + # The implementations of _update() and _update_non_slot() are identical + # except _update() passes `var` as the first argument to `fn()`. + return self._update_non_slot(var, fn, (var,) + tuple(args), kwargs, group) + + def _update_non_slot(self, colocate_with, fn, args, kwargs, group): + del colocate_with + with ops.device(self._device), distribute_lib.UpdateContext(self._device): + result = fn(*args, **kwargs) + if group: + return result + else: + return nest.map_structure(self._local_results, result) + + def read_var(self, replica_local_var): + """Read the aggregate value of a replica-local variable.""" + return array_ops.identity(replica_local_var) + + def _local_results(self, value): + return (value,) + + def value_container(self, value): + return value + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings.""" + return False + + @property + def _num_replicas_in_sync(self): + return 1 + + @property + def worker_devices(self): + return (self._device,) + + @property + def parameter_devices(self): + return (self._device,) + + def non_slot_devices(self, var_list): + del var_list + return (self._device,) + + @property + def experimental_should_init(self): + return True + + @property + def experimental_between_graph(self): + return False + + @property + def should_checkpoint(self): + return True + + @property + def should_save_summary(self): + return True + + # TODO(priyag): Delete this once all strategies use global batch size. + @property + def _global_batch_size(self): + """Global and per-replica batching are equivalent for OneDeviceStrategy.""" + return True + + @property + def _support_per_replica_values(self): + return False + + def _get_local_replica_id(self, replica_id_in_sync_group): + return replica_id_in_sync_group + + +class _OneDeviceReplicaContext(distribute_lib.ReplicaContext): + """ReplicaContext for OneDeviceStrategy.""" + + def __init__(self, strategy): + distribute_lib.ReplicaContext.__init__( + self, strategy, replica_id_in_sync_group=0) + + @property + def devices(self): + return self._strategy.extended.worker_devices diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/packed_distributed_variable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/packed_distributed_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..df56a942c7499f98de769a5b5381b8ca159283ce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/packed_distributed_variable.py @@ -0,0 +1,366 @@ +# 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. +# ============================================================================== +"""A variable which packs a list of variables distributed across devices.""" + +from tensorflow.python.distribute import device_util +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops + + +class PackedDistributedVariable(resource_variable_ops.BaseResourceVariable): + """A variable which packs multiple variables distributed across devices. + + It's only supported when eager execution is enabled. + For op-by-op execution, use an unpacked handle on the current device; for + function execution, use the packed handle to reduce the overhead of function + calls. + """ + + def __init__(self, distributed_variables=None, name=None, **unused_kwargs): + """Packs a list of variables which are distributed across devices. + + Args: + distributed_variables: A list of distributed Variables to pack. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + """ + if not ops.executing_eagerly_outside_functions(): + raise ValueError( + "PackedDistributedVariable should be created in eager mode.") + if not distributed_variables: + raise ValueError("Expect a non-empty list of variables to pack.") + for i, var in enumerate(distributed_variables): + if not resource_variable_ops.is_resource_variable(var): + raise ValueError("Expect a list of ResourceVariables to pack, " + "but the %d-th variable is %s" % (i, type(var))) + + self._distributed_variables = distributed_variables + self._devices = [v.device for v in distributed_variables] + with ops.init_scope(): + with ops.name_scope(name, "Variable", skip_on_eager=False) as name: + handle = ops.pack_eager_tensors( + [var.handle for var in distributed_variables]) + handle_name = ops.name_from_scope_name(name) + unique_id = "%s_%d" % (handle_name, ops.uid()) + super(PackedDistributedVariable, self).__init__( + trainable=distributed_variables[0].trainable, + shape=distributed_variables[0].shape, + dtype=distributed_variables[0].dtype, + handle=handle, + synchronization=distributed_variables[0].synchronization, + constraint=distributed_variables[0].constraint, + aggregation=distributed_variables[0].aggregation, + distribute_strategy=distributed_variables[0]._distribute_strategy, # pylint: disable=protected-access + name=name, + unique_id=unique_id, + handle_name=handle_name, + graph_element=None, + initial_value=None, + initializer_op=None, + is_initialized_op=None, + cached_value=None, + caching_device=None, + is_distributed_variables=True) + + @property + def devices(self): + return self._devices + + def on_device(self, device): + return PackedVarAndDevice(self, device) + + def get_var_on_device(self, device): + for i, d in enumerate(self._devices): + if d == device: + return self._distributed_variables[i] + raise ValueError("Device %s is not found" % device) + + def get_var_on_current_device(self): + current_device = device_util.canonicalize(device_util.current()) + return self.get_var_on_device(current_device) + + def initial_value(self, device): + """Returns the Tensor used as the initial value for the variable.""" + return self.get_var_on_device(device).initial_value + + @property + def handle(self): + if context.executing_eagerly(): + return self.get_var_on_current_device().handle + else: + return self._handle + + @property + def packed_handle(self): + return self._handle + + def _read_variable_op(self): + if context.executing_eagerly(): + return self.get_var_on_current_device().value() + else: + return super(PackedDistributedVariable, self)._read_variable_op() + + def value(self): + return self._read_variable_op() + + def is_initialized(self, name=None): + if context.executing_eagerly(): + result = self._distributed_variables[0].is_initialized() + for v in self._distributed_variables[1:-1]: + result = math_ops.logical_and(result, v.is_initialized()) + result = math_ops.logical_and( + result, self._distributed_variables[-1].is_initialized(), name=name) + else: + with ops.device(self._devices[0]): + result = super(PackedDistributedVariable, self).is_initialized(name) + for d in self._devices[1:-1]: + with ops.device(d): + initialized = super(PackedDistributedVariable, + self).is_initialized(name) + result = math_ops.logical_and(result, initialized) + with ops.device(self._devices[-1]): + initialized = super(PackedDistributedVariable, + self).is_initialized(name) + result = math_ops.logical_and(result, initialized, name=name) + return result + + def _update(self, update_fn, value, **kwargs): + if context.executing_eagerly(): + return update_fn(self.get_var_on_current_device(), value, **kwargs) + else: + return update_fn(super(PackedDistributedVariable, self), value, **kwargs) + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + assign_sub_fn = lambda var, *a, **kw: var.assign_sub(*a, **kw) + return self._update( + update_fn=assign_sub_fn, + value=delta, + use_locking=use_locking, + name=name, + read_value=read_value) + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + assign_add_fn = lambda var, *a, **kw: var.assign_add(*a, **kw) + return self._update( + update_fn=assign_add_fn, + value=delta, + use_locking=use_locking, + name=name, + read_value=read_value) + + def assign(self, value, use_locking=None, name=None, read_value=True): + assign_fn = lambda var, *a, **kw: var.assign(*a, **kw) + return self._update( + update_fn=assign_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + scatter_sub_fn = lambda var, *a, **kw: var.scatter_sub(*a, **kw) + return self._update( + update_fn=scatter_sub_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + scatter_add_fn = lambda var, *a, **kw: var.scatter_add(*a, **kw) + return self._update( + update_fn=scatter_add_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + scatter_mul_fn = lambda var, *a, **kw: var.scatter_mul(*a, **kw) + return self._update( + update_fn=scatter_mul_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + scatter_div_fn = lambda var, *a, **kw: var.scatter_div(*a, **kw) + return self._update( + update_fn=scatter_div_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + scatter_min_fn = lambda var, *a, **kw: var.scatter_min(*a, **kw) + return self._update( + update_fn=scatter_min_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + scatter_max_fn = lambda var, *a, **kw: var.scatter_max(*a, **kw) + return self._update( + update_fn=scatter_max_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + scatter_update_fn = lambda var, *a, **kw: var.scatter_update(*a, **kw) + return self._update( + update_fn=scatter_update_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + if context.executing_eagerly(): + return self.get_var_on_current_device()._dense_var_to_tensor( # pylint: disable=protected-access + dtype=dtype, + name=name, + as_ref=as_ref) + else: + return super(PackedDistributedVariable, self)._dense_var_to_tensor( # pylint: disable=protected-access + dtype=dtype, + name=name, + as_ref=as_ref) + + +class PackedVarAndDevice(object): + """Holds a packed distributed variable and a device.""" + + def __init__(self, var, device): + self._var = var + self._device = device + + def __getattr__(self, name): + # Exceptions raised inside the contextmanager can cause a reference + # cycle.[1] The cycle involves the current frame, which holds the reference + # to the outer frame. Tensorflow, e.g. iterators, relies on object + # finalizers to clean up resources. Such references prevents the resource + # from being deleted and can cause leaks and errors. One corner the case is + # that iterators are kept alive and the garbage collector happens to run + # after auto control dependencies; this causes the deletion to lose the + # control dependencies to operations that uses such resources. + # + # Catch and re-raise the exception seems to workaround the issue. + # + # [1] https://bugs.python.org/issue43533 + try: + with ops.device(self._device): + return getattr(self._var, name) + except: # pylint: disable=try-except-raise + raise + + def var(self): + return self._var + + def value(self): + with ops.device(self._device): + return self._var.value() + + def read_value(self): + with ops.device(self._device): + return self._var.read_value() + + @property + def initial_value(self): + return self._var.initial_value(self._device) + + def initialized_value(self): + with ops.device(self._device): + return self._var.initialized_value() + + @property + def device(self): + return self._device + + @property + def handle(self): + with ops.device(self._device): + return self._var.handle + + def on_device_handle(self): + with ops.device(self._device): + return self._var.get_var_on_current_device().handle + + @property + def op(self) -> ops.Operation: + with ops.device(self._device): + return self._var.op + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + with ops.device(self._device): + return self._var.assign_sub(delta, use_locking, name, read_value) + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + with ops.device(self._device): + return self._var.assign_add(delta, use_locking, name, read_value) + + def assign(self, value, use_locking=None, name=None, read_value=True): + with ops.device(self._device): + return self._var.assign(value, use_locking, name, read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_sub(sparse_delta, use_locking, name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_add(sparse_delta, use_locking, name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_mul(sparse_delta, use_locking, name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_div(sparse_delta, use_locking, name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_min(sparse_delta, use_locking, name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_max(sparse_delta, use_locking, name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + with ops.device(self._device): + return self._var.scatter_update(sparse_delta, use_locking, name) + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + with ops.device(self._device): + return self._var._dense_var_to_tensor( # pylint: disable=protected-access + dtype=dtype, + name=name, + as_ref=as_ref) + + def _as_graph_element(self): + return self._var._as_graph_element() # pylint: disable=protected-access + + +def _tensor_conversion_packed_var_and_device(var, + dtype=None, + name=None, + as_ref=False): + return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + PackedVarAndDevice, _tensor_conversion_packed_var_and_device) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parallel_device/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parallel_device/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parallel_device/parallel_device.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parallel_device/parallel_device.py new file mode 100644 index 0000000000000000000000000000000000000000..771925efa2372ccc39669c13d570f06369c6eea0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parallel_device/parallel_device.py @@ -0,0 +1,232 @@ +# 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. +# ============================================================================== +"""Utility for eagerly executing operations in parallel on multiple devices.""" + +import threading +import weakref + +from tensorflow.python import _pywrap_parallel_device +from tensorflow.python.distribute import device_util +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variables +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.util import nest +from tensorflow.python.util import variable_utils + +_next_device_number = 0 +_next_device_number_lock = threading.Lock() + +_all_parallel_devices = weakref.WeakValueDictionary() + + +def unpack(tensor): + """Finds `tensor`'s parallel device and unpacks its components.""" + parallel_device = _all_parallel_devices.get(tensor.device, None) + if parallel_device is None: + raise ValueError("{} is not a parallel device".format(tensor.device)) + return parallel_device.unpack(tensor) + + +# TODO(allenl): Expand this docstring once things like getting components on and +# off the device are stable. +# +# TODO(allenl): Make multi-client work; we need an offset for device IDs, and an +# indication of how many other devices there are total for collectives which +# don't have a number of participants hard-coded in their attributes. +class ParallelDevice(object): + """A device which executes operations in parallel.""" + + def __init__(self, components): + """Creates a device which executes operations in parallel on `components`. + + Args: + components: A list of device names. Each operation executed on the + returned device executes on these component devices. + + Returns: + A string with the name of the newly created device. + """ + global _next_device_number, _next_device_number_lock + self.components = tuple(device_util.canonicalize(d) for d in components) + if not self.components: + raise ValueError("ParallelDevice requires at least one component.") + ctx = context.context() + with _next_device_number_lock: + # TODO(allenl): Better names for parallel devices (right now "CUSTOM" is + # special-cased). + self._name = "{}/device:CUSTOM:{}".format(ctx.host_address_space(), + _next_device_number) + _next_device_number += 1 + device, device_info = _pywrap_parallel_device.GetParallelDeviceCapsules( + self._name, self.components) + context.register_custom_device(device, self._name, device_info) + self._device_ids = None + self._device_scope = None + _all_parallel_devices[self._name] = self + + def _pack_tensor(self, *tensors): + """Helper to pack plain-old-tensors, not structures or composites.""" + for tensor in tensors: + if not isinstance( + tensor, + ( + tensor_lib.Tensor, + composite_tensor.CompositeTensor, + variables.Variable, + ), + ): + raise ValueError( + ("Every component to pack onto the ParallelDevice must already be " + "a tensor, got {}. Consider running `tf.constant` or " + "`tf.convert_to_tensor` first on literal values.") + .format(tensors)) + with ops.device(self._name): + return tpu_ops.tpu_replicated_input(inputs=tensors) + + def pack(self, tensors): + """Create a tensor on the parallel device from a sequence of tensors. + + Args: + tensors: A list of tensors, one per device in `self.components`. The list + can contain composite tensors and nests (lists, dicts, etc. supported by + `tf.nest`) with the same structure for each device, but every component + of nests must already be a `tf.Tensor` or composite. Passing + `tf.Variable` objects reads their value, it does not share a mutable + reference between the packed and unpacked forms. + + Returns: + A tensor placed on the ParallelDevice. For nested structures, returns a + single structure containing tensors placed on the ParallelDevice (same + structure as each component of `tensors`). + + Raises: + ValueError: If the length of `tensors` does not match the number of + component devices, or if there are non-tensor inputs. + + """ + self._assert_eager() + if len(tensors) != len(self.components): + raise ValueError( + ("Creating a parallel tensor requires one tensor per component. " + "Got {} but was expecting {}.") + .format(len(tensors), len(self.components))) + with ops.device(None): + # Explicitly read variable values. This can not be done on the parallel + # device since the tensors are to be packed. + tensors = variable_utils.convert_variables_to_tensors(tensors) + return nest.map_structure(self._pack_tensor, *tensors, + expand_composites=True) + + def _unpack_tensor(self, parallel_tensor): + """Helper to unpack a single tensor.""" + if not isinstance( + parallel_tensor, + ( + tensor_lib.Tensor, + composite_tensor.CompositeTensor, + variables.Variable, + ), + ): + raise ValueError("Expected a tensor, got {}.".format(parallel_tensor)) + with ops.device(self._name): + return tpu_ops.tpu_replicated_output( + parallel_tensor, num_replicas=len(self.components)) + + def unpack(self, parallel_tensor): + """Unpack a parallel tensor into its components. + + Args: + parallel_tensor: A tensor, composite tensor, or `tf.nest` of such placed + on the ParallelDevice. Passing `tf.Variable` objects reads their value, + it does not share a mutable reference between the packed and unpacked + forms. + + Returns: + A list with the same length as `self.components` each with the same + structure as `parallel_tensor`, containing component tensors. + + """ + self._assert_eager() + unpacked_components = [[] for _ in range(len(self.components))] + with ops.device(self._name): + parallel_tensor = variable_utils.convert_variables_to_tensors( + parallel_tensor) + for tensor in nest.flatten(parallel_tensor, expand_composites=True): + for accumulator, unpacked_tensor in zip( + unpacked_components, self._unpack_tensor(tensor)): + accumulator.append(unpacked_tensor) + return [nest.pack_sequence_as(parallel_tensor, unpacked, + expand_composites=True) + for unpacked in unpacked_components] + + @property + def device_ids(self): + """A parallel tensor with scalar integers numbering component devices. + + Each device ID is placed on its corresponding device, in the same order as + the `components` constructor argument. + + Returns: + A parallel tensor containing 0 on the first device, 1 on the second, etc. + """ + if self._device_ids is None: + # device_ids may be called from inside a tf.function, in which case the + # function captures the eager tensor. We can't pack tensors in a function + # at the moment, and even if we could we don't want to hold on to a + # symbolic tensor, so we need to init_scope out of the function + # temporarily. + with ops.init_scope(): + # TODO(allenl): Functions which capture eager device ID tensors won't be + # saveable in SavedModels. Ideally we'd run a DeviceID op every time + # device IDs are required, with functions using the op in their bodies + # but not hard-coding a fixed number of devices (so they can be re-used + # with a different replica count). + device_ids_list = [] + for index, device in enumerate(self.components): + with ops.device(device): + # The identity op ensures each device ID tensor is placed on its + # device. + device_ids_list.append( + array_ops.identity(constant_op.constant(index))) + self._device_ids = self.pack(device_ids_list) + + return self._device_ids + + def _assert_eager(self): + """Verifies that tracing is not active.""" + if not context.executing_eagerly(): + raise NotImplementedError( + "ParallelDevice is currently not supported inside `tf.function`. It " + "can however run calls to a `tf.function` in parallel:\n\n" + "with ParallelDevice() as p:\n f()") + + def __enter__(self): + """Runs ops in parallel, makes variables which save independent buffers.""" + if self._device_scope is not None: + raise AssertionError( + "Re-entered a ParallelDevice scope without first exiting it.") + self._assert_eager() + self._device_scope = ops.device(self._name) + self._device_scope.__enter__() + return self + + def __exit__(self, typ, exc, tb): + self._device_scope.__exit__(typ, exc, tb) + self._device_scope = None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parameter_server_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parameter_server_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..8d66ad7fdfd3a39e9f5bf870032bfdca892991dc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parameter_server_strategy.py @@ -0,0 +1,693 @@ +# 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. +# ============================================================================== +"""Class implementing a multi-worker parameter server tf.distribute strategy.""" + +import copy + + +from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import input_util +from tensorflow.python.distribute import mirrored_run +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute import numpy_dataset +from tensorflow.python.distribute import ps_values +from tensorflow.python.distribute import values +from tensorflow.python.distribute.cluster_resolver import cluster_resolver as cluster_resolver_lib +from tensorflow.python.distribute.cluster_resolver import tfconfig_cluster_resolver +from tensorflow.python.distribute.v1 import input_lib as input_lib_v1 +from tensorflow.python.eager import context +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import device_setter +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +_LOCAL_CPU = "/device:CPU:0" + + +@tf_export(v1=["distribute.experimental.ParameterServerStrategy"]) # pylint: disable=missing-docstring +class ParameterServerStrategyV1(distribute_lib.StrategyV1): + """An asynchronous multi-worker parameter server tf.distribute strategy. + + This strategy requires two roles: workers and parameter servers. Variables and + updates to those variables will be assigned to parameter servers and other + operations are assigned to workers. + + When each worker has more than one GPU, operations will be replicated on all + GPUs. Even though operations may be replicated, variables are not and each + worker shares a common view for which parameter server a variable is assigned + to. + + By default it uses `TFConfigClusterResolver` to detect configurations for + multi-worker training. This requires a 'TF_CONFIG' environment variable and + the 'TF_CONFIG' must have a cluster spec. + + This class assumes each worker is running the same code independently, but + parameter servers are running a standard server. This means that while each + worker will synchronously compute a single gradient update across all GPUs, + updates between workers proceed asynchronously. Operations that occur only on + the first replica (such as incrementing the global step), will occur on the + first replica *of every worker*. + + It is expected to call `call_for_each_replica(fn, ...)` for any + operations which potentially can be replicated across replicas (i.e. multiple + GPUs) even if there is only CPU or one GPU. When defining the `fn`, extra + caution needs to be taken: + + 1) It is generally not recommended to open a device scope under the strategy's + scope. A device scope (i.e. calling `tf.device`) will be merged with or + override the device for operations but will not change the device for + variables. + + 2) It is also not recommended to open a colocation scope (i.e. calling + `tf.compat.v1.colocate_with`) under the strategy's scope. For colocating + variables, use `strategy.extended.colocate_vars_with` instead. Colocation of + ops will possibly create device assignment conflicts. + + Note: This strategy only works with the Estimator API. Pass an instance of + this strategy to the `experimental_distribute` argument when you create the + `RunConfig`. This instance of `RunConfig` should then be passed to the + `Estimator` instance on which `train_and_evaluate` is called. + + For Example: + ``` + strategy = tf.distribute.experimental.ParameterServerStrategy() + run_config = tf.estimator.RunConfig( + experimental_distribute.train_distribute=strategy) + estimator = tf.estimator.Estimator(config=run_config) + tf.estimator.train_and_evaluate(estimator,...) + ``` + """ + + def __init__(self, cluster_resolver=None): + """Initializes this strategy with an optional `cluster_resolver`. + + Args: + cluster_resolver: Optional + `tf.distribute.cluster_resolver.ClusterResolver` object. Defaults to a + `tf.distribute.cluster_resolver.TFConfigClusterResolver`. + """ + if cluster_resolver is None: + cluster_resolver = tfconfig_cluster_resolver.TFConfigClusterResolver() + super(ParameterServerStrategyV1, self).__init__( + ParameterServerStrategyExtended( + self, cluster_resolver=cluster_resolver)) + distribute_lib.distribution_strategy_gauge.get_cell("V1").set( + "ParameterServerStrategy") + + def experimental_distribute_dataset(self, dataset, options=None): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`experimental_distribute_datasets_from_function`." + ) + self._raise_pss_error_if_eager() + super(ParameterServerStrategyV1, + self).experimental_distribute_dataset(dataset=dataset, + options=options) + + def distribute_datasets_from_function(self, dataset_fn, options=None): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`experimental_distribute_datasets_from_function` " + "of tf.distribute.MirroredStrategy") + self._raise_pss_error_if_eager() + super(ParameterServerStrategyV1, self).distribute_datasets_from_function( + dataset_fn=dataset_fn, options=options) + + def run(self, fn, args=(), kwargs=None, options=None): + self._raise_pss_error_if_eager() + super(ParameterServerStrategyV1, self).run( + fn, args=args, kwargs=kwargs, options=options) + + def scope(self): + self._raise_pss_error_if_eager() + return super(ParameterServerStrategyV1, self).scope() + + def _raise_pss_error_if_eager(self): + if context.executing_eagerly(): + raise NotImplementedError( + "`tf.compat.v1.distribute.experimental.ParameterServerStrategy` " + "currently only works with the tf.Estimator API") + + +# TODO(josh11b): Switch to V2 when we no longer need to support tf.compat.v1. +class ParameterServerStrategyExtended(distribute_lib.StrategyExtendedV1): + """Implementation of ParameterServerStrategy and CentralStorageStrategy.""" + + def __init__(self, + container_strategy, + cluster_resolver=None, + compute_devices=None, + parameter_device=None): + super(ParameterServerStrategyExtended, self).__init__(container_strategy) + self._initialize_strategy( + cluster_resolver=cluster_resolver, + compute_devices=compute_devices, + parameter_device=parameter_device) + + # We typically don't need to do all-reduce in this strategy. + self._cross_device_ops = ( + cross_device_ops_lib.ReductionToOneDevice(reduce_to_device=_LOCAL_CPU)) + + def _initialize_strategy(self, + cluster_resolver=None, + compute_devices=None, + parameter_device=None): + if cluster_resolver and cluster_resolver.cluster_spec(): + self._initialize_multi_worker(cluster_resolver) + else: + self._initialize_local( + compute_devices, parameter_device, cluster_resolver=cluster_resolver) + + def _initialize_multi_worker(self, cluster_resolver): + """Initialize devices for multiple workers. + + It creates variable devices and compute devices. Variables and operations + will be assigned to them respectively. We have one compute device per + replica. The variable device is a device function or device string. The + default variable device assigns variables to parameter servers in a + round-robin fashion. + + Args: + cluster_resolver: a descendant of `ClusterResolver` object. + + Raises: + ValueError: if the cluster doesn't have ps jobs. + """ + # TODO(b/126786766): TFConfigClusterResolver returns wrong number of GPUs in + # some cases. + if isinstance( + cluster_resolver, tfconfig_cluster_resolver.TFConfigClusterResolver): + num_gpus = context.num_gpus() + else: + num_gpus = cluster_resolver.num_accelerators().get("GPU", 0) + + # Save the num_gpus_per_worker for configure method. + self._num_gpus_per_worker = num_gpus + + cluster_spec = cluster_resolver.cluster_spec() + task_type = cluster_resolver.task_type + task_id = cluster_resolver.task_id + if not task_type or task_id is None: + raise ValueError("When `cluster_spec` is given, you must also specify " + "`task_type` and `task_id`") + cluster_spec = multi_worker_util.normalize_cluster_spec(cluster_spec) + assert cluster_spec.as_dict() + + self._worker_device = "/job:%s/task:%d" % (task_type, task_id) + self._input_host_device = numpy_dataset.SingleDevice(self._worker_device) + + # Define compute devices which is a list of device strings and one for each + # replica. When there are GPUs, replicate operations on these GPUs. + # Otherwise, place operations on CPU. + if num_gpus > 0: + compute_devices = tuple( + "%s/device:GPU:%d" % (self._worker_device, i) + for i in range(num_gpus)) + else: + compute_devices = (self._worker_device,) + + self._compute_devices = [ + device_util.canonicalize(d) for d in compute_devices] + + # In distributed mode, place variables on ps jobs in a round-robin fashion. + # Note that devices returned from `replica_device_setter` are not + # canonical and therefore we don't canonicalize all variable devices to + # make them consistent. + # TODO(yuefengz): support passing a strategy object to control variable + # assignment. + # TODO(yuefengz): merge the logic of replica_device_setter into this + # class. + num_ps_replicas = len(cluster_spec.as_dict().get("ps", [])) + if num_ps_replicas == 0: + raise ValueError("The cluster spec needs to have `ps` jobs.") + self._variable_device = device_setter.replica_device_setter( + ps_tasks=num_ps_replicas, + worker_device=self._worker_device, + merge_devices=True, + cluster=cluster_spec) + + # The `_parameter_devices` is needed for the `parameter_devices` property + # and is a list of all variable devices. Here parameter devices are all + # tasks of the "ps" job. + self._parameter_devices = tuple(map("/job:ps/task:{}".format, + range(num_ps_replicas))) + + # Add a default device so that ops without specified devices will not end up + # on other workers. + self._default_device = self._worker_device + + self._is_chief = multi_worker_util.is_chief(cluster_spec, task_type, + task_id) + self._cluster_spec = cluster_spec + self._task_type = task_type + self._task_id = task_id + + logging.info( + "Multi-worker ParameterServerStrategy with " + "cluster_spec = %r, task_type = %r, task_id = %r, " + "num_ps_replicas = %r, is_chief = %r, compute_devices = %r, " + "variable_device = %r", cluster_spec.as_dict(), task_type, task_id, + num_ps_replicas, self._is_chief, self._compute_devices, + self._variable_device) + + # TODO(yuefengz): get rid of cluster_resolver argument when contrib's + # version no longer depends on this class. + def _initialize_local(self, + compute_devices, + parameter_device, + cluster_resolver=None): + """Initialize local devices for training.""" + self._worker_device = device_util.canonicalize("/device:CPU:0") + self._input_host_device = numpy_dataset.SingleDevice(self._worker_device) + + if compute_devices is None: + if not cluster_resolver: + num_gpus = context.num_gpus() + else: + num_gpus = cluster_resolver.num_accelerators().get("GPU", 0) + # Save the num_gpus_per_worker for configure method which is used by the + # contrib version. + self._num_gpus_per_worker = num_gpus + + compute_devices = device_util.local_devices_from_num_gpus(num_gpus) + + compute_devices = [device_util.canonicalize(d) for d in compute_devices] + + if parameter_device is None: + # If there is only one GPU, put everything on that GPU. Otherwise, place + # variables on CPU. + if len(compute_devices) == 1: + parameter_device = compute_devices[0] + else: + parameter_device = _LOCAL_CPU + + self._variable_device = parameter_device + self._compute_devices = compute_devices + self._parameter_devices = (parameter_device,) + self._is_chief = True + self._cluster_spec = None + self._task_type = None + self._task_id = None + + logging.info( + "ParameterServerStrategy (CentralStorageStrategy if you are using a " + "single machine) with compute_devices = %r, variable_device = %r", + compute_devices, self._variable_device) + + def _input_workers_with_options(self, options=None): + if not options or options.experimental_fetch_to_device: + return input_lib.InputWorkers( + [(self._worker_device, self._compute_devices)]) + else: + return input_lib.InputWorkers( + [(self._worker_device, + (self._worker_device,) * len(self._compute_devices))]) + + @property + def _input_workers(self): + return self._input_workers_with_options() + + def _validate_colocate_with_variable(self, colocate_with_variable): + distribute_utils.validate_colocate(colocate_with_variable, self) + + def _experimental_distribute_dataset(self, dataset, options): + return input_util.get_distributed_dataset( + dataset, + self._input_workers_with_options(options), + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync, + options=options) + + def _make_dataset_iterator(self, dataset): + return input_lib_v1.DatasetIterator( + dataset, + self._input_workers, + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync) + + def _make_input_fn_iterator( + self, + input_fn, + replication_mode=distribute_lib.InputReplicationMode.PER_WORKER): + """Distributes the dataset to each local GPU.""" + if self._cluster_spec: + input_pipeline_id = multi_worker_util.id_in_cluster( + self._cluster_spec, self._task_type, self._task_id) + num_input_pipelines = multi_worker_util.worker_count( + self._cluster_spec, self._task_type) + else: + input_pipeline_id = 0 + num_input_pipelines = 1 + input_context = distribute_lib.InputContext( + num_input_pipelines=num_input_pipelines, + input_pipeline_id=input_pipeline_id, + num_replicas_in_sync=self._num_replicas_in_sync) + return input_lib_v1.InputFunctionIterator(input_fn, self._input_workers, + [input_context], + self._container_strategy()) + + def _experimental_make_numpy_dataset(self, numpy_input, session): + return numpy_dataset.one_host_numpy_dataset( + numpy_input, self._input_host_device, session) + + def _distribute_datasets_from_function(self, dataset_fn, options): + if self._cluster_spec: + input_pipeline_id = multi_worker_util.id_in_cluster( + self._cluster_spec, self._task_type, self._task_id) + num_input_pipelines = multi_worker_util.worker_count( + self._cluster_spec, self._task_type) + else: + input_pipeline_id = 0 + num_input_pipelines = 1 + + input_context = distribute_lib.InputContext( + num_input_pipelines=num_input_pipelines, + input_pipeline_id=input_pipeline_id, + num_replicas_in_sync=self._num_replicas_in_sync) + + return input_util.get_distributed_datasets_from_function( + dataset_fn, + self._input_workers_with_options(options), [input_context], + self._container_strategy(), + options=options) + + def _experimental_distribute_values_from_function(self, value_fn): + per_replica_values = [] + for replica_id in range(self._num_replicas_in_sync): + per_replica_values.append( + value_fn(distribute_lib.ValueContext(replica_id, + self._num_replicas_in_sync))) + return distribute_utils.regroup(per_replica_values, always_wrap=True) + + def _broadcast_to(self, tensor, destinations): + # This is both a fast path for Python constants, and a way to delay + # converting Python values to a tensor until we know what type it + # should be converted to. Otherwise we have trouble with: + # global_step.assign_add(1) + # since the `1` gets broadcast as an int32 but global_step is int64. + if isinstance(tensor, (float, int)): + return tensor + if not cross_device_ops_lib.check_destinations(destinations): + # TODO(josh11b): Use current logical device instead of 0 here. + destinations = self._compute_devices + return self._cross_device_ops.broadcast(tensor, destinations) + + def _allow_variable_partition(self): + return not context.executing_eagerly() + + def _create_var_creator(self, next_creator, **kwargs): + if self._num_replicas_in_sync > 1: + aggregation = kwargs.pop("aggregation", vs.VariableAggregation.NONE) + if aggregation not in ( + vs.VariableAggregation.NONE, + vs.VariableAggregation.SUM, + vs.VariableAggregation.MEAN, + vs.VariableAggregation.ONLY_FIRST_REPLICA + ): + raise ValueError("Invalid variable aggregation mode: " + aggregation + + " for variable: " + kwargs["name"]) + + def var_creator(**kwargs): + """Create an AggregatingVariable and fix up collections.""" + # Record what collections this variable should be added to. + collections = kwargs.pop("collections", None) + if collections is None: + collections = [ops.GraphKeys.GLOBAL_VARIABLES] + kwargs["collections"] = [] + + # Create and wrap the variable. + v = next_creator(**kwargs) + wrapped = ps_values.AggregatingVariable(self._container_strategy(), v, + aggregation) + + # Add the wrapped variable to the requested collections. + # The handling of eager mode and the global step matches + # ResourceVariable._init_from_args(). + if not context.executing_eagerly(): + g = ops.get_default_graph() + # If "trainable" is True, next_creator() will add the contained + # variable to the TRAINABLE_VARIABLES collection, so we manually + # remove it and replace with the wrapper. We can't set "trainable" + # to False for next_creator() since that causes functions like + # implicit_gradients to skip those variables. + if kwargs.get("trainable", True): + collections.append(ops.GraphKeys.TRAINABLE_VARIABLES) + l = g.get_collection_ref(ops.GraphKeys.TRAINABLE_VARIABLES) + if v in l: + l.remove(v) + g.add_to_collections(collections, wrapped) + elif ops.GraphKeys.GLOBAL_STEP in collections: + ops.add_to_collections(ops.GraphKeys.GLOBAL_STEP, wrapped) + + return wrapped + return var_creator + else: + return next_creator + + # TODO(yuefengz): Not all ops in device_setter.STANDARD_PS_OPS will go through + # this creator, such as "MutableHashTable". + def _create_variable(self, next_creator, **kwargs): + var_creator = self._create_var_creator(next_creator, **kwargs) + + if "colocate_with" in kwargs: + colocate_with = kwargs["colocate_with"] + if isinstance(colocate_with, numpy_dataset.SingleDevice): + with ops.device(colocate_with.device): + return var_creator(**kwargs) + with ops.device(None): + with ops.colocate_with(colocate_with): + return var_creator(**kwargs) + + with ops.colocate_with(None, ignore_existing=True): + with ops.device(self._variable_device): + return var_creator(**kwargs) + + def _call_for_each_replica(self, fn, args, kwargs): + return mirrored_run.call_for_each_replica(self._container_strategy(), fn, + args, kwargs) + + def _verify_destinations_not_different_worker(self, destinations): + if not self._cluster_spec: + return + if destinations is None: + return + for d in cross_device_ops_lib.get_devices_from(destinations): + d_spec = tf_device.DeviceSpec.from_string(d) + if d_spec.job == self._task_type and d_spec.task != self._task_id: + raise ValueError( + "Cannot reduce to another worker: %r, current worker is %r" % + (d, self._worker_device)) + + def _gather_to_implementation(self, value, destinations, axis, + options): + self._verify_destinations_not_different_worker(destinations) + if not isinstance(value, values.DistributedValues): + return value + return self._cross_device_ops._gather( # pylint: disable=protected-access + value, + destinations=destinations, + axis=axis, + options=options) + + def _reduce_to(self, reduce_op, value, destinations, options): + self._verify_destinations_not_different_worker(destinations) + if not isinstance(value, values.DistributedValues): + # pylint: disable=protected-access + return cross_device_ops_lib.reduce_non_distributed_value( + reduce_op, value, destinations, self._num_replicas_in_sync) + return self._cross_device_ops.reduce( + reduce_op, value, destinations=destinations, options=options) + + def _batch_reduce_to(self, reduce_op, value_destination_pairs, options): + for _, destinations in value_destination_pairs: + self._verify_destinations_not_different_worker(destinations) + return self._cross_device_ops.batch_reduce(reduce_op, + value_destination_pairs, options) + + def _select_single_value(self, structured): + """Select any single value in `structured`.""" + + def _select_fn(x): # pylint: disable=g-missing-docstring + if isinstance(x, values.Mirrored) or isinstance(x, values.PerReplica): + return x._primary # pylint: disable=protected-access + else: + return x + + return nest.map_structure(_select_fn, structured) + + def _update(self, var, fn, args, kwargs, group): + if isinstance(var, ps_values.AggregatingVariable): + var = var.get() + if not resource_variable_ops.is_resource_variable(var): + raise ValueError( + "You can not update `var` %r. It must be a Variable." % var) + with ops.colocate_with(var), distribute_lib.UpdateContext(var.device): + result = fn(var, *self._select_single_value(args), + **self._select_single_value(kwargs)) + if group: + return result + else: + return nest.map_structure(self._local_results, result) + + # TODO(yuefengz): does it need to call _select_single_value? + def _update_non_slot(self, colocate_with, fn, args, kwargs, group): + with ops.device( + colocate_with.device), distribute_lib.UpdateContext(colocate_with): + result = fn(*args, **kwargs) + if group: + return result + else: + return nest.map_structure(self._local_results, result) + + def value_container(self, val): + if (hasattr(val, "_aggregating_container") and + not isinstance(val, ps_values.AggregatingVariable)): + wrapper = val._aggregating_container() # pylint: disable=protected-access + if wrapper is not None: + return wrapper + return val + + def read_var(self, var): + # No need to distinguish between normal variables and replica-local + # variables. + return array_ops.identity(var) + + def _configure(self, + session_config=None, + cluster_spec=None, + task_type=None, + task_id=None): + """Configures the strategy class with `cluster_spec`. + + The strategy object will be re-initialized if `cluster_spec` is passed to + `configure` but was not passed when instantiating the strategy. + + Args: + session_config: Session config object. + cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the + cluster configurations. + task_type: the current task type. + task_id: the current task id. + + Raises: + ValueError: if `cluster_spec` is given but `task_type` or `task_id` is + not. + """ + if cluster_spec: + # Use the num_gpus_per_worker recorded in constructor since _configure + # doesn't take num_gpus. + cluster_resolver = cluster_resolver_lib.SimpleClusterResolver( + cluster_spec=multi_worker_util.normalize_cluster_spec(cluster_spec), + task_type=task_type, + task_id=task_id, + num_accelerators={"GPU": self._num_gpus_per_worker}) + self._initialize_multi_worker(cluster_resolver) + + if session_config: + session_config.CopyFrom(self._update_config_proto(session_config)) + + def _update_config_proto(self, config_proto): + updated_config = copy.deepcopy(config_proto) + if not self._cluster_spec: + updated_config.isolate_session_state = True + return updated_config + + updated_config.isolate_session_state = False + + assert self._task_type + assert self._task_id is not None + + # The device filters prevent communication between workers. + del updated_config.device_filters[:] + if self._task_type in ["chief", "worker"]: + updated_config.device_filters.extend( + ["/job:%s/task:%d" % (self._task_type, self._task_id), "/job:ps"]) + elif self._task_type == "evaluator": + updated_config.device_filters.append( + "/job:%s/task:%d" % (self._task_type, self._task_id)) + return updated_config + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings.""" + return self._cluster_spec is not None + + @property + def _num_replicas_in_sync(self): + return len(self._compute_devices) + + @property + def worker_devices(self): + return self._compute_devices + + @property + def worker_devices_by_replica(self): + return [[d] for d in self._compute_devices] + + @property + def parameter_devices(self): + return self._parameter_devices + + def non_slot_devices(self, var_list): + return min(var_list, key=lambda x: x.name) + + @property + def experimental_between_graph(self): + # TODO(yuefengz): Should this return False in the local case? + return True + + @property + def experimental_should_init(self): + return self._is_chief + + @property + def should_checkpoint(self): + return self._is_chief + + @property + def should_save_summary(self): + return self._is_chief + + # TODO(priyag): Delete this once all strategies use global batch size. + @property + def _global_batch_size(self): + """`make_dataset_iterator` and `make_numpy_iterator` use global batch size. + + `make_input_fn_iterator` assumes per-replica batching. + + Returns: + Boolean. + """ + return True + + def _get_local_replica_id(self, replica_id_in_sync_group): + return replica_id_in_sync_group + + def _get_replica_id_in_sync_group(self, replica_id): + return replica_id diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parameter_server_strategy_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parameter_server_strategy_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..f927e85a394799af44110027251a5ddf6140cf1b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/parameter_server_strategy_v2.py @@ -0,0 +1,1009 @@ +# 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. +# ============================================================================== +"""Parameter server strategy V2 class. + +This is currently under development and the API is subject to change. +""" + +import functools +import os +import threading + +from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import input_util +from tensorflow.python.distribute import mirrored_run +from tensorflow.python.distribute import multi_worker_util +from tensorflow.python.distribute import parameter_server_strategy +from tensorflow.python.distribute import ps_values +from tensorflow.python.distribute import sharded_variable +from tensorflow.python.distribute import values +from tensorflow.python.distribute.cluster_resolver import cluster_resolver as base_cluster_resolver +from tensorflow.python.distribute.coordinator import cluster_coordinator +from tensorflow.python.eager import context +from tensorflow.python.eager import remote +from tensorflow.python.framework import config +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training import server_lib +from tensorflow.python.util import keras_deps +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tsl.protobuf import coordination_config_pb2 + + +ALLOWED_TASK_TYPES = ("chief", "worker", "ps") +# This sets the coordination service's internal heartbeat timeout. In testing, a +# value of 1 led to some spurious reports of unavailability, so a higher value +# is used. Refer to the discussion in b/249134783 for more. +_HEARTBEAT_TIMEOUT_SECS = 5 + +# Set the number of retries during initial connection for fault tolerance. +# Retries follow an exponential backoff waiting period as defined in the +# runtime, with min value 1ms, max value 10s, and exponent 1.3. So 50 retries +# enables ~3 minutes of retrying. In general, this means the first 35 retries +# consist of 42 seconds of backoff waiting, and each subsequent retry waits for +# 10 seconds. So to enable 30 minutes of retrying, we would want +# 35 + (30 * 60 - 42) // 10 = 210 retries. +_SET_SERVER_DEF_RETRIES = 50 + + +@tf_export( + "distribute.experimental.ParameterServerStrategy", + "distribute.ParameterServerStrategy", + v1=[]) +class ParameterServerStrategyV2(distribute_lib.Strategy): + """An multi-worker tf.distribute strategy with parameter servers. + + Parameter server training is a common data-parallel method to scale up a + machine learning model on multiple machines. A parameter server training + cluster consists of workers and parameter servers. Variables are created on + parameter servers and they are read and updated by workers in each step. + By default, workers read and update these variables independently without + synchronizing with each other. Under this configuration, it is known as + asynchronous training. + + In TensorFlow 2, we recommend an architecture based on central coordination + for parameter server training. Each worker and parameter server runs a + `tf.distribute.Server`, and on top of that, a coordinator task is responsible + for creating resources on workers and parameter servers, dispatching + functions, and coordinating the training. The coordinator uses a + `tf.distribute.experimental.coordinator.ClusterCoordinator` to coordinate the + cluster, and a `tf.distribute.experimental.ParameterServerStrategy` to define + variables on parameter servers and computation on workers. + + For the training to work, the coordinator dispatches `tf.function`s to be + executed on remote workers. Upon receiving requests from the coordinator, a + worker executes the `tf.function` by reading the variables from parameter + servers, executing the ops, and updating the variables on the parameter + servers. Each of the worker only processes the requests from the coordinator, + and communicates with parameter servers, without direct interactions with + other workers in the cluster. + + As a result, failures of some workers do not prevent the cluster from + continuing the work, and this allows the cluster to train with instances that + can be occasionally unavailable (e.g. preemptible or spot instances). The + coordinator and parameter servers though, must be available at all times for + the cluster to make progress. + + Note that the coordinator is not one of the training workers. Instead, it + creates resources such as variables and datasets, dispatches `tf.function`s, + saves checkpoints and so on. In addition to workers, parameter servers and + the coordinator, an optional evaluator can be run on the side that + periodically reads the checkpoints saved by the coordinator and runs + evaluations against each checkpoint. + + `ParameterServerStrategy` is supported with two training APIs: [Custom + Training Loop (CTL)] + (https://www.tensorflow.org/tutorials/distribute/custom_training) + and [Keras Training API, also known as `Model.fit`] + (https://www.tensorflow.org/tutorials/distribute/keras). CTL is recommended + when users prefer to define the details of their training loop, and + `Model.fit` is recommended when users prefer a high-level abstraction and + handling of training. + + When using a CTL, `ParameterServerStrategy` has to work in conjunction with a + `tf.distribute.experimental.coordinator.ClusterCoordinator` object. + + When using `Model.fit`, currently only the + `tf.keras.utils.experimental.DatasetCreator` input type is supported. + + __Example code for coordinator__ + + This section provides code snippets that are intended to be run on (the only) + one task that is designated as the coordinator. Note that `cluster_resolver`, + `variable_partitioner`, and `dataset_fn` arguments are explained in the + following "Cluster setup", "Variable partitioning", and "Dataset preparation" + sections. + + With a CTL, + + ```python + # Prepare a strategy to use with the cluster and variable partitioning info. + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=..., + variable_partitioner=...) + coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( + strategy=strategy) + + # Prepare a distribute dataset that will place datasets on the workers. + distributed_dataset = coordinator.create_per_worker_dataset(dataset_fn=...) + + with strategy.scope(): + model = ... + optimizer, metrics = ... # Keras optimizer/metrics are great choices + checkpoint = tf.train.Checkpoint(model=model, optimizer=optimizer) + checkpoint_manager = tf.train.CheckpointManager( + checkpoint, checkpoint_dir, max_to_keep=2) + # `load_checkpoint` infers initial epoch from `optimizer.iterations`. + initial_epoch = load_checkpoint(checkpoint_manager) or 0 + + @tf.function + def worker_fn(iterator): + + def replica_fn(inputs): + batch_data, labels = inputs + # calculate gradient, applying gradient, metrics update etc. + + strategy.run(replica_fn, args=(next(iterator),)) + + for epoch in range(initial_epoch, num_epoch): + distributed_iterator = iter(distributed_dataset) # Reset iterator state. + for step in range(steps_per_epoch): + + # Asynchronously schedule the `worker_fn` to be executed on an arbitrary + # worker. This call returns immediately. + coordinator.schedule(worker_fn, args=(distributed_iterator,)) + + # `join` blocks until all scheduled `worker_fn`s finish execution. Once it + # returns, we can read the metrics and save checkpoints as needed. + coordinator.join() + logging.info('Metric result: %r', metrics.result()) + train_accuracy.reset_states() + checkpoint_manager.save() + ``` + + With `Model.fit`, + + ```python + # Prepare a strategy to use with the cluster and variable partitioning info. + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=..., + variable_partitioner=...) + + # A dataset function takes a `input_context` and returns a `Dataset` + def dataset_fn(input_context): + dataset = tf.data.Dataset.from_tensors(...) + return dataset.repeat().shard(...).batch(...).prefetch(...) + + # With `Model.fit`, a `DatasetCreator` needs to be used. + input = tf.keras.utils.experimental.DatasetCreator(dataset_fn=...) + + with strategy.scope(): + model = ... # Make sure the `Model` is created within scope. + model.compile(optimizer="rmsprop", loss="mse", steps_per_execution=..., ...) + + # Optional callbacks to checkpoint the model, back up the progress, etc. + callbacks = [tf.keras.callbacks.ModelCheckpoint(...), ...] + + # `steps_per_epoch` is required with `ParameterServerStrategy`. + model.fit(input, epochs=..., steps_per_epoch=..., callbacks=callbacks) + ``` + + __Example code for worker and parameter servers__ + + In addition to the coordinator, there should be tasks designated as + "worker" or "ps". They should run the following code to start a TensorFlow + server, waiting for coordinator's requests: + + ```python + # Provide a `tf.distribute.cluster_resolver.ClusterResolver` that serves + # the cluster information. See below "Cluster setup" section. + cluster_resolver = ... + + server = tf.distribute.Server( + cluster_resolver.cluster_spec(), + job_name=cluster_resolver.task_type, + task_index=cluster_resolver.task_id, + protocol="grpc") + + # Blocking the process that starts a server from exiting. + server.join() + ``` + + __Cluster setup__ + + In order for the tasks in the cluster to know other tasks' addresses, + a `tf.distribute.cluster_resolver.ClusterResolver` is required to be used + in coordinator, worker, and ps. The + `tf.distribute.cluster_resolver.ClusterResolver` is responsible for providing + the cluster information, as well as the task type and id of the current task. + See `tf.distribute.cluster_resolver.ClusterResolver` for more information. + + If `TF_CONFIG` environment variable is set, a + `tf.distribute.cluster_resolver.TFConfigClusterResolver` should be used as + well. + + Since there are assumptions in + `tf.distribute.experimental.ParameterServerStrategy` around the naming of the + task types, "chief", "ps", and "worker" should be used in the + `tf.distribute.cluster_resolver.ClusterResolver` to refer to the coordinator, + parameter servers, and workers, respectively. + + The following example demonstrates setting `TF_CONFIG` for the task designated + as a parameter server (task type "ps") and index 1 (the second task), in a + cluster with 1 chief, 2 parameter servers, and 3 workers. Note that it needs + to be set before the use of + `tf.distribute.cluster_resolver.TFConfigClusterResolver`. + + Example code for cluster setup: + ```python + os.environ['TF_CONFIG'] = ''' + { + "cluster": { + "chief": ["chief.example.com:2222"], + "ps": ["ps0.example.com:2222", "ps1.example.com:2222"], + "worker": ["worker0.example.com:2222", "worker1.example.com:2222", + "worker2.example.com:2222"] + }, + "task": { + "type": "ps", + "index": 1 + } + } + ''' + ``` + + If you prefer to run the same binary for all tasks, you will need to let the + binary branch into different roles at the beginning of the program: + ```python + # If coordinator, create a strategy and start the training program. + if cluster_resolver.task_type == 'chief': + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver) + ... + + # If worker/ps, create a server + elif cluster_resolver.task_type in ("worker", "ps"): + server = tf.distribute.Server(...) + ... + ``` + Alternatively, you can also start a bunch of TensorFlow servers in advance and + connect to them later. The coordinator can be in the same cluster or on any + machine that has connectivity to workers and parameter servers. This is + covered in our guide and tutorial. + + __Variable creation with `strategy.scope()`__ + + `tf.distribute.experimental.ParameterServerStrategy` follows the + `tf.distribute` API contract where variable creation is expected to be inside + the context manager returned by `strategy.scope()`, in order to be correctly + placed on parameter servers in a round-robin manner: + + ```python + # In this example, we're assuming having 3 ps. + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=...) + coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( + strategy=strategy) + + # Variables should be created inside scope to be placed on parameter servers. + # If created outside scope such as `v1` here, it would be placed on the + # coordinator. + v1 = tf.Variable(initial_value=0.0) + + with strategy.scope(): + v2 = tf.Variable(initial_value=1.0) + v3 = tf.Variable(initial_value=2.0) + v4 = tf.Variable(initial_value=3.0) + v5 = tf.Variable(initial_value=4.0) + + # v2 through v5 are created in scope and are distributed on parameter servers. + # Default placement is round-robin but the order should not be relied on. + assert v2.device == "/job:ps/replica:0/task:0/device:CPU:0" + assert v3.device == "/job:ps/replica:0/task:1/device:CPU:0" + assert v4.device == "/job:ps/replica:0/task:2/device:CPU:0" + assert v5.device == "/job:ps/replica:0/task:0/device:CPU:0" + ``` + + See `distribute.Strategy.scope` for more information. + + __Variable partitioning__ + + Having dedicated servers to store variables means being able to divide up, or + "shard" the variables across the ps. Partitioning large variable among ps is a + commonly used technique to boost training throughput and mitigate memory + constraints. It enables parallel computations and updates on different shards + of a variable, and often yields better load balancing across parameter + servers. Without sharding, models with large variables (e.g, embeddings) that + can't fit into one machine's memory would otherwise be unable to train. + + With `tf.distribute.experimental.ParameterServerStrategy`, if a + `variable_partitioner` is provided to `__init__` and certain conditions are + satisfied, the resulting variables created in scope are sharded across the + parameter servers, in a round-robin fashion. The variable reference returned + from `tf.Variable` becomes a type that serves as the container of the sharded + variables. One can access `variables` attribute of this container for the + actual variable components. If building model with `tf.Module` or Keras, + the variable components are collected in the `variables` alike attributes. + + It is recommended to use size-based partitioners like + `tf.distribute.experimental.partitioners.MinSizePartitioner` to avoid + partitioning small variables, which could have negative impact on model + training speed. + + ```python + # Partition the embedding layer into 2 shards. + variable_partitioner = ( + tf.distribute.experimental.partitioners.MinSizePartitioner( + min_shard_bytes=(256 << 10), + max_shards = 2)) + strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver=..., + variable_partitioner = variable_partitioner) + with strategy.scope(): + embedding = tf.keras.layers.Embedding(input_dim=1024, output_dim=1024) + assert len(embedding.variables) == 2 + assert isinstance(embedding.variables[0], tf.Variable) + assert isinstance(embedding.variables[1], tf.Variable) + assert embedding.variables[0].shape == (512, 1024) + assert embedding.variables[1].shape == (512, 1024) + ``` + + The sharded variable container can be converted to a `Tensor` via + `tf.convert_to_tensor`. This means the container can be directly used in most + Python Ops where such `Tensor` conversion automatically happens. For example, + in the above code snippet, `x * self.w` would implicitly apply the said tensor + conversion. Note that such conversion can be expensive, as the variable + components need to be transferred from multiple parameter servers to where + the value is used. + + `tf.nn.embedding_lookup` on the other hand doesn't apply the tensor + conversion, and performs parallel lookups on the variable components instead. + This is crucial to scale up embedding lookups when the embedding table + variable is large. + + When a partitioned variable is saved to a `SavedModel`, it will be saved as if + it is one single variable. This improves serving efficiency by eliminating + a number of Ops that handle the partiton aspects. + + Known limitations of variable partitioning: + + * Number of partitions must not change across Checkpoint saving/loading. + + * After saving partitioned variables to a SavedModel, the SavedModel can't be + loaded via `tf.saved_model.load`. + + * Partition variable doesn't directly work with `tf.GradientTape`, please use + the `variables` attributes to get the actual variable components and use + them in gradient APIs instead. + + __Dataset preparation__ + + With `tf.distribute.experimental.ParameterServerStrategy`, a dataset is + created in each of the workers to be used for training. This is done by + creating a `dataset_fn` that takes no argument and returns a + `tf.data.Dataset`, and passing the `dataset_fn` into + `tf.distribute.experimental.coordinator. + ClusterCoordinator.create_per_worker_dataset`. We recommend the dataset to be + shuffled and repeated to have the examples run through the training as evenly + as possible. + + ```python + def dataset_fn(): + filenames = ... + dataset = tf.data.Dataset.from_tensor_slices(filenames) + + # Dataset is recommended to be shuffled, and repeated. + return dataset.shuffle(buffer_size=...).repeat().batch(batch_size=...) + + coordinator = + tf.distribute.experimental.coordinator.ClusterCoordinator(strategy=...) + distributed_dataset = coordinator.create_per_worker_dataset(dataset_fn) + ``` + + __Limitations__ + + * `tf.distribute.experimental.ParameterServerStrategy` in TF2 is experimental, + and the API is subject to further changes. + + * When using `Model.fit`, `tf.distribute.experimental.ParameterServerStrategy` + must be used with a `tf.keras.utils.experimental.DatasetCreator`, and + `steps_per_epoch` must be specified. + """ + + # pyformat: disable + def __init__(self, cluster_resolver: base_cluster_resolver.ClusterResolver, variable_partitioner: sharded_variable.Partitioner = None): + """Initializes the TF2 parameter server strategy. + + This initializes the `tf.distribute.experimental.ParameterServerStrategy` + object to be ready for use with + `tf.distribute.experimental.coordinator.ClusterCoordinator`. + + Args: + cluster_resolver: a `tf.distribute.cluster_resolver.ClusterResolver` + object. + variable_partitioner: + a `distribute.experimental.partitioners.Partitioner` that specifies + how to partition variables. If `None`, variables will not be + partitioned. + + * Predefined partitioners in `tf.distribute.experimental.partitioners` + can be used for this argument. A commonly used partitioner is + `MinSizePartitioner(min_shard_bytes = 256 << 10, max_shards = num_ps)`, + which allocates at least 256K per shard, and each ps gets at most one + shard. + + * `variable_partitioner` will be called for each variable created under + strategy `scope` to instruct how the variable should be partitioned. + Variables that have only one partition along the partitioning axis + (i.e., no need for partition) will be created as a normal `tf.Variable`. + + * Only the first / outermost axis partitioning is supported. + + * Div partition strategy is used to partition variables. Assuming we + assign consecutive integer ids along the first axis of a variable, then + ids are assigned to shards in a contiguous manner, while attempting to + keep each shard size identical. If the ids do not evenly divide the + number of shards, each of the first several shards will be assigned one + more id. For instance, a variable whose first dimension is 13 has 13 + ids, and they are split across 5 shards as: + `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`. + + * Variables created under `strategy.extended.colocate_vars_with` will + not be partitioned. + """ + # pyformat: enable + self._cluster_resolver = cluster_resolver + + self._verify_args_and_config(cluster_resolver) + self._cluster_coordinator = None + logging.info( + "`tf.distribute.experimental.ParameterServerStrategy` is initialized " + "with cluster_spec: %s", cluster_resolver.cluster_spec()) + + if os.getenv("TF_PSS_ENABLE_COORDINATION_SERVICE"): + self._configure_coordination_service(cluster_resolver.cluster_spec()) + # TODO(b/167894802): Make coordinator, worker, and ps names customizable. + self._connect_to_cluster(coordinator_name="chief") + self._extended = ParameterServerStrategyV2Extended(self, cluster_resolver, + variable_partitioner) + super(ParameterServerStrategyV2, self).__init__(self._extended) + distribute_lib.distribution_strategy_gauge.get_cell("V2").set( + "ParameterServerStrategy") + self._should_use_with_coordinator = True + # Used while constructing distributed iterators. + self._canonicalize_devices = False + # Used to check if isinstance() without having to import this module + self._is_parameter_server_strategy_v2 = True + + def _configure_coordination_service(self, cluster_spec: base_cluster_resolver.ClusterSpec): + if context.context().coordination_service is None: + coordinated_jobs = ["worker", "ps"] + coordinated_job_config = [] + for job in coordinated_jobs: + if job in cluster_spec.jobs: + coordinated_job_config.append( + coordination_config_pb2.CoordinatedJob( + name=job, + num_tasks=cluster_spec.num_tasks(job))) + context.context().configure_coordination_service( + service_type="standalone", + service_leader=multi_worker_util.coordination_leader( + cluster_spec), + heartbeat_timeout_in_ms=_HEARTBEAT_TIMEOUT_SECS * 1000, + allow_new_incarnation_to_reconnect=True) + + def _connect_to_cluster(self, coordinator_name: str): + if coordinator_name in ["worker", "ps"]: + raise ValueError("coordinator name should not be 'worker' or 'ps'.") + cluster_spec = self._cluster_resolver.cluster_spec() + self._num_workers = len(cluster_spec.as_dict().get("worker", ())) + self._num_ps = len(cluster_spec.as_dict().get("ps", ())) + + device_filters = server_lib.ClusterDeviceFilters() + # For any worker, only the devices on ps and coordinator nodes are visible + for i in range(self._num_workers): + device_filters.set_device_filters( + "worker", i, ["/job:ps", "/job:%s" % coordinator_name]) + # Similarly for any ps, only the devices on workers and coordinator are + # visible + for i in range(self._num_ps): + device_filters.set_device_filters( + "ps", i, ["/job:worker", "/job:%s" % coordinator_name]) + + # Allow at most one outstanding RPC for each worker at a certain time. This + # is to simplify worker failure handling in the runtime + os.environ["TF_ENABLE_EAGER_CLIENT_STREAMING_ENQUEUE"] = "False" + + # Disable async executors to make context.async_wait a no-op. This avoids + # sending RPCs to remote workers since the executors used by PSStrategy + # are known to be always synchronous. + os.environ["TF_PS_DISABLE_ASYNC_EXECUTOR_GLOBALLY"] = "True" + + logging.info("%s is now connecting to cluster with cluster_spec: %r", + self.__class__.__name__, cluster_spec) + remote.connect_to_cluster( + cluster_spec, + job_name=coordinator_name, + protocol=self._cluster_resolver.rpc_layer, + cluster_device_filters=device_filters) + + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "ps_strategy_num_workers").set(self._num_workers) + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "ps_strategy_num_ps").set(self._num_ps) + + # Explicitly connect to the cluster here. Enable retries in case of worker + # preemptions during connection. + context.set_server_def_retries(_SET_SERVER_DEF_RETRIES) + # Perform connection by initializing context. + context.ensure_initialized() + + def _verify_args_and_config(self, cluster_resolver: base_cluster_resolver.ClusterResolver): + if not cluster_resolver.cluster_spec(): + raise ValueError("Cluster spec must be non-empty in " + "`tf.distribute.cluster_resolver.ClusterResolver`.") + cluster_spec = cluster_resolver.cluster_spec() + + # The following checks if the task types are allowed (chief, ps, worker). + multi_worker_util._validate_cluster_spec( # pylint: disable=protected-access + cluster_spec, cluster_resolver.task_type, cluster_resolver.task_id) + + if multi_worker_util.task_count(cluster_spec, "ps") < 1: + raise ValueError("There must be at least one ps.") + + if multi_worker_util.task_count(cluster_spec, "worker") < 1: + raise ValueError("There must be at least one worker.") + + +class ParameterServerStrategyV2Extended( + parameter_server_strategy.ParameterServerStrategyExtended +): + """Extended class for ParameterServerStrategyV2. + + Please see `tf.distribute.StrategyExtended` doc for more information. + """ + + def __init__( + self, + container_strategy, + cluster_resolver: base_cluster_resolver.ClusterResolver, + variable_partitioner, + ): + """Initialization of ParameterServerStrategyV2Extended.""" + super(ParameterServerStrategyV2Extended, self).__init__(container_strategy) + self._num_ps = len(cluster_resolver.cluster_spec().as_dict().get("ps", [])) + self._num_workers = len( + cluster_resolver.cluster_spec().as_dict().get("worker", []) + ) + self._variable_count = 0 + + self._variable_partitioner = variable_partitioner + # The following two attrs are to verify that `ParameterServerStrategy` + # methods are properly used with a `ClusterCoordinator`. + self._used_with_coordinator = False + self._being_scheduled = False + self._set_num_gpus() + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_gpus_per_worker").set(self._num_gpus_per_worker) + + # Don't canonicalize the devices here since this code is executed on Chief, + # but we want the reduce evaluation to be done on each worker. Placer will + # automatically choose the right device based on current context. + # TODO(ishark): Use select_cross_device_ops instead. + self._cross_device_ops = cross_device_ops_lib.ReductionToOneDevice( + reduce_to_device="/device:CPU:0") + self._cross_device_ops._canonicalize_devices = False # pylint: disable=protected-access + self._allow_run_without_coordinator = False + self._coordinator_creation_lock = threading.Lock() + + def _set_num_gpus(self): + devices = config.list_logical_devices("GPU") + per_worker_gpus = {} + for d in devices: + d_spec = tf_device.DeviceSpec.from_string(d.name) + if d_spec.device_type == "GPU" and d_spec.job == "worker": + # TODO(b/167894802): update if worker name is customizable + job_spec = d_spec.replace(device_type=None, device_index=None) + per_worker_gpus[job_spec] = per_worker_gpus.get(job_spec, 0) + 1 + + num_gpus = 0 + for _, count in per_worker_gpus.items(): + if num_gpus > 0 and count != num_gpus: + raise ValueError("Mismatched number of GPUs per worker") + num_gpus = count + + self._num_gpus_per_worker = num_gpus + logging.info(f"Number of GPUs on workers: {self._num_gpus_per_worker}") + + @property + def _num_replicas_in_sync(self): + return self._num_gpus_per_worker or 1 + + def _create_var_creator(self, next_creator, **kwargs): + aggregation = kwargs.pop("aggregation", vs.VariableAggregation.NONE) + + def var_creator(**kwargs): + """Create an AggregatingVariable.""" + # Create and wrap the variable. + v = next_creator(**kwargs) + wrapped_v = ps_values.CachingVariable(v) + wrapped = ps_values.AggregatingVariable(self._container_strategy(), + wrapped_v, aggregation) + return wrapped + + if self._num_replicas_in_sync > 1: + if aggregation not in (vs.VariableAggregation.NONE, + vs.VariableAggregation.SUM, + vs.VariableAggregation.MEAN, + vs.VariableAggregation.ONLY_FIRST_REPLICA): + raise ValueError("Invalid variable aggregation mode: " + aggregation + + " for variable: " + kwargs["name"]) + return var_creator + else: + + def variable_creator_single_replica(**kwargs): + v = next_creator(**kwargs) + return ps_values.CachingVariable(v) + + return variable_creator_single_replica + + def _create_per_worker_variable(self, next_creator, **kwargs): + """Create an unsynced, unaggregated variable on each worker.""" + return ps_values.PerWorkerVariable( + self._container_strategy(), next_creator, **kwargs) + + def _create_variable(self, next_creator, **kwargs): + """Implements StrategyExtendedV2._create_variable. + + Creates a `Variable` or a `ShardedVariable`. A `ShardedVariable` will be + created if satisfying all the following criteria: + 1. `self._variable_partitioner` results in more than one partition on the + first axis. + 2. variable's rank is greater than 0. + 3. variable is not colocated with another variable. + Otherwise a `Variable` will be created. + + Args: + next_creator: See `variable_scope.variable_creator_scope`; the next + creator in the chain. + **kwargs: Passed through to the next creator. + + Returns: + A `Variable` or `ShardedVariable`. + """ + if kwargs.pop("per_worker_variable", False): + logging.info("Creating per worker variable") + return self._create_per_worker_variable(next_creator, **kwargs) + + var_creator = self._create_var_creator(next_creator, **kwargs) + if "colocate_with" in kwargs: # Never partition colocated_with variables. + colocate_with = kwargs["colocate_with"] + # Clear the variable scope to avoid possible conflicts between device + # scope and colocation scope. + with ops.device(None): + with ops.colocate_with(colocate_with): + var = var_creator(**kwargs) + logging.debug( + "Creating variable (name:%s, shape:%r) that colocates with %s", + var.name, var.shape, kwargs["colocate_with"].name) + return var + + if self._variable_partitioner is None: + return self._create_variable_round_robin(var_creator, **kwargs) + + name = kwargs.get("name", None) + dtype = kwargs.get("dtype", None) + shape = kwargs.get("shape", None) + initial_value = kwargs.get("initial_value", None) + if initial_value is None: + # If we are loading, next_creator will return an UninitializedVariable + v = next_creator(**kwargs) + if not isinstance(v, resource_variable_ops.UninitializedVariable): + raise ValueError( + "It looks like you are using `ParameterServerStrategy` with a" + " `variable_partitioner`, and trying to create a variable without" + " specifying `initial_value`. This is not allowed. Please specify" + " the `initial_value`." + ) + elif shape is None or dtype is None: + raise ValueError( + "It looks like you are trying to load a `SavedModel` using " + "`tf.saved_model.load` within a `ParameterServerStrategy` scope, " + "but the `SavedModel` is missing shape or dtype information." + ) + else: + + def initializer(shape, dtype, **kwargs): + if "partition_shape" in kwargs: + shape = kwargs["partition_shape"] + return array_ops.zeros(shape, dtype) + + initial_value = functools.partial(initializer, shape=shape, dtype=dtype) + + # Two cases where initial_value can be a callable: + # 1. initial_value is passed as a callable, e.g, an `initializer` class. + # 2. restoring from checkpoint, initial_value is a + # "CheckpointInitialValueCallable". + init_from_fn = callable(initial_value) + + if init_from_fn and (shape is None or dtype is None): + init_from_fn = False + initial_value = initial_value() + if not init_from_fn: + # The initial_value is created on coordinator, it will need to be sent to + # ps for variable initialization, which can be inefficient and can + # potentially hit the 2GB limit on protobuf serialization. + initial_value = ops.convert_to_tensor(initial_value, dtype=dtype) + dtype = initial_value.dtype + shape = initial_value.shape + else: + shape = tensor_shape.as_shape(shape) + + if shape.rank == 0: # Skip partitioning rank-0 variable. + return self._create_variable_round_robin(var_creator, **kwargs) + + num_partitions = self._variable_partitioner(shape=shape, dtype=dtype) + if not num_partitions or num_partitions[0] == 0 or any( + v != 1 for v in num_partitions[1:]): + raise ValueError( + "variable_partitioner must return a list/tuple whose elements are 1" + " besides the first element (non-zero), got: %r" % num_partitions) + + if num_partitions[0] == 1: # no partition + return self._create_variable_round_robin(var_creator, **kwargs) + + # Use "div" partition strategy to partition the variable. + num_partitions = min(num_partitions[0], shape[0]) + base = shape[0] // num_partitions + extra = shape[0] % num_partitions + # An example: num_partitions=4, shape[0]=10, partitions: [3, 3, 2, 2] + # offsets: [0, 3, 6, 8, 10] + offsets = [] + for i in range(num_partitions): + if i == 0: + offsets.append(0) + else: + prev_shard_size = base + (1 if i - 1 < extra else 0) + offsets.append(offsets[i - 1] + prev_shard_size) + offsets.append(shape[0]) + + def init_shard_fn(shard_index): + if not init_from_fn: + logging.log_if( + logging.WARN, _INEFFICIENT_INIT_WARNING % name, shard_index == 0 and + shape.num_elements() > _LARGE_VARIABLE_NUM_ELEMENTS) + return initial_value[offsets[shard_index]:offsets[shard_index + 1]] + partition_shape = (offsets[shard_index + 1] - + offsets[shard_index],) + shape[1:] + partition_offset = (offsets[shard_index],) + (0,) * len(shape[1:]) + arg_spec = tf_inspect.getfullargspec(initial_value) + if ("shard_info" not in arg_spec.args and + "shard_info" not in arg_spec.kwonlyargs): + try: + value = initial_value( + partition_shape=partition_shape, + partition_offset=partition_offset) + except (TypeError, ValueError): + # TypeError: Initializer doesn't accept kwargs + # ValueError: Initializer doesn't accept partition kwargs + # In both cases we go ahead creating the full value and then slice. + value = initial_value() + + if value.shape == partition_shape: + # Initializer supports partition: value is the partition value. + return value + else: + # Initializer doesn't support partition: value is the full value + # and needs to be sliced to get the partition value. + logging.log_if( + logging.WARN, _INEFFICIENT_INIT_WARNING % name, + shard_index == 0 and + shape.num_elements() > _LARGE_VARIABLE_NUM_ELEMENTS) + return value[offsets[shard_index]:offsets[shard_index + 1]] + else: + # For compatibility with `CheckpointInitialValueCallable`. + return initial_value( + shard_info=trackable.ShardInfo( + shape=tensor_shape.as_shape(partition_shape), + offset=partition_offset)) + + var_list = [] + for i in range(num_partitions): + kwargs["shape"] = (offsets[i + 1] - offsets[i],) + shape[1:] + kwargs["initial_value"] = lambda: init_shard_fn(i) + if name is not None: + kwargs["name"] = "{}/part_{}".format(name, i) + var_list.append(self._create_variable_round_robin(var_creator, **kwargs)) + + result = sharded_variable.ShardedVariable(var_list) + return result + + def _create_variable_round_robin(self, next_creator, **kwargs): + # Clear the colocation scope to avoid possible conflicts between device + # scope and colocation scope. + with ops.colocate_with(None, ignore_existing=True): + # Explicitly set CPU:0 device for PS in case create variable is called + # inside replica_fn and worker has with GPU:0 scope. + with ops.device("/job:ps/task:%d/device:CPU:0" % + (self._variable_count % self._num_ps)): + var = next_creator(**kwargs) + log_method = ( + logging.info if os.getenv("TF_PSS_VERBOSE_VARIABLE_PLACEMENT") + else logging.debug + ) + log_method( + "Creating variable (name:%s, shape:%r) on " + "/job:ps/task:%d/device:CPU:0", var.name, var.shape, + (self._variable_count % self._num_ps)) + self._variable_count += 1 + return var + + def _resource_creator_scope(self): + + with self._coordinator_creation_lock: + if not self._container_strategy()._cluster_coordinator: # pylint: disable=protected-access + cluster_coordinator.ClusterCoordinator( + strategy=self._container_strategy()) + + # TODO(wxinyi): We should warn the user of the inefficiency of creating + # `StaticHashTable` inside a `@tf.function`-wrapped `dataset_fn` to be + # distributed with `distribute_datasets_from_function` and + # `create_per_worker_dataset`. This is because the `dataset_fn` does not + # use the same `default_graph` as `scope` to which the + # `resource_creator_stack` belongs. Thus, `StaticHashTable` creation inside + # `dataset_fn` is not intercepted. And since its resource creation under a + # `tf.function` is lifted out, all workers will share the same resource on + # the coordinator which incurs worker-coordinator communication overhead. + + def lookup_creator(next_creator, *args, **kwargs): + if keras_deps.get_load_context_function()(): + return (ps_values.RestoredDistributedTable( + self._container_strategy(), lambda: next_creator(*args, **kwargs))) # pylint: disable=protected-access + else: + return ps_values.DistributedTable(self._container_strategy(), + lambda: next_creator(*args, **kwargs)) # pylint: disable=protected-access + + def restored_lookup_creator(next_creator, *args, **kwargs): + return (ps_values.RestoredDistributedTable( + self._container_strategy(), lambda: next_creator(*args, **kwargs))) # pylint: disable=protected-access + + return [ + ops.resource_creator_scope("StaticHashTable", lookup_creator), + ops.resource_creator_scope("RestoredStaticHashTable", + restored_lookup_creator) + ] + + def _assert_used_with_cluster_coordinator(self): + if (not self._used_with_coordinator and + not self._allow_run_without_coordinator): + raise NotImplementedError( + "`tf.distribute.experimental.ParameterServerStrategy` must be used " + "with `tf.distribute.experimental.coordinator.ClusterCoordinator` in " + "a custom training loop. If you are using `Model.fit`, please supply " + "a dataset function directly to a " + "`tf.keras.utils.experimental.DatasetCreator` instead.") + + def _assert_being_scheduled_by_cluster_coordinator(self): + if not self._being_scheduled and not self._allow_run_without_coordinator: + logging.warning( + "A `tf.distribute.experimental.ParameterServerStrategy` method is " + "invoked without using `ClusterCoordinator.schedule`. If you are not " + "tracing a tf.function, this method is possibly executed on the " + "coordinator, which can be slow. To properly dispatch functions to " + "run on workers, methods like `run` or `reduce` should be used " + "within a function passed to `tf.distribute.experimental.coordinator." + "ClusterCoordinator.schedule`.") + + # options is not used right now. But we may want to support options while + # creating InputWorkers in future, similar to MirroredStrategy. + def _input_workers_with_options(self, options=None): + input_workers_devices = (("/device:CPU:0", self.worker_devices),) + return input_lib.InputWorkers( + input_workers_devices, canonicalize_devices=False) + + def _experimental_distribute_dataset(self, dataset, options): + input_workers_devices = self._input_workers_with_options() + + # If this DistributedDataset is created outside ClusterCoordinator, i,e, + # outside a tf.function, we don't build its underlying datasets immediately + # until it is passed to ClusterCoordinator.create_per_worker_dataset. + return input_util.get_distributed_dataset( + dataset, + input_workers_devices, + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync, + options=options, + build=ops.inside_function()) # will be built by ClusterCoordinator + + def _distribute_datasets_from_function(self, dataset_fn, options): + # There is no synchronization beyond a worker and thus, the number of + # input pipelines in sync is only 1 per worker. + input_pipeline_id_in_sync = 0 + num_input_pipelines_in_sync = 1 + + input_context = distribute_lib.InputContext( + num_input_pipelines=num_input_pipelines_in_sync, + input_pipeline_id=input_pipeline_id_in_sync, + num_replicas_in_sync=self._num_replicas_in_sync) + + # If this DistributedDatasetFromFunction is created outside + # ClusterCoordinator, i,e, outside a tf.function, we don't build its + # underlying datasets immediately until it is passed to + # ClusterCoordinator.create_per_worker_dataset. + return input_util.get_distributed_datasets_from_function( + dataset_fn, + self._input_workers_with_options(options), [input_context], + self._container_strategy(), + options=options, + build=ops.inside_function()) # will be built by ClusterCoordinator + + @property + def worker_devices(self): + num_gpus = self._num_gpus_per_worker + if num_gpus > 0: + compute_devices = tuple("/device:GPU:%d" % (i,) for i in range(num_gpus)) + else: + compute_devices = ("/device:CPU:0",) + return compute_devices + + def _call_for_each_replica(self, fn, args, kwargs): + self._assert_being_scheduled_by_cluster_coordinator() + + return mirrored_run.call_for_each_replica(self._container_strategy(), fn, + args, kwargs) + + def _reduce(self, reduce_op, value): + self._assert_being_scheduled_by_cluster_coordinator() + dst = device_util.current() or self._default_device or "/device:CPU:0" + destinations = device_util.canonicalize_without_job_and_task(dst) + result = self._local_results( + self.reduce_to(reduce_op, value, destinations))[0] + return result + + def _reduce_to(self, reduce_op, value, destinations, options): + self._assert_being_scheduled_by_cluster_coordinator() + + def get_values(x): + if isinstance(x, values.DistributedValues): + return self._cross_device_ops.reduce( + reduce_op, x, destinations=destinations) # pylint: disable=protected-access + return x + + return nest.map_structure(get_values, value) + + +# The warning that will be logged if the way we initialize sharded variables +# is memory-inefficient. +_INEFFICIENT_INIT_WARNING = ( + "Large variable %s is partitioned but not initialized in a " + "memory-efficient way. On each shard, the full value is first being " + "created and then sliced into smaller values. To reduce the memory " + "footprint, explicitly specify `dtype` and `shape` when creating " + "variables, and use `tf.initializers` to initialize the variable. " + "Note that some initializers (e.g., orthogonal) don't support " + "memory-efficient initialization and there is not much you can do here.") + +_LARGE_VARIABLE_NUM_ELEMENTS = 1e9 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/ps_values.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/ps_values.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9eedf6984704b9d35dcd20562ae02f47850b05 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/ps_values.py @@ -0,0 +1,964 @@ +# 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. +# ============================================================================== +"""Various classes representing distributed values for PS.""" + +import contextlib +import copy +import functools +import threading +import weakref + +import numpy as np + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import values +from tensorflow.python.distribute import values_util +from tensorflow.python.distribute.coordinator import coordinator_context +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.saved_model import save_context +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import core + + +TRACKABLE_RESOURCE_METHODS = [ + "_create_resource", "_initialize", "_destroy_resource" +] + + +# Variable used in PSStrategy TF 1, TF2 and CentralStorageStrategy. +class AggregatingVariable(resource_variable_ops.BaseResourceVariable, + core.Tensor): + """A wrapper around a variable that aggregates updates across replicas.""" + + def __init__(self, strategy, v, aggregation): + self._distribute_strategy = strategy + self._v = v + # NOTE: We don't use "_distributed_container" here because we don't want + # to trigger that code path in regroup(). + v._aggregating_container = weakref.ref(self) # pylint: disable=protected-access + self._aggregation = aggregation + + def __deepcopy__(self, memo): + """Perform a deepcopy of the `AggregatingVariable`. + + Unlike the deepcopy of a regular tf.Variable, this keeps the original + strategy and devices of the `AggregatingVariable`. To avoid confusion + with the behavior of deepcopy on a regular `Variable` (which does + copy into new devices), we only allow a deepcopy of a `AggregatingVariable` + within its originating strategy scope. + + Args: + memo: The memoization object for `deepcopy`. + + Returns: + A deep copy of the current `AggregatingVariable`. + + Raises: + RuntimeError: If trying to deepcopy into a different strategy. + """ + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + v = copy.deepcopy(self._v, memo) + + copied_variable = type(self)( + strategy=self._distribute_strategy, + v=v, + aggregation=self._aggregation) + + memo[id(self)] = copied_variable + + return copied_variable + + def get(self): + return self._v + + @property + def distribute_strategy(self): + return self._distribute_strategy + + def __getattr__(self, name): + return getattr(self._v, name) + + def _assign_func(self, *args, **kwargs): + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + f = kwargs.pop("f") + if distribute_lib.in_cross_replica_context(): + if distribute_lib.get_update_replica_id() is not None: + # We are calling an assign function in an update context. + return f(self._v, *args, **kwargs) + + # We are calling an assign function in cross replica context, wrap it in + # an update call. + return self._distribute_strategy.extended.update( + self, f, args=args, kwargs=kwargs) + else: + replica_context = distribute_lib.get_replica_context() + assert replica_context + # We are calling an assign function in replica context. + # We reduce the value we want to assign/add/sub. More details about how + # we handle the different use cases can be found in the _reduce method. + # We call the function with the reduced value. + if self._aggregation == vs.VariableAggregation.NONE: + raise ValueError( + values_util.aggregation_error_msg.format( + variable_type="AggregatingVariable")) + + def merge_fn(strategy, + value, + use_locking=False, + name=None, + read_value=True): + v = values_util.apply_aggregation(strategy, value, self._aggregation, + self) + if name and isinstance(name, values.PerReplica): + name = name.values[0] + return strategy.extended.update( + self, + f, + args=(v,), + kwargs={ + "use_locking": use_locking, + "name": name, + "read_value": read_value + }) + return replica_context.merge_call(merge_fn, args=args, kwargs=kwargs) + + def assign_sub(self, *args, **kwargs): + assign_sub_fn = lambda var, *a, **kw: var.assign_sub(*a, **kw) + return self._assign_func(f=assign_sub_fn, *args, **kwargs) + + def assign_add(self, *args, **kwargs): + assign_add_fn = lambda var, *a, **kw: var.assign_add(*a, **kw) + return self._assign_func(f=assign_add_fn, *args, **kwargs) + + def assign(self, *args, **kwargs): + assign_fn = lambda var, *a, **kw: var.assign(*a, **kw) + return self._assign_func(f=assign_fn, *args, **kwargs) + + @property + def initializer(self): + return self._v.initializer + + def initialized_value(self): + return self._v.initialized_value() + + @property + def initial_value(self): + return self._v.initial_value + + @property + def op(self) -> ops.Operation: + return self._v.op + + def value(self): + return self._v.value() + + def read_value(self): + return self._v.read_value() + + def sparse_read(self, indices, name=None): + return self._v.sparse_read(indices, name=name) + + def eval(self, session=None): + return self._v.eval(session) + + @property + def graph(self): + return self._v.graph + + @property + def device(self): + return self._v.device + + @property + def shape(self): + return self._v.shape + + @property + def aggregation(self): + return self._aggregation + + @property + def synchronization(self): + return self._v.synchronization + + @property + def name(self): + return self._v.name + + @property + def trainable(self): + return self._v.trainable + + @property + def dtype(self): + return self._v.dtype + + # TODO(josh11b): Test saving & restoring. + def _gather_saveables_for_checkpoint(self): + if isinstance(self._v, CachingVariable): + return self._v._gather_saveables_for_checkpoint() # pylint:disable=protected-access + return {trackable.VARIABLE_VALUE_KEY: self._v} + + def _export_to_saved_model_graph(self, object_map, tensor_map, + options, **kwargs): + """For implementing `Trackable`.""" + # By delegating this method to the wrapped variable, SavedModel with + # AggregatingVariable are identical to SavedModel with normal variables. + resource_list = self._v._export_to_saved_model_graph(object_map, tensor_map, # pylint:disable=protected-access + options, **kwargs) + object_map[self] = object_map[self._v] + return resource_list + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable`.""" + # Create a copy of `self._v` to object_map, then create a new copy of self + # that wraps the copy of `self._v`. + # When updating value, only the lowest-level variable will actually do that, + # the copy of `AggregatingVariable` is more like a shell. + self._v._copy_trackable_to_cpu(object_map) # pylint:disable=protected-access + if self not in object_map: + # If copy of `self` not populated yet, initialize one. + object_map[self] = AggregatingVariable(self._distribute_strategy, + object_map[self._v], + self._aggregation) + + # pylint: disable=multiple-statements + def __add__(self, o): + return self._v + o + + def __radd__(self, o): + return o + self._v + + def __sub__(self, o): + return self._v - o + + def __rsub__(self, o): + return o - self._v + + def __mul__(self, o): + return self._v * o + + def __rmul__(self, o): + return o * self._v + + def __truediv__(self, o): + return self._v / o + + def __rtruediv__(self, o): + return o / self._v + + def __floordiv__(self, o): + return self._v // o + + def __rfloordiv__(self, o): + return o // self._v + + def __mod__(self, o): + return self._v % o + + def __rmod__(self, o): + return o % self._v + + def __lt__(self, o): + return self._v < o + + def __le__(self, o): + return self._v <= o + + def __gt__(self, o): + return self._v > o + + def __ge__(self, o): + return self._v >= o + + def __and__(self, o): + return self._v & o + + def __rand__(self, o): + return o & self._v + + def __or__(self, o): + return self._v | o + + def __ror__(self, o): + return o | self._v + + def __xor__(self, o): + return self._v ^ o + + def __rxor__(self, o): + return o ^ self._v + + def __getitem__(self, o): + return self._v[o] + + def __pow__(self, o, modulo=None): + return pow(self._v, o, modulo) + + def __rpow__(self, o): + return pow(o, self._v) + + def __invert__(self): + return ~self._v + + def __neg__(self): + return -self._v + + def __abs__(self): + return abs(self._v) + + def __div__(self, o): + try: + return self._v.__div__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __rdiv__(self, o): + try: + return self._v.__rdiv__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __matmul__(self, o): + try: + return self._v.__matmul__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __rmatmul__(self, o): + try: + return self._v.__rmatmul__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __str__(self): + return str(self._v) + + def __repr__(self): + return repr(self._v) + + def _should_act_as_resource_variable(self): + """Pass resource_variable_ops.is_resource_variable check.""" + pass + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + return self._v._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +class CachingVariable(resource_variable_ops.BaseResourceVariable, core.Tensor): + """A wrapper around a variable that caches read value locally.""" + + def __init__(self, v): + self._v = v + self._cache = None + self._current_new_cache_scope_count = 0 + + def get(self): + return self._v + + def __getattr__(self, name): + return getattr(self._v, name) + + def read_value(self): + if distribute_utils.caching_scope_local.in_caching_scope(): + return self.cached_read_value() + return self._v.read_value() + + def sparse_read(self, indices, name=None): + return self._v.sparse_read(indices, name=name) + + def cached_read_value(self): + if (distribute_utils.caching_scope_local.new_cache_scope_count > + self._current_new_cache_scope_count): + self._current_new_cache_scope_count += 1 + self._cache = None + + with ops.device("CPU:0"): + if self._cache is not None: + return self._cache + else: + self._cache = array_ops.identity(self._v) + return self._cache + + def assign_sub(self, *args, **kwargs): + return self._v.assign_sub(*args, **kwargs) + + def assign_add(self, *args, **kwargs): + return self._v.assign_add(*args, **kwargs) + + def assign(self, *args, **kwargs): + return self._v.assign(*args, **kwargs) + + @property + def initializer(self): + return self._v.initializer + + def initialized_value(self): + return self._v.initialized_value() + + @property + def initial_value(self): + return self._v.initial_value + + @property + def op(self) -> ops.Operation: + return self._v.op + + def value(self): + if distribute_utils.caching_scope_local.in_caching_scope(): + return self.cached_read_value() + return self._v.value() + + def eval(self, session=None): + return self._v.eval(session) + + @property + def graph(self): + return self._v.graph + + @property + def device(self): + return self._v.device + + @property + def shape(self): + return self._v.shape + + @property + def synchronization(self): + return self._v.synchronization + + @property + def name(self): + return self._v.name + + @property + def trainable(self): + return self._v.trainable + + @property + def dtype(self): + return self._v.dtype + + @property + def constraint(self): + return self._v.constraint + + def __array__(self, dtype=None): + return np.asarray(self.numpy(), dtype=dtype) + + def __complex__(self): + return complex(self.value().numpy()) + + def __int__(self): + return int(self.value().numpy()) + + def __float__(self): + return float(self.value().numpy()) + + def numpy(self): + if context.executing_eagerly(): + return self.read_value().numpy() + else: + raise NotImplementedError( + "numpy() is only available when eager execution is enabled.") + + def __str__(self): + return str(self._v) + + def __repr__(self): + return repr(self._v) + + def _should_act_as_resource_variable(self): + """Pass resource_variable_ops.is_resource_variable check.""" + pass + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + if distribute_utils.caching_scope_local.in_caching_scope(): + return self.cached_read_value() + return self._v._dense_var_to_tensor(dtype=dtype, name=name, as_ref=False) # pylint: disable=protected-access + + @classmethod + def _overload_overloadable_operators(cls): + """Register overloads for all operators.""" + for operator in tensor.Tensor.OVERLOADABLE_OPERATORS: + # Overloading __eq__ or __ne__ does not work as expected. + if operator == "__eq__" or operator == "__ne__": + continue + cls._tensor_overload_operator(operator) + + @classmethod + def _tensor_overload_operator(cls, operator): + """Delegate an operator overload to `tensor.Tensor`.""" + tensor_operator = getattr(tensor.Tensor, operator) + + def _operator(v, *args, **kwargs): + return tensor_operator(v.value(), *args, **kwargs) # pylint: disable=protected-access + setattr(cls, operator, _operator) + + def _gather_saveables_for_checkpoint(self): + return {trackable.VARIABLE_VALUE_KEY: self._v} + + def _export_to_saved_model_graph(self, object_map, tensor_map, + options, **kwargs): + """For implementing `Trackable`.""" + # By delegating this method to the wrapped variable, SavedModel with + # AggregatingVariable are identical to SavedModel with normal variables. + resource_list = self._v._export_to_saved_model_graph(object_map, tensor_map, # pylint:disable=protected-access + options, **kwargs) + object_map[self] = object_map[self._v] + return resource_list + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable`.""" + # Create a copy of `self._v` to object_map, then create a new copy of self + # that wraps the copy of `self._v`. + # When updating value, only the lowest-level variable will actually do that, + # the copy of `CachingVariable` is more like a shell. + self._v._copy_trackable_to_cpu(object_map) # pylint:disable=protected-access + if self not in object_map: + # If copy of `self` not populated yet, initialize one. + object_map[self] = CachingVariable(object_map[self._v]) + + +# Register a conversion function which reads the value of the variable, +# allowing instances of the class to be used as tensors. +def _tensor_conversion_aggregate(var, dtype=None, name=None, as_ref=False): + return var._dense_var_to_tensor(dtype, name, as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + AggregatingVariable, _tensor_conversion_aggregate) + + +# Register a conversion function which reads the value of the variable, +# allowing instances of the class to be used as tensors. +def _tensor_conversion_caching(var, dtype=None, name=None, as_ref=False): + return var._dense_var_to_tensor(dtype, name, as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + CachingVariable, _tensor_conversion_caching) + +CachingVariable._overload_overloadable_operators() # pylint: disable=protected-access + + +class PerWorkerVariable(resource_variable_ops.BaseResourceVariable): + """A wrapper around unsynced variables created on workers. + + `PerWorkerVariable`s are variables that are stored on workers and not + synchronized. A `PerWorkerVariable` is really a wrapper around multiple + independent `Variable`s stored on independent worker machines. + `PerWorkerVariable` is currently only tested and supported when used with + `ParameterServerStrategy`. A `PerWorkerVariable` can be created by creating a + `Variable` within strategy scope and using the `per_worker_variable` flag, + e.g.: + + ``` + with strategy.scope(): + var = tf.Variable(initial_value=0.0, per_worker_variable=True) + ``` + + The implementation modifies the graph to ensure that a worker's local version + of the variable is used for computation at call time, while needing only one + function trace and requiring no code changes beyond the `per_worker_variable` + flag. `PerWorkerVariable`s can thus be treated like a standard `Variable`, but + support is experimental and not all ops have been tested. + + All per-worker values can be retrieved and read into a list via + `PerWorkerVariable.read_all()`. + + Caveats: + - `PerWorkerVariable`s should not be used as direct inputs to a + `tf.function`. That is, they should not appear in a tf.function header as + an input argument. However they can still be read and manipulated in a + `tf.function`. + - The `shape` argument must be fully-defined (no `None` entries) or left + empty. Partially-defined shapes are not yet supported. + - Automatic control dependencies do not work with `PerWorkerVariable`s, so + returning a `PerWorkerVariable` is not supported, and `read_all()` should + be used to retrieve values. (TODO: b/286052052) + - `PerWorkerVariable`s should not be created within a `tf.function`. + """ + + def __init__(self, strategy, next_creator, **kwargs): + self._coordinator = strategy._cluster_coordinator + self._per_worker_vars = None + self._var_creator = functools.partial(next_creator, **kwargs) + + self._coordinator_instance = next_creator(**kwargs) + + # Set ResourceVariable attributes based on kwargs + if kwargs.get("in_graph_mode") is None: + with ops.init_scope(): + self._in_graph_mode = not context.executing_eagerly() + else: + self._in_graph_mode = kwargs["in_graph_mode"] + + self._cached_value = None + self._shape = self._coordinator_instance.shape + self._dtype = self._coordinator_instance.dtype + self._trainable = False # not supported + self._unique_id = kwargs.get("unique_id") + if kwargs.get("handle_name") is None: + self._handle_name = "Variable:0" + else: + self._handle_name = kwargs["handle_name"] + ":0" + self._validate_shape = kwargs.get("validate_shape", True) + + @classmethod + def _variable_call(cls, *args, **kwargs): + """Override to be a no-op to avoid metaclass creating ResourceVariables.""" + return None + + @property + def handle(self): + if context.executing_eagerly() or save_context.in_save_context(): + return self._coordinator_instance.handle + else: + self._maybe_create_per_worker_vars() + closure, spec = self.handle_call_time_value() + return ops.get_default_graph().capture_call_time_value( + closure, + spec) + + def handle_call_time_value(self): + """Returns a closure to run for a handle at call time and its spec. + + This function is called in self.handle to create a placeholder + which returns a handle on some worker or on the coordinator. + """ + + def closure(): + dispatch_context = coordinator_context.get_current_dispatch_context() + if dispatch_context: + remote_value = self._per_worker_vars._values[ # pylint: disable=protected-access + dispatch_context.worker_index] + ret = dispatch_context.maybe_get_remote_value(remote_value) + return ret.handle + else: + # Only needed for tracing + return self._coordinator_instance.handle + return closure, PerWorkerVariableSpec( + value=self._coordinator_instance.handle) + + def _maybe_create_per_worker_vars(self): + """Create variable on each worker if it hasn't been created.""" + if not self._per_worker_vars: + self._per_worker_vars = ( + self._coordinator._create_per_worker_variables(self._var_creator)) # pylint: disable=protected-access + + def read_all(self): + """Synchronously read variables from all workers into a list of Tensors.""" + return [wv.get() for wv in self._per_worker_vars._values] # pylint: disable=protected-access + + +class PerWorkerVariableSpec(tensor.TensorSpec): + def __init__(self, value=None, name=None): + super().__init__(value.shape, value.dtype, name=name) + self._value = value + + def placeholder_value(self, placeholder_context): + placeholder = super().placeholder_value(placeholder_context) + handle_data_util.set_handle_data(placeholder, self._value._handle_data) # pylint: disable=protected-access + return placeholder + + +class DistributedTable(lookup_ops.StaticHashTable): + """A distributed StaticHashTable for ParameterServerStrategy. + + An instance of DistributedTable has copies of a StaticHashTable and its + resource handle on the coordinator of each worker, created at the + DistributedTable instance initialization time with initializers on each + worker. Users can call methods on a DistributedTable as if it were a + StaticHashTable, which leads to execution with the resource local to the + consumer worker (or the coordinator, if calling from the coordinator). This + implementation relies on the fact that the methods of StaticHashTable are + queried with the resource handle (instead of the python object). + + Currently, at saving time, a DistributedTable is saved as a StaticHashTable on + the coordinator, and restoring a DistributedTable from SavedModel is not + supported. + """ + + def __init__(self, strategy, wrapped_creator): + distribute_lib.distribution_strategy_input_api_counter.get_cell( + self.__class__.__name__, "PSSDistributedLookupTable").increase_by(1) + self._coordinator_instance = wrapped_creator() + self._wrapped_creator = wrapped_creator + self._coordinator = strategy._cluster_coordinator + # self._distributed_table is a RemoteValue mapping worker_index to + # RemoteValue that wraps a resource handle on the worker + self._distributed_table = None + self._distributed_table_creation_lock = threading.Lock() + + if not save_context.in_save_context(): + self._maybe_build_distributed_table() + + def __getattr__(self, attr): + # This allows copy.copy(DistributedTable), e.g. at saving time. + # (DistributedVariable uses the same fix.) When copying an object, copy.copy + # doesn't invoke its __init__ method, instead it makes a new empty object, + # then copies the attributes over. copy.copy looks for attributes like + # "__setstate__" in case the object implements its custom unpickling. Since + # DistributedTable doesn't have those attributes defined, __getattr__ will + # be invoked, which tries to access the `_coordinator_instance` attribute. + # But that doesn't exist either because this is an empty object, and again + # __getattr__ is invoked, leading to an infinite recursion. + if attr == "_coordinator_instance": + raise AttributeError() + + if attr in self._coordinator_instance.__dict__: + attr_value = self._coordinator_instance.__dict__[attr] + if callable(attr_value): + + def wrapper(*args, **kwargs): + return attr_value(self, *args, **kwargs) + + return wrapper + elif isinstance(attr_value, property): + return attr_value + else: + return getattr(self._coordinator_instance, attr) + else: + return getattr(self._coordinator_instance, attr) + + def resource_handle_call_time_value(self): + """Returns a closure to run for a resource handle at call time and its spec. + + This function is called in self.resource_handle to create a placeholder + which returns a resource handle on some worker or on the coordinator. + """ + + def closure(): + # function to be evaluated at function call time, returning a nest of + # tensors compatible with `spec`. + dispatch_context = coordinator_context.get_current_dispatch_context() + if dispatch_context: + remote_value = self._distributed_table._values[ # pylint: disable=protected-access + dispatch_context.worker_index] + ret = dispatch_context.maybe_get_remote_value(remote_value) + return ret + + else: + return self._coordinator_instance.resource_handle + + return closure, tensor.TensorSpec([], dtype=dtypes.resource) + + def _maybe_build_distributed_table(self): + """Create table objects and resources on each worker if hasn't been created.""" + with self._distributed_table_creation_lock: + if not self._distributed_table: + + def create_copy(): + new_table = self._wrapped_creator() + ret = new_table.resource_handle + return ret + + self._distributed_table = ( + self._coordinator._create_per_worker_resources(create_copy)) # pylint: disable=protected-access + + @property + def resource_handle(self): + if context.executing_eagerly() or save_context.in_save_context(): + return self._coordinator_instance.resource_handle + else: + self._maybe_build_distributed_table() + closure, spec = self.resource_handle_call_time_value() + return ops.get_default_graph().capture_call_time_value( + closure, + spec, + default_value=self._coordinator_instance.resource_handle) + + @property + def is_distributed_table(self): + return True + + def __tf_experimental_restore_capture__( + self, concrete_function, internal_capture): + closure, spec = self.resource_handle_call_time_value() + concrete_function.graph.replace_capture_with_deferred_capture( + self._coordinator_instance.resource_handle, + closure, + spec, + default_value=self._coordinator_instance.resource_handle, + placeholder=internal_capture) + return concrete_function.graph.deferred_external_captures[-1] + + +_local_resource_restore_context = threading.local() + + +def get_current_local_resource_restore_context(): + try: + return _local_resource_restore_context.current + except AttributeError: + return None + + +@contextlib.contextmanager +def with_local_resource_restore_context(instance): + previous_context = getattr(_local_resource_restore_context, "current", None) + _local_resource_restore_context.current = LocalResourceRestoreContext( + instance) + yield + _local_resource_restore_context.current = previous_context + + +class LocalResourceRestoreContext(object): + """Class holding information of a distributed instance, e.g. StaticHashTable. + + Pairing use with context manager `with_local_resource_restore_context` allows + operations under this context manager to conveniently gets information of a + component of the `RestoredDistributedTable` (and other restored distributed + `CapturableResource` if we're supporting their distribution in the future), + instead of looking it up from the mapping of the worker-to-resource handle. + This is especially useful when we know which instance the operations should + execute with and the mapping is not available yet. + """ + + def __init__(self, instance): + self.instance = instance + + +class RestoredDistributedTable(DistributedTable): + """A restored and distributed StaticHashTable for ParameterServerStrategy.""" + + def __init__(self, strategy, wrapped_creator): + # Wait for all resource functions to have been set before building the table + self._has_resource_functions = threading.Condition() + super().__init__(strategy, wrapped_creator) + + def resource_handle_call_time_value(self): + """Returns a closure to run for a resource handle at call time and its spec. + + This function is called in self.resource_handle to create a placeholder + which returns a resource handle on some worker or on the coordinator. + """ + + def closure(): + # function to be evaluated at function call time, returning a nest of + # tensors compatible with `spec`. + dispatch_context = coordinator_context.get_current_dispatch_context() + if dispatch_context: + local_resource_restore_context = ( + get_current_local_resource_restore_context()) + + # A LocalResourceRestoreContext is entered in the process of remote + # table creation and initialization if we're in the process of loading + # from a SavedModel. A LocalResourceRestoreContext carries the + # information regarding which table is being created and initialized. In + # order to initialize a table, we need the restored `_initialize` + # function, which captures this closure as table resource. And when this + # closure is executed, we will read the table info from the + # LocalResourceRestoreContext and return its handle, rather than + # following the normal procedure of fetching from + # `self._distributed_table`, because we're still in the middle of + # building `self._distributed_table`. + if local_resource_restore_context: + remote_value = local_resource_restore_context.instance.resource_handle + + else: + remote_value = self._distributed_table._values[ # pylint: disable=protected-access + dispatch_context.worker_index] + + ret = dispatch_context.maybe_get_remote_value(remote_value) + return ret + + else: + + return self._coordinator_instance.resource_handle + + return closure, tensor.TensorSpec(shape=(), dtype=dtypes.resource) + + def __setattr__(self, name, value): + if name in TRACKABLE_RESOURCE_METHODS: + # When a StaticHashTable is loaded with `tf.saved_model.load`, it becomes + # a RestoredResource with dummy `_create_resource`, `_initialize`, and + # `_destroy_resource" methods. Similarly, when loaded with + # `tf.keras.models.load_model`, its initializer becomes a dummy one. In + # both cases, these methods needs to be set to some RestoredFunctions + # through `__setattr__`. Thus we need to store and set these methods for + # the distributed tables (a.k.a. `self._distributed_table`) on the + # workers too, besides setting for the coordinator instance. However, we + # cannot set them at this point, since the distributed tables have not + # been created. We store them in '_restored_function' and set them to the + # distributed tables when they're created in + # `self._maybe_build_distributed_table.create_copy`. + if not hasattr(self, "_restored_function"): + self._restored_function = {} + self._restored_function[name] = value + if all(method in self._restored_function + for method in TRACKABLE_RESOURCE_METHODS): + with self._has_resource_functions: + self._has_resource_functions.notify_all() + return self._coordinator_instance.__setattr__(name, value) + else: + return super(RestoredDistributedTable, self).__setattr__(name, value) + + def _create_resource(self): + """A function that creates a resource handle for a table on coordinator.""" + return self._coordinator_instance._create_resource() # pylint: disable=protected-access + + def _initialize(self): + """A function that initializes the resource.""" + return self._coordinator_instance._initialize() # pylint: disable=protected-access + + def _destroy_resource(self): + """A function that destroys the resource.""" + return self._coordinator_instance._destroy_resource() # pylint: disable=protected-access + + def _maybe_build_distributed_table(self): + """Create table objects and resources on each worker if hasn't been created.""" + with self._distributed_table_creation_lock: + if not self._distributed_table: + + def create_copy(): + new_table = self._wrapped_creator() + # Wait until all resource functions are available before setting them + # on new_table. + with self._has_resource_functions: + while not hasattr(self, "_restored_function") or any( + method not in self._restored_function + for method in TRACKABLE_RESOURCE_METHODS): + self._has_resource_functions.wait() + + if hasattr(self, "_restored_function"): + with with_local_resource_restore_context(new_table): + for name, tf_function in self._restored_function.items(): + setattr(new_table, name, tf_function) + init_op = new_table._initialize() # pylint: disable=protected-access + if not context.executing_eagerly(): + ops.add_to_collection(ops.GraphKeys.TABLE_INITIALIZERS, init_op) + + ret = new_table.resource_handle + return ret + + self._distributed_table = ( + self._coordinator._create_per_worker_resources(create_copy)) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/reduce_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/reduce_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d5a2cef5b6c69c0c78b50c1f83c50a5370a404 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/reduce_util.py @@ -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. +# ============================================================================== +"""Utilities for reduce operations.""" + +import enum + +from tensorflow.python.ops import variable_scope +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("distribute.ReduceOp") +class ReduceOp(enum.Enum): + """Indicates how a set of values should be reduced. + + * `SUM`: Add all the values. + * `MEAN`: Take the arithmetic mean ("average") of the values. + """ + # TODO(priyag): Add the following types: + # `MIN`: Return the minimum of all values. + # `MAX`: Return the maximum of all values. + SUM = "SUM" + MEAN = "MEAN" + + @staticmethod + def from_variable_aggregation(aggregation): + mapping = { + variable_scope.VariableAggregation.SUM: ReduceOp.SUM, + variable_scope.VariableAggregation.MEAN: ReduceOp.MEAN, + } + + reduce_op = mapping.get(aggregation) + if not reduce_op: + raise ValueError("Could not convert from `tf.VariableAggregation` %s to" + "`tf.distribute.ReduceOp` type" % aggregation) + return reduce_op diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/sharded_variable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/sharded_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..12c9ed9aa3ed102c607b7df89a238dd3c13942f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/sharded_variable.py @@ -0,0 +1,1040 @@ +# 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. +# ============================================================================== +"""ShardedVariable class.""" +import copy +import math +from typing import Sequence +import weakref + +import numpy as np + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices as indexed_slices_lib +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import partitioned_variables +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables as variables_lib +from tensorflow.python.saved_model import save_context +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training.saving import saveable_object_util +from tensorflow.python.util import dispatch +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('distribute.experimental.partitioners.Partitioner', v1=[]) +class Partitioner(object): + """Partitioner base class: all partitiners inherit from this class. + + Partitioners should implement a `__call__` method with the following + signature: + + ```python + def __call__(self, shape, dtype, axis=0): + # Partitions the given `shape` and returns the partition results. + # See docstring of `__call__` method for the format of partition results. + ``` + """ + + def __call__(self, shape, dtype, axis=0): + """Partitions the given `shape` and returns the partition results. + + Examples of a partitioner that allocates a fixed number of shards: + + ```python + partitioner = FixedShardsPartitioner(num_shards=2) + partitions = partitioner(tf.TensorShape([10, 3], tf.float32), axis=0) + print(partitions) # [2, 0] + ``` + + Args: + shape: a `tf.TensorShape`, the shape to partition. + dtype: a `tf.dtypes.Dtype` indicating the type of the partition value. + axis: The axis to partition along. Default: outermost axis. + + Returns: + A list of integers representing the number of partitions on each axis, + where i-th value correponds to i-th axis. + """ + raise NotImplementedError + + +@tf_export('distribute.experimental.partitioners.FixedShardsPartitioner', v1=[]) +class FixedShardsPartitioner(Partitioner): + """Partitioner that allocates a fixed number of shards. + + Examples: + + >>> # standalone usage: + >>> partitioner = FixedShardsPartitioner(num_shards=2) + >>> partitions = partitioner(tf.TensorShape([10, 3]), tf.float32) + >>> [2, 1] + >>> + >>> # use in ParameterServerStrategy + >>> # strategy = tf.distribute.experimental.ParameterServerStrategy( + >>> # cluster_resolver=cluster_resolver, variable_partitioner=partitioner) + """ + + def __init__(self, num_shards): + """Creates a new `FixedShardsPartitioner`. + + Args: + num_shards: `int`, number of shards to partition. + """ + self._num_shards = num_shards + + def __call__(self, shape, dtype, axis=0): + del dtype + result = [1] * len(shape) + result[axis] = min(self._num_shards, shape.dims[axis].value) + return result + + +@tf_export('distribute.experimental.partitioners.MinSizePartitioner', v1=[]) +class MinSizePartitioner(Partitioner): + """Partitioner that allocates a minimum size per shard. + + This partitioner ensures each shard has at least `min_shard_bytes`, and tries + to allocate as many shards as possible, i.e., keeping shard size as small as + possible. The maximum number of such shards (upper bound) is given by + `max_shards`. + + Examples: + + >>> partitioner = MinSizePartitioner(min_shard_bytes=4, max_shards=2) + >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32) + >>> [2, 1] + >>> partitioner = MinSizePartitioner(min_shard_bytes=4, max_shards=10) + >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32) + >>> [6, 1] + >>> + >>> # use in ParameterServerStrategy + >>> # strategy = tf.distribute.experimental.ParameterServerStrategy( + >>> # cluster_resolver=cluster_resolver, variable_partitioner=partitioner) + """ + + def __init__( + self, min_shard_bytes=256 << 10, max_shards=1, bytes_per_string=16 + ): + """Creates a new `MinSizePartitioner`. + + Args: + min_shard_bytes: Minimum bytes of each shard. Defaults to 256K. + max_shards: Upper bound on the number of shards. Defaults to 1. + bytes_per_string: If the partition value is of type string, this provides + an estimate of how large each string is. + """ + if min_shard_bytes < 1: + raise ValueError( + 'Argument `min_shard_bytes` must be positive. ' + f'Received: {min_shard_bytes}' + ) + if max_shards < 1: + raise ValueError( + f'Argument `max_shards` must be positive. Received: {max_shards}' + ) + if bytes_per_string < 1: + raise ValueError( + 'Argument `bytes_per_string` must be positive. ' + f'Received: {bytes_per_string}' + ) + self._min_shard_bytes = min_shard_bytes + self._max_shards = max_shards + self._bytes_per_string = bytes_per_string + + def __call__(self, shape, dtype, axis=0): + return partitioned_variables.min_max_variable_partitioner( + max_partitions=self._max_shards, + axis=axis, + min_slice_size=self._min_shard_bytes, + bytes_per_string_element=self._bytes_per_string, + )(shape, dtype) + + +@tf_export('distribute.experimental.partitioners.MaxSizePartitioner', v1=[]) +class MaxSizePartitioner(Partitioner): + """Partitioner that keeps shards below `max_shard_bytes`. + + This partitioner ensures each shard has at most `max_shard_bytes`, and tries + to allocate as few shards as possible, i.e., keeping shard size as large + as possible. + + If the partitioner hits the `max_shards` limit, then each shard may end up + larger than `max_shard_bytes`. By default `max_shards` equals `None` and no + limit on the number of shards is enforced. + + Examples: + + >>> partitioner = MaxSizePartitioner(max_shard_bytes=4) + >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32) + >>> [6, 1] + >>> partitioner = MaxSizePartitioner(max_shard_bytes=4, max_shards=2) + >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32) + >>> [2, 1] + >>> partitioner = MaxSizePartitioner(max_shard_bytes=1024) + >>> partitions = partitioner(tf.TensorShape([6, 1]), tf.float32) + >>> [1, 1] + >>> + >>> # use in ParameterServerStrategy + >>> # strategy = tf.distribute.experimental.ParameterServerStrategy( + >>> # cluster_resolver=cluster_resolver, variable_partitioner=partitioner) + """ + + def __init__(self, max_shard_bytes, max_shards=None, bytes_per_string=16): + """Creates a new `MaxSizePartitioner`. + + Args: + max_shard_bytes: The maximum size any given shard is allowed to be. + max_shards: The maximum number of shards in `int` created taking + precedence over `max_shard_bytes`. + bytes_per_string: If the partition value is of type string, this provides + an estimate of how large each string is. + """ + if max_shard_bytes < 1: + raise ValueError( + 'Argument `max_shard_bytes` must be positive. ' + f'Received {max_shard_bytes}' + ) + if max_shards and max_shards < 1: + raise ValueError( + f'Argument `max_shards` must be positive. Received {max_shards}' + ) + if bytes_per_string < 1: + raise ValueError( + 'Argument `bytes_per_string` must be positive. ' + f'Received: {bytes_per_string}' + ) + + self._max_shard_bytes = max_shard_bytes + self._max_shards = max_shards + self._bytes_per_string = bytes_per_string + + def __call__(self, shape, dtype, axis=0): + return partitioned_variables.variable_axis_size_partitioner( + max_shard_bytes=self._max_shard_bytes, + max_shards=self._max_shards, + bytes_per_string_element=self._bytes_per_string, + axis=axis, + )(shape, dtype) + + +class ShardedVariableSpec(type_spec.TypeSpec): + """Type specification for a `ShardedVariable`.""" + + __slots__ = ['_variable_specs'] + + value_type = property(lambda self: ShardedVariable) + + def __init__(self, *variable_specs): + self._variable_specs = tuple(variable_specs) + + def _serialize(self): + return self._variable_specs + + @property + def _component_specs(self): + return self._variable_specs + + def _to_components(self, value): + return tuple(value.variables) + + def _from_components(self, variables): + return ShardedVariable(variables) + + def _cast(self, value, _): + return value + + +class ShardedVariableMixin(trackable.Trackable): + """Mixin for ShardedVariable.""" + + # TODO(b/170877138): Remove this mixin once fixed. This mixin is required + # since TPUEmbeddingVariable can't be a CompositeTensor. + + def __init__(self, variables, name='ShardedVariable'): + """Treats `variables` as shards of a larger Variable. + + Example: + + ``` + variables = [ + tf.Variable(..., shape=(10, 100), dtype=tf.float32), + tf.Variable(..., shape=(15, 100), dtype=tf.float32), + tf.Variable(..., shape=(5, 100), dtype=tf.float32) + ] + sharded_variable = ShardedVariableMixin(variables) + assert sharded_variable.shape.as_list() == [30, 100] + ``` + + Args: + variables: A list of `ResourceVariable`s that comprise this sharded + variable. Variables should not be shared between different + `ShardedVariableMixin` objects. + name: String. Name of this container. Defaults to "ShardedVariable". + """ + super(ShardedVariableMixin, self).__init__() + self._variables = variables + self._name = name + + if ( + not isinstance(variables, Sequence) + or not variables + or any(not isinstance(v, variables_lib.Variable) for v in variables) + ): + raise TypeError( + 'Argument `variables` should be a non-empty list of ' + f'`variables.Variable`s. Received {variables}' + ) + + var_dtypes = {v.dtype for v in variables} + if len(var_dtypes) > 1: + raise ValueError( + 'All elements in argument `variables` must have the same dtype. ' + f'Received dtypes: {[v.dtype for v in variables]}' + ) + + first_var = variables[0] + self._dtype = first_var.dtype + + # All variables must have the same shape for axes > 0. + higher_dim_shapes = {tuple(v.shape.as_list()[1:]) for v in variables} + if len(higher_dim_shapes) > 1: + raise ValueError( + 'All elements in argument `variables` must have the same shapes ' + 'except for the first axis. ' + f'Received shapes: {[v.shape for v in variables]}' + ) + first_dim = sum(int(v.shape.as_list()[0]) for v in variables) + self._shape = tensor_shape.TensorShape( + [first_dim] + first_var.shape.as_list()[1:] + ) + + for v in variables: + v._sharded_container = weakref.ref(self) + + self._var_offsets = [ + [0 for _ in range(len(first_var.shape))] for _ in range(len(variables)) + ] + for i in range(1, len(variables)): + # Always partition on the first axis. Offsets on other axes are 0. + self._var_offsets[i][0] += ( + self._var_offsets[i - 1][0] + variables[i - 1].shape.as_list()[0] + ) + + save_slice_info = [v._get_save_slice_info() for v in variables] # pylint: disable=protected-access + if any(slice_info is not None for slice_info in save_slice_info): + raise ValueError( + '`SaveSliceInfo` should not be set for all elements in argument ' + '`variables`. `ShardedVariable` will infer `SaveSliceInfo` according ' + 'to the order of the elements `variables`. ' + f'Received save slice info {save_slice_info}' + ) + + # We create an uninitialized saving_variable with the full shape, which can + # be later captured in signatures so that the signatures can treat this + # ShardedVariable as one single variable. + self._saving_variable = resource_variable_ops.UninitializedVariable( + shape=self._shape, + dtype=self._dtype, + name=self._name, + trainable=self._variables[0].trainable, + synchronization=variables_lib.VariableSynchronization.NONE, + aggregation=variables_lib.VariableAggregation.NONE, + ) + + def __iter__(self): + """Return an iterable for accessing the underlying sharded variables.""" + return iter(self._variables) + + def __getitem__(self, slice_spec): + """Extracts the specified region as a Tensor from the sharded variable. + + The API contract is identical to `Tensor.__getitem__`. Assignment to the + sliced range is not yet supported. + + Args: + slice_spec: The arguments to __getitem__, specifying the global slicing of + the sharded variable. + + Returns: + The appropriate slice of tensor based on `slice_spec`. + + Raises: + IndexError: If a slice index is out of bound. + TypeError: If `spec_spec` contains Tensor. + """ + + # TODO(b/177482728): Support tensor input. + # TODO(b/177482728): Support slice assign, similar to variable slice assign. + + if ( + isinstance(slice_spec, bool) + or ( + isinstance(slice_spec, tensor_lib.Tensor) + and slice_spec.dtype == dtypes.bool + ) + or (isinstance(slice_spec, np.ndarray) and slice_spec.dtype == bool) + ): + tensor = _var_to_tensor(self) + return array_ops.boolean_mask(tensor=tensor, mask=slice_spec) + + if not isinstance(slice_spec, (list, tuple)): + slice_spec = (slice_spec,) + + s = slice_spec[0] + if isinstance(s, slice): + first_dim_slice_specs = self._decompose_slice_spec(s) + values = [] + for i, var in enumerate(self._variables): + if first_dim_slice_specs[i] is not None: + all_dim_slice_spec = (first_dim_slice_specs[i],) + slice_spec[1:] + values.append(var[all_dim_slice_spec]) + if s.step is not None and s.step < 0: + values.reverse() + if not values: + return constant_op.constant( + [], dtype=self._dtype, shape=((0,) + self._shape[1:]) + ) + return array_ops.concat(values, axis=0) + elif s is Ellipsis: + return array_ops.concat( + [var[slice_spec] for var in self._variables], axis=0 + ) + elif s is array_ops.newaxis: + return array_ops.concat( + [var[slice_spec[1:]] for var in self._variables], axis=0 + )[array_ops.newaxis] + else: + if isinstance(s, tensor_lib.Tensor): + raise TypeError( + 'ShardedVariable: using Tensor for indexing is not allowed.' + ) + if s < 0: + s += self._shape[0] + if s < 0 or s >= self._shape[0]: + raise IndexError( + f'ShardedVariable: slice index {s} of dimension 0 out of bounds.' + ) + for i in range(len(self._variables)): + if i == len(self._variables) - 1 or ( + s > self._var_offsets[i][0] and s < self._var_offsets[i + 1][0] + ): + return self._variables[i][ + (s - self._var_offsets[i][0],) + slice_spec[1:] + ] + + def _decompose_slice_spec(self, slice_spec): + """Decompose a global slice_spec into a list of per-variable slice_spec. + + `ShardedVariable` only supports first dimension partitioning, thus + `slice_spec` must be for first dimension. + + Args: + slice_spec: A python `slice` object that specifies the global slicing. + + Returns: + A list of python `slice` objects or None specifying the local slicing for + each component variable. None means no slicing. + + For example, given component variables: + v0 = [0, 1, 2] + v1 = [3, 4, 5] + v2 = [6, 7, 8, 9] + + If `slice_spec` is slice(start=None, stop=None, step=None), we will have: + v0[returned[0]] = [0, 1, 2] + v1[returned[1]] = [3, 4, 5] + v2[returned[2]] = [6, 7, 8, 9] + If `slice_spec` is slice(start=2, stop=8, step=3), we will have: + v0[returned[0]] = [2] + v1[returned[1]] = [5] + returned[2] == None + If `slice_spec` is slice(start=9, stop=3, step=-2), we will have: + returned[0] == None + v1[returned[1]] = [5] + v2[returned[2]] = [9, 7] + """ + if ( + isinstance(slice_spec.start, tensor_lib.Tensor) + or isinstance(slice_spec.stop, tensor_lib.Tensor) + or isinstance(slice_spec.step, tensor_lib.Tensor) + ): + raise TypeError( + 'ShardedVariable: using Tensor in slice_spec is not allowed. Please ' + 'file a feature request with the TensorFlow team.' + ) + + result = [] + # Normalize start, end and stop. + slice_step = slice_spec.step if slice_spec.step is not None else 1 + if slice_step == 0: + raise ValueError('slice step cannot be zero') + slice_start = slice_spec.start + if slice_start is None: + slice_start = 0 if slice_step > 0 else self._shape[0] - 1 + elif slice_start < 0: + slice_start += self._shape[0] + slice_end = slice_spec.stop + if slice_end is None: + # After the normalization, we no longer interpret negative index, thus + # "-1" conceptually refers to the element before the first one, which + # doesn't exist. This is to ease the decomposition code. + slice_end = self._shape[0] if slice_step > 0 else -1 + elif slice_end < 0: + slice_end += self._shape[0] + + # To find the local slice_spec of each component variable, we start from + # the start of the global slice, and iterate through each variable. + # When iterating on a variable, we move the cursor (`cur`) to the first + # index that falls into the variable's range, which becomes the start of + # the variable's local slice_spec. The end of the local_spec is determined + # by using whatever is smaller between global slice end and variable range + # end. + cur = slice_start + if slice_step > 0: + for i in range(len(self._var_offsets)): + var_start = self._var_offsets[i][0] + var_end = ( + self._var_offsets[i + 1][0] + if i < len(self._var_offsets) - 1 + else self._shape[0] + ) + if cur < var_start: + cur += slice_step * int(math.ceil((var_start - cur) / slice_step)) + if cur >= var_end or cur >= slice_end: + result.append(None) + else: + start = cur - var_start + end = min(slice_end, var_end) - var_start + result.append(slice(start, end, slice_step)) + else: # slice_step < 0 + for i in range(len(self._var_offsets) - 1, -1, -1): + var_start = self._var_offsets[i][0] + var_end = ( + self._var_offsets[i + 1][0] + if i < len(self._var_offsets) - 1 + else self._shape[0] + ) + if cur >= var_end: + cur += slice_step * int(math.ceil((var_end - cur - 1) / slice_step)) + if cur < var_start or cur <= slice_end: + result.append(None) + else: + start = cur - var_start + if slice_end >= var_start: + end = slice_end - var_start + else: + end = None # no explicit end: slice until hitting the boundary. + result.append(slice(start, end, slice_step)) + + result.reverse() + + return result + + @property + def _type_spec(self): + return ShardedVariableSpec( + *( + resource_variable_ops.VariableSpec(v.shape, v.dtype) + for v in self._variables + ) + ) + + @property + def variables(self): + """The list of `Variable`s that make up the shards of this object.""" + if save_context.in_save_context(): + return [self._saving_variable] + return self._variables + + @property + def name(self): + """The name of this object. Used for checkpointing.""" + return self._name + + @property + def dtype(self): + """The dtype of all `Variable`s in this object.""" + return self._dtype + + @property + def shape(self): + """The overall shape, combining all shards along axis `0`.""" + return self._shape + + def assign(self, value, use_locking=None, name=None, read_value=True): + for i, v in enumerate(self._variables): + v.assign(array_ops.slice(value, self._var_offsets[i], v.shape.as_list())) + return self + + def assign_add(self, delta, use_locking=False, name=None, read_value=True): + for i, v in enumerate(self._variables): + v.assign_add( + array_ops.slice(delta, self._var_offsets[i], v.shape.as_list()) + ) + return self + + def assign_sub(self, delta, use_locking=False, name=None, read_value=True): + for i, v in enumerate(self._variables): + v.assign_sub( + array_ops.slice(delta, self._var_offsets[i], v.shape.as_list()) + ) + return self + + def _decompose_indices(self, indices): + """Decompose a global 1D indices into a list of per-variable indices.""" + if indices.shape.rank != 1: + raise ValueError( + 'ShardedVariable: indices must be 1D Tensor for sparse operations. ' + f'Received shape: {indices.shape}' + ) + + base = self._shape[0] // len(self._variables) + extra = self._shape[0] % len(self._variables) + + # Assert that sharding conforms to "div" sharding + expect_first_dim = [base] * len(self._variables) + for i in range(extra): + expect_first_dim[i] = expect_first_dim[i] + 1 + actual_first_dim = [v.shape.as_list()[0] for v in self._variables] + if expect_first_dim != actual_first_dim: + raise NotImplementedError( + 'scater_xxx ops are not supported in ShardedVariale that does not ' + 'conform to "div" sharding' + ) + + # For index that falls into the partition that has extra 1, assignment is + # `index // (base + 1)` (no less than `(indices - extra) // base`) + # For index that falls into the partition that doesn't has extra 1, + # assignment is `(indices - extra) // base` (no less than + # `indices // (base + 1)`) + # + # Example: + # base = 10, extra = 2, partitions: [0, 11), [11, 22), [22, 32) + # index = 10 -> partition_assigment = 0 + # index = 22 -> partition_assiment = 2 + partition_assignments = math_ops.maximum( + indices // (base + 1), (indices - extra) // base + ) + local_indices = array_ops.where( + partition_assignments < extra, + indices % (base + 1), + (indices - extra) % base, + ) + # For whatever reason `dynamic_partition` only supports int32 + partition_assignments = math_ops.cast(partition_assignments, dtypes.int32) + per_var_indices = data_flow_ops.dynamic_partition( + local_indices, partition_assignments, len(self._variables) + ) + + return per_var_indices, partition_assignments + + def _decompose_indexed_slices(self, indexed_slices): + """Decompose a global `IndexedSlices` into a list of per-variable ones.""" + per_var_indices, partition_assignments = self._decompose_indices( + indexed_slices.indices + ) + per_var_values = data_flow_ops.dynamic_partition( + indexed_slices.values, partition_assignments, len(self._variables) + ) + + return [ + indexed_slices_lib.IndexedSlices( + values=per_var_values[i], indices=per_var_indices[i] + ) + for i in range(len(self._variables)) + ] + + # ==================== scatter ops implementations ======================== # + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_add.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_add(per_var_sparse_delta[i], name=new_name) + return self + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_div.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_div(per_var_sparse_delta[i], name=new_name) + return self + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_max.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_max(per_var_sparse_delta[i], name=new_name) + return self + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_min.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_min(per_var_sparse_delta[i], name=new_name) + return self + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_mul.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_mul(per_var_sparse_delta[i], name=new_name) + return self + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_sub.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_sub(per_var_sparse_delta[i], name=new_name) + return self + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.scatter_update.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.scatter_update(per_var_sparse_delta[i], name=new_name) + return self + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + """Implements tf.Variable.batch_scatter_update.""" + per_var_sparse_delta = self._decompose_indexed_slices(sparse_delta) + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + v.batch_scatter_update(per_var_sparse_delta[i], name=new_name) + return self + + # ================== scatter ops implementations END ====================== # + + def sparse_read(self, indices, name=None): + """Implements tf.Variable.sparse_read.""" + per_var_indices, _ = self._decompose_indices(indices) + result = [] + for i, v in enumerate(self._variables): + new_name = None + if name is not None: + new_name = '{}/part_{}'.format(name, i) + result.append(v.sparse_read(per_var_indices[i], name=new_name)) + return array_ops.concat(result, axis=0) + + def _gather_saveables_for_checkpoint(self): + """Return a `Saveable` for each shard. See `Trackable`.""" + + def _saveable_factory(name=self.name): + """Creates `SaveableObject`s for this `ShardedVariable`.""" + saveables = [] + dims = len(self._variables[0].shape) + var_offset = [0 for _ in range(dims)] + for v in self._variables: + save_slice_info = variables_lib.Variable.SaveSliceInfo( + full_name=self.name, + full_shape=self.shape.as_list(), + var_offset=copy.copy(var_offset), + var_shape=v.shape.as_list(), + ) + saveables.append( + saveable_object_util.ResourceVariableSaveable( + v, save_slice_info.spec, name + ) + ) + var_offset[0] += int(v.shape[0]) + return saveables + + return {trackable.VARIABLE_VALUE_KEY: _saveable_factory} + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable` async checkpointing.""" + # This is not implemented in the ShardedVariableMixin class because multiple + # classes inherit from it. If your class contains values that should be + # copied to CPU for async checkpointing, please implement this in the class + # definition. + + def _export_to_saved_model_graph( + self, object_map, tensor_map, options, **kwargs + ): + """For implementing `Trackable` SavedModel export.""" + resource_list = [] + for v in self._variables + [self._saving_variable]: + resource_list.extend( + v._export_to_saved_model_graph( # pylint:disable=protected-access + object_map, tensor_map, options, **kwargs + ) + ) + object_map[self] = ShardedVariable( + [object_map[self._saving_variable]], name=self.name + ) + return resource_list + + @property + def _unique_id(self): + # String-replace to ensure uniqueness for checkpoint tracking + return self.variables[0]._unique_id.replace('part_0', 'sharded') # pylint: disable=protected-access + + @property + def _distribute_strategy(self): + return self.variables[0]._distribute_strategy # pylint: disable=protected-access + + @property + def _shared_name(self): + return self._name + + @property + def is_sharded_variable(self): + return True + + def numpy(self): + """Copies the values in this ShardedVariable to a NumPy array. + + First converts to a single Tensor using the registered conversion function, + which concatenates the shards, then uses Tensor.numpy() to convert to + a NumPy array. + + Returns: + A NumPy array of the same shape and dtype. + """ + return _var_to_tensor(self).numpy() + + +@tf_export('__internal__.distribute.ShardedVariable', v1=[]) +class ShardedVariable(ShardedVariableMixin, composite_tensor.CompositeTensor): + """A container for `Variables` that should be treated as shards. + + Variables that are too large to fit on a single device (e.g., large + embeddings) + may need to be sharded over multiple devices. This class maintains a list of + smaller variables that can be independently stored on separate devices (eg, + multiple parameter servers), and saves and restores those variables as if they + were a single larger variable. + + Objects of this class can be saved with a given number of shards and then + restored from a checkpoint into a different number of shards. + + Objects of this class can be saved to SavedModel format using + `tf.saved_model.save`. The SavedModel can be used by programs like TF serving + APIs. It is not yet supported to load the SavedModel with + `tf.saved_model.load`. + + Since `ShardedVariable` can be saved and then restored to different number of + shards depending on the restore environments, for example, TF serving APIs + would restore to one shard for serving efficiency, when using + `ShardedVariable` in a tf.function, one should generally not assume it has the + same number of shards across save and load. + + Sharding is only supported along the first dimension. + + >>> class Model(tf.Module): + ... def __init__(self): + ... self.sharded_variable = ShardedVariable([ + ... tf.Variable([3.0], dtype=tf.float32), + ... tf.Variable([2.0], dtype=tf.float32) + ... ]) + ... + ... @tf.function(input_signature=[tf.TensorSpec([], dtype=tf.int32)]) + ... def fn(self, x): + ... return tf.nn.embedding_lookup(self.sharded_variable.variables, x) + ... + ... @tf.function(input_signature=[tf.TensorSpec([], dtype=tf.int32)]) + ... def serve_fn(self, x): + ... return tf.nn.embedding_lookup(self.sharded_variable.variables, x) + >>> + >>> model = Model() + >>> model.fn(1).numpy() + 2.0 + >>> tf.saved_model.save(model, export_dir='/tmp/saved_model', + ... signatures=model.serve_fn) + """ + + @property + def _type_spec(self): + return ShardedVariableSpec( + *(resource_variable_ops.VariableSpec(v.shape, v.dtype) + for v in self._variables)) + + @classmethod + def _overload_all_operators(cls): + """Register overloads for all operators.""" + for operator in tensor_lib.Tensor.OVERLOADABLE_OPERATORS: + if operator == '__getitem__': + continue + + cls._overload_operator(operator) + + @classmethod + def _overload_operator(cls, operator): + """Delegate an operator overload to `tensor_lib.Tensor`.""" + tensor_operator = getattr(tensor_lib.Tensor, operator) + + def _operator(v, *args, **kwargs): + return tensor_operator(_var_to_tensor(v), *args, **kwargs) + + setattr(cls, operator, _operator) + + def __tf_experimental_restore_capture__( + self, concrete_function, internal_capture + ): + # Avoid restoring captures for functions that use ShardedVariable - the + # layer will be recreated during Keras model loading + # TODO(jmullenbach): support loading models with ShardedVariables using + # tf.saved_model.load + return None + + def _should_act_as_resource_variable(self): + """Pass resource_variable_ops.is_resource_variable check.""" + return True + + def _write_object_proto(self, proto, options): + resource_variable_ops.write_object_proto_for_resource_variable( + self._saving_variable, proto, options, enforce_naming=False + ) + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable` async checkpointing.""" + if self in object_map: + # If populated already, simply loop through sub-variables to copy values. + for v in self._variables: + v._copy_trackable_to_cpu(object_map) # pylint: disable=protected-access + else: + # If not populated, populate first, then copy. + copied_vars = [] + for v in self._variables: + # This step will both instantiate `v`'s CPU copy and copy its value. + v._copy_trackable_to_cpu(object_map) # pylint: disable=protected-access + copied_vars.append(object_map[v]) + new_var = ShardedVariable(copied_vars, name=self.name) + object_map[self] = new_var + + +def _var_to_tensor(var, dtype=None, name=None, as_ref=False): + """Converts a `ShardedVariable` to a `Tensor`.""" + del name + if dtype is not None and not dtype.is_compatible_with(var.dtype): + raise ValueError( + 'Incompatible type conversion requested to type {!r} for variable ' + 'of type {!r}'.format(dtype.name, var.dtype.name) + ) + if as_ref: + raise NotImplementedError( + "ShardedVariable doesn't support being used as a reference." + ) + # We use op dispatch mechanism to override embedding_lookup ops when called + # with ShardedVariable. This requires embedding_lookup ops to raise TypeError + # when called with ShardedVariable. However since ShardedVariable can be + # converted to a tensor via concat, embedding_lookup ops would silently + # do the convertion and never raise a TypeError. To be able to properly + # raise a TypeError, namescope is used to detect if this method is called + # within a embedding_lookup op. + # NOTE: This doesn't work in eager mode since op namescope is always cleared + # in eager. This also breaks if user sets the name of embedding_lookup op + # with something that doesn't contain str "embedding_lookup". + # + # TODO(chenkai): Find a more robust way to do this, which should not rely + # on namescope. + if 'embedding_lookup' in ops.get_name_scope(): + raise TypeError( + 'Converting ShardedVariable to tensor in embedding lookup' + ' ops is disallowed.' + ) + return array_ops.concat(var.variables, axis=0) + + +# Register a conversion function which reads the value of the variable, +# allowing instances of the class to be used as tensors. +tensor_conversion_registry.register_tensor_conversion_function( + ShardedVariable, _var_to_tensor +) + +ShardedVariable._overload_all_operators() # pylint: disable=protected-access + + +# Override the behavior of embedding_lookup(sharded_variable, ...) +@dispatch.dispatch_for_types(embedding_ops.embedding_lookup, ShardedVariable) +def embedding_lookup( + params, + ids, + partition_strategy='mod', + name=None, + validate_indices=True, + max_norm=None, +): + if isinstance(params, list): + params = params[0] + return embedding_ops.embedding_lookup( + params.variables, + ids, + partition_strategy, + name, + validate_indices, + max_norm, + ) + + +# Separately override safe_embedding_lookup_sparse, to avoid conversion of +# ShardedVariable to tensor. +@dispatch.dispatch_for_api(embedding_ops.safe_embedding_lookup_sparse) +def safe_embedding_lookup_sparse( + embedding_weights: ShardedVariable, + sparse_ids, + sparse_weights=None, + combiner='mean', + default_id=None, + name=None, + partition_strategy='div', + max_norm=None, + allow_fast_lookup=False, +): + """Pass the individual shard variables as a list.""" + return embedding_ops.safe_embedding_lookup_sparse( + embedding_weights.variables, + sparse_ids, + sparse_weights=sparse_weights, + combiner=combiner, + default_id=default_id, + name=name, + partition_strategy=partition_strategy, + max_norm=max_norm, + allow_fast_lookup=allow_fast_lookup, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/shared_variable_creator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/shared_variable_creator.py new file mode 100644 index 0000000000000000000000000000000000000000..6f73ba7dc87b78572450e687091f182b6f494aec --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/shared_variable_creator.py @@ -0,0 +1,93 @@ +# 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. +# ============================================================================== +"""Utility to re-use variables created on first device on subsequent devices.""" + +import re + +_VARIABLE_UNIQUIFYING_REGEX = re.compile(r"_\d/") +_VARIABLE_UNIQUIFYING_REGEX_AT_END = re.compile(r"_\d$") + + +def _canonicalize_variable_name(name): + # If no name is specified, uses default name "Variable". + if name is None: + return "Variable" + # Replace all instances of "_/" with "/" + name = _VARIABLE_UNIQUIFYING_REGEX.sub("/", name) + # Replace any instances of "_" at the end of the string with "" + name = _VARIABLE_UNIQUIFYING_REGEX_AT_END.sub("", name) + return name + + +def make_fn(shared_variable_store, device_id): + """Construct the variable creator function for device `device_id`. + + Constructs custom variable creator functions for the given device. + On first device (device_id == 0), it creates the variable using the + `next_creator`, and stores it in the provided `shared_variable_store`. + On all other devices (device_id > 0), it tries to re-use the variable + already created with the same name. If no such variable exists, it throws an + error. + Additionally, we de-uniquify variable names before checking for matches. This + helps re-use variables which are intended to be the same but have different + names due to variable uniquification happening upstream. Since this might + mean we may have multiple variables with the same canonical name, we store + them in a list per canonical name and return them in the same order as well. + + Args: + shared_variable_store: A dictionary that we will use to store variables + created on the first device, and re-used by creators for other devices. + device_id: Integer index of the device whose creator should be + constructed. + + Returns: + An appropriate creator function based on device_id. + + """ + variable_scope_access_index = {} + assert isinstance(device_id, int) + + def create_new_variable(next_creator, **kwargs): + """Create the variable using `next_creator` and store it.""" + canonical_name = _canonicalize_variable_name(kwargs.get("name")) + v = next_creator(**kwargs) + + if canonical_name not in shared_variable_store: + shared_variable_store[canonical_name] = [] + shared_variable_store[canonical_name].append(v) + return v + + def reuse_variable(next_creator, **kwargs): + """Re-use existing variable from store with same name (in order).""" + del next_creator + name = kwargs.get("name") + canonical_name = _canonicalize_variable_name(name) + + try: + variable_index = variable_scope_access_index.get(canonical_name, 0) + v = shared_variable_store[canonical_name][variable_index] + # TODO(priyag): Make this variable re-use more robust by adding checks + # that the requested shape and dtype match the existing variable. + variable_scope_access_index[canonical_name] = variable_index + 1 + return v + except (KeyError, IndexError): + raise RuntimeError( + "Tried to create variable {} with mismatching name on device {}". + format(name, device_id)) + + if device_id == 0: + return create_new_variable + else: + return reuse_variable diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/single_loss_example.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/single_loss_example.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa7bf65b9aa9f093d17226fe448aeccd1f909a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/single_loss_example.py @@ -0,0 +1,117 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A simple network to use in tests and examples.""" + +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.distribute import step_fn +from tensorflow.python.distribute import strategy_test_lib +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.layers import core +from tensorflow.python.layers import normalization +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops + + +def single_loss_example(optimizer_fn, distribution, use_bias=False, + iterations_per_step=1): + """Build a very simple network to use in tests and examples.""" + + def dataset_fn(): + return dataset_ops.Dataset.from_tensors([[1.]]).repeat() + + optimizer = optimizer_fn() + layer = core.Dense(1, use_bias=use_bias) + + def loss_fn(ctx, x): + del ctx + y = array_ops.reshape(layer(x), []) - constant_op.constant(1.) + return y * y + + single_loss_step = step_fn.StandardSingleLossStep( + dataset_fn, loss_fn, optimizer, distribution, iterations_per_step) + + # Layer is returned for inspecting the kernels in tests. + return single_loss_step, layer + + +def minimize_loss_example(optimizer, use_bias=False, use_callable_loss=True): + """Example of non-distribution-aware legacy code.""" + + def dataset_fn(): + dataset = dataset_ops.Dataset.from_tensors([[1.]]).repeat() + # TODO(isaprykin): batch with drop_remainder causes shapes to be + # fully defined for TPU. Remove this when XLA supports dynamic shapes. + return dataset.batch(1, drop_remainder=True) + + layer = core.Dense(1, use_bias=use_bias) + + def model_fn(x): + """A very simple model written by the user.""" + + def loss_fn(): + y = array_ops.reshape(layer(x), []) - constant_op.constant(1.) + return y * y + + if strategy_test_lib.is_optimizer_v2_instance(optimizer): + return optimizer.minimize(loss_fn, lambda: layer.trainable_variables) + elif use_callable_loss: + return optimizer.minimize(loss_fn) + else: + return optimizer.minimize(loss_fn()) + + return model_fn, dataset_fn, layer + + +def batchnorm_example(optimizer_fn, + batch_per_epoch=1, + momentum=0.9, + renorm=False, + update_ops_in_replica_mode=False): + """Example of non-distribution-aware legacy code with batch normalization.""" + + def dataset_fn(): + # input shape is [16, 8], input values are increasing in both dimensions. + return dataset_ops.Dataset.from_tensor_slices( + [[[float(x * 8 + y + z * 100) + for y in range(8)] + for x in range(16)] + for z in range(batch_per_epoch)]).repeat() + + optimizer = optimizer_fn() + batchnorm = normalization.BatchNormalization( + renorm=renorm, momentum=momentum, fused=False) + layer = core.Dense(1, use_bias=False) + + def model_fn(x): + """A model that uses batchnorm.""" + + def loss_fn(): + y = batchnorm(x, training=True) + with ops.control_dependencies( + ops.get_collection(ops.GraphKeys.UPDATE_OPS) + if update_ops_in_replica_mode else []): + loss = math_ops.reduce_mean( + math_ops.reduce_sum(layer(y)) - constant_op.constant(1.)) + # `x` and `y` will be fetched by the gradient computation, but not `loss`. + return loss + + if strategy_test_lib.is_optimizer_v2_instance(optimizer): + return optimizer.minimize(loss_fn, lambda: layer.trainable_variables) + + # Callable loss. + return optimizer.minimize(loss_fn) + + return model_fn, dataset_fn, batchnorm diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/step_fn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/step_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..9d0bf67081e95f2ec9a4454e399b30b8a54173d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/step_fn.py @@ -0,0 +1,110 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""The step function abstraction represents a single training step.""" + +from tensorflow.python.eager import backprop +from tensorflow.python.training import optimizer as optimizer_lib + + +class Step(object): + """Interface for performing each step of a training algorithm.""" + + def __init__(self, distribution): + self._distribution = distribution + + @property + def distribution(self): + return self._distribution + + def initialize(self): + return [] + + def __call__(self): + """Perform one step of this training algorithm.""" + raise NotImplementedError("must be implemented in descendants") + + # TODO(priyag): Add an method to access initialization and finalize ops. + + +class StandardInputStep(Step): + """Step with a standard implementation of input handling. + + Args: + dataset_fn: a function that returns a tf.data Dataset that produces the + input for the model. + """ + + def __init__(self, dataset_fn, distribution): + super(StandardInputStep, self).__init__(distribution) + self._iterator = distribution.make_input_fn_iterator(lambda _: dataset_fn()) + + def initialize(self): + return self._iterator.initializer + + +class StandardSingleLossStep(StandardInputStep): + """A step function that implements a training step for a feed forward network. + + An instance of this class is intended to be used as a callable: + + ```python + ... + step = step_fn.StandardSingleLossStep( + dataset, loss_fn, optimizer, distribution) + + # Run a single training step on a given DistributionStrategy: + step(distribution) + ... + ``` + + Args: + dataset_fn: a function that returns a tf.data Dataset that produces the + input for the model. + loss_fn: a function that takes a context and inputs as arguments. It returns + the loss for those inputs. `context` is an instance of + `values.MultiStepContext` that will be passed when `loss_fn` is run. + `context` can be used to specify the outputs to be returned from + `loss_fn`, among other things. + optimizer: an optimizer that implements an update rule. + distribution: a `DistributionStrategy` object. + """ + + def __init__(self, dataset_fn, loss_fn, optimizer, distribution, + iterations_per_step=1): + super(StandardSingleLossStep, self).__init__(dataset_fn, distribution) + self._loss_fn = loss_fn + self._optimizer = optimizer + self._iterations_per_step = iterations_per_step + + def __call__(self): + with self._distribution.scope(): + def step_fn(ctx, inputs): + """Function to run one iteration with one input.""" + gradients_fn = backprop.implicit_grad(self._loss_fn) + gradients_fn = optimizer_lib.get_filtered_grad_fn(gradients_fn) + + grads_and_vars = self.distribution.extended.call_for_each_replica( + gradients_fn, args=(ctx, inputs)) + # If threads use layers, then we need to run the first step + # sequentially, so that layers.build() is not executed in parallel. + # Otherwise, multiple sets of mirrored variables are going to be + # created. + return self._optimizer._distributed_apply( # pylint: disable=protected-access + self.distribution, grads_and_vars) + + # TODO(priyag): Return the outputs, context, etc as well. + ctx = self.distribution.extended.experimental_run_steps_on_iterator( + step_fn, self._iterator, self._iterations_per_step) + return ctx.run_op diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/strategy_combinations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/strategy_combinations.py new file mode 100644 index 0000000000000000000000000000000000000000..98cfdc44efeb221b2a3f6e888872184100af7296 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/strategy_combinations.py @@ -0,0 +1,756 @@ +# 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. +# ============================================================================== +"""Strategy combinations for combinations.combine().""" + +import sys +import unittest +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python import tf2 +from tensorflow.python.distribute import central_storage_strategy +from tensorflow.python.distribute import cluster_resolver +from tensorflow.python.distribute import collective_all_reduce_strategy +from tensorflow.python.distribute import combinations +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import mirrored_strategy as mirrored_lib +from tensorflow.python.distribute import multi_process_runner +from tensorflow.python.distribute import multi_worker_test_base +from tensorflow.python.distribute import one_device_strategy as one_device_lib +from tensorflow.python.distribute import parameter_server_strategy_v2 +from tensorflow.python.distribute import sharded_variable +from tensorflow.python.distribute import test_util +from tensorflow.python.distribute import tpu_strategy as tpu_lib +from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver +from tensorflow.python.eager import context +from tensorflow.python.eager import remote +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import errors +from tensorflow.python.framework import test_util as framework_test_util +from tensorflow.python.platform import flags +from tensorflow.python.tpu import device_assignment as device_assignment_lib +from tensorflow.python.training import server_lib +from tensorflow.python.util.tf_export import tf_export + +_did_connect_to_cluster = False +_topology = None +CollectiveAllReduceExtended = ( + collective_all_reduce_strategy.CollectiveAllReduceExtended +) + + +def _version_chooser(tf1_cls, tf2_cls): + def creator(*args, **kwargs): + if tf2.enabled(): + return tf2_cls(*args, **kwargs) + return tf1_cls(*args, **kwargs) + + return creator + + +MirroredStrategy = _version_chooser( + mirrored_lib.MirroredStrategyV1, mirrored_lib.MirroredStrategy +) +CentralStorageStrategy = _version_chooser( + central_storage_strategy.CentralStorageStrategyV1, + central_storage_strategy.CentralStorageStrategy, +) +OneDeviceStrategy = _version_chooser( + one_device_lib.OneDeviceStrategyV1, one_device_lib.OneDeviceStrategy +) +# Only V2 CollectiveAllReduceStrategy combinations are supported. +CollectiveAllReduceStrategy = ( + collective_all_reduce_strategy.CollectiveAllReduceStrategy +) + + +# pylint: disable=missing-docstring +def _get_tpu_strategy_creator( + steps_per_run, + use_single_core=False, + enable_packed_variable=False, + enable_spmd_xla_paritioning=False, + **kwargs +): + def _create_tpu_strategy(): + FLAGS = flags.FLAGS # pylint: disable=invalid-name + global _did_connect_to_cluster + global _topology + + try: + # Attempt to locally discover the TPU. This will fail for Cloud TPU, in + # which case we fall back to the values passed as flags. + resolver = tpu_cluster_resolver.TPUClusterResolver() + did_automatically_resolve = True + except ValueError: + did_automatically_resolve = False + + # These flags will be defined by tpu_test_wrapper.py. + resolver = tpu_cluster_resolver.TPUClusterResolver( + tpu=hasattr(FLAGS, "tpu") and FLAGS.tpu or "", + zone=hasattr(FLAGS, "zone") and FLAGS.zone or None, + project=hasattr(FLAGS, "project") and FLAGS.project or None, + ) + + # Only connect once per process, rather than per test method. + if not _did_connect_to_cluster: + if getattr(FLAGS, "tpu", "") or did_automatically_resolve: + remote.connect_to_cluster(resolver) + _did_connect_to_cluster = True + _topology = tpu_cluster_resolver.initialize_tpu_system(resolver) + + device_assignment = None + if use_single_core: + device_assignment = device_assignment_lib.DeviceAssignment( + _topology, + core_assignment=device_assignment_lib.SINGLE_CORE_ASSIGNMENT, + ) + + # Steps per run is only supported in TF 1.x + if tf2.enabled(): + strategy = tpu_lib.TPUStrategyV2( + resolver, + device_assignment, + experimental_spmd_xla_partitioning=enable_spmd_xla_paritioning, + **kwargs + ) + else: + strategy = tpu_lib.TPUStrategyV1( + resolver, steps_per_run, device_assignment, **kwargs + ) + if enable_packed_variable and enable_spmd_xla_paritioning: + raise ValueError("Packed Variable is not compatiable with SPMD mode") + strategy._enable_packed_variable_in_eager_mode = ( # pylint: disable=protected-access + enable_packed_variable + ) + return strategy + + return _create_tpu_strategy + + +def _mirrored_strategy_with_collective_key_base(devices): + required_cpus_nums = sum( + 1 + for d in devices + if tf_device.DeviceSpec.from_string(d).device_type == "CPU" + ) + + # If required virtual CPUs are not setup yet, config the logical devices. + if required_cpus_nums > len(context.context().list_logical_devices("CPU")): + context._reset_context() # pylint: disable=protected-access + test_util.set_logical_devices_to_at_least("CPU", required_cpus_nums) + + # Increase collective base key to avoid key collision across subtests. + mirrored_lib.MirroredStrategyV1._collective_key_base += 100000 + mirrored_lib.MirroredStrategy._collective_key_base += 100000 + return MirroredStrategy(devices) + + +def _mirrored_strategy_with_no_merge_call(devices): + mirrored_lib.MirroredStrategyV1._collective_key_base += 100000 + mirrored_lib.MirroredStrategy._collective_key_base += 100000 + out = MirroredStrategy(devices) + # Stub out merge call usage. + out.extended._use_merge_call = lambda: False # pylint: disable=protected-access + return out + + +def _get_multi_worker_mirrored_creator(required_gpus, use_merge_call=True): + def _create_multi_worker_mirrored(): + tf_config = cluster_resolver.TFConfigClusterResolver() + master = tf_config.master() + if tf_config.rpc_layer: + # Strip off the rpc_layer suffix. + master = master[len("%s://" % tf_config.rpc_layer) :] + resolver = cluster_resolver.SimpleClusterResolver( + cluster_spec=tf_config.cluster_spec(), + task_type=tf_config.task_type, + task_id=tf_config.task_id, + master=master, + environment=tf_config.environment, + num_accelerators={"GPU": required_gpus}, + rpc_layer=tf_config.rpc_layer or "grpc", + ) + # Disable health check and coordination service. We don't have a reliable + # way to shutdown the strategy (and thus the strategy health check or + # coordination service heartbeat) at the end of a test. Turning on the + # strategy health check or coordination service heartbeat causes some + # flakiness since we re-create part of the server when creating a strategy, + # and our tests are capable of handling failures. + CollectiveAllReduceExtended._enable_check_health = ( # pylint: disable=protected-access + False + ) + context.context().configure_coordination_service(service_type="") + # Always create the strategy in eager mode so that it starts the server and + # configures the eager context. The eager context can no longer be + # configured after initialization. + with context.eager_mode(): + strategy = CollectiveAllReduceStrategy(cluster_resolver=resolver) + + if not use_merge_call: + strategy.extended._use_merge_call = lambda: False # pylint: disable=protected-access + # TODO(b/152320929): Wait for the cluster before proceeding, otherwise + # collectives may hang if any worker launches collectives before the chief + # creates the strategy. + try: + multi_process_runner.get_barrier().wait() + except ValueError: + # If the creator is called in the main process, + # multi_process_runner.get_barrier() raises ValueError, which is safe to + # ignore. + pass + return strategy + + def skip_if_cannot_start_grpc_server(): + try: + return _create_multi_worker_mirrored() + except errors.UnknownError as e: + if "Could not start gRPC server" in e.message and ( + len(sys.argv) >= 1 and "bazel" in sys.argv[0] + ): + raise unittest.SkipTest("Cannot start std servers.") + else: + raise + + return skip_if_cannot_start_grpc_server + + +# Due to b/195615322, FixedShardsPartitioner will wrongly partition +# RNG state, so we use MinSizePartitioner as the default. Maximum RNG +# state size is int64[3] which is 8 * 3 bytes, so we set +# min_shard_bytes to 8 * 3 + 1. +DEFAULT_PARTITIONER = sharded_variable.MinSizePartitioner( + min_shard_bytes=8 * 3 + 1, max_shards=2 +) + + +def _get_ps_strategy_creator( + num_workers, + num_ps, + required_gpus=0, + variable_partitioner=DEFAULT_PARTITIONER, +): + def _create_ps_strategy(resolver, variable_partitioner): + return parameter_server_strategy_v2.ParameterServerStrategyV2( + resolver, variable_partitioner=variable_partitioner + ) + + def _create_parameter_server(): + if framework_test_util.is_xla_enabled(): + # To address test failures resulting in XLA with MultiProcessRunner, + # continue to use in-process cluster for XLA tests. + cluster_def = multi_worker_test_base.create_in_process_cluster( + num_workers=num_workers, num_ps=num_ps, rpc_layer="grpc" + ) + resolver = cluster_resolver.SimpleClusterResolver( + server_lib.ClusterSpec(cluster_def), + num_accelerators={"GPU": required_gpus}, + rpc_layer="grpc", + ) + return _create_ps_strategy(resolver, variable_partitioner) + else: + tf_config = cluster_resolver.TFConfigClusterResolver() + cluster_def = tf_config.cluster_spec().as_dict() + if not cluster_def: + # When MultiProcessRunner cluster is used, the cluster is not created + # initially when the decorator is called. When the test runs, initially + # this method is invoked via decorator before setting up the + # MultiProcessRunner with worker and ps in the combinations.py. After + # setup is done, the subprocess invokes this method again to get + # strategy object. We return None strategy when the main thread invokes + # this method before setting up cluster. + # Returning None is fine here, since this thread will proceed to create + # MultiProcessRunner and invoke tests with decorator inside + # subprocesses. + return None + # MultiProcessRunner is already setup and this method is invoked from a + # subprocess running the actual test. + resolver = cluster_resolver.SimpleClusterResolver( + server_lib.ClusterSpec(cluster_def), + num_accelerators={"GPU": required_gpus}, + task_type=tf_config.task_type, + task_id=tf_config.task_id, + environment=tf_config.environment, + rpc_layer=tf_config.rpc_layer or "grpc", + ) + if tf_config.task_type in ("worker", "ps"): + worker_config = config_pb2.ConfigProto() + worker_config.inter_op_parallelism_threads = 4 # max num_workers + 1 + + try: + server = server_lib.Server( + cluster_def, + job_name=tf_config.task_type, + task_index=tf_config.task_id, + protocol="grpc", + config=worker_config, + ) + except errors.UnknownError as e: + if "Could not start gRPC server" in e.message: + raise unittest.SkipTest("Cannot start std servers.") + else: + raise + + # Blocking the process that starts a server from exiting. + server.join() + + return _create_ps_strategy(resolver, variable_partitioner) + + return _create_parameter_server + + +def _deferred_pool_runner( + has_chief, num_workers, initializer=None, share_gpu=True +): + """Returns a callable that returns the pool runner. + + It creates the pool runner only upon first invocation. This avoids creating it + when this file is imported. + + Args: + has_chief: whether there should be a chief. + num_workers: the number of workers excluding the chief. + initializer: initializer of each process. + share_gpu: whether to share GPU between the workers. + + Returns: + A callable that returns the runner. + """ + + container = [] + + def get_or_create(): + if not container: + cluster_spec = multi_worker_test_base.create_cluster_spec( + has_chief=has_chief, num_workers=num_workers, num_ps=0, has_eval=False + ) + runner = multi_process_runner.MultiProcessPoolRunner( + cluster_spec, initializer=initializer, share_gpu=share_gpu + ) + container.append(runner) + return container[0] + + return get_or_create + + +# We need to create the strategy in the initializer to start the server before +# any test runs. +_two_worker_pool = _deferred_pool_runner( + has_chief=True, + num_workers=1, + initializer=_get_multi_worker_mirrored_creator(required_gpus=0), +) + +# Two-worker pool where each worker gets it's own GPU. Useful for testing MWMS +# on a single host. +_two_worker_pool_noshare = _deferred_pool_runner( + has_chief=True, + num_workers=1, + initializer=_get_multi_worker_mirrored_creator(required_gpus=0), + share_gpu=False, +) +_four_worker_pool = _deferred_pool_runner( + has_chief=True, + num_workers=3, + initializer=_get_multi_worker_mirrored_creator(required_gpus=0), +) + +# pylint: disable=g-long-lambda +default_strategy = combinations.NamedDistribution( + "Default", + distribute_lib._get_default_strategy, # pylint: disable=protected-access + required_gpus=None, +) +one_device_strategy = combinations.NamedDistribution( + "OneDeviceCPU", lambda: OneDeviceStrategy("/cpu:0"), required_gpus=None +) +one_device_strategy_gpu = combinations.NamedDistribution( + "OneDeviceGPU", lambda: OneDeviceStrategy("/gpu:0"), required_gpus=1 +) +one_device_strategy_on_worker_1 = combinations.NamedDistribution( + "OneDeviceOnWorker1CPU", + lambda: OneDeviceStrategy("/job:worker/replica:0/task:1/cpu:0"), + required_gpus=None, +) +one_device_strategy_gpu_on_worker_1 = combinations.NamedDistribution( + "OneDeviceOnWorker1GPU", + lambda: OneDeviceStrategy("/job:worker/replica:0/task:1/gpu:0"), + required_gpus=1, +) +tpu_strategy = combinations.NamedDistribution( + "TPU", _get_tpu_strategy_creator(steps_per_run=2), required_tpu=True +) +tpu_strategy_packed_var = combinations.NamedDistribution( + "TPUPackedVar", + _get_tpu_strategy_creator(steps_per_run=2, enable_packed_variable=True), + required_tpu=True, +) +tpu_strategy_spmd = combinations.NamedDistribution( + "TPUUseSPMD", + _get_tpu_strategy_creator( + steps_per_run=2, enable_spmd_xla_paritioning=True + ), + required_tpu=True, +) +tpu_strategy_one_step = combinations.NamedDistribution( + "TPUOneStep", _get_tpu_strategy_creator(steps_per_run=1), required_tpu=True +) +tpu_strategy_one_core = combinations.NamedDistribution( + "TPUOneCore", + _get_tpu_strategy_creator(steps_per_run=2, use_single_core=True), + required_tpu=True, +) +tpu_strategy_one_step_one_core = combinations.NamedDistribution( + "TPUOneStepOneCore", + _get_tpu_strategy_creator(steps_per_run=1, use_single_core=True), + required_tpu=True, +) +cloud_tpu_strategy = combinations.NamedDistribution( + "CloudTPU", + _get_tpu_strategy_creator(steps_per_run=2), + required_tpu=True, + use_cloud_tpu=True, +) +mirrored_strategy_with_one_cpu = combinations.NamedDistribution( + "Mirrored1CPU", + lambda: _mirrored_strategy_with_collective_key_base(["/cpu:0"]), +) +mirrored_strategy_with_one_gpu = combinations.NamedDistribution( + "Mirrored1GPU", + lambda: _mirrored_strategy_with_collective_key_base(["/gpu:0"]), + required_gpus=1, +) +mirrored_strategy_with_gpu_and_cpu = combinations.NamedDistribution( + "MirroredCPUAndGPU", + lambda: _mirrored_strategy_with_collective_key_base(["/gpu:0", "/cpu:0"]), + required_gpus=1, +) +mirrored_strategy_with_two_cpus = combinations.NamedDistribution( + "Mirrored2CPUs", + lambda: _mirrored_strategy_with_collective_key_base(["/cpu:0", "/cpu:1"]), + required_gpus=0, +) +mirrored_strategy_with_two_gpus = combinations.NamedDistribution( + "Mirrored2GPUs", + lambda: _mirrored_strategy_with_collective_key_base(["/gpu:0", "/gpu:1"]), + required_gpus=2, +) +mirrored_strategy_with_two_gpus_no_merge_call = combinations.NamedDistribution( + "Mirrored2GPUsNoMergeCall", + lambda: _mirrored_strategy_with_no_merge_call(["/gpu:0", "/gpu:1"]), + required_physical_gpus=2, +) +# Should call set_virtual_cpus_to_at_least(3) in your test's setUp methods. +# Deprecated, use mirrored_strategy_with_two_cpus instead. +mirrored_strategy_with_cpu_1_and_2 = combinations.NamedDistribution( + "Mirrored2CPU", + lambda: _mirrored_strategy_with_collective_key_base(["/cpu:1", "/cpu:2"]), +) +mirrored_strategy_with_cpu_1_and_2.__doc__ = ( + """Mirrored strategy with 2 virtual CPUs. + + Should set up logical devices before use + """ +) +central_storage_strategy_with_two_gpus = combinations.NamedDistribution( + "CentralStorage2GPUs", + lambda: CentralStorageStrategy(["/gpu:0", "/gpu:1"]), + required_gpus=2, +) +central_storage_strategy_with_gpu_and_cpu = combinations.NamedDistribution( + "CentralStorageCPUAndGPU", + lambda: CentralStorageStrategy(["/gpu:0", "/cpu:0"]), + required_gpus=1, +) +# chief + 1 worker, with CPU. +multi_worker_mirrored_2x1_cpu = combinations.NamedDistribution( + "MultiWorkerMirrored2x1CPU", + _get_multi_worker_mirrored_creator(required_gpus=0), + has_chief=True, + num_workers=1, + pool_runner_fn=_two_worker_pool, + no_xla=True, +) +# chief + 1 worker, with 1 GPU each. +multi_worker_mirrored_2x1_gpu = combinations.NamedDistribution( + "MultiWorkerMirrored2x1GPU", + _get_multi_worker_mirrored_creator(required_gpus=1), + has_chief=True, + num_workers=1, + required_gpus=1, + pool_runner_fn=_two_worker_pool, + share_gpu=False, +) + +# Same as above, but not sharing the GPU between the workers. +multi_worker_mirrored_2x1_gpu_noshare = combinations.NamedDistribution( + "MultiWorkerMirrored2x1GPUNoShare", + _get_multi_worker_mirrored_creator(required_gpus=1), + has_chief=True, + num_workers=1, + required_gpus=1, + pool_runner_fn=_two_worker_pool_noshare, + share_gpu=False, +) +# chief + 1 worker, with 2 GPU each. +multi_worker_mirrored_2x2_gpu = combinations.NamedDistribution( + "MultiWorkerMirrored2x2GPU", + _get_multi_worker_mirrored_creator(required_gpus=2), + has_chief=True, + num_workers=1, + required_gpus=2, + pool_runner_fn=_two_worker_pool, + no_xla=True, +) +multi_worker_mirrored_2x2_gpu_no_merge_call = combinations.NamedDistribution( + "MultiWorkerMirrored2x2GPUNoMergeCall", + _get_multi_worker_mirrored_creator(required_gpus=2, use_merge_call=False), + has_chief=True, + num_workers=1, + required_physical_gpus=2, + pool_runner_fn=_two_worker_pool, + no_xla=True, +) +# chief + 3 workers, with CPU. +multi_worker_mirrored_4x1_cpu = combinations.NamedDistribution( + "MultiWorkerMirrored4x1CPU", + _get_multi_worker_mirrored_creator(required_gpus=0), + has_chief=True, + num_workers=3, + pool_runner_fn=_four_worker_pool, + no_xla=True, +) + + +def parameter_server_strategy_fn( + name, + num_workers, + num_ps, + required_gpus=0, + variable_partitioner=DEFAULT_PARTITIONER, +): + return combinations.NamedDistribution( + name, + _get_ps_strategy_creator( + num_workers=num_workers, + num_ps=num_ps, + required_gpus=required_gpus, + variable_partitioner=variable_partitioner, + ), + required_gpus=required_gpus, + num_workers=num_workers, + has_chief=True, + num_ps=num_ps, + ) + + +parameter_server_strategy_3worker_2ps_cpu = parameter_server_strategy_fn( + "ParameterServer3Worker2PSCPU", num_workers=3, num_ps=2 +) +parameter_server_strategy_1worker_2ps_cpu = parameter_server_strategy_fn( + "ParameterServer1Worker2PSCPU", num_workers=1, num_ps=2 +) +parameter_server_strategy_3worker_2ps_1gpu = parameter_server_strategy_fn( + "ParameterServer3Worker2PS1GPU", num_workers=3, num_ps=2, required_gpus=1 +) +parameter_server_strategy_1worker_2ps_1gpu = parameter_server_strategy_fn( + "ParameterServer1Worker2PS1GPU", num_workers=1, num_ps=2, required_gpus=1 +) + +graph_and_eager_modes = ["graph", "eager"] + + +# TODO(crccw): remove after tf-nightly picks up the new API. +def set_virtual_cpus_to_at_least(num_virtual_cpus): + test_util.set_logical_devices_to_at_least("CPU", num_virtual_cpus) + + +strategies_minus_tpu = [ + default_strategy, + one_device_strategy, + one_device_strategy_gpu, + mirrored_strategy_with_gpu_and_cpu, + mirrored_strategy_with_two_gpus, + central_storage_strategy_with_gpu_and_cpu, +] + +strategies_minus_default_and_tpu = [ + one_device_strategy, + one_device_strategy_gpu, + mirrored_strategy_with_gpu_and_cpu, + mirrored_strategy_with_two_gpus, +] + +tpu_strategies = [ + tpu_strategy, # steps_per_run=2 + tpu_strategy_one_step, + tpu_strategy_packed_var, + cloud_tpu_strategy, +] + +all_strategies_minus_default = strategies_minus_default_and_tpu + tpu_strategies + +all_strategies = strategies_minus_tpu + tpu_strategies + +two_replica_strategies = [ + mirrored_strategy_with_gpu_and_cpu, + mirrored_strategy_with_two_gpus, + multi_worker_mirrored_2x1_cpu, + multi_worker_mirrored_2x1_gpu, + tpu_strategy, # steps_per_run=2 + tpu_strategy_one_step, + central_storage_strategy_with_gpu_and_cpu, +] + +four_replica_strategies = [ + multi_worker_mirrored_2x2_gpu, + multi_worker_mirrored_4x1_cpu, +] + +# TODO(b/159831907): replace with two_replica_strategies after the tests using +# it work with MWMS. +multidevice_strategies = [ + mirrored_strategy_with_gpu_and_cpu, + mirrored_strategy_with_two_gpus, + tpu_strategy, # steps_per_run=2 + tpu_strategy_one_step, +] + +multiworker_strategies = [ + multi_worker_mirrored_2x1_cpu, + multi_worker_mirrored_2x1_gpu, + multi_worker_mirrored_2x2_gpu, +] + + +def strategy_minus_tpu_combinations(): + return combinations.combine( + distribution=strategies_minus_tpu, mode=["graph", "eager"] + ) + + +def tpu_strategy_combinations(): + return combinations.combine(distribution=tpu_strategies, mode=["graph"]) + + +def all_strategy_combinations(): + return strategy_minus_tpu_combinations() + tpu_strategy_combinations() + + +def all_strategy_minus_default_and_tpu_combinations(): + return combinations.combine( + distribution=[ + one_device_strategy, + one_device_strategy_gpu, + mirrored_strategy_with_gpu_and_cpu, + mirrored_strategy_with_two_gpus, + ], + mode=["graph", "eager"], + ) + + +def all_strategy_combinations_minus_default(): + return ( + all_strategy_minus_default_and_tpu_combinations() + + tpu_strategy_combinations() + ) + + +tf_export( + "__internal__.distribute.combinations.central_storage_strategy_with_gpu_and_cpu", + v1=[], +).export_constant(__name__, "central_storage_strategy_with_gpu_and_cpu") +tf_export( + "__internal__.distribute.combinations.central_storage_strategy_with_two_gpus", + v1=[], +).export_constant(__name__, "central_storage_strategy_with_two_gpus") +tf_export( + "__internal__.distribute.combinations.cloud_tpu_strategy", v1=[] +).export_constant(__name__, "cloud_tpu_strategy") +tf_export( + "__internal__.distribute.combinations.default_strategy", v1=[] +).export_constant(__name__, "default_strategy") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_cpu_1_and_2", + v1=[], +).export_constant(__name__, "mirrored_strategy_with_cpu_1_and_2") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_two_cpus", + v1=[], +).export_constant(__name__, "mirrored_strategy_with_two_cpus") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_gpu_and_cpu", + v1=[], +).export_constant(__name__, "mirrored_strategy_with_gpu_and_cpu") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_one_cpu", v1=[] +).export_constant(__name__, "mirrored_strategy_with_one_cpu") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_one_gpu", v1=[] +).export_constant(__name__, "mirrored_strategy_with_one_gpu") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_two_gpus", + v1=[], +).export_constant(__name__, "mirrored_strategy_with_two_gpus") +tf_export( + "__internal__.distribute.combinations.mirrored_strategy_with_two_gpus_no_merge_call", + v1=[], +).export_constant(__name__, "mirrored_strategy_with_two_gpus_no_merge_call") +tf_export( + "__internal__.distribute.combinations.multi_worker_mirrored_2x1_cpu", v1=[] +).export_constant(__name__, "multi_worker_mirrored_2x1_cpu") +tf_export( + "__internal__.distribute.combinations.multi_worker_mirrored_2x1_gpu", v1=[] +).export_constant(__name__, "multi_worker_mirrored_2x1_gpu") +tf_export( + "__internal__.distribute.combinations.multi_worker_mirrored_2x1_gpu_noshare", + v1=[], +).export_constant(__name__, "multi_worker_mirrored_2x1_gpu_noshare") +tf_export( + "__internal__.distribute.combinations.multi_worker_mirrored_2x2_gpu", v1=[] +).export_constant(__name__, "multi_worker_mirrored_2x2_gpu") +tf_export( + "__internal__.distribute.combinations.multi_worker_mirrored_2x2_gpu_no_merge_call", + v1=[], +).export_constant(__name__, "multi_worker_mirrored_2x2_gpu_no_merge_call") +tf_export( + "__internal__.distribute.combinations.one_device_strategy", v1=[] +).export_constant(__name__, "one_device_strategy") +tf_export( + "__internal__.distribute.combinations.one_device_strategy_gpu", v1=[] +).export_constant(__name__, "one_device_strategy_gpu") +tf_export( + "__internal__.distribute.combinations.tpu_strategy", v1=[] +).export_constant(__name__, "tpu_strategy") +tf_export( + "__internal__.distribute.combinations.parameter_server_strategy_3worker_2ps_cpu", + v1=[], +).export_constant(__name__, "parameter_server_strategy_3worker_2ps_cpu") +tf_export( + "__internal__.distribute.combinations.parameter_server_strategy_1worker_2ps_cpu", + v1=[], +).export_constant(__name__, "parameter_server_strategy_1worker_2ps_cpu") +tf_export( + "__internal__.distribute.combinations.parameter_server_strategy_3worker_2ps_1gpu", + v1=[], +).export_constant(__name__, "parameter_server_strategy_3worker_2ps_1gpu") +tf_export( + "__internal__.distribute.combinations.parameter_server_strategy_1worker_2ps_1gpu", + v1=[], +).export_constant(__name__, "parameter_server_strategy_1worker_2ps_1gpu") +tf_export( + "__internal__.distribute.combinations.tpu_strategy_one_core", v1=[] +).export_constant(__name__, "tpu_strategy_one_core") +tf_export( + "__internal__.distribute.combinations.tpu_strategy_packed_var", v1=[] +).export_constant(__name__, "tpu_strategy_packed_var") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/strategy_test_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/strategy_test_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..911fccc7e56fd21440e42ddba6e77d8ce6577721 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/strategy_test_lib.py @@ -0,0 +1,825 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Library for testing DistributionStrategy descendants.""" + +import functools +import os +import tempfile + +import numpy as np + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.distribute import collective_all_reduce_strategy as mwms_lib +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import mirrored_strategy as mirrored_lib +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.lib.io import tf_record +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import init_ops_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import summary_ops_v2 as summary_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.training import optimizer +from tensorflow.python.training import training_util +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect + + +class _TestException(Exception): + pass + + +# Conditionally wrap the fn in a def_function.function (so it runs in graph +# mode). +def _maybe_run_in_function(fn, run_in_function=False): + if not run_in_function or not context.executing_eagerly(): + return fn + else: + return def_function.function()(fn) + + +# May be the argument to either distribution.extended.call_for_each_replica() or +# get_replica_context().merge_call() +def _raise_exception_fn(_=None): + raise _TestException() + + +# Must be the argument to a distribution.extended.call_for_each_replica() call, +# calls a get_replica_context().merge_call() that raises an exception. +def _merge_raises_fn(): + distribute_lib.get_replica_context().merge_call(_raise_exception_fn) + + +# Must be the argument to a get_replica_context().merge_call() call, calls +# dist.extended.call_for_each_replica() with a function that raises an +# exception. +def _call_raises_fn(dist): + dist.extended.call_for_each_replica(_raise_exception_fn) + + +# Must be the argument to a distribution.extended.call_for_each_replica() call, +# calls a get_replica_context().merge_call() that calls a +# call_for_each_replica() that raises an exception. +def _merge_call_raises_fn(): + distribute_lib.get_replica_context().merge_call(_call_raises_fn) + + +# Must be the argument to a get_replica_context().merge_call() call, calls +# dist.extended.call_for_each_replica() with a function that calls a +# get_replica_context().merge_call() that raises an exception. +def _call_merge_raises_fn(dist): + dist.extended.call_for_each_replica(_merge_raises_fn) + + +# Must be the argument to a distribution.extended.call_for_each_replica() call, +# calls a get_replica_context().merge_call() that calls a +# call_for_each_replica() that calls a get_replica_context().merge_call() that +# raises an exception. +def _merge_call_merge_raises_fn(): + distribute_lib.get_replica_context().merge_call(_call_merge_raises_fn) + + +def _events_from_logdir(test_case, logdir): + """Reads summary events from log directory.""" + test_case.assertTrue(gfile.Exists(logdir)) + files = gfile.ListDirectory(logdir) + test_case.assertLen(files, 1) + records = list(tf_record.tf_record_iterator(os.path.join(logdir, files[0]))) + result = [] + for r in records: + event = event_pb2.Event() + event.ParseFromString(r) + result.append(event) + return result + + +def create_variable_like_keras_layer(name, shape, dtype): + """Utitlity for create variables that works like variable in keras layer.""" + initializer = functools.partial( + init_ops_v2.GlorotUniform(), shape, dtype=dtype) + return variables.Variable( + initial_value=initializer, name=name, trainable=True) + + +def is_optimizer_v2_instance(optimizer_obj): + # For a optimizer instance, the v2 implementation has var_list as a required + # argument. + arg_spec = tf_inspect.getfullargspec(optimizer_obj.minimize) + return "var_list" in arg_spec.args[:-len(arg_spec.defaults)] + + +def is_mirrored_strategy(strategy: distribute_lib.Strategy) -> bool: + return isinstance( + strategy, + (mirrored_lib.MirroredStrategy, mirrored_lib.MirroredStrategyV1)) + + +def is_multi_worker_mirrored_strategy( + strategy: distribute_lib.Strategy) -> bool: + return isinstance(strategy, (mwms_lib.CollectiveAllReduceStrategy, + mwms_lib.CollectiveAllReduceStrategyV1)) + + +def is_tpu_strategy(strategy: distribute_lib.Strategy) -> bool: + return isinstance(strategy, + (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV1, + tpu_strategy.TPUStrategyV2)) + + +class DistributionTestBase(test.TestCase): + """Some tests that should work with any DistributionStrategy.""" + + def _test_minimize_loss_eager(self, d): + with d.scope(): + kernel = create_variable_like_keras_layer( + name="kernel", shape=(1, 1), dtype=dtypes.float32) + def loss(x): + y = array_ops.reshape( + math_ops.mat_mul(x, kernel), []) - array_ops.identity(1.) + return y * y + # TODO(isaprykin): Extract implicit_grad+get_filtered_grad_fn into a + # common `implicit_grad` function and put it in DistributionStrategy. + grad_fn = backprop.implicit_grad(loss) + grad_fn = optimizer.get_filtered_grad_fn(grad_fn) + + def update(v, g): + return v.assign_sub(0.2 * g) + + one = array_ops.identity([[1.]]) + + def step(): + """Perform one optimization step.""" + # Run forward & backward to get gradients, variables list. + g_v = d.extended.call_for_each_replica(grad_fn, args=(one,)) + + # Update the variables using the gradients and the update() function. + before_list = [] + after_list = [] + for g, v in g_v: + fetched = d.extended.read_var(v) + before_list.append(fetched) + # control_dependencies irrelevant but harmless in eager execution + with ops.control_dependencies([fetched]): + g = d.extended.reduce_to( + reduce_util.ReduceOp.SUM, g, destinations=v) + with ops.control_dependencies( + d.extended.update(v, update, args=(g,), group=False)): + after_list.append(d.extended.read_var(v)) + return before_list, after_list + + for i in range(10): + b, a = step() + if i == 0: + before, = b # pylint: disable=unbalanced-tuple-unpacking + after, = a # pylint: disable=unbalanced-tuple-unpacking + + error_before = abs(before.numpy() - 1) + error_after = abs(after.numpy() - 1) + # Error should go down + self.assertLess(error_after, error_before) + + def _test_minimize_loss_graph(self, + d, + soft_placement=False, + learning_rate=0.2): + config = config_pb2.ConfigProto() + config.allow_soft_placement = soft_placement + config.gpu_options.per_process_gpu_memory_fraction = 0.3 + with context.graph_mode(), \ + ops.Graph().as_default(), \ + self.cached_session(config=config) as sess, \ + d.scope(): + kernel = create_variable_like_keras_layer( + name="kernel", shape=(1, 1), dtype=dtypes.float32) + + def loss(x): + y = array_ops.reshape( + math_ops.mat_mul(x, kernel), []) - array_ops.identity(1.) + return y * y + + grad_fn = backprop.implicit_grad(loss) + + def update(v, g): + return v.assign_sub(learning_rate * g) + + one = array_ops.identity([[1.]]) + + def step(): + """Perform one optimization step.""" + # Run forward & backward to get gradients, variables list. + g_v = d.extended.call_for_each_replica(grad_fn, args=(one,)) + + # Update the variables using the gradients and the update() function. + before_list = [] + after_list = [] + for g, v in g_v: + fetched = d.extended.read_var(v) + before_list.append(fetched) + with ops.control_dependencies([fetched]): + g = d.extended.reduce_to( + reduce_util.ReduceOp.SUM, g, destinations=v) + with ops.control_dependencies( + d.extended.update(v, update, args=(g,), group=False)): + after_list.append(d.extended.read_var(v)) + return before_list, after_list + + before_out, after_out = step() + variables.global_variables_initializer().run() + for i in range(10): + b, a = sess.run((before_out, after_out)) + if i == 0: + before, = b + after, = a + + error_before = abs(before - 1) + error_after = abs(after - 1) + # Error should go down + self.assertLess(error_after, error_before) + + def _test_summary_for_replica_zero_only(self, d): + logdir = tempfile.mkdtemp() + + def run_fn(): + """Function executed for each replica.""" + with summary_writer.as_default(): + replica_id = distribute_lib.get_replica_context().replica_id_in_sync_group + return summary_ops.write("a", replica_id) + + with self.cached_session() as sess, d.scope(), \ + summary_ops.always_record_summaries(): + # We need global_step because summary writing op *always* has global_step + # as input, even when we always record summary or never record summary. + global_step = training_util.get_or_create_global_step() + if not context.executing_eagerly(): + # When executing eagerly, variables are initialized immediately after + # creation, and its initializer will be None. + global_step.initializer.run() + summary_ops.set_step(0) + summary_writer = summary_ops.create_file_writer(logdir) + output = d.extended.call_for_each_replica(run_fn) + unwrapped = d.unwrap(output) + if not context.executing_eagerly(): + sess.run(summary_writer.init()) + sess.run(unwrapped) + sess.run(summary_writer.close()) + + events = _events_from_logdir(self, logdir) + # There will be 2 entries: 1 summary file header entry, and 1 entry + # written by replica 0. + self.assertLen(events, 2) + self.assertEqual(events[1].summary.value[0].tag, "a") + self.assertEqual(events[1].summary.value[0].simple_value, 0.0) + + def _test_replica_id(self, d): + with d.scope(): + expected_devices = [False] * len(d.extended.worker_devices) + + def mark_devices_fn(): + replica_id = self.evaluate( + distribute_lib.get_replica_context().replica_id_in_sync_group) + self.assertLess(replica_id, len(d.extended.worker_devices)) + self.assertFalse(expected_devices[replica_id]) + expected_devices[replica_id] = True + + d.extended.call_for_each_replica(mark_devices_fn) + self.assertAllEqual(expected_devices, + [True] * len(d.extended.worker_devices)) + + def _test_call_and_merge_exceptions(self, dist): + with dist.scope(): + with self.assertRaises(_TestException): + dist.extended.call_for_each_replica(_raise_exception_fn) + with self.assertRaises(_TestException): + dist.extended.call_for_each_replica(_merge_raises_fn) + with self.assertRaises(_TestException): + dist.extended.call_for_each_replica(_merge_call_raises_fn) + with self.assertRaises(_TestException): + dist.extended.call_for_each_replica(_merge_call_merge_raises_fn) + + def _input_fn_to_test_input_context(self, dataset_or_callable_fn, + expected_num_replicas_in_sync, + expected_num_input_pipelines, + expected_input_pipeline_id): + # Use a list of one element as counter so that it can be captured by the + # `_input_fn`. This counter is incremented by 1 each time an input_fn is + # called. We use this counter to check whether the `input_pipeline_id` + # matches the counter in the in-graph replication. + worker_id_counter = [0] + + def _input_fn(input_context): + """Input fn for testing.""" + self.assertIsNotNone(input_context) + self.assertEqual(expected_num_replicas_in_sync, + input_context.num_replicas_in_sync) + self.assertEqual(expected_num_input_pipelines, + input_context.num_input_pipelines) + if expected_input_pipeline_id is not None: + self.assertEqual(expected_input_pipeline_id, + input_context.input_pipeline_id) + else: + self.assertEqual(worker_id_counter[0], input_context.input_pipeline_id) + worker_id_counter[0] += 1 + + return dataset_or_callable_fn() + + return _input_fn + + def _test_input_fn_iterable( + self, strategy, input_fn, expected_values, ignore_order=False): + assert_same = self.assertCountEqual if ignore_order else self.assertEqual + + iterable = strategy.distribute_datasets_from_function(input_fn) + if context.executing_eagerly(): + iterator = iter(iterable) + + for expected_value in expected_values: + computed_value = self.evaluate( + list(strategy.experimental_local_results(next(iterator)))) + assert_same(expected_value, computed_value) + + with self.assertRaises(StopIteration): + self.evaluate(strategy.experimental_local_results(next(iterator))) + + # After re-initializing the iterator, should be able to iterate again. + iterator = iter(iterable) + + for expected_value in expected_values: + computed_value = self.evaluate( + list(strategy.experimental_local_results(next(iterator)))) + assert_same(expected_value, computed_value) + else: + iterator = dataset_ops.make_initializable_iterator(iterable) + self._test_input_fn_iterator(iterator, strategy.extended.worker_devices, + expected_values, test_reinitialize=True, + ignore_order=ignore_order) + + def _test_input_fn_iterator(self, + iterator, + devices, + expected_values, + sess=None, + test_reinitialize=True, + ignore_order=False): + evaluate = lambda x: sess.run(x) if sess else self.evaluate(x) + evaluate(iterator.initializer) + + for expected_value in expected_values: + next_element = iterator.get_next() + computed_value = evaluate( + [distribute_utils.select_replica(r, next_element) for r in + range(len(devices))]) + if ignore_order: + self.assertCountEqual(expected_value, computed_value) + else: + self.assertEqual(expected_value, computed_value) + + with self.assertRaises(errors.OutOfRangeError): + next_element = iterator.get_next() + evaluate( + [distribute_utils.select_replica(r, next_element) for r in + range(len(devices))]) + + # After re-initializing the iterator, should be able to iterate again. + if test_reinitialize: + evaluate(iterator.initializer) + + for expected_value in expected_values: + next_element = iterator.get_next() + computed_value = evaluate([ + distribute_utils.select_replica(r, next_element) for r in + range(len(devices)) + ]) + if ignore_order: + self.assertCountEqual(expected_value, computed_value) + else: + self.assertEqual(expected_value, computed_value) + + def _test_global_step_update(self, strategy): + with strategy.scope(): + global_step = variable_scope.get_variable( + "global_step", + shape=[], + dtype=dtypes.int64, + initializer=init_ops.zeros_initializer(), + trainable=False, + aggregation=variables.VariableAggregation.ONLY_FIRST_REPLICA) + self.evaluate(variables.global_variables_initializer()) + + def model_fn(): + train_op = global_step.assign_add(1) + value = global_step.read_value() + return train_op, value + + train_ops, value = strategy.extended.call_for_each_replica(model_fn) + self.evaluate(strategy.group(train_ops)) + global_step_tensors = strategy.experimental_local_results(value) + global_step_values = self.evaluate(global_step_tensors) + self.assertEqual((1,) * len(global_step_tensors), global_step_values) + + def _test_numpy_dataset(self, strategy, session=None, run_in_function=False): + if not isinstance(strategy, distribute_lib.StrategyV1): + self.skipTest("n/a: V1 only") + cached_session = session or self.cached_session() + with strategy.scope(), cached_session as sess: + x = np.asarray([[1, 2], [6, 12], [2, 4], [5, 10], [3, 6], [4, 8]]) + y = np.asarray([5, 4, 3, 2, 1, 0]) + batch_size = 6 + if not strategy.extended._global_batch_size: # pylint: disable=protected-access + batch_size = batch_size // strategy.num_replicas_in_sync + + ds = strategy.extended.experimental_make_numpy_dataset( + (x, y), session=sess or self.cached_session()) + ds = ds.repeat(2) # 2 epochs + # We need to use the drop_remainder argument to get a known static + # input shape which is required for TPUs. + drop_remainder = strategy.extended.experimental_require_static_shapes + ds = ds.batch(batch_size, drop_remainder=drop_remainder) + i = strategy.make_dataset_iterator(ds) + + self.evaluate(i.initializer) + + def run_and_concatenate(strategy, i): + x, y = strategy.experimental_run( + _maybe_run_in_function(lambda z: z, run_in_function), i) + x, y = self.evaluate((strategy.experimental_local_results(x), + strategy.experimental_local_results(y))) + return np.concatenate(x), np.concatenate(y) + + x_1, y_1 = run_and_concatenate(strategy, i) + self.assertAllEqual(x, x_1) + self.assertAllEqual(y, y_1) + x_2, y_2 = run_and_concatenate(strategy, i) + self.assertAllEqual(x, x_2) + self.assertAllEqual(y, y_2) + with self.assertRaises(errors.OutOfRangeError): + run_and_concatenate(strategy, i) + + def _test_trainable_variable(self, strategy): + for cls in [variable_v1.VariableV1, variables.Variable]: + with strategy.scope(): + v1 = cls(1.0) + self.assertEqual(True, v1.trainable) + + v2 = cls(1.0, synchronization=variables.VariableSynchronization.ON_READ) + self.assertEqual(False, v2.trainable) + + v3 = cls(1.0, synchronization=variables.VariableSynchronization.ON_READ, + trainable=True) + self.assertEqual(True, v3.trainable) + + v4 = cls(1.0, synchronization=variables.VariableSynchronization.ON_READ, + trainable=False) + self.assertEqual(False, v4.trainable) + + +class OneDeviceDistributionTestBase(test.TestCase): + """Some tests that should work with any one-device DistributionStrategy.""" + + def _test_run(self, strategy): + out1 = strategy.run(lambda: array_ops.identity(4.)) + self.assertAllEqual([4.], self.evaluate(strategy.unwrap(out1))) + + out2 = strategy.run(lambda x: {"a": x * 2, "b": x * x}, args=(out1,)) + out2_vals = self.evaluate(nest.map_structure(strategy.unwrap, out2)) + self.assertAllEqual([8.], out2_vals["a"]) + self.assertAllEqual([16.], out2_vals["b"]) + + out3 = strategy.run(lambda b, a: a + 2 * b + 2, kwargs=out2) + self.assertAllEqual([42.], self.evaluate(strategy.unwrap(out3))) + + def _test_all_reduce_sum(self, strategy): + self._test_collective_comms( + strategy, _all_sum, inputs=(4., [42., 43.]), expected=(4., [42., 43.])) + + def _test_all_reduce_sum_gradients(self, strategy): + self._test_collective_comms_gradients( + strategy, _all_sum, inputs=[4.], expected_grads=[4.]) + + def _test_all_reduce_sum_gradient_tape(self, strategy): + self._test_collective_comms_gradient_tape( + strategy, _all_sum, inputs=[4.], expected_grads=[4.]) + + def _test_all_reduce_mean(self, strategy): + self._test_collective_comms( + strategy, _all_mean, inputs=(2., [21., 22.]), expected=(2., [21., 22.])) + + def _test_all_reduce_mean_gradients(self, strategy): + self._test_collective_comms_gradients( + strategy, _all_mean, inputs=[5.], expected_grads=[5.]) + + def _test_all_reduce_mean_gradient_tape(self, strategy): + self._test_collective_comms_gradient_tape( + strategy, _all_mean, inputs=[5.], expected_grads=[5.]) + + def _test_collective_comms(self, strategy, comm_fn, inputs, expected): + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.from_tensors(inputs)) + + self.evaluate(inputs.initialize()) + outputs = self.evaluate( + list( + map(strategy.experimental_local_results, + strategy.experimental_run(comm_fn, inputs)))) + self.assertAllEqual([expected[0]], outputs[0]) + self.assertAllEqual([expected[1]], outputs[1]) + + def _test_collective_comms_gradients(self, strategy, comm_fn, inputs, + expected_grads): + if context.executing_eagerly(): + self.skipTest("`tf.gradients` is not supported with eager execution.") + + def step(c): + x = array_ops.identity(42.) + y = comm_fn(x) * c + return gradients_impl.gradients(y, [x])[0] + + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.from_tensors(inputs)) + + self.evaluate(inputs.initialize()) + self.assertAllEqual( + expected_grads, + self.evaluate( + strategy.experimental_local_results( + strategy.experimental_run(step, inputs)))) + + def _test_collective_comms_gradient_tape(self, strategy, comm_fn, inputs, + expected_grads): + + def step(c): + x = array_ops.identity(42.) + with backprop.GradientTape() as tape: + tape.watch(x) + y = comm_fn(x) * c + return tape.gradient(y, x) + + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.from_tensors(inputs)) + + self.evaluate(inputs.initialize()) + self.assertAllEqual( + expected_grads, + self.evaluate( + strategy.experimental_local_results( + strategy.experimental_run(step, inputs)))) + + def _test_device_and_input_device_are_colocated(self, strategy): + if context.executing_eagerly(): + self.skipTest( + "cross-device tests are not supported with eager execution.") + workers, _ = test_util.create_local_cluster(2, 0) + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.range(5)) + comm_fn = lambda x: x + 1 + run_op = strategy.experimental_run(comm_fn, inputs) + with session_lib.Session(target=workers[1].target) as sess: + sess.run(inputs.initialize()) + sess.run(run_op) + + def _test_device_and_input_device_are_colocated_with_function(self, strategy): + if context.executing_eagerly(): + self.skipTest( + "cross-device tests are not supported with eager execution.") + workers, _ = test_util.create_local_cluster(2, 0) + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.range(5)) + comm_fn = lambda x: x + 1 + experimental_run = def_function.function()(strategy.experimental_run) + with ops.device("/job:worker/replica:0/task:1/device:CPU:0"): + # The tf.function must be defined on the right device as well. + run_op = experimental_run(comm_fn, inputs) + with session_lib.Session(target=workers[1].target) as sess: + sess.run(inputs.initialize()) + sess.run(run_op) + + +class TwoDeviceDistributionTestBase(test.TestCase): + """Some tests that should work with any two-device DistributionStrategy.""" + + def _test_run(self, strategy, run_in_function=False): + out1 = strategy.run(_maybe_run_in_function( + lambda: distribute_lib.get_replica_context().replica_id_in_sync_group + 1, + run_in_function)) + self.assertAllEqual([1, 2], self.evaluate(strategy.unwrap(out1))) + + out2 = strategy.run(_maybe_run_in_function( + lambda x: {"a": x * 2, "b": x * x}, run_in_function), args=(out1,)) + out2_vals = self.evaluate(nest.map_structure(strategy.unwrap, out2)) + self.assertAllEqual([2, 4], out2_vals["a"]) + self.assertAllEqual([1, 4], out2_vals["b"]) + + out3 = strategy.run(_maybe_run_in_function( + lambda b, a: a + 2 * b + 2, run_in_function), kwargs=out2) + self.assertAllEqual([6, 14], self.evaluate(strategy.unwrap(out3))) + + def _test_all_reduce_sum(self, strategy, run_in_function=False): + self._test_collective_comms( + strategy, + _all_sum, + inputs=([1., 3.], [[39., 2.], [3., 41.]]), + expected=(4., [42., 43.]), + run_in_function=run_in_function) + + def _test_all_reduce_sum_gradients(self, strategy, run_in_function=False): + self._test_collective_comms_gradients( + strategy, _all_sum, inputs=[1., 3.], expected_grads=[4., 4.], + run_in_function=run_in_function) + + def _test_all_reduce_sum_gradient_tape(self, strategy, run_in_function=False): + self._test_collective_comms_gradient_tape( + strategy, _all_sum, inputs=[1., 3.], expected_grads=[4., 4.], + run_in_function=run_in_function) + + def _test_all_reduce_mean(self, strategy, run_in_function=False): + self._test_collective_comms( + strategy, + _all_mean, + inputs=([1., 3.], [[39., 2.], [3., 41.]]), + expected=(2., [21., 21.5]), + run_in_function=run_in_function) + + def _test_all_reduce_mean_gradients(self, strategy, run_in_function=False): + self._test_collective_comms_gradients( + strategy, _all_mean, inputs=[1., 3.], expected_grads=[2., 2.], + run_in_function=run_in_function) + + def _test_all_reduce_mean_gradient_tape(self, strategy, + run_in_function=False): + self._test_collective_comms_gradient_tape( + strategy, _all_mean, inputs=[1., 3.], expected_grads=[2., 2.], + run_in_function=run_in_function) + + def _test_collective_comms(self, strategy, comm_fn, inputs, expected, + run_in_function=False): + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.from_tensor_slices(inputs)) + + self.evaluate(inputs.initialize()) + outputs = self.evaluate( + list( + map(strategy.experimental_local_results, + strategy.experimental_run( + _maybe_run_in_function(comm_fn, run_in_function), inputs)))) + self.assertAllEqual([expected[0], expected[0]], outputs[0]) + self.assertAllEqual([expected[1], expected[1]], outputs[1]) + + def _test_collective_comms_gradients(self, strategy, comm_fn, inputs, + expected_grads, run_in_function=False): + if context.executing_eagerly() and not run_in_function: + self.skipTest("`tf.gradients` is not supported with eager execution " + "without using tf.functions.") + + def step(c): + x = array_ops.identity(42.) + y = comm_fn(x) * c + return gradients_impl.gradients(y, [x])[0] + + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.from_tensor_slices(inputs)) + + self.evaluate(inputs.initialize()) + self.assertAllEqual( + expected_grads, + self.evaluate( + strategy.experimental_local_results( + strategy.experimental_run( + _maybe_run_in_function(step, run_in_function), inputs)))) + + def _test_collective_comms_gradient_tape(self, strategy, comm_fn, inputs, + expected_grads, + run_in_function=False): + + def step(c): + x = array_ops.identity(42.) + with backprop.GradientTape() as tape: + tape.watch(x) + y = comm_fn(x) * c + return tape.gradient(y, x) + + inputs = strategy.make_input_fn_iterator( + lambda _: dataset_ops.Dataset.from_tensor_slices(inputs)) + + self.evaluate(inputs.initialize()) + self.assertAllEqual( + expected_grads, + self.evaluate( + strategy.experimental_local_results( + strategy.experimental_run( + _maybe_run_in_function(step, run_in_function), + inputs)))) + + +class RemoteSingleWorkerMirroredStrategyBase(DistributionTestBase): + """Tests for a Remote single worker.""" + + def _get_num_gpus(self): + pass + + def _testNumReplicasInSync(self, distribution): + self.assertEqual(self._get_num_gpus(), distribution.num_replicas_in_sync) + + def _testMinimizeLoss(self, distribution): + if context.executing_eagerly(): + self._test_minimize_loss_eager(distribution) + else: + self._test_minimize_loss_graph(distribution, learning_rate=0.05) + + def _testDeviceScope(self, distribution): + with distribution.scope(): + a = array_ops.identity(1.) + with ops.device("/cpu:0"): + b = array_ops.identity(1.) + if context.executing_eagerly(): + device = "/job:worker/replica:0/task:0/device:CPU:0" + else: + device = "/job:worker/replica:0/task:0" + self.assertEqual(a.device, device) + self.assertEqual(b.device, "/job:worker/replica:0/task:0/device:CPU:0") + + def _testMakeInputFnIteratorWithDataset(self, distribution): + dataset_fn = lambda: dataset_ops.Dataset.range(100) + num_gpus = self._get_num_gpus() # pylint: disable=assignment-from-no-return + num_workers = 1 + + expected_values = [[i+j for j in range(num_gpus)] * num_workers + for i in range(0, 100, num_gpus)] + + # Dummy cached_session is used in Eager + with self.cached_session() as sess: + # `expected_input_pipeline_id` is None because the input_fn will be called + # multiple times, each with a different input_pipeline_id. + input_fn = self._input_fn_to_test_input_context( + dataset_fn, + expected_num_replicas_in_sync=num_workers*num_gpus, + expected_num_input_pipelines=num_workers, + expected_input_pipeline_id=None) + iterator = distribution.make_input_fn_iterator(input_fn) + self._test_input_fn_iterator( + iterator, distribution.extended.worker_devices, expected_values, sess) + + def _testMakeInputFnIteratorWithCallable(self, distribution): + def fn(): + dataset = dataset_ops.Dataset.range(100) + it = dataset_ops.make_one_shot_iterator(dataset) + return it.get_next + + num_gpus = self._get_num_gpus() # pylint: disable=assignment-from-no-return + num_workers = 1 + + expected_values = [] + for i in range(0, 100, num_gpus): + expected_values.append([i+j for j in range(num_gpus)] * num_workers) + + # Dummy cached_session is used in Eager + with self.cached_session() as sess: + # `expected_input_pipeline_id` is None because the input_fn will be called + # multiple times, each with a different input_pipeline_id. + input_fn = self._input_fn_to_test_input_context( + fn, + expected_num_replicas_in_sync=num_workers*num_gpus, + expected_num_input_pipelines=num_workers, + expected_input_pipeline_id=None) + iterator = distribution.make_input_fn_iterator(input_fn) + self._test_input_fn_iterator( + iterator, distribution.extended.worker_devices, expected_values, sess, + test_reinitialize=False, ignore_order=True) + + +def _all_sum(value): + ctx = distribute_lib.get_replica_context() + return ctx.all_reduce(reduce_util.ReduceOp.SUM, value) + + +def _all_mean(value): + ctx = distribute_lib.get_replica_context() + return ctx.all_reduce(reduce_util.ReduceOp.MEAN, value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/summary_op_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/summary_op_util.py new file mode 100644 index 0000000000000000000000000000000000000000..7ccb6a181bd2065c846bf002291640b6cb2410ea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/summary_op_util.py @@ -0,0 +1,44 @@ +# 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. +#============================================================================== +"""Contains utility functions used by summary ops in distribution strategy.""" + + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util + + +def skip_summary(): + """Determines if summary should be skipped. + + If using multiple replicas in distributed strategy, skip summaries on all + replicas except the first one (replica_id=0). + + Returns: + True if the summary is skipped; False otherwise. + """ + + # TODO(priyag): Add a new optional argument that will provide multiple + # alternatives to override default behavior. (e.g. run on last replica, + # compute sum or mean across replicas). + replica_context = distribute_lib.get_replica_context() + if not replica_context: + return False + # TODO(b/118385803): when replica_id of _TPUReplicaContext is properly + # initialized, remember to change here as well. + replica_id = replica_context.replica_id_in_sync_group + if isinstance(replica_id, tensor.Tensor): + replica_id = tensor_util.constant_value(replica_id) + return replica_id and replica_id > 0 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..8dbf6c020c1242d876d44d8700ead00b071dc005 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/test_util.py @@ -0,0 +1,301 @@ +# 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. +# ============================================================================== +"""Test utilities.""" + +import collections +import dataclasses +import functools +import io +import itertools +import threading + +from absl import app + +from tensorflow.python.compat import v2_compat +from tensorflow.python.distribute import collective_all_reduce_strategy +from tensorflow.python.distribute import multi_process_runner +from tensorflow.python.distribute import multi_worker_test_base +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.distribute import values +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.util import nest + +try: + import objgraph # pylint:disable=g-import-not-at-top +except ImportError: + objgraph = None + + +@dataclasses.dataclass +class TestClusterParams: + cluster: dict + max_num_worker: int + max_num_ps: int + + +def get_cluster_def(cluster_params, num_workers, num_ps): + if (num_workers > cluster_params.max_num_worker or + num_ps > cluster_params.max_num_ps): + raise ValueError("Requesting more servers than the maximum, adjust" + "cluster params' max_num_ps and max_num_worker") + if cluster_params.cluster is None: + cluster_params.cluster = multi_worker_test_base.create_in_process_cluster( + num_workers=cluster_params.max_num_worker, + num_ps=cluster_params.max_num_ps) + return { + "worker": cluster_params.cluster["worker"][:num_workers], + "ps": cluster_params.cluster["ps"][:num_ps], + } + + +def gather(strategy, value): + """Gathers value from all workers. + + This is intended for tests before we implement an official all-gather API. + + Args: + strategy: a `tf.distribute.Strategy`. + value: a nested structure of n-dim `tf.distribute.DistributedValue` of + `tf.Tensor`, or of a `tf.Tensor` if the strategy only has one replica. + Cannot contain tf.sparse.SparseTensor. + + Returns: + a (n+1)-dim `tf.Tensor`. + """ + return nest.map_structure(functools.partial(_gather, strategy), value) + + +def _gather(strategy, value): + """Gathers a single value.""" + # pylint: disable=protected-access + if not isinstance(value, values.DistributedValues): + value = values.PerReplica([ops.convert_to_tensor(value)]) + if not isinstance(strategy.extended, + collective_all_reduce_strategy.CollectiveAllReduceExtended): + return array_ops_stack.stack(value._values) + assert len(strategy.extended.worker_devices) == len(value._values) + inputs = [array_ops.expand_dims_v2(v, axis=0) for v in value._values] + return strategy.gather(values.PerReplica(inputs), axis=0) + # pylint: enable=protected-access + + +def set_logical_devices_to_at_least(device, num): + """Create logical devices of at least a given number.""" + if num < 1: + raise ValueError("`num` must be at least 1 not %r" % (num,)) + physical_devices = config.list_physical_devices(device) + if not physical_devices: + raise RuntimeError("No {} found".format(device)) + if len(physical_devices) >= num: + return + # By default each physical device corresponds to one logical device. We create + # multiple logical devices for the last physical device so that we have `num` + # logical devices. + num = num - len(physical_devices) + 1 + logical_devices = [] + for _ in range(num): + if device.upper() == "GPU": + logical_devices.append( + context.LogicalDeviceConfiguration(memory_limit=2048)) + else: + logical_devices.append(context.LogicalDeviceConfiguration()) + # Create logical devices from the last device since sometimes the first GPU + # is the primary graphic card and may have less memory available. + config.set_logical_device_configuration(physical_devices[-1], logical_devices) + + +def _set_logical_devices(): + if config.list_physical_devices("GPU"): + set_logical_devices_to_at_least("GPU", 2) + if config.list_physical_devices("CPU"): + set_logical_devices_to_at_least("CPU", 2) + + +def main(enable_v2_behavior=True, config_logical_devices=True): + """All-in-one main function for tf.distribute tests.""" + if config_logical_devices: + app.call_after_init(_set_logical_devices) + if enable_v2_behavior: + v2_compat.enable_v2_behavior() + else: + v2_compat.disable_v2_behavior() + multi_process_runner.test_main() + + +def _op_dependencies(op): + """Returns the data and control dependencies of a tf.Operation combined.""" + deps = [] + for node in itertools.chain(op.inputs, op.control_inputs): + if isinstance(node, tensor.Tensor): + node = node.op + assert isinstance(node, ops.Operation) + deps.append(node) + return deps + + +def topological_sort_operations(operations): + """Topological sorts a list of operations. + + This does a topological sort of the operations in a graph. The edges include + both data dependencies and control dependencies. Note that the edge goes from + an operation to its dependencies. + + The sort is intentionally unstable, reversing orders of operations and + dependencies on ties. + + Args: + operations: a list of tf.Operation in the same graph. + + Returns: + A map from a tf.Operation to its topological order. + """ + in_degrees = collections.OrderedDict() + for op in reversed(operations): + if op not in in_degrees: + in_degrees[op] = 0 + for next_op in reversed(_op_dependencies(op)): + in_degrees[next_op] = in_degrees.get(next_op, 0) + 1 + nexts = [] + for op, in_degree in in_degrees.items(): + if in_degree == 0: + nexts.append(op) + order = {} + next_order = 0 + while nexts: + op, nexts = nexts[0], nexts[1:] + order[op] = next_order + next_order += 1 + for next_op in reversed(_op_dependencies(op)): + in_degrees[next_op] -= 1 + if in_degrees[next_op] == 0: + nexts.append(next_op) + assert len(order) == len(operations) + return order + + +def _exists_dependency(start, end): + """Returns whether there exists a dependency chain from start to end.""" + nexts = [start] + while nexts: + op, nexts = nexts[0], nexts[1:] + for next_op in _op_dependencies(op): + if next_op == end: + return True + nexts.append(next_op) + return False + + +def assert_sequential_execution(order, operations): + """Asserts there's a deterministic execution order between the operations. + + Args: + order: a map from a tf.Operation to its topological order. + operations: a list of operations that should be executed sequentially. It + can be given in any order. + """ + # Topological ordering guarantees that, if there's a dependency from N_a to + # N_b, then order[N_a] < order[N_b]. If there do exist a path of dependencies + # among the operations, it always goes from a operation with a smaller + # topological order to one with a larger topological order. Therefore, we only + # need to sort the operations by their topological orders, and verify that + # there's a path of dependency between adjacent pairs. + operations = sorted(operations, key=lambda op: order[op]) + for i in range(len(operations) - 1): + if not _exists_dependency(operations[i], operations[i + 1]): + print(operations[i].graph.as_graph_def()) + raise AssertionError( + "No dependency between {} and {}. Graph is dumped to stdout.".format( + operations[i].name, operations[i + 1].name)) + + +def get_running_threads(): + """Returns a set of all running thread names.""" + running_threads = set() + for thread in threading.enumerate(): + if thread.name is not None: + running_threads.add(thread.name) + return running_threads + + +def has_thread(prefix, running_threads): + """Returns whether any 'running_threads' is prefixed with 'prefix'. + + Args: + prefix: The prefix of the expected thread name. + running_threads: A collection of the running thread names. + """ + for thread in running_threads: + if thread.startswith(prefix): + return True + return False + + +def show_backref(target, max_depth=3): + """Returns a dot graph of all the objects that are referencing the target. + + A object referencing graph is useful to debug memory leak like circular + reference. objgraph provides a good visualization of the memory graph than + most python built-in utilities like gc.get_referrers(), which are not + human-readable sometimes. + + The dot graph will be written to a string IO object, and can be rendered with + graphviz in operating system. + E.g. dot -Tpng {$dot_graph} -o output.png + Args: + target: The target object for the memory graph. + max_depth: The maximum depth of the graph. By default 3 layers of references + are used. Increases this a lot may result in the graph growing too big. + + Returns: + A string that contains the object reference graph. + Raises: + NotImplementedError: if objgraph is not installed. + """ + if objgraph is None: + raise NotImplementedError("objgraph is not installed.") + string_io = io.StringIO() + objgraph.show_backrefs(target, max_depth=max_depth, output=string_io) + graph = string_io.getvalue() + string_io.close() + return graph + + +def create_per_replica(strategy, value_list): + """Creates a PerReplica of Tensors from the value_list.""" + if len(strategy.extended.worker_devices) != len(value_list): + raise ValueError( + "the length of values must be the same as the number of worker devices") + tensors = [] + for device, value in zip(strategy.extended.worker_devices, value_list): + with ops.device(device): + tensors.append(ops.convert_to_tensor(value)) + return values.PerReplica(tensors) + + +def is_tpu_strategy(strategy): + """Returns whether the strategy is a TPU strategy.""" + return isinstance(strategy, + (tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV1, + tpu_strategy.TPUStrategyV2)) + + +def reset_context(): + """Resets eager context.""" + context._reset_context() # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_replicated_variable.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_replicated_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..e8fbb20acd379f9f1367512a9f81448c8b2a5133 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_replicated_variable.py @@ -0,0 +1,331 @@ +# 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. +# ============================================================================== +"""A Variable class that is replicated to logical cores for model parallelism.""" +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from collections import abc +import contextlib + +from tensorflow.python.compiler.xla.experimental import xla_sharding +from tensorflow.python.distribute import tpu_util +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import gen_tpu_partition_ops as tpu_partition_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables as variables_lib +from tensorflow.python.saved_model import save_context +from tensorflow.python.trackable import base as trackable + + +def _on_device_update(update_fn, var, value, **kwargs): + with ops.device(var.device): + return update_fn(var, value, **kwargs) + + +class TPUReplicatedVariable(variables_lib.Variable): + """Container for replicated `Variables` that are treated as a single variable. + + This class maintains a list of replicated variables that are stored on + separate logic TPU devices. TF2XLA bridge accesses these variables as + if they were a single variable. + """ + + def __init__(self, variables, name='TPUReplicatedVariable'): + """Treats `variables` as a replicated list of `tf.Variable`s. + + Example: + + ``` + variables = [ + tf.Variable(..., shape=(10, 100), dtype=tf.float32), + tf.Variable(..., shape=(10, 100), dtype=tf.float32), + tf.Variable(..., shape=(10, 100), dtype=tf.float32), + tf.Variable(..., shape=(10, 100), dtype=tf.float32), + ] + replicated_variable = TPUReplicatedVariable(variables) + assert replicated_variable.shape.as_list() == [10, 100] + ``` + + Args: + variables: A list of `ResourceVariable`s that comprise this replicated + variable. Variables should not be shared between different + `TPUReplicatedVariable` objects. + name: String. Name of this container. Defaults to "TPUReplicatedVariable". + """ + if not isinstance(variables, abc.Sequence) or not variables or any( + not isinstance(v, variables_lib.Variable) for v in variables): + raise TypeError('Argument `variables` should be a non-empty list of ' + f'`variables.Variable`s. Received {variables}') + + if any(v.dtype != variables[0].dtype for v in variables): + raise ValueError( + 'All elements in argument `variables` must have the same dtype. ' + f'Received dtypes: {[v.dtype for v in variables]}') + + if any(v.shape != variables[0].shape for v in variables): + raise ValueError( + 'All elements in argument `variables` must have the same shape. ' + f'Received shapes: {[v.shape for v in variables]}') + + self._vars = variables + self._name = name + self._common_name = self._name.split(':')[0] + self._cached_value = None + + def __iter__(self): + """Return an iterable for accessing the underlying sharded variables.""" + return iter(self._vars) + + @property + def name(self): + """The name of this object. Used for checkpointing.""" + return self._name + + @property + def dtype(self): + """The dtype of all `Variable`s in this object.""" + return self._vars[0].dtype + + @property + def is_initialized(self): + return self._vars[0].is_initialized + + @property + def trainable(self): + return self._vars[0].trainable + + @property + def device(self): + """The device this variable is on.""" + return self._vars[0].device + + @contextlib.contextmanager + def _handle_graph(self): + with self.handle.graph.as_default(): + yield + + @contextlib.contextmanager + def _assign_dependencies(self): + if self._cached_value is not None: + with ops.control_dependencies([self._cached_value]): + yield + else: + yield + + @property + def constraint(self): + return self._vars[0].constraint + + @property + def _in_graph_mode(self): + return self._vars[0]._in_graph_mode # pylint: disable=protected-access + + @property + def _unique_id(self): + return self._vars[0]._unique_id # pylint: disable=protected-access + + @property + def graph(self): + return self._vars[0].graph + + @property + def _shared_name(self): + return self._common_name + + @property + def synchronization(self): + return variable_scope.VariableSynchronization.NONE + + @property + def aggregation(self): + return variable_scope.VariableAggregation.NONE + + @property + def variables(self): + """The list of `Variables`.""" + if save_context.in_save_context(): + return [self._vars[0]] + return self._vars + + def _export_to_saved_model_graph(self, object_map, tensor_map, + options, **kwargs): + """For implementing `Trackable`.""" + first_var = self._vars[0] + resource_list = first_var._export_to_saved_model_graph( # pylint:disable=protected-access + object_map, tensor_map, options, **kwargs) + for v in self._vars[1:]: + object_map[v] = object_map[first_var] + tensor_map[v.handle] = tensor_map[first_var.handle] + resource_list.append(v.handle) + object_map[self] = object_map[first_var] + tensor_map[self] = tensor_map[first_var.handle] + resource_list.append(self) + return resource_list + + def _serialize_to_tensors(self): + return {trackable.VARIABLE_VALUE_KEY: self._vars[0]} + + def _restore_from_tensors(self, restored_tensors): + restored_tensor = restored_tensors[trackable.VARIABLE_VALUE_KEY] + return self.assign(restored_tensor) + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable`.""" + if self in object_map: + # If populated already, just update the values to the copy. + for v in self._vars: + v._copy_trackable_to_cpu(object_map) # pylint: disable=protected-access + else: + # If not populated, populate first, then copy over the values. + copied_vars = [] + for v in self._vars: + v._copy_trackable_to_cpu(object_map) # pylint: disable=protected-access + copied_vars.append(object_map[v]) + new_var = TPUReplicatedVariable(copied_vars, name=self.name) + object_map[self] = new_var + + @property + def shape(self): + return self._vars[0].shape + + @property + def handle(self): + if save_context.in_save_context() or context.executing_eagerly(): + return self._vars[0].handle + + if tpu_util.enclosing_tpu_context() is None: + raise NotImplementedError('TPUReplicatedVariable.handle is not available ' + 'outside tpu context or save context') + else: + with tpu_util.outside_or_skip_tpu_context(): + packed_var = getattr(self, '_packed_var', None) + + # TODO(b/202047549): Enable packed variables with soft device placement + if packed_var is None or config.get_soft_device_placement(): + tensor = tpu_partition_ops.tpu_partitioned_input_v2( + [v.handle for v in self._vars], + partition_dims=[], is_packed=False) + else: + tensor = tpu_partition_ops.tpu_partitioned_input_v2( + [packed_var.packed_handle], partition_dims=[], is_packed=True) + + return xla_sharding.replicate(tensor) + + def _read_variable_op(self): + return gen_resource_variable_ops.read_variable_op(self.handle, self.dtype) + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + """Converts a variable to a tensor.""" + # pylint: disable=protected-access + if tpu_util.enclosing_tpu_context() is None: + return self.read_value() + else: + return self._read_variable_op() + + def read_value(self): + return self._vars[0].read_value() + + def _update(self, update_fn, value, **kwargs): + """Converts the value to tensor and updates the variable list.""" + input_tensor = ops.convert_to_tensor( + value, name='value_in_tensor', dtype=self.dtype) + + return control_flow_ops.group( + *tuple( + _on_device_update(update_fn, v, input_tensor, **kwargs) + for v in self.variables)) + + def assign(self, value, use_locking=False, name=None, read_value=True): + if tpu_util.enclosing_tpu_context() is None or context.executing_eagerly(): + assign_fn = lambda var, *a, **ka: var.assign(*a, **ka) + return self._update( + assign_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_variable_op)( + self, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + if tpu_util.enclosing_tpu_context() is None or context.executing_eagerly(): + assign_sub_fn = lambda var, *a, **ka: var.assign_sub(*a, **ka) + return self._update( + assign_sub_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_sub_variable_op)( + self, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + if tpu_util.enclosing_tpu_context() is None or context.executing_eagerly(): + assign_add_fn = lambda var, *a, **ka: var.assign_add(*a, **ka) + return self._update( + assign_add_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_add_variable_op)( + self, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def __str__(self): + debug_str = ',\n'.join( + ' %d: %s' % (i, v) for i, v in enumerate(self._vars)) + return '%s:{\n%s\n}' % (self.__class__.__name__, debug_str) + + def __repr__(self): + debug_repr = ',\n'.join( + ' %d: %r' % (i, v) for i, v in enumerate(self._vars)) + return '%s:{\n%s\n}' % (self.__class__.__name__, debug_repr) + + +# Register a conversion function which reads the value of the variable, +# allowing instances of the class to be used as tensors. +def _tensor_conversion_tpu_replicated_var(var, + dtype=None, + name=None, + as_ref=False): + return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + TPUReplicatedVariable, _tensor_conversion_tpu_replicated_var) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_strategy.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..53f6caa6f61ca3c45e1303d2563dd2aefaf45ecb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_strategy.py @@ -0,0 +1,2072 @@ +# 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. +# ============================================================================== +"""TPU Strategy.""" + +import atexit +import collections +import contextlib +import copy +import functools +import weakref + +from absl import logging +import numpy as np + +from tensorflow.python.autograph.core import ag_ctx as autograph_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.compiler.xla.experimental import xla_sharding +from tensorflow.python.distribute import cross_device_ops as cross_device_ops_lib +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import distribute_utils +from tensorflow.python.distribute import input_lib +from tensorflow.python.distribute import input_util +from tensorflow.python.distribute import numpy_dataset +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import tpu_replicated_variable +from tensorflow.python.distribute import tpu_util +from tensorflow.python.distribute import tpu_values +from tensorflow.python.distribute import values +from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver as tpu_cluster_resolver_lib +from tensorflow.python.distribute.v1 import input_lib as input_lib_v1 +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.eager import function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device as tf_device +from tensorflow.python.framework import device_spec +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables as variables_lib +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.saved_model import save_context +from tensorflow.python.tpu import device_assignment as device_assignment_lib # pylint: disable=unused-import +from tensorflow.python.tpu import tpu +from tensorflow.python.tpu import tpu_hardware_feature +from tensorflow.python.tpu import training_loop +from tensorflow.python.tpu.ops import tpu_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import tf_export +from tensorflow.python.util import tf_inspect + +_XLA_OP_BY_OP_INPUTS_LIMIT = 200 + +_EXPERIMENTAL_TPU_BATCH_VARIABLE_INITIALIZATION = False + + +def enable_batch_variable_initialization(): + """Whether to batch variable initialization in tf.function.""" + return ( + _EXPERIMENTAL_TPU_BATCH_VARIABLE_INITIALIZATION + and context.executing_eagerly() + and not save_context.in_save_context() + ) + + +@contextlib.contextmanager +def maybe_init_scope(): + if ops.executing_eagerly_outside_functions(): + yield + else: + with ops.init_scope(): + yield + + +def validate_run_function(fn): + """Validate the function passed into strategy.run.""" + + # We allow three types of functions/objects passed into TPUStrategy + # run in eager mode: + # 1. a user annotated tf.function + # 2. a ConcreteFunction, this is mostly what you get from loading a saved + # model. + # 3. a callable object and the `__call__` method itself is a tf.function. + # + # Otherwise we return an error, because we don't support eagerly running + # run in TPUStrategy. + + if (context.executing_eagerly() + and not isinstance(fn, def_function.Function) + and not isinstance(fn, function.ConcreteFunction) + and not ( + callable(fn) and isinstance(fn.__call__, def_function.Function)) + ): + raise NotImplementedError( + "TPUStrategy.run(fn, ...) does not support pure eager " + "execution. please make sure the function passed into " + "`strategy.run` is a `tf.function` or " + "`strategy.run` is called inside a `tf.function` if " + "eager behavior is enabled.") + + +def _maybe_partial_apply_variables(fn, args, kwargs): + """Inspects arguments to partially apply any DistributedVariable. + + This avoids an automatic cast of the current variable value to tensor. + + Note that a variable may be captured implicitly with Python scope instead of + passing it to run(), but supporting run() keeps behavior consistent + with MirroredStrategy. + + Since positional arguments must be applied from left to right, this function + does some tricky function inspection to move variable positional arguments + into kwargs. As a result of this, we can't support passing Variables as *args, + nor as args to functions which combine both explicit positional arguments and + *args. + + Args: + fn: The function to run, as passed to run(). + args: Positional arguments to fn, as passed to run(). + kwargs: Keyword arguments to fn, as passed to run(). + + Returns: + A tuple of the function (possibly wrapped), args, kwargs (both + possibly filtered, with members of args possibly moved to kwargs). + If no variables are found, this function is a noop. + + Raises: + ValueError: If the function signature makes unsupported use of *args, or if + too many arguments are passed. + """ + + def is_distributed_var(x): + flat = nest.flatten(x) + return flat and isinstance(flat[0], values.DistributedVariable) + + # We will split kwargs into two dicts, one of which will be applied now. + var_kwargs = {} + nonvar_kwargs = {} + + if kwargs: + var_kwargs = {k: v for k, v in kwargs.items() if is_distributed_var(v)} + if var_kwargs: + nonvar_kwargs = { + k: v for k, v in kwargs.items() if not is_distributed_var(v) + } + + # Dump the argument names of `fn` to a list. This will include both positional + # and keyword arguments, but since positional arguments come first we can + # look up names of positional arguments by index. + positional_args = [] + index_of_star_args = None + for i, p in enumerate(tf_inspect.signature(fn).parameters.values()): + # Class methods define "self" as first argument, but we don't pass "self". + # Note that this is a heuristic, as a method can name its first argument + # something else, and a function can define a first argument "self" as well. + # In both of these cases, using a Variable will fail with an unfortunate + # error about the number of arguments. + # inspect.is_method() seems not to work here, possibly due to the use of + # tf.function(). + if i == 0 and p.name == "self": + continue + + if p.kind == tf_inspect.Parameter.POSITIONAL_OR_KEYWORD: + positional_args.append(p.name) + + elif p.kind == tf_inspect.Parameter.VAR_POSITIONAL: + # We'll raise an error later if a variable is passed to *args, since we + # can neither pass it by name nor partially apply it. This case only + # happens once at most. + index_of_star_args = i + + elif p.kind == tf_inspect.Parameter.POSITIONAL_ONLY: + # This is a rare Python feature, indicating a / in the arg list. + if var_kwargs or any(is_distributed_var(a) for a in args): + raise ValueError( + "Mixing Variables and positional-only parameters not supported by " + f"TPUStrategy. Received {len(var_kwargs)} DistributedVariables in " + f"**kwargs and {sum(is_distributed_var(a) for a in args)} in *args," + " expected zero for both." + ) + return fn, args, kwargs + + star_args = [] + have_seen_var_arg = False + + for i, a in enumerate(args): + if is_distributed_var(a): + if index_of_star_args is not None and i >= index_of_star_args: + raise ValueError( + "TPUStrategy.run() cannot handle Variables passed to *args. " + "Either name the function argument, or capture the Variable " + "implicitly.") + if len(positional_args) <= i: + raise ValueError( + "Too many positional arguments passed to call to TPUStrategy.run()." + ) + var_kwargs[positional_args[i]] = a + have_seen_var_arg = True + else: + if index_of_star_args is not None and i >= index_of_star_args: + if have_seen_var_arg: + raise ValueError( + "TPUStrategy.run() cannot handle both Variables and a mix of " + "positional args and *args. Either remove the *args, or capture " + "the Variable implicitly.") + else: + star_args.append(a) + continue + + if len(positional_args) <= i: + raise ValueError( + "Too many positional arguments passed to call to TPUStrategy.run()." + ) + nonvar_kwargs[positional_args[i]] = a + + if var_kwargs: + return functools.partial(fn, **var_kwargs), star_args, nonvar_kwargs + return fn, args, kwargs + + +@tf_export.tf_export("distribute.TPUStrategy", v1=[]) +class TPUStrategyV2(distribute_lib.Strategy): + """Synchronous training on TPUs and TPU Pods. + + To construct a TPUStrategy object, you need to run the + initialization code as below: + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + >>> tf.config.experimental_connect_to_cluster(resolver) + >>> tf.tpu.experimental.initialize_tpu_system(resolver) + >>> strategy = tf.distribute.TPUStrategy(resolver) + + While using distribution strategies, the variables created within the + strategy's scope will be replicated across all the replicas and can be kept in + sync using all-reduce algorithms. + + To run TF2 programs on TPUs, you can either use `.compile` and + `.fit` APIs in `tf.keras` with TPUStrategy, or write your own customized + training loop by calling `strategy.run` directly. Note that + TPUStrategy doesn't support pure eager execution, so please make sure the + function passed into `strategy.run` is a `tf.function` or + `strategy.run` is called inside a `tf.function` if eager + behavior is enabled. See more details in https://www.tensorflow.org/guide/tpu. + + `distribute_datasets_from_function` and + `experimental_distribute_dataset` APIs can be used to distribute the dataset + across the TPU workers when writing your own training loop. If you are using + `fit` and `compile` methods available in `tf.keras.Model`, then Keras will + handle the distribution for you. + + An example of writing customized training loop on TPUs: + + >>> with strategy.scope(): + ... model = tf.keras.Sequential([ + ... tf.keras.layers.Dense(2, input_shape=(5,)), + ... ]) + ... optimizer = tf.keras.optimizers.SGD(learning_rate=0.1) + + >>> def dataset_fn(ctx): + ... x = np.random.random((2, 5)).astype(np.float32) + ... y = np.random.randint(2, size=(2, 1)) + ... dataset = tf.data.Dataset.from_tensor_slices((x, y)) + ... return dataset.repeat().batch(1, drop_remainder=True) + >>> dist_dataset = strategy.distribute_datasets_from_function( + ... dataset_fn) + >>> iterator = iter(dist_dataset) + + >>> @tf.function() + ... def train_step(iterator): + ... + ... def step_fn(inputs): + ... features, labels = inputs + ... with tf.GradientTape() as tape: + ... logits = model(features, training=True) + ... loss = tf.keras.losses.sparse_categorical_crossentropy( + ... labels, logits) + ... + ... grads = tape.gradient(loss, model.trainable_variables) + ... optimizer.apply_gradients(zip(grads, model.trainable_variables)) + ... + ... strategy.run(step_fn, args=(next(iterator),)) + + >>> train_step(iterator) + + For the advanced use cases like model parallelism, you can set + `experimental_device_assignment` argument when creating TPUStrategy to specify + number of replicas and number of logical devices. Below is an example to + initialize TPU system with 2 logical devices and 1 replica. + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + >>> tf.config.experimental_connect_to_cluster(resolver) + >>> topology = tf.tpu.experimental.initialize_tpu_system(resolver) + >>> device_assignment = tf.tpu.experimental.DeviceAssignment.build( + ... topology, + ... computation_shape=[1, 1, 1, 2], + ... num_replicas=1) + >>> strategy = tf.distribute.TPUStrategy( + ... resolver, experimental_device_assignment=device_assignment) + + Then you can run a `tf.add` operation only on logical device 0. + + >>> @tf.function() + ... def step_fn(inputs): + ... features, _ = inputs + ... output = tf.add(features, features) + ... + ... # Add operation will be executed on logical device 0. + ... output = strategy.experimental_assign_to_logical_device(output, 0) + ... return output + >>> dist_dataset = strategy.distribute_datasets_from_function( + ... dataset_fn) + >>> iterator = iter(dist_dataset) + >>> strategy.run(step_fn, args=(next(iterator),)) + + `experimental_spmd_xla_partitioning` enables the experimental XLA SPMD feature + for model parallelism. This flag can reduce the compilation time and HBM + requirements. When running in this mode, every input tensor must either be + partitioned (via `strategy.experimental_split_to_logical_devices`) or fully + replicated (via `strategy.experimental_replicate_to_logical_devices`) to all + logical devices. And calling `strategy.experimental_assign_to_logical_device` + will result in a ValueError in this mode. + """ + + def __init__(self, + tpu_cluster_resolver=None, + experimental_device_assignment=None, + experimental_spmd_xla_partitioning=False): + """Synchronous training in TPU donuts or Pods. + + Args: + tpu_cluster_resolver: A + `tf.distribute.cluster_resolver.TPUClusterResolver` instance, which + provides information about the TPU cluster. If None, it will assume + running on a local TPU worker. + experimental_device_assignment: Optional + `tf.tpu.experimental.DeviceAssignment` to specify the placement of + replicas on the TPU cluster. + experimental_spmd_xla_partitioning: If True, enable the SPMD (Single + Program Multiple Data) mode in XLA compiler. This flag only affects the + performance of XLA compilation and the HBM requirement of the compiled + TPU program. Ceveat: if this flag is True, calling + `tf.distribute.TPUStrategy.experimental_assign_to_logical_device` will + result in a ValueError. + """ + super().__init__( + TPUExtended( + self, + tpu_cluster_resolver, + device_assignment=experimental_device_assignment, + use_spmd_for_xla_partitioning=experimental_spmd_xla_partitioning, + enable_data_reorder=experimental_device_assignment is not None, + ) + ) + distribute_lib.distribution_strategy_gauge.get_cell("V2").set("TPUStrategy") + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_workers").set(self.extended.num_hosts) + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_replicas_per_worker").set(self.extended.num_replicas_per_host) + # Packed variable is used to reduce the overhead of function execution. + # For a DistributedVariable, only one variable handle is captured into a + # function graph. It's only supported in eager mode. + self._enable_packed_variable_in_eager_mode = True + + def run(self, fn, args=(), kwargs=None, options=None): + """Run the computation defined by `fn` on each TPU replica. + + Executes ops specified by `fn` on each replica. If `args` or `kwargs` have + `tf.distribute.DistributedValues`, such as those produced by a + `tf.distribute.DistributedDataset` from + `tf.distribute.Strategy.experimental_distribute_dataset` or + `tf.distribute.Strategy.distribute_datasets_from_function`, + when `fn` is executed on a particular replica, it will be executed with the + component of `tf.distribute.DistributedValues` that correspond to that + replica. + + `fn` may call `tf.distribute.get_replica_context()` to access members such + as `all_reduce`. + + All arguments in `args` or `kwargs` should either be nest of tensors or + `tf.distribute.DistributedValues` containing tensors or composite tensors. + + Example usage: + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + >>> tf.config.experimental_connect_to_cluster(resolver) + >>> tf.tpu.experimental.initialize_tpu_system(resolver) + >>> strategy = tf.distribute.TPUStrategy(resolver) + >>> @tf.function + ... def run(): + ... def value_fn(value_context): + ... return value_context.num_replicas_in_sync + ... distributed_values = ( + ... strategy.experimental_distribute_values_from_function(value_fn)) + ... def replica_fn(input): + ... return input * 2 + ... return strategy.run(replica_fn, args=(distributed_values,)) + >>> result = run() + + Args: + fn: The function to run. The output must be a `tf.nest` of `Tensor`s. + args: (Optional) Positional arguments to `fn`. + kwargs: (Optional) Keyword arguments to `fn`. + options: (Optional) An instance of `tf.distribute.RunOptions` specifying + the options to run `fn`. + + Returns: + Merged return value of `fn` across replicas. The structure of the return + value is the same as the return value from `fn`. Each element in the + structure can either be `tf.distribute.DistributedValues`, `Tensor` + objects, or `Tensor`s (for example, if running on a single replica). + """ + validate_run_function(fn) + + fn, args, kwargs = _maybe_partial_apply_variables(fn, args, kwargs) + + # Note: the target function is converted to graph even when in Eager mode, + # so autograph is on by default here. + fn = autograph.tf_convert(fn, autograph_ctx.control_status_ctx()) + options = options or distribute_lib.RunOptions() + return self.extended.tpu_run(fn, args, kwargs, options) + + @property + def cluster_resolver(self): + """Returns the cluster resolver associated with this strategy. + + `tf.distribute.TPUStrategy` provides the associated + `tf.distribute.cluster_resolver.ClusterResolver`. If the user provides one + in `__init__`, that instance is returned; if the user does not, a default + `tf.distribute.cluster_resolver.TPUClusterResolver` is provided. + """ + return self.extended._tpu_cluster_resolver # pylint: disable=protected-access + + def experimental_assign_to_logical_device(self, tensor, logical_device_id): + """Adds annotation that `tensor` will be assigned to a logical device. + + This adds an annotation to `tensor` specifying that operations on + `tensor` will be invoked on logical core device id `logical_device_id`. + When model parallelism is used, the default behavior is that all ops + are placed on zero-th logical device. + + ```python + + # Initializing TPU system with 2 logical devices and 4 replicas. + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + tf.config.experimental_connect_to_cluster(resolver) + topology = tf.tpu.experimental.initialize_tpu_system(resolver) + device_assignment = tf.tpu.experimental.DeviceAssignment.build( + topology, + computation_shape=[1, 1, 1, 2], + num_replicas=4) + strategy = tf.distribute.TPUStrategy( + resolver, experimental_device_assignment=device_assignment) + iterator = iter(inputs) + + @tf.function() + def step_fn(inputs): + output = tf.add(inputs, inputs) + + # Add operation will be executed on logical device 0. + output = strategy.experimental_assign_to_logical_device(output, 0) + return output + + strategy.run(step_fn, args=(next(iterator),)) + ``` + + Args: + tensor: Input tensor to annotate. + logical_device_id: Id of the logical core to which the tensor will be + assigned. + + Raises: + ValueError: The logical device id presented is not consistent with total + number of partitions specified by the device assignment or the TPUStrategy + is constructed with `experimental_spmd_xla_partitioning=True`. + + Returns: + Annotated tensor with identical value as `tensor`. + """ + if self.extended._use_spmd_for_xla_partitioning: # pylint: disable=protected-access + raise ValueError( + "Cannot assign a tensor to a logical device in SPMD mode. To disable " + "SPMD, Please construct the TPUStrategy with " + "`experimental_spmd_xla_partitioning=False`") + + num_logical_devices_per_replica = self.extended._tpu_devices.shape[1] # pylint: disable=protected-access + if (logical_device_id < 0 or + logical_device_id >= num_logical_devices_per_replica): + raise ValueError("`logical_core_id` to assign must be lower then total " + "number of logical devices per replica. Received " + "logical device id {} but there are only total of {} " + "logical devices in replica.".format( + logical_device_id, num_logical_devices_per_replica)) + return xla_sharding.assign_device( + tensor, logical_device_id, use_sharding_op=True) + + def experimental_split_to_logical_devices(self, tensor, partition_dimensions): + """Adds annotation that `tensor` will be split across logical devices. + + This adds an annotation to tensor `tensor` specifying that operations on + `tensor` will be split among multiple logical devices. Tensor `tensor` will + be split across dimensions specified by `partition_dimensions`. + The dimensions of `tensor` must be divisible by corresponding value in + `partition_dimensions`. + + For example, for system with 8 logical devices, if `tensor` is an image + tensor with shape (batch_size, width, height, channel) and + `partition_dimensions` is [1, 2, 4, 1], then `tensor` will be split + 2 in width dimension and 4 way in height dimension and the split + tensor values will be fed into 8 logical devices. + + ```python + # Initializing TPU system with 8 logical devices and 1 replica. + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + tf.config.experimental_connect_to_cluster(resolver) + topology = tf.tpu.experimental.initialize_tpu_system(resolver) + device_assignment = tf.tpu.experimental.DeviceAssignment.build( + topology, + computation_shape=[1, 2, 2, 2], + num_replicas=1) + # Construct the TPUStrategy. Since we are going to split the image across + # logical devices, here we set `experimental_spmd_xla_partitioning=True` + # so that the partitioning can be compiled in SPMD mode, which usually + # results in faster compilation and smaller HBM requirement if the size of + # input and activation tensors are much bigger than that of the model + # parameters. Note that this flag is suggested but not a hard requirement + # for `experimental_split_to_logical_devices`. + strategy = tf.distribute.TPUStrategy( + resolver, experimental_device_assignment=device_assignment, + experimental_spmd_xla_partitioning=True) + + iterator = iter(inputs) + + @tf.function() + def step_fn(inputs): + inputs = strategy.experimental_split_to_logical_devices( + inputs, [1, 2, 4, 1]) + + # model() function will be executed on 8 logical devices with `inputs` + # split 2 * 4 ways. + output = model(inputs) + return output + + strategy.run(step_fn, args=(next(iterator),)) + ``` + Args: + tensor: Input tensor to annotate. + partition_dimensions: An unnested list of integers with the size equal to + rank of `tensor` specifying how `tensor` will be partitioned. The + product of all elements in `partition_dimensions` must be equal to the + total number of logical devices per replica. + + Raises: + ValueError: 1) If the size of partition_dimensions does not equal to rank + of `tensor` or 2) if product of elements of `partition_dimensions` does + not match the number of logical devices per replica defined by the + implementing DistributionStrategy's device specification or + 3) if a known size of `tensor` is not divisible by corresponding + value in `partition_dimensions`. + + Returns: + Annotated tensor with identical value as `tensor`. + """ + num_logical_devices_per_replica = self.extended._tpu_devices.shape[1] # pylint: disable=protected-access + num_partition_splits = np.prod(partition_dimensions) + input_shape = tensor.shape + tensor_rank = len(input_shape) + + if tensor_rank != len(partition_dimensions): + raise ValueError("Length of `partition_dimensions` must equal to the " + "rank of `tensor.shape` ({}). Received " + "len(partition_dimensions)={}.".format( + tensor_rank, len(partition_dimensions))) + + for dim_index, dim_size in enumerate(input_shape): + if dim_size is None: + continue + + split_size = partition_dimensions[dim_index] + if dim_size % split_size != 0: + raise ValueError("Tensor shape at `partition_dimensions[{}]` must be " + "divisible by corresponding value specified " + "by `partition_dimensions` ({}). Received: {}.".format( + dim_index, split_size, dim_size)) + + if num_partition_splits != num_logical_devices_per_replica: + raise ValueError( + "The product of `partition_dimensions` should be the same as the " + "number of logical devices (={}). Received `partition_dimensions`={}," + "and their product is {}.".format(num_logical_devices_per_replica, + partition_dimensions, + num_partition_splits)) + + tile_assignment = np.arange(num_partition_splits).reshape( + partition_dimensions) + return xla_sharding.tile(tensor, tile_assignment, use_sharding_op=True) + + def experimental_replicate_to_logical_devices(self, tensor): + """Adds annotation that `tensor` will be replicated to all logical devices. + + This adds an annotation to tensor `tensor` specifying that operations on + `tensor` will be invoked on all logical devices. + + ```python + # Initializing TPU system with 2 logical devices and 4 replicas. + resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + tf.config.experimental_connect_to_cluster(resolver) + topology = tf.tpu.experimental.initialize_tpu_system(resolver) + device_assignment = tf.tpu.experimental.DeviceAssignment.build( + topology, + computation_shape=[1, 1, 1, 2], + num_replicas=4) + strategy = tf.distribute.TPUStrategy( + resolver, experimental_device_assignment=device_assignment) + + iterator = iter(inputs) + + @tf.function() + def step_fn(inputs): + images, labels = inputs + images = strategy.experimental_split_to_logical_devices( + inputs, [1, 2, 4, 1]) + + # model() function will be executed on 8 logical devices with `inputs` + # split 2 * 4 ways. + output = model(inputs) + + # For loss calculation, all logical devices share the same logits + # and labels. + labels = strategy.experimental_replicate_to_logical_devices(labels) + output = strategy.experimental_replicate_to_logical_devices(output) + loss = loss_fn(labels, output) + + return loss + + strategy.run(step_fn, args=(next(iterator),)) + ``` + Args: + tensor: Input tensor to annotate. + + Returns: + Annotated tensor with identical value as `tensor`. + """ + return xla_sharding.replicate(tensor, use_sharding_op=True) + + +@tf_export.tf_export("distribute.experimental.TPUStrategy", v1=[]) +@deprecation.deprecated_endpoints("distribute.experimental.TPUStrategy") +class TPUStrategy(distribute_lib.Strategy): + """Synchronous training on TPUs and TPU Pods. + + To construct a TPUStrategy object, you need to run the + initialization code as below: + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + >>> tf.config.experimental_connect_to_cluster(resolver) + >>> tf.tpu.experimental.initialize_tpu_system(resolver) + >>> strategy = tf.distribute.experimental.TPUStrategy(resolver) + + While using distribution strategies, the variables created within the + strategy's scope will be replicated across all the replicas and can be kept in + sync using all-reduce algorithms. + + To run TF2 programs on TPUs, you can either use `.compile` and + `.fit` APIs in `tf.keras` with TPUStrategy, or write your own customized + training loop by calling `strategy.run` directly. Note that + TPUStrategy doesn't support pure eager execution, so please make sure the + function passed into `strategy.run` is a `tf.function` or + `strategy.run` is called inside a `tf.function` if eager + behavior is enabled. + """ + + def __init__(self, + tpu_cluster_resolver=None, + device_assignment=None): + """Synchronous training in TPU donuts or Pods. + + Args: + tpu_cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, + which provides information about the TPU cluster. + device_assignment: Optional `tf.tpu.experimental.DeviceAssignment` to + specify the placement of replicas on the TPU cluster. + """ + logging.warning( + "`tf.distribute.experimental.TPUStrategy` is deprecated, please use " + "the non-experimental symbol `tf.distribute.TPUStrategy` instead.") + + super().__init__( + TPUExtended( + self, + tpu_cluster_resolver, + device_assignment=device_assignment, + enable_data_reorder=device_assignment is not None, + ) + ) + distribute_lib.distribution_strategy_gauge.get_cell("V2").set("TPUStrategy") + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_workers").set(self.extended.num_hosts) + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_replicas_per_worker").set(self.extended.num_replicas_per_host) + # Packed variable is used to reduce the overhead of function execution. + # For a DistributedVariable, only one variable handle is captured into a + # function graph. It's only supported in eager mode. + self._enable_packed_variable_in_eager_mode = True + + # TODO(cjfj): Modify `_call_for_each_replica` in `TPUExtended` such that this + # can use the default implementation. + # This implementation runs a single step. It does not use infeed or outfeed. + def run(self, fn, args=(), kwargs=None, options=None): + """See base class.""" + validate_run_function(fn) + + fn, args, kwargs = _maybe_partial_apply_variables(fn, args, kwargs) + + # Note: the target function is converted to graph even when in Eager mode, + # so autograph is on by default here. + fn = autograph.tf_convert(fn, autograph_ctx.control_status_ctx()) + options = options or distribute_lib.RunOptions() + return self.extended.tpu_run(fn, args, kwargs, options) + + @property + def cluster_resolver(self): + """Returns the cluster resolver associated with this strategy. + + `tf.distribute.experimental.TPUStrategy` provides the + associated `tf.distribute.cluster_resolver.ClusterResolver`. If the user + provides one in `__init__`, that instance is returned; if the user does + not, a default + `tf.distribute.cluster_resolver.TPUClusterResolver` is provided. + """ + return self.extended._tpu_cluster_resolver # pylint: disable=protected-access + + +@tf_export.tf_export(v1=["distribute.experimental.TPUStrategy"]) +class TPUStrategyV1(distribute_lib.StrategyV1): + """TPU distribution strategy implementation.""" + + def __init__(self, + tpu_cluster_resolver=None, + steps_per_run=None, + device_assignment=None): + """Initializes the TPUStrategy object. + + Args: + tpu_cluster_resolver: A tf.distribute.cluster_resolver.TPUClusterResolver, + which provides information about the TPU cluster. + steps_per_run: Number of steps to run on device before returning to the + host. Note that this can have side-effects on performance, hooks, + metrics, summaries etc. + This parameter is only used when Distribution Strategy is used with + estimator or keras. + device_assignment: Optional `tf.tpu.experimental.DeviceAssignment` to + specify the placement of replicas on the TPU cluster. Currently only + supports the usecase of using a single core within a TPU cluster. + """ + super().__init__(TPUExtended( + self, tpu_cluster_resolver, steps_per_run, device_assignment)) + distribute_lib.distribution_strategy_gauge.get_cell("V1").set("TPUStrategy") + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_workers").set(self.extended.num_hosts) + distribute_lib.distribution_strategy_replica_gauge.get_cell( + "num_replicas_per_worker").set(self.extended.num_replicas_per_host) + # Packed variable is used to reduce the overhead of function execution. + # For a DistributedVariable, only one variable handle is captured into a + # function graph. It's only supported in eager mode. + self._enable_packed_variable_in_eager_mode = True + + @property + def steps_per_run(self): + """DEPRECATED: use .extended.steps_per_run instead.""" + return self._extended.steps_per_run + + # TODO(cjfj): Modify `_call_for_each_replica` in `TPUExtended` such that this + # can use the default implementation. + # This implementation runs a single step. It does not use infeed or outfeed. + def run(self, fn, args=(), kwargs=None, options=None): + """Run `fn` on each replica, with the given arguments. + + Executes ops specified by `fn` on each replica. If `args` or `kwargs` have + "per-replica" values, such as those produced by a "distributed `Dataset`", + when `fn` is executed on a particular replica, it will be executed with the + component of those "per-replica" values that correspond to that replica. + + `fn` may call `tf.distribute.get_replica_context()` to access members such + as `all_reduce`. + + All arguments in `args` or `kwargs` should either be nest of tensors or + per-replica objects containing tensors or composite tensors. + + Users can pass strategy specific options to `options` argument. An example + to enable bucketizing dynamic shapes in `TPUStrategy.run` + is: + + >>> resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='') + >>> tf.config.experimental_connect_to_cluster(resolver) + >>> tf.tpu.experimental.initialize_tpu_system(resolver) + >>> strategy = tf.distribute.experimental.TPUStrategy(resolver) + + >>> options = tf.distribute.RunOptions( + ... experimental_bucketizing_dynamic_shape=True) + + >>> dataset = tf.data.Dataset.range( + ... strategy.num_replicas_in_sync, output_type=dtypes.float32).batch( + ... strategy.num_replicas_in_sync, drop_remainder=True) + >>> input_iterator = iter(strategy.experimental_distribute_dataset(dataset)) + + >>> @tf.function() + ... def step_fn(inputs): + ... output = tf.reduce_sum(inputs) + ... return output + + >>> strategy.run(step_fn, args=(next(input_iterator),), options=options) + + Args: + fn: The function to run. The output must be a `tf.nest` of `Tensor`s. + args: (Optional) Positional arguments to `fn`. + kwargs: (Optional) Keyword arguments to `fn`. + options: (Optional) An instance of `tf.distribute.RunOptions` specifying + the options to run `fn`. + + Returns: + Merged return value of `fn` across replicas. The structure of the return + value is the same as the return value from `fn`. Each element in the + structure can either be "per-replica" `Tensor` objects or `Tensor`s + (for example, if running on a single replica). + """ + validate_run_function(fn) + + fn, args, kwargs = _maybe_partial_apply_variables(fn, args, kwargs) + + fn = autograph.tf_convert(fn, autograph_ctx.control_status_ctx()) + options = options or distribute_lib.RunOptions() + return self.extended.tpu_run(fn, args, kwargs, options) + + +# TODO(josh11b): Switch to V2 when we no longer need to support tf.compat.v1. +class TPUExtended(distribute_lib.StrategyExtendedV1): + """Implementation of TPUStrategy.""" + + def __init__( + self, + container_strategy, + tpu_cluster_resolver=None, + steps_per_run=None, + device_assignment=None, + use_spmd_for_xla_partitioning=False, + enable_data_reorder=False, + ): + super().__init__(container_strategy) + + if tpu_cluster_resolver is None: + tpu_cluster_resolver = tpu_cluster_resolver_lib.TPUClusterResolver("") + + if steps_per_run is None: + # TODO(frankchn): Warn when we are being used by DS/Keras and this is + # not specified. + steps_per_run = 1 + + # `self._tpu_function_cache` is a dict of `tf.function`s, thus if a + # `tf.function` is passed into `strategy.run` in eager mode, the + # `tf.function` won't get retraced. + self._tpu_function_cache = weakref.WeakKeyDictionary() + + self._tpu_cluster_resolver = tpu_cluster_resolver + self._tpu_metadata = self._tpu_cluster_resolver.get_tpu_system_metadata() + self._device_assignment = device_assignment + + tpu_devices_flat = [ + d.name for d in self._tpu_metadata.devices if "device:TPU:" in d.name] + + # `self._tpu_devices` is a two-dimensional NumPy array of strings. It is + # indexed using `[replica_id][logical_device_id]`. + if device_assignment is None: + self._tpu_devices = np.array( + [[d] for d in tpu_devices_flat], dtype=object) + else: + job_name = device_spec.DeviceSpecV2.from_string(tpu_devices_flat[0]).job + + tpu_devices = [] + for replica_id in range(device_assignment.num_replicas): + replica_devices = [] + + for logical_core in range(device_assignment.num_cores_per_replica): + replica_devices.append( + device_util.canonicalize( + device_assignment.tpu_device( + replica=replica_id, + logical_core=logical_core, + job=job_name))) + + tpu_devices.append(replica_devices) + self._tpu_devices = np.array(tpu_devices, dtype=object) + + self._host_device = device_util.get_host_for_device(self._tpu_devices[0][0]) + + # Preload the data onto the TPUs. Currently we always preload onto logical + # device 0 for each replica. + # TODO(cjfj): Create `InputWorkers` lazily, allowing users to place the + # input onto a different logical device? + self._device_input_worker_devices = collections.OrderedDict() + self._host_input_worker_devices = collections.OrderedDict() + for tpu_device in self._tpu_devices[:, 0]: + host_device = device_util.get_host_for_device(tpu_device) + self._device_input_worker_devices.setdefault(host_device, []) + self._device_input_worker_devices[host_device].append(tpu_device) + self._host_input_worker_devices.setdefault(host_device, []) + self._host_input_worker_devices[host_device].append(host_device) + + # Create the replica order based on the assigned device order. + # This replica order will be used to match the IteratorGetNext ops + # with the device assigment. + self._replica_order = ( + self._get_replica_order(self._tpu_devices[:, 0]) + if enable_data_reorder + else None + ) + + # TODO(sourabhbajaj): Remove this once performance of running one step + # at a time is comparable to multiple steps. + self.steps_per_run = steps_per_run + self._require_static_shapes = True + + self.experimental_enable_get_next_as_optional = True + + self._logical_device_stack = [0] + + if context.executing_eagerly(): + # In async remote eager, we want to sync the executors before exiting the + # program. + atexit.register(context.async_wait) + + # Flag to turn on VariablePolicy. Var policy is deprecated because there is + # another effort unifying DistributedVariables (see values_v2.py). SPMD XLA + # partitioning is not implemented for var policies. + # TODO(b/202048882): remove var policy from TPUStrategy. + self._use_var_policy = not use_spmd_for_xla_partitioning + + # Flag to enable XLA SPMD partitioning. + self._use_spmd_for_xla_partitioning = use_spmd_for_xla_partitioning + + self._using_custom_device = False + devices = self._tpu_devices[:, self._logical_device_stack[-1]] + for d in devices: + if context.is_custom_device(d): + self._using_custom_device = True + break + + def _get_replica_order(self, tpu_devices): + """Get the replica order based on the tpu device order. + + For example, if the tpu_devices are: + '/job:worker/replica:0/task:0/device:TPU:0', + '/job:worker/replica:0/task:0/device:TPU:2', + '/job:worker/replica:0/task:1/device:TPU:0', + '/job:worker/replica:0/task:1/device:TPU:2', + '/job:worker/replica:0/task:1/device:TPU:6', + '/job:worker/replica:0/task:1/device:TPU:4', + '/job:worker/replica:0/task:0/device:TPU:6', + '/job:worker/replica:0/task:0/device:TPU:4', + + the returned replica order will be: + [0, 1, 7, 6, 2, 3, 5, 4] + + This replica order will be used to reorder the data returned by the + iterators, + so that they can be placed on the same node as their computation graphs. + + Args: + tpu_devices (List[str]): A list of tpu device names in the order of + replicas. + + Returns: + A list containing the order ids of corresponding TPU devices. + """ + devices_with_ids = [] + for i, tpu_device in enumerate(tpu_devices): + spec = tf_device.DeviceSpec.from_string(tpu_device) + devices_with_ids.append(( + ( + spec.job, + spec.replica, + spec.device_type, + spec.task, + spec.device_index, + ), + i, + )) + return [i for _, i in sorted(devices_with_ids)] + + def _validate_colocate_with_variable(self, colocate_with_variable): + distribute_utils.validate_colocate(colocate_with_variable, self) + + def _make_dataset_iterator(self, dataset): + """Make iterators for each of the TPU hosts.""" + input_workers = input_lib.InputWorkers( + tuple(self._device_input_worker_devices.items())) + return input_lib_v1.DatasetIterator( + dataset, + input_workers, + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync) + + def _make_input_fn_iterator( + self, + input_fn, + replication_mode=distribute_lib.InputReplicationMode.PER_WORKER): + input_contexts = [] + input_workers = input_lib.InputWorkers( + tuple(self._device_input_worker_devices.items())) + num_workers = input_workers.num_workers + for i in range(num_workers): + input_contexts.append( + distribute_lib.InputContext( + num_input_pipelines=num_workers, + input_pipeline_id=i, + num_replicas_in_sync=self._num_replicas_in_sync)) + return input_lib_v1.InputFunctionIterator(input_fn, input_workers, + input_contexts, + self._container_strategy()) + + def _experimental_make_numpy_dataset(self, numpy_input, session): + return numpy_dataset.one_host_numpy_dataset( + numpy_input, numpy_dataset.SingleDevice(self._host_device), + session) + + def _get_input_workers(self, options): + if not options or options.experimental_fetch_to_device: + return input_lib.InputWorkers( + tuple(self._device_input_worker_devices.items())) + else: + return input_lib.InputWorkers( + tuple(self._host_input_worker_devices.items())) + + def _check_spec(self, element_spec): + if isinstance(element_spec, values.PerReplicaSpec): + element_spec = element_spec._component_specs # pylint: disable=protected-access + specs = nest.flatten_with_joined_string_paths(element_spec) + for path, spec in specs: + if isinstance(spec, (sparse_tensor.SparseTensorSpec, + ragged_tensor.RaggedTensorSpec)): + raise ValueError( + "Found tensor {} with spec {}. TPUStrategy does not support " + "distributed datasets with device prefetch when using sparse or " + "ragged tensors. If you intend to use sparse or ragged tensors, " + "please pass a tf.distribute.InputOptions object with " + "experimental_fetch_to_device set to False to your dataset " + "distribution function.".format(path, type(spec))) + + def _experimental_distribute_dataset(self, dataset, options): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + "`experimental_distribute_datasets_from_function`." + ) + if options is None or options.experimental_fetch_to_device: + self._check_spec(dataset.element_spec) + + return input_util.get_distributed_dataset( + dataset, + self._get_input_workers(options), + self._container_strategy(), + num_replicas_in_sync=self._num_replicas_in_sync, + options=options, + replica_order=self._replica_order, + ) + + def _distribute_datasets_from_function(self, dataset_fn, options): + if (options and options.experimental_replication_mode == + distribute_lib.InputReplicationMode.PER_REPLICA): + raise NotImplementedError( + "InputReplicationMode.PER_REPLICA " + "is only supported in " + " `experimental_distribute_datasets_from_function` " + "of tf.distribute.MirroredStrategy") + input_workers = self._get_input_workers(options) + input_contexts = [] + num_workers = input_workers.num_workers + for i in range(num_workers): + input_contexts.append(distribute_lib.InputContext( + num_input_pipelines=num_workers, + input_pipeline_id=i, + num_replicas_in_sync=self._num_replicas_in_sync)) + + distributed_dataset = input_util.get_distributed_datasets_from_function( + dataset_fn, + input_workers, + input_contexts, + self._container_strategy(), + options=options, + replica_order=self._replica_order, + ) + + # We can only check after the dataset_fn is called. + if options is None or options.experimental_fetch_to_device: + self._check_spec(distributed_dataset.element_spec) + return distributed_dataset + + def _experimental_distribute_values_from_function(self, value_fn): + per_replica_values = [] + for replica_id in range(self._num_replicas_in_sync): + per_replica_values.append( + value_fn(distribute_lib.ValueContext(replica_id, + self._num_replicas_in_sync))) + return distribute_utils.regroup(per_replica_values, always_wrap=True) + + # TODO(priyag): Deal with OutOfRange errors once b/111349762 is fixed. + # TODO(sourabhbajaj): Remove the initial_loop_values parameter when we have + # a mechanism to infer the outputs of `fn`. Pending b/110550782. + def _experimental_run_steps_on_iterator( + self, fn, multi_worker_iterator, iterations, initial_loop_values=None): + # Wrap `fn` for repeat. + if initial_loop_values is None: + initial_loop_values = {} + initial_loop_values = nest.flatten(initial_loop_values) + ctx = input_lib.MultiStepContext() + + def run_fn(inputs): + """Single step on the TPU device.""" + fn_result = fn(ctx, inputs) + flat_last_step_outputs = nest.flatten(ctx.last_step_outputs) + if flat_last_step_outputs: + with ops.control_dependencies([fn_result]): + return [array_ops.identity(f) for f in flat_last_step_outputs] + else: + return fn_result + + # We capture the control_flow_context at this point, before we run `fn` + # inside a while_loop and TPU replicate context. This is useful in cases + # where we might need to exit these contexts and get back to the outer + # context to do some things, for e.g. create an op which should be + # evaluated only once at the end of the loop on the host. One such usage + # is in creating metrics' value op. + self._outer_control_flow_context = ( + ops.get_default_graph()._get_control_flow_context()) # pylint: disable=protected-access + + def rewrite_fn(*args): + """The rewritten step fn running on TPU.""" + del args + + per_replica_inputs = multi_worker_iterator.get_next() + replicate_inputs = [] + for replica_id in range(self._num_replicas_in_sync): + select_replica = lambda x: distribute_utils.select_replica( # pylint: disable=g-long-lambda + replica_id, x) # pylint: disable=cell-var-from-loop + replicate_inputs.append((nest.map_structure( + select_replica, per_replica_inputs),)) + + replicate_outputs = tpu.replicate( + run_fn, + replicate_inputs, + device_assignment=self._device_assignment, + xla_options=tpu.XLAOptions(use_spmd_for_xla_partitioning=self + ._use_spmd_for_xla_partitioning)) + # If run_fn has tensor outputs, tpu.replicate returns a list of list. We + # will flatten it in this case. If run_fn has no tensor outputs, + # tpu.replicate returns a list of no_ops, we will keep the output as it + # is. + if isinstance(replicate_outputs[0], list): + replicate_outputs = nest.flatten(replicate_outputs) + + return replicate_outputs + + # TODO(sourabhbajaj): The input to while loop should be based on the + # output type of the step_fn + assert isinstance(initial_loop_values, list) + initial_loop_values = initial_loop_values * self._num_replicas_in_sync + + # Put the while loop op on TPU host 0. + with ops.device(self._host_device): + if self.steps_per_run == 1: + replicate_outputs = rewrite_fn() + else: + replicate_outputs = training_loop.repeat(iterations, rewrite_fn, + initial_loop_values) + + del self._outer_control_flow_context + ctx.run_op = control_flow_ops.group(replicate_outputs) + + if isinstance(replicate_outputs, list): + # Filter out any ops from the outputs, typically this would be the case + # when there were no tensor outputs. + last_step_tensor_outputs = [ + x for x in replicate_outputs if not isinstance(x, ops.Operation) + ] + + # Outputs are currently of the structure (flattened) + # [output0_device0, output1_device0, output2_device0, + # output0_device1, output1_device1, output2_device1, + # ...] + # Convert this to the following structure instead: (grouped by output) + # [[output0_device0, output0_device1], + # [output1_device0, output1_device1], + # [output2_device0, output2_device1]] + output_num = len(last_step_tensor_outputs) // self._num_replicas_in_sync + last_step_tensor_outputs = [ + last_step_tensor_outputs[i::output_num] for i in range(output_num) + ] + else: + # no tensors returned. + last_step_tensor_outputs = [] + + _set_last_step_outputs(ctx, last_step_tensor_outputs) + return ctx + + def _call_for_each_replica(self, fn, args, kwargs): + # TODO(jhseu): Consider making it so call_for_each_replica implies that + # we're in a tpu.rewrite(), and update TPUMirroredVariable accordingly. + with _TPUReplicaContext(self._container_strategy()): + return fn(*args, **kwargs) + + @contextlib.contextmanager + def experimental_logical_device(self, logical_device_id): + """Places variables and ops on the specified logical device.""" + num_logical_devices_per_replica = self._tpu_devices.shape[1] + if logical_device_id >= num_logical_devices_per_replica: + raise ValueError( + "`logical_device_id` not in range (was {}, but there are only {} " + "logical devices per replica).".format( + logical_device_id, num_logical_devices_per_replica)) + + self._logical_device_stack.append(logical_device_id) + try: + if tpu_util.enclosing_tpu_context() is None: + yield + else: + with ops.device(tpu.core(logical_device_id)): + yield + finally: + self._logical_device_stack.pop() + + def _experimental_initialize_system(self): + """Experimental method added to be used by Estimator. + + This is a private method only to be used by Estimator. Other frameworks + should directly be calling `tf.tpu.experimental.initialize_tpu_system` + """ + tpu_cluster_resolver_lib.initialize_tpu_system(self._tpu_cluster_resolver) + + def _create_variable(self, next_creator, **kwargs): + """Create a TPUMirroredVariable. See `DistributionStrategy.scope`.""" + # TODO(bfontain): Replace all uses of skip_mirrored_creator with + # a trivial custom_tpu_variable_creator. + if kwargs.pop("skip_mirrored_creator", False): + return next_creator(**kwargs) + + custom_tpu_variable_creator = kwargs.pop( + "custom_tpu_variable_creator", None + ) + if custom_tpu_variable_creator is not None: + return custom_tpu_variable_creator(next_creator, **kwargs) + + colocate_with = kwargs.pop("colocate_with", None) + if colocate_with is None: + devices = self._tpu_devices[:, self._logical_device_stack[-1]] + elif isinstance(colocate_with, numpy_dataset.SingleDevice): + with ops.device(colocate_with.device): + return next_creator(**kwargs) + else: + devices = colocate_with._devices # pylint: disable=protected-access + + num_replicas, num_cores_per_replica = self._tpu_devices.shape + + def _create_mirrored_tpu_variables(**kwargs): + """Returns a list of `tf.Variable`s. + + The list contains `number_replicas` `tf.Variable`s and can be used to + initialize a `TPUMirroredVariable`. + + Args: + **kwargs: the keyword arguments for creating a variable + """ + initial_value = None + value_list = [] + for i, d in enumerate(devices): + with ops.device(d): + if i == 0: + initial_value = kwargs["initial_value"] + # Note: some v1 code expects variable initializer creation to happen + # inside a init_scope. + with maybe_init_scope(): + initial_value = initial_value() if callable( + initial_value) else initial_value + + if i > 0: + # Give replicas meaningful distinct names: + var0name = value_list[0].name.split(":")[0] + # We append a / to variable names created on replicas with id > 0 to + # ensure that we ignore the name scope and instead use the given + # name as the absolute name of the variable. + kwargs["name"] = "%s/replica_%d/" % (var0name, i) + kwargs["initial_value"] = initial_value + + with context.device_policy(context.DEVICE_PLACEMENT_SILENT): + v = next_creator(**kwargs) + + assert not isinstance(v, tpu_values.TPUMirroredVariable) + value_list.append(v) + return value_list + + def _create_mirrored_tpu_replicated_variables(**kwargs): + """Returns a list of `TPUReplicatedVariable`s. + + The list consists of `num_replicas` `TPUReplicatedVariable`s and can be + used to initialize a `TPUMirroredVariable`. Each `TPUReplicatedVariable` + contains a list of `tf.Variable`s which are replicated to + `num_cores_per_replica` logical cores to enable XLA SPMD compilation. + + Args: + **kwargs: the keyword arguments for creating a variable + """ + initial_value = kwargs["initial_value"] + # Note: some v1 code expects variable initializer creation to happen + # inside a init_scope. + with maybe_init_scope(): + initial_value = initial_value() if callable( + initial_value) else initial_value + + mirrored_replicated_var_list = [] + + for replica_id in range(num_replicas): + replicated_var_list = [] + for logic_core_id in range(num_cores_per_replica): + with ops.device(self._tpu_devices[replica_id][logic_core_id]): + kwargs["initial_value"] = initial_value + v = next_creator(**kwargs) + replicated_var_list.append(v) + replica_name = "{}/r:{}".format(kwargs["name"], replica_id) + tpu_replicated_var = tpu_replicated_variable.TPUReplicatedVariable( + variables=replicated_var_list, name=replica_name) + + mirrored_replicated_var_list.append(tpu_replicated_var) + return mirrored_replicated_var_list + + # TODO(b/271767559): Consider either changing the innermost default_creator + # to uninitialized_variable_creator or only swapping the next_creator with + # uninitialized_variable_creator if the next_creator is the default_creator. + + def uninitialized_variable_creator(**kwargs): + uninitialized_variable = tpu_util.TPUUninitializedVariable(**kwargs) + + self.lazy_variable_tracker.add_uninitialized_var( + uninitialized_variable + ) + setattr(uninitialized_variable, "_lazy_scope", self.lazy_variable_tracker) + return uninitialized_variable + + def _create_uninitialized_mirrored_tpu_variables(**kwargs): + """Returns a list of `tf.Variable`s. + + The list contains `number_replicas` `tf.Variable`s and can be used to + initialize a `TPUMirroredVariable`. + + Args: + **kwargs: the keyword arguments for creating a variable + """ + if kwargs.get("initial_value", None) is None: + return _create_mirrored_tpu_variables(**kwargs) + + value_list = [] + initial_value = None + + for i, d in enumerate(devices): + with ops.device(d): + if i == 0: + initial_value = kwargs.get("initial_value", None) + + with maybe_init_scope(): + if initial_value is not None: + if callable(initial_value): + initial_value = initial_value() + + initial_value = ops.convert_to_tensor( + initial_value, dtype=kwargs.get("dtype", None) + ) + + if i > 0: + # Give replicas meaningful distinct names: + var0name = value_list[0].name.split(":")[0] + # We append a / to variable names created on replicas with id > 0 to + # ensure that we ignore the name scope and instead use the given + # name as the absolute name of the variable. + kwargs["name"] = "%s/replica_%d/" % (var0name, i) + + kwargs["initial_value"] = initial_value + + if kwargs.get("dtype", None) is None: + kwargs["dtype"] = kwargs["initial_value"].dtype + + if kwargs.get("shape", None) is None: + kwargs["shape"] = kwargs["initial_value"].shape + + with context.device_policy(context.DEVICE_PLACEMENT_SILENT): + v = uninitialized_variable_creator(**kwargs) + + assert not isinstance(v, tpu_values.TPUMirroredVariable) + value_list.append(v) + return value_list + + def _create_uninitialized_mirrored_tpu_replicated_variables(**kwargs): + """Returns a list of `TPUReplicatedVariable`s. + + The list consists of `num_replicas` `TPUReplicatedVariable`s and can be + used to initialize a `TPUMirroredVariable`. Each `TPUReplicatedVariable` + contains a list of `tf.Variable`s which are replicated to + `num_cores_per_replica` logical cores to enable XLA SPMD compilation. + + Args: + **kwargs: the keyword arguments for creating a variable + """ + dtype = kwargs.get("dtype", None) + shape = kwargs.get("shape", None) + initial_value = kwargs.get("initial_value", None) + + if initial_value is None: + return _create_mirrored_tpu_replicated_variables(**kwargs) + + with maybe_init_scope(): + if initial_value is not None: + if callable(initial_value): + initial_value = initial_value() + + initial_value = ops.convert_to_tensor( + initial_value, dtype=dtype + ) + + kwargs["initial_value"] = initial_value + + if dtype is None: + kwargs["dtype"] = kwargs["initial_value"].dtype + if shape is None: + kwargs["shape"] = kwargs["initial_value"].shape + + mirrored_replicated_var_list = [] + + for replica_id in range(num_replicas): + replicated_var_list = [] + for logic_core_id in range(num_cores_per_replica): + with ops.device(self._tpu_devices[replica_id][logic_core_id]): + v = uninitialized_variable_creator(**kwargs) + replicated_var_list.append(v) + replica_name = "{}/r:{}".format(kwargs["name"], replica_id) + tpu_replicated_var = tpu_replicated_variable.TPUReplicatedVariable( + variables=replicated_var_list, name=replica_name + ) + + mirrored_replicated_var_list.append(tpu_replicated_var) + return mirrored_replicated_var_list + + if not self._using_custom_device and enable_batch_variable_initialization(): + if self._use_spmd_for_xla_partitioning and num_cores_per_replica > 1: + real_creator = _create_uninitialized_mirrored_tpu_replicated_variables + else: + real_creator = _create_uninitialized_mirrored_tpu_variables + + kwargs["experimental_batch_initialization"] = True + + else: + if self._use_spmd_for_xla_partitioning and num_cores_per_replica > 1: + real_creator = _create_mirrored_tpu_replicated_variables + else: + real_creator = _create_mirrored_tpu_variables + + mirrored_variable = distribute_utils.create_mirrored_variable( + self._container_strategy(), + real_creator, + distribute_utils.TPU_VARIABLE_CLASS_MAPPING, + distribute_utils.TPU_VARIABLE_POLICY_MAPPING, + **kwargs, + ) + + if not self._using_custom_device and enable_batch_variable_initialization(): + setattr(mirrored_variable, "_lazy_scope", self.lazy_variable_tracker) + + return mirrored_variable + + @property + def lazy_variable_tracker(self): + if not getattr(self, "_lazy_variable_tracker", None): + self._lazy_variable_tracker = tpu_util.LazyVariableTracker() + return self._lazy_variable_tracker + + def _resource_creator_scope(self): + + def lookup_creator(next_creator, *args, **kwargs): + host_to_table = collections.OrderedDict() + for host_device in self._device_input_worker_devices.keys(): + with ops.device(host_device): + host_to_table[host_device] = next_creator(*args, **kwargs) + + return values.PerWorkerResource(self._container_strategy(), host_to_table) + + # TODO(b/194362531): Define creator(s) for other resources. + return ops.resource_creator_scope("StaticHashTable", lookup_creator) + + def _gather_to_implementation(self, value, destinations, axis, options): + if not isinstance(value, values.DistributedValues): + return value + + value_list = list(value.values) + # pylint: disable=protected-access + if isinstance( + value, + values.DistributedVariable) and value._packed_variable is not None: + value_list = list( + value._packed_variable.on_device(d) + for d in value._packed_variable.devices) + # pylint: enable=protected-access + + # Currently XLA op by op mode has a limit for the number of inputs for a + # single op, thus we break one `add_n` op into a group of `add_n` ops to + # work around the constraint. + if len(value.values) <= _XLA_OP_BY_OP_INPUTS_LIMIT: + output = array_ops.concat(value_list, axis=axis) + else: + output = array_ops.concat( + value_list[:_XLA_OP_BY_OP_INPUTS_LIMIT], axis=axis) + for i in range(_XLA_OP_BY_OP_INPUTS_LIMIT, len(value_list), + _XLA_OP_BY_OP_INPUTS_LIMIT - 1): + output = array_ops.concat( + [output] + value_list[i:i + _XLA_OP_BY_OP_INPUTS_LIMIT - 1], + axis=axis) + + output = self._broadcast_output(destinations, output) + return output + + def _broadcast_output(self, destinations, output): + devices = cross_device_ops_lib.get_devices_from(destinations) + + if len(devices) == 1: + # If necessary, copy to requested destination. + dest_canonical = device_util.canonicalize(devices[0]) + host_canonical = device_util.canonicalize(self._host_device) + + if dest_canonical != host_canonical: + with ops.device(dest_canonical): + output = array_ops.identity(output) + else: + output = cross_device_ops_lib.simple_broadcast(output, destinations) + + return output + + def _reduce_to(self, reduce_op, value, destinations, options): + if (isinstance(value, values.DistributedValues) or + tensor_util.is_tf_type(value) + ) and tpu_util.enclosing_tpu_context() is not None: + if reduce_op == reduce_util.ReduceOp.MEAN: + # TODO(jhseu): Revisit once we support model-parallelism. + # scalar_mul maintains the type of value: tensor or IndexedSlices. + value = math_ops.scalar_mul((1./self._num_replicas_in_sync), value) + elif reduce_op != reduce_util.ReduceOp.SUM: + raise NotImplementedError( + f"`reduce_op`={reduce_op} is not supported. Currently we only " + "support ReduceOp.SUM and ReduceOp.MEAN in TPUStrategy.") + return tpu_ops.cross_replica_sum(value) + + if not isinstance(value, values.DistributedValues): + # This function handles reducing values that are not PerReplica or + # Mirrored values. For example, the same value could be present on all + # replicas in which case `value` would be a single value or value could + # be 0. + return cross_device_ops_lib.reduce_non_distributed_value( + reduce_op, value, destinations, self._num_replicas_in_sync) + + value_list = value.values + # pylint: disable=protected-access + if isinstance( + value, + values.DistributedVariable) and value._packed_variable is not None: + value_list = tuple( + value._packed_variable.on_device(d) + for d in value._packed_variable.devices) + # pylint: enable=protected-access + + # Currently XLA op by op mode has a limit for the number of inputs for a + # single op, thus we break one `add_n` op into a group of `add_n` ops to + # work around the constraint. + # TODO(cjfj): Detect when it is possible to use `cross_replica_sum`. + if len(value.values) <= _XLA_OP_BY_OP_INPUTS_LIMIT: + output = math_ops.add_n(value_list) + else: + output = array_ops.zeros_like(value_list[0], dtype=value_list[0].dtype) + for i in range(0, len(value_list), _XLA_OP_BY_OP_INPUTS_LIMIT): + output += math_ops.add_n(value_list[i:i + _XLA_OP_BY_OP_INPUTS_LIMIT]) + + if reduce_op == reduce_util.ReduceOp.MEAN: + output *= (1. / len(value_list)) + + output = self._broadcast_output(destinations, output) + return output + + def _update(self, var, fn, args, kwargs, group): + assert isinstance(var, tpu_values.TPUVariableMixin) or isinstance( + var, resource_variable_ops.BaseResourceVariable) + if tpu_util.enclosing_tpu_context() is not None: + if group: + return fn(var, *args, **kwargs) + else: + return (fn(var, *args, **kwargs),) + + # Inside `tf.function`, we don't expand PackedVariable in python as it will + # be expanded later during function instantiation in the runtime. + packed_var = var._packed_variable # pylint: disable=protected-access + if packed_var is not None and not context.executing_eagerly(): + if group: + return fn(packed_var, *args, **kwargs) + else: + return (fn(packed_var, *args, **kwargs),) + + # Otherwise, we revert to MirroredStrategy behavior and update the variable + # on each replica directly. + updates = [] + values_and_devices = [] + if packed_var is not None: + for device in packed_var.devices: + values_and_devices.append((packed_var, device)) + else: + for value in var.values: + values_and_devices.append((value, value.device)) + + if (var.synchronization != variables_lib.VariableSynchronization.ON_READ and + var.aggregation != variables_lib.VariableAggregation.NONE): + distribute_utils.assert_mirrored(args) + distribute_utils.assert_mirrored(kwargs) + for i, value_and_device in enumerate(values_and_devices): + value = value_and_device[0] + device = value_and_device[1] + name = "update_%d" % i + with ops.device(device), \ + distribute_lib.UpdateContext(i), \ + ops.name_scope(name): + # If args and kwargs are not mirrored, the value is returned as is. + updates.append( + fn(value, *distribute_utils.select_replica(i, args), + **distribute_utils.select_replica(i, kwargs))) + return distribute_utils.update_regroup(self, updates, group) + + def read_var(self, var): + assert isinstance(var, tpu_values.TPUVariableMixin) or isinstance( + var, resource_variable_ops.BaseResourceVariable) + return var.read_value() + + def value_container(self, value): + return value + + def _broadcast_to(self, tensor, destinations): + del destinations + # This is both a fast path for Python constants, and a way to delay + # converting Python values to a tensor until we know what type it + # should be converted to. Otherwise we have trouble with: + # global_step.assign_add(1) + # since the `1` gets broadcast as an int32 but global_step is int64. + if isinstance(tensor, (float, int)): + return tensor + if tpu_util.enclosing_tpu_context() is not None: + broadcast_tensor = [tensor for _ in range(self._num_replicas_in_sync)] + result = tpu_ops.all_to_all( + broadcast_tensor, + concat_dimension=0, + split_dimension=0, + split_count=self._num_replicas_in_sync) + + # This uses the broadcasted value from the first replica because the only + # caller of this is for ONLY_FIRST_REPLICA variables aggregation. + return result[0] + return tensor + + @property + def num_hosts(self): + if self._device_assignment is None: + return self._tpu_metadata.num_hosts + + return len(set([self._device_assignment.host_device(r) + for r in range(self._device_assignment.num_replicas)])) + + @property + def num_replicas_per_host(self): + if self._device_assignment is None: + return self._tpu_metadata.num_of_cores_per_host + + # TODO(sourabhbajaj): Remove this method we use inputs and remove infeed + # as the computation of num_replicas_per_host is not a constant + # when using device_assignment. This is a temporary workaround to support + # StatefulRNN as everything is 1 in that case. + # This method needs to take host_id as input for correct computation. + max_models_per_host = (self._tpu_metadata.num_of_cores_per_host // + self._device_assignment.num_cores_per_replica) + return min(self._device_assignment.num_replicas, max_models_per_host) + + @property + def _num_replicas_in_sync(self): + if self._device_assignment is None: + return self._tpu_metadata.num_cores + return self._device_assignment.num_replicas + + @property + def experimental_between_graph(self): + return False + + @property + def experimental_should_init(self): + return True + + @property + def should_checkpoint(self): + return True + + @property + def should_save_summary(self): + return True + + @property + def worker_devices(self): + return tuple(self._tpu_devices[:, self._logical_device_stack[-1]]) + + @property + def parameter_devices(self): + return self.worker_devices + + @property + def tpu_hardware_feature(self): + """Return the `tf.tpu.experimental.HardwareFeature` class.""" + return tpu_hardware_feature.HardwareFeature( + self._tpu_cluster_resolver.tpu_hardware_feature) + + def non_slot_devices(self, var_list): + return self._host_device + + def _update_non_slot(self, colocate_with, fn, args, kwargs, group): + del colocate_with + with ops.device(self._host_device), distribute_lib.UpdateContext(None): + result = fn(*args, **kwargs) + if group: + return result + else: + return nest.map_structure(self._local_results, result) + + def _configure(self, + session_config=None, + cluster_spec=None, + task_type=None, + task_id=None): + del cluster_spec, task_type, task_id + if session_config: + session_config.CopyFrom(self._update_config_proto(session_config)) + + def _update_config_proto(self, config_proto): + updated_config = copy.deepcopy(config_proto) + updated_config.isolate_session_state = True + cluster_spec = self._tpu_cluster_resolver.cluster_spec() + if cluster_spec: + updated_config.cluster_def.CopyFrom(cluster_spec.as_cluster_def()) + return updated_config + + # TODO(priyag): Delete this once all strategies use global batch size. + @property + def _global_batch_size(self): + """`make_dataset_iterator` and `make_numpy_iterator` use global batch size. + + `make_input_fn_iterator` assumes per-replica batching. + + Returns: + Boolean. + """ + return True + + def tpu_run(self, fn, args, kwargs, options=None): + func = self._tpu_function_creator(fn, options) + return func(args, kwargs) + + def _tpu_function_creator(self, fn, options): + if context.executing_eagerly() and fn in self._tpu_function_cache: + return self._tpu_function_cache[fn] + + strategy = self._container_strategy() + + def tpu_function(args, kwargs): + """TF Function used to replicate the user computation.""" + logging.vlog(1, + "`TPUStrategy.run` is called with [args: %s] [kwargs: %s]", + args, kwargs) + + if kwargs is None: + kwargs = {} + + # Used to re-structure flattened output tensors from `tpu.replicate()` + # into a structured format. + result = [[]] + + def replicated_fn(replica_id, replica_args, replica_kwargs): + """Wraps user function to provide replica ID and `Tensor` inputs.""" + with _TPUReplicaContext(strategy, replica_id_in_sync_group=replica_id): + result[0] = fn(*replica_args, **replica_kwargs) + return result[0] + + replicate_inputs = [] # By replica. + for i in range(strategy.num_replicas_in_sync): + replicate_inputs.append( + [constant_op.constant(i, dtype=dtypes.int32), + distribute_utils.select_replica(i, args), + distribute_utils.select_replica(i, kwargs)]) + + # Construct and pass `maximum_shapes` so that we could support dynamic + # shapes using dynamic padder. + if options.experimental_enable_dynamic_batch_size and replicate_inputs: + maximum_shapes = [] + flattened_list = nest.flatten(replicate_inputs[0]) + for input_tensor in flattened_list: + if tensor_util.is_tf_type(input_tensor): + rank = input_tensor.shape.rank + else: + rank = np.ndim(input_tensor) + if rank is None: + raise ValueError( + "input tensor {} to TPUStrategy.run() has unknown rank, " + "which is not allowed".format(input_tensor)) + maximum_shape = tensor_shape.TensorShape([None] * rank) + maximum_shapes.append(maximum_shape) + maximum_shapes = nest.pack_sequence_as(replicate_inputs[0], + maximum_shapes) + else: + maximum_shapes = None + + if options.experimental_bucketizing_dynamic_shape: + padding_spec = tpu.PaddingSpec.POWER_OF_TWO + else: + padding_spec = None + + with strategy.scope(): + xla_options = options.experimental_xla_options or tpu.XLAOptions( + use_spmd_for_xla_partitioning=self._use_spmd_for_xla_partitioning) + replicate_outputs = tpu.replicate( + replicated_fn, + replicate_inputs, + device_assignment=self._device_assignment, + maximum_shapes=maximum_shapes, + padding_spec=padding_spec, + xla_options=xla_options) + + # Remove all no ops that may have been added during 'tpu.replicate()' + filter_ops = lambda x: [o for o in x if not isinstance(o, ops.Operation)] + if isinstance(result[0], list): + result[0] = filter_ops(result[0]) + + # Workaround for `tpu.replicate` behaviour when single `Tensor` returned. + if result[0] is None or isinstance(result[0], ops.Operation): + replicate_outputs = [None] * len(replicate_outputs) + else: + replicate_outputs = [ + nest.pack_sequence_as(result[0], filter_ops(nest.flatten(output))) + for output in replicate_outputs + ] + return distribute_utils.regroup(replicate_outputs) + + if context.executing_eagerly(): + tpu_function = def_function.function(tpu_function) + self._tpu_function_cache[fn] = tpu_function + return tpu_function + + def _in_multi_worker_mode(self): + """Whether this strategy indicates working in multi-worker settings.""" + # TPUStrategy has different distributed training structure that the whole + # cluster should be treated as single worker from higher-level (e.g. Keras) + # library's point of view. + # TODO(rchao): Revisit this as we design a fault-tolerance solution for + # TPUStrategy. + return False + + def _get_local_replica_id(self, replica_id_in_sync_group): + return replica_id_in_sync_group + + +def _make_axis_nonnegative(axis, rank): + # Convert a potentially negative `axis` to a non-negative one. + if isinstance(axis, int): + if axis >= 0: + return axis + else: + return axis + rank + else: + return array_ops.where_v2( + math_ops.greater_equal(axis, 0), + axis, + axis + rank) + + +# List of Tensor dtypes supported by cross_replica_sum(). +_DTYPES_SUPPORTED_BY_CROSS_REPLICA_SUM = ( + dtypes.bfloat16, + dtypes.float16, + dtypes.float32, + dtypes.float64, + dtypes.int32, + dtypes.uint32, +) + + +class _TPUReplicaContext(distribute_lib.ReplicaContext): + """Replication Context class for TPU Strategy.""" + + # TODO(sourabhbajaj): Call for each replica should be updating this. + # TODO(b/118385803): Always properly initialize replica_id. + def __init__(self, strategy, replica_id_in_sync_group=0): + distribute_lib.ReplicaContext.__init__( + self, strategy, replica_id_in_sync_group=replica_id_in_sync_group) + + @property + def devices(self): + distribute_lib.require_replica_context(self) + ds = self._strategy + replica_id = tensor_util.constant_value(self.replica_id_in_sync_group) + + if replica_id is None: # Non-constant `Tensor` inside `tpu.replicate`. + # TODO(cjfj): Return other devices when model parallelism is supported. + return (tpu.core(0),) + else: + return (ds.extended.worker_devices[replica_id],) + + def experimental_logical_device(self, logical_device_id): + """Places variables and ops on the specified logical device.""" + return self.strategy.extended.experimental_logical_device(logical_device_id) + + def _compute_all_gather_output_shape(self, value_shape, value_rank, axis): + if isinstance(value_rank, int): + output_shape = list(value_shape) + output_shape[axis] *= self.num_replicas_in_sync + else: + output_shape = array_ops.where_v2( + math_ops.equal(math_ops.range(value_rank), axis), + value_shape * context.num_replicas_in_sync, + value_shape) + return output_shape + + def all_gather(self, value, axis, experimental_hints=None): + del experimental_hints + for v in nest.flatten(value): + if isinstance(v, indexed_slices.IndexedSlices): + raise NotImplementedError("all_gather does not support IndexedSlices") + + def _all_gather_tensor(value, axis): + value = ops.convert_to_tensor(value) + + # Compute the shape and rank and rank of the input tensor. Use static + # shapes when possible to help with shape inference in graph mode, but + # fall back on dynamic shapes when necessary. + if value.shape.rank is None: + value_rank = array_ops.rank(value) + value_shape = array_ops.shape(value) + else: + value_rank = value.shape.rank + value_shape = value.shape.as_list() + value_shape_tensor = array_ops.shape(value) + for i in range(len(value_shape)): + if value_shape[i] is None: + value_shape[i] = value_shape_tensor[i] + + # In the code below, we will insert a new "replica" dimension immediately + # *before* `axis`. To ensure that it's inserted before and not after, we + # must make `axis` non-negative. + axis = _make_axis_nonnegative(axis, value_rank) + + # Create a list or 1D int Tensor such as + # [1, 1, ..., 1, num_replicas_in_sync, 1, ..., 1], + # which is equal to `num_replicas_in_sync` at index `axis` + # and is equal to 1 everywhere else. + if isinstance(value_rank, int): + replica_broadcast_shape = [1] * (value_rank + 1) + replica_broadcast_shape[axis] = self.num_replicas_in_sync + else: + replica_broadcast_shape = array_ops.where_v2( + math_ops.equal(math_ops.range(value_rank+1), axis), + self.num_replicas_in_sync, + 1) + + output_shape = self._compute_all_gather_output_shape( + value_shape, value_rank, axis) + + if value.dtype in _DTYPES_SUPPORTED_BY_CROSS_REPLICA_SUM: + # optimized all_gather implementation based on cross_replica_sum(). + replica_id_mask = array_ops.one_hot( + self.replica_id_in_sync_group, self.num_replicas_in_sync) + replica_id_mask = array_ops.reshape( + replica_id_mask, replica_broadcast_shape) + replica_id_mask = math_ops.cast(replica_id_mask, value.dtype) + + gathered_value = array_ops.expand_dims(value, axis) * replica_id_mask + gathered_value = self.all_reduce( + reduce_util.ReduceOp.SUM, gathered_value) + return array_ops.reshape(gathered_value, output_shape) + else: + # value.dtype isn't supported by cross_replica_sum(), so we fall back + # on a less efficient implementation based on all_to_all(). + + # The underlying AllToAllOp first do a split of the input value and then + # cross-replica communication and concatenation of the result. So we + # concatenate the local tensor here first. + inputs = array_ops.expand_dims(value, axis=axis) + inputs = array_ops.tile(inputs, replica_broadcast_shape) + unordered_output = tpu_ops.all_to_all( + inputs, + concat_dimension=axis, + split_dimension=axis, + split_count=self.num_replicas_in_sync) + + # Re-order since xla.replica_id and ReplicaContext.replica_id mismatch. + # Start by computing a permutation -- a 1D Tensor which maps + # tensor[xla.replica_id] = ReplicaContext.replica_id + concat_replica_id = array_ops.reshape( + self.replica_id_in_sync_group, [1]) + concat_replica_id = array_ops.tile( + concat_replica_id, [self.num_replicas_in_sync]) + xla_to_replica_context_id = tpu_ops.all_to_all( + concat_replica_id, + concat_dimension=0, + split_dimension=0, + split_count=self.num_replicas_in_sync) + + # Now invert the mapping to get + # tensor[ReplicaContext.replica_id] = xla.replica_id + replica_context_to_xla_id = math_ops.argmax( + array_ops.one_hot(xla_to_replica_context_id, + self.num_replicas_in_sync), + axis=0) + + # Reorder the output elements so that they're sorted based on + # ReplicaContext.replica_id instead of xla.replica_id. + sorted_with_extra_dim = array_ops.gather( + unordered_output, replica_context_to_xla_id, axis=axis) + return array_ops.reshape(sorted_with_extra_dim, output_shape) + + ys = [_all_gather_tensor(t, axis=axis) for t in nest.flatten(value)] + return nest.pack_sequence_as(value, ys) + + +def _set_last_step_outputs(ctx, last_step_tensor_outputs): + """Sets the last step outputs on the given context.""" + # Convert replicate_outputs to the original dict structure of + # last_step_outputs. + last_step_tensor_outputs_dict = nest.pack_sequence_as( + ctx.last_step_outputs, last_step_tensor_outputs) + + for name, reduce_op in ctx._last_step_outputs_reduce_ops.items(): # pylint: disable=protected-access + output = last_step_tensor_outputs_dict[name] + # For outputs that aren't reduced, return a PerReplica of all values. Else + # take the first value from the list as each value should be the same. + if reduce_op is None: + last_step_tensor_outputs_dict[name] = values.PerReplica(output) + else: + # TODO(priyag): Should this return the element or a list with 1 element + last_step_tensor_outputs_dict[name] = output[0] + ctx._set_last_step_outputs(last_step_tensor_outputs_dict) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3167e069df3603c534084966909ada957b10ef18 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_util.py @@ -0,0 +1,192 @@ +# 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. +# ============================================================================== +"""Utility functions for TPU.""" + +import contextlib + +from tensorflow.python.distribute import packed_distributed_variable as packed +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.tpu import tpu_replication + + +def enclosing_tpu_context(): + """Returns the TPUReplicateContext, which exists inside a tpu.rewrite().""" + return enclosing_tpu_context_and_graph()[0] + + +def enclosing_tpu_context_and_graph(): + """Returns the TPUReplicateContext which exists inside a tpu.rewrite(), and its associated graph.""" + graph = ops.get_default_graph() + while graph is not None: + ctx = graph._get_control_flow_context() # pylint: disable=protected-access + while ctx is not None: + if isinstance(ctx, tpu_replication.TPUReplicateContext): + return ctx, graph + ctx = ctx.outer_context + # This may be a FuncGraph due to defuns or v2 control flow. We need to + # find the original graph with the XLAControlFlowContext. + graph = getattr(graph, "outer_graph", None) + return None, None + + +@contextlib.contextmanager +def outside_or_skip_tpu_context(): + """Returns a context manager that skips current enclosing context if there is any.""" + ctx, graph = enclosing_tpu_context_and_graph() + if ctx is None: + yield + else: + saved_context = graph._get_control_flow_context() # pylint: disable=protected-access + graph._set_control_flow_context(ctx.outer_context) # pylint: disable=protected-access + yield + graph._set_control_flow_context(saved_context) # pylint: disable=protected-access + + +@contextlib.contextmanager +def _maybe_enter_graph(tensor): + # Note: might have an eager tensor but not be executing eagerly when + # building functions. + if (context.executing_eagerly() or isinstance(tensor, ops.EagerTensor) or + ops.has_default_graph()): + yield + else: + with tensor.graph.as_default(): + yield + + +@contextlib.contextmanager +def _maybe_on_device(var): + # Add a device scope for packed variables. + if isinstance(var, packed.PackedVarAndDevice): + with ops.device(var.device): + yield + else: + yield + + +def make_raw_assign_fn(raw_assign_fn, use_handle=True): + """Wrap `raw_assign_fn` with the proper graph context and device scope. + + Args: + raw_assign_fn: the function to be wrapped. + use_handle: if True, the `raw_assign_fn` will be applied to the handle of a + variable; otherwise it will be applied to the variable itself. + + Returns: + The wrapped function. + """ + + def assign_fn(var, value, use_locking=False, name=None, read_value=True): + del use_locking # Unused. + + handle = var.handle if use_handle else var + with _maybe_enter_graph(handle), _maybe_on_device(var): + op = raw_assign_fn( + handle, ops.convert_to_tensor(value, dtype=var.dtype), name=name) + with ops.control_dependencies([op]): + if read_value: + return var._read_variable_op() if use_handle else var.read_value() # pylint: disable=protected-access + else: + return op + + return assign_fn + + +def make_raw_scatter_xxx_fn(raw_scatter_xxx_fn): + """Wrap `raw_scatter_xxx_fn` so that it can be called w/ and w/o packed handle.""" + + def scatter_xxx_fn(var, sparse_delta, use_locking=False, name=None): # pylint: disable=missing-docstring + del use_locking # Unused. + + handle = var.handle + with _maybe_enter_graph(handle), _maybe_on_device(var): + op = raw_scatter_xxx_fn( + handle, + sparse_delta.indices, + ops.convert_to_tensor(sparse_delta.values, var.dtype), + name=name) + with ops.control_dependencies([op]): + return var._read_variable_op() # pylint: disable=protected-access + + return scatter_xxx_fn + + +class LazyVariableTracker(object): + """Class to track uninitialized lazy variables.""" + + def __init__(self): + self._uninitialized_var_list = [] + + def initialize_all(self): + """Initialize all uninitialized lazy variables stored in scope.""" + + def assign_function(uninitialized_var_list): + for var in uninitialized_var_list: + val = var._initial_value # pylint: disable=protected-access + packed_var = getattr(var, "_packed_var", None) + handle = getattr(packed_var, "packed_handle", var.handle) + + with ops.device(handle.device): + resource_variable_ops.AssignVariableOp(resource=handle, value=val) + return constant_op.constant([]) + + assign_tf_function = def_function.function( + assign_function, autograph=False, jit_compile=False,) + + with ops.init_scope(): + if len(self._uninitialized_var_list) > 1: + assign_tf_function(self._uninitialized_var_list) + else: + assign_function(self._uninitialized_var_list) + + self._uninitialized_var_list = [] + + def add_uninitialized_var(self, var): + self._uninitialized_var_list.append(var) + + +class TPUUninitializedVariable(resource_variable_ops.UninitializedVariable): + """UninitializedVariable component for TPU. + + Sometimes user might assign (different values) to a single component of a + mirrored TPU variable. Thus we need to initialize_all when the assign* or read + is invoked on a single component. + """ + + def read_value(self): + self._lazy_scope.initialize_all() + return super().read_value() + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + self._lazy_scope.initialize_all() + return super().assign_sub( + delta, use_locking=use_locking, name=name, read_value=read_value + ) + + def assign(self, value, use_locking=None, name=None, read_value=True): + self._lazy_scope.initialize_all() + return super().assign( + value, use_locking=use_locking, name=name, read_value=read_value + ) + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + self._lazy_scope.initialize_all() + return super().assign_add( + delta, use_locking=use_locking, name=name, read_value=read_value + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_values.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_values.py new file mode 100644 index 0000000000000000000000000000000000000000..83efe9bf7fadc54bb2123afc64a5e4d34ded4d48 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/tpu_values.py @@ -0,0 +1,601 @@ +# 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. +# ============================================================================== +"""Various classes representing TPU distributed values. + +Note that the tests are in values_test.py . + +""" + +from tensorflow.python.distribute import packed_distributed_variable as packed +from tensorflow.python.distribute import tpu_replicated_variable +from tensorflow.python.distribute import tpu_util +from tensorflow.python.distribute import values +from tensorflow.python.distribute import values_util +from tensorflow.python.eager import context +from tensorflow.python.eager import tape +from tensorflow.python.framework import ops +from tensorflow.python.ops import gen_resource_variable_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_scope + + +_scatter_error_msg = ("{op_name} is only supported for distributed " + "variable (variable created within certain " + "`tf.distribute.Strategy` scope) with NONE " + " aggregation, got: {aggregation}.") + + +class TPUVariableMixin(object): + """Mixin for TPU variables.""" + + def __init__(self, *args, **kwargs): + super(TPUVariableMixin, self).__init__(*args, **kwargs) + + # Handle ID is needed for `get_replicated_var_handle` to cache the variables + # correctly since in eager mode different variables can have the same name. + if ops.executing_eagerly_outside_functions(): + self._handle_id = self._common_name + "_" + str(id(self._primary)) + else: + self._handle_id = self._common_name + + def __getattr__(self, name): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUVariableMixin, self).__getattr__(name) + else: + raise AttributeError( + f"`TPUVariableMixin.{name}` not accessible within a TPU context.") + + def get(self): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUVariableMixin, self).get() + else: + raise NotImplementedError( + "`TPUVariableMixin.get()` is not supported within a TPU context.") + + def _get_as_operand(self): + return self.read_value() + + @property + def handle(self): + """The handle by which this variable can be accessed.""" + # If we're in a tpu.rewrite(), return the replicated handle. + tpu_context = tpu_util.enclosing_tpu_context() + if tpu_context is None or context.executing_eagerly(): + var = self._get_on_device_or_primary() + if isinstance(var, packed.PackedVarAndDevice): + return var.on_device_handle() + else: + return var.handle + else: + is_packed = self._packed_var is not None + val = self._values + if is_packed: + val = [self._packed_var] + + return tpu_context.get_replicated_var_handle(self._common_name, + self._handle_id, val, + self._is_mirrored(), + is_packed) + + @property + def device(self): + return self.handle.device + + def _read_variable_op(self): + """Reads the value of this variable.""" + if self.trainable: + tape.variable_accessed(self) + + handle = self.handle + if getattr(handle, "is_packed", False): + # Add a device scope for a packed variable handle. + with ops.device(self._get_on_device_or_primary().device): + return gen_resource_variable_ops.read_variable_op(handle, self.dtype) + else: + return gen_resource_variable_ops.read_variable_op(handle, self.dtype) + + def read_value(self): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUVariableMixin, self).read_value() + else: + return self._read_variable_op() + + def value(self): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUVariableMixin, self).value() + else: + return self._read_variable_op() + + def _as_graph_element(self): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUVariableMixin, self)._as_graph_element() # pylint: disable=protected-access + else: + return None + + @property + def op(self): + if values_util.is_saving_non_distributed(): + return self._primary.op + return values.DistributedVarOp(self._primary.op.name, + self._primary.op.graph, + self._primary.op.traceback, + self._primary.op.type) + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + """Converts a variable to a tensor.""" + # pylint: disable=protected-access + if tpu_util.enclosing_tpu_context() is None: + return super(TPUVariableMixin, self)._dense_var_to_tensor( + dtype=dtype, name=name, as_ref=as_ref) + # pylint: enable=protected-access + elif dtype is not None and dtype != self.dtype: + return math_ops.cast(self.read_value(), dtype) + else: + return self.handle if as_ref else self.read_value() + + +class TPUDistributedVariable(TPUVariableMixin, values.DistributedVariable): + """DistributedVariable subclass for TPUStrategy.""" + + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign_sub(value, use_locking, name, read_value) + return self._policy.assign_sub( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign_add(value, use_locking, name, read_value) + return self._policy.assign_add( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign(value, use_locking, name, read_value) + return self._policy.assign( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_sub(sparse_delta, use_locking, name) + return self._policy.scatter_sub( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_add(sparse_delta, use_locking, name) + return self._policy.scatter_add( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_mul(sparse_delta, use_locking, name) + return self._policy.scatter_mul( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_div(sparse_delta, use_locking, name) + return self._policy.scatter_div( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_min(sparse_delta, use_locking, name) + return self._policy.scatter_min( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_max(sparse_delta, use_locking, name) + return self._policy.scatter_max( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_update(sparse_delta, use_locking, name) + return self._policy.scatter_update( + self, sparse_delta, use_locking=use_locking, name=name) + + +class TPUMirroredVariable(TPUVariableMixin, values.MirroredVariable): + """Holds a map from replica to TPU variables whose values are kept in sync.""" + + def _is_replicated_or_sharded_to_logical_cores(self): + """Returns whether each of the underlying variables is replicated or sharded to logical cores. + + If True, the handles of the underlying variables are not available outside a + TPU context. + """ + return isinstance(self._primary, + tpu_replicated_variable.TPUReplicatedVariable) + + @property + def device(self): + if (self._is_replicated_or_sharded_to_logical_cores() and + tpu_util.enclosing_tpu_context() is None): + return self._primary.device + return super(TPUMirroredVariable, self).device + + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + tpu_context = tpu_util.enclosing_tpu_context() + if (self._is_replicated_or_sharded_to_logical_cores() and + tpu_context is None): + assign_sub_fn = lambda v, *a, **ka: v.assign_sub(*a, **ka) + return self._update( + update_fn=assign_sub_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + if (tpu_context and + self.aggregation == variable_scope.VariableAggregation.NONE): + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_sub_variable_op)( + self, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + return assign_sub( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + tpu_context = tpu_util.enclosing_tpu_context() + if (self._is_replicated_or_sharded_to_logical_cores() and + tpu_context is None): + assign_add_fn = lambda v, *a, **ka: v.assign_add(*a, **ka) + return self._update( + update_fn=assign_add_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + if (tpu_context and + self.aggregation == variable_scope.VariableAggregation.NONE): + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_add_variable_op)( + self, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + return assign_add( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign(self, value, use_locking=False, name=None, read_value=True): + tpu_context = tpu_util.enclosing_tpu_context() + if (self._is_replicated_or_sharded_to_logical_cores() and + tpu_context is None): + assign_fn = lambda v, *a, **ka: v.assign(*a, **ka) + return self._update( + update_fn=assign_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + if (tpu_util.enclosing_tpu_context() and + self.aggregation == variable_scope.VariableAggregation.NONE): + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_variable_op)( + self, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + return assign( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def scatter_sub(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_sub(*args, **kwargs) + raise NotImplementedError + + def scatter_add(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_add(*args, **kwargs) + raise NotImplementedError + + def scatter_max(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_max(*args, **kwargs) + raise NotImplementedError + + def scatter_min(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_min(*args, **kwargs) + raise NotImplementedError + + def scatter_mul(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_mul(*args, **kwargs) + raise NotImplementedError + + def scatter_div(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_div(*args, **kwargs) + raise NotImplementedError + + def scatter_update(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_update(*args, **kwargs) + raise NotImplementedError + + +class TPULazyDistributedVariable(TPUDistributedVariable): + """TPU Mirrored variable to be initialized lazily in a batch.""" + + def _initialize_if_uninitialized(self): + if getattr(self, "_is_lazily_initialized", False): + return + self._lazy_scope.initialize_all() + + self._is_lazily_initialized = True + + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + self._initialize_if_uninitialized() + return super().assign_sub( + value, use_locking, name, read_value + ) + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + self._initialize_if_uninitialized() + return super().assign_add( + value, use_locking, name, read_value + ) + + def assign(self, value, use_locking=False, name=None, read_value=True): + self._initialize_if_uninitialized() + + return super().assign( + value, use_locking, name, read_value + ) + + def read_value(self): + self._initialize_if_uninitialized() + return super().read_value() + + +class TPUSyncOnReadVariable(TPUVariableMixin, values.SyncOnReadVariable): + """Holds a map from replica to variables whose values are reduced on save.""" + + def assign_sub(self, *args, **kwargs): + if tpu_util.enclosing_tpu_context() is None: + return values.SyncOnReadVariable.assign_sub(self, *args, **kwargs) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_sub_variable_op)(self, *args, + **kwargs) + + def assign_add(self, *args, **kwargs): + if tpu_util.enclosing_tpu_context() is None: + return values.SyncOnReadVariable.assign_add(self, *args, **kwargs) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_add_variable_op)(self, *args, + **kwargs) + + def assign(self, *args, **kwargs): + if tpu_util.enclosing_tpu_context() is None: + return values.SyncOnReadVariable.assign(self, *args, **kwargs) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_variable_op)(self, *args, **kwargs) + + +# Common method between OnWrite and Mirrored variables. +def assign_sub(var, value, use_locking=False, name=None, read_value=True): + assign_sub_fn = tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_sub_variable_op) + return var._update( # pylint: disable=protected-access + update_fn=assign_sub_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + +def assign_add(var, value, use_locking=False, name=None, read_value=True): + assign_add_fn = tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_add_variable_op) + return var._update( # pylint: disable=protected-access + update_fn=assign_add_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + +def assign(var, value, use_locking=False, name=None, read_value=True): + assign_fn = tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_variable_op) + return var._update( # pylint: disable=protected-access + update_fn=assign_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + +class TPUOnWritePolicy(values.OnWritePolicy): + """Policy defined for `tf.VariableSynchronization.ON_WRITE` synchronization. + + This policy is created when `synchronization` is set to + `tf.VariableSynchronization.AUTO` or `tf.VariableSynchronization.ON_WRITE`. + """ + + def assign_sub(self, + var, + value, + use_locking=False, + name=None, + read_value=True): + if (tpu_util.enclosing_tpu_context() and + var.aggregation == variable_scope.VariableAggregation.NONE): + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_sub_variable_op)( + var, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + return assign_sub( + var, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign_add(self, + var, + value, + use_locking=False, + name=None, + read_value=True): + if (tpu_util.enclosing_tpu_context() and + var.aggregation == variable_scope.VariableAggregation.NONE): + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_add_variable_op)( + var, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + return assign_add( + var, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign(self, var, value, use_locking=False, name=None, read_value=True): + if (tpu_util.enclosing_tpu_context() and + var.aggregation == variable_scope.VariableAggregation.NONE): + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_variable_op)( + var, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + return assign( + var, value, use_locking=use_locking, name=name, read_value=read_value) + + def _scatter_xxx(self, + raw_scater_xxx_fn, + op_name, + var, + sparse_delta, + use_locking=False, + name=None): + scater_xxx_fn = tpu_util.make_raw_scatter_xxx_fn(raw_scater_xxx_fn) + if tpu_util.enclosing_tpu_context(): + if self._aggregation != variable_scope.VariableAggregation.NONE: + raise NotImplementedError( + _scatter_error_msg.format( + op_name=op_name, aggregation=self._aggregation)) + return scater_xxx_fn( + var, sparse_delta=sparse_delta, use_locking=use_locking, name=name) + else: + return var._update( # pylint: disable=protected-access + update_fn=scater_xxx_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + def scatter_sub(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_sub, + "scatter_sub", var, sparse_delta, use_locking, + name) + + def scatter_add(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_add, + "scatter_add", var, sparse_delta, use_locking, + name) + + def scatter_max(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_max, + "scatter_max", var, sparse_delta, use_locking, + name) + + def scatter_min(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_min, + "scatter_min", var, sparse_delta, use_locking, + name) + + def scatter_mul(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_mul, + "scatter_mul", var, sparse_delta, use_locking, + name) + + def scatter_div(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_div, + "scatter_div", var, sparse_delta, use_locking, + name) + + def scatter_update(self, var, sparse_delta, use_locking=False, name=None): + return self._scatter_xxx(gen_resource_variable_ops.resource_scatter_update, + "scatter_update", var, sparse_delta, use_locking, + name) + + +class TPUOnReadPolicy(values.OnReadPolicy): + """Policy defined for `tf.VariableSynchronization.ON_READ` synchronization. + + This policy is created when `synchronization` is set to + `tf.VariableSynchronization.ON_READ` and `aggregation` is set to any of the + values allowed by the `tf.VariableAggregation` enum such as `NONE`, `SUM`, + `MEAN` or `ONLY_FIRST_REPLICA`when creating a `tf.Variable` in `tf.distribute` + scope. + """ + + def assign_sub(self, var, *args, **kwargs): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUOnReadPolicy, self).assign_sub(var, *args, **kwargs) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_sub_variable_op)(var, *args, + **kwargs) + + def assign_add(self, var, *args, **kwargs): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUOnReadPolicy, self).assign_add(var, *args, **kwargs) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_add_variable_op)(var, *args, + **kwargs) + + def assign(self, var, *args, **kwargs): + if tpu_util.enclosing_tpu_context() is None: + return super(TPUOnReadPolicy, self).assign(var, *args, **kwargs) + else: + return tpu_util.make_raw_assign_fn( + gen_resource_variable_ops.assign_variable_op)(var, *args, **kwargs) + + def scatter_sub(self, *args, **kwargs): + raise NotImplementedError + + def scatter_add(self, *args, **kwargs): + raise NotImplementedError + + def scatter_max(self, *args, **kwargs): + raise NotImplementedError + + def scatter_min(self, *args, **kwargs): + raise NotImplementedError + + def scatter_mul(self, *args, **kwargs): + raise NotImplementedError + + def scatter_div(self, *args, **kwargs): + raise NotImplementedError + + def scatter_update(self, *args, **kwargs): + raise NotImplementedError diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/all_reduce.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/all_reduce.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1e14413b745be5ee336ae7c560f14f42a614ad --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/all_reduce.py @@ -0,0 +1,862 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Utilities to construct a TF subgraph implementing distributed All-Reduce.""" + +import collections +import math + +from tensorflow.python.framework import device as device_lib +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nccl_ops + + +def _flatten_tensors(tensors): + """Check tensors for isomorphism and flatten. + + Args: + tensors: list of `tf.Tensor` which must all have the same shape. + + Returns: + tensors: a list of `tf.Tensor` which are flattened (1D) views of tensors + shape: the original shape of each element of input tensors + + Raises: + ValueError: tensors are empty or non-isomorphic or have unknown shape. + """ + if not tensors: + raise ValueError("tensors cannot be empty") + shape = tensors[0].shape + for tensor in tensors: + shape = shape.merge_with(tensor.shape) + if not shape.is_fully_defined(): + raise ValueError("Tensors must have statically known shape.") + if len(shape) != 1: + reshaped = [] + for t in tensors: + with ops.colocate_with(t): + reshaped.append(array_ops.reshape(t, [-1])) + tensors = reshaped + return tensors, shape + + +def _reshape_tensors(tensors, shape): + """Reshape tensors flattened by _flatten_tensors. + + Args: + tensors: list of `tf.Tensor` of identical length 1D tensors. + shape: list of integers describing the desired shape. Product of + the elements must equal the length of each tensor. + + Returns: + list of `tf.Tensor` which are the reshaped inputs. + """ + reshaped = [] + for t in tensors: + with ops.colocate_with(t): + reshaped.append(array_ops.reshape(t, shape)) + return reshaped + + +def _padded_split(tensor, pieces): + """Like split for 1D tensors but pads-out case where len % pieces != 0. + + Args: + tensor: `tf.Tensor` that must be 1D. + pieces: a positive integer specifying the number of pieces into which + tensor should be split. + + Returns: + list of `tf.Tensor` of length pieces, which hold the values of + thin input tensor, in order. The final tensor may + be zero-padded on the end to make its size equal to those of all + of the other tensors. + + Raises: + ValueError: The input tensor is not 1D. + """ + shape = tensor.shape + if 1 != len(shape): + raise ValueError("input tensor must be 1D") + tensor_len = shape.dims[0].value + with ops.colocate_with(tensor): + if tensor_len % pieces != 0: + # pad to an even length + chunk_size = 1 + tensor_len // pieces + if pieces > tensor_len: + # This is an edge case that should not come up in practice, + # i.e. a different reduction algorithm would be better, + # but we'll make it work just for completeness. + pad_len = pieces - tensor_len + extended_whole = array_ops.concat( + [tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0) + parts = array_ops.split(extended_whole, pieces) + return parts, pad_len + elif (pieces - 1) * chunk_size >= tensor_len: + # Another edge case of limited real interest. + pad_len = (pieces * chunk_size) % tensor_len + extended_whole = array_ops.concat( + [tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0) + parts = array_ops.split(extended_whole, pieces) + return parts, pad_len + else: + last_chunk_size = tensor_len - (pieces - 1) * chunk_size + pad_len = chunk_size - last_chunk_size + piece_lens = [chunk_size for _ in range(pieces - 1)] + [last_chunk_size] + parts = array_ops.split(tensor, piece_lens) + parts[-1] = array_ops.concat( + [parts[-1], array_ops.zeros([pad_len], dtype=tensor.dtype)], 0) + return parts, pad_len + else: + return array_ops.split(tensor, pieces), 0 + + +def _strip_padding(tensors, pad_len): + """Strip the suffix padding added by _padded_split. + + Args: + tensors: list of `tf.Tensor` of identical length 1D tensors. + pad_len: number of elements to be stripped from the end of each tensor. + + Returns: + list of `tf.Tensor` which are the stripped inputs. + + Raises: + ValueError: tensors must be a non-empty list of 1D tensors, and + each must be longer than pad_len. + """ + if not tensors: + raise ValueError("tensors cannot be empty") + shape = tensors[0].shape + if len(shape) > 1: + raise ValueError("tensors must be 1D") + prefix_len = int(shape[0] - pad_len) + if prefix_len < 0: + raise ValueError("pad_len longer than tensor") + stripped = [] + for t in tensors: + with ops.colocate_with(t): + stripped.append(array_ops.slice(t, [0], [prefix_len])) + return stripped + + +def _ragged_split(tensor, pieces): + """Like split for 1D tensors but allows case where len % pieces != 0. + + Args: + tensor: `tf.Tensor` that must be 1D. + pieces: a positive integer specifying the number of pieces into which + tensor should be split. + + Returns: + list of `tf.Tensor` of length pieces, which hold the values of + the input tensor, in order. The final tensor may be shorter + than the others, which will all be of equal length. + + Raises: + ValueError: input tensor must be 1D. + """ + shape = tensor.shape + if 1 != len(shape): + raise ValueError("input tensor must be 1D") + tensor_len = shape.dims[0].value + chunk_size = tensor_len // pieces + with ops.colocate_with(tensor): + if tensor_len != (pieces * chunk_size): + # last piece will be short + assert pieces > 1 + last_chunk_size = tensor_len - ((pieces - 1) * chunk_size) + assert last_chunk_size > 0 + piece_lens = [chunk_size for _ in range(pieces - 1)] + [last_chunk_size] + return array_ops.split(tensor, piece_lens) + else: + return array_ops.split(tensor, pieces) + + +def _ring_permutations(num_workers, num_subchunks, gpu_perm): + """"Generate an array of device index arrays, one for each subchunk. + + In the basic ring reduction algorithm there are size(T)/num_devices + data chunks and each device process one chunk per tick, i.e. sending + one chunk and receiving one chunk. The idea of subchunking is that + each device processes num_subchunks smaller data regions per tick, + and the ring rank permutation is different for each subchunk index + so that a device is potentially sending to and receiving from + num_subchunks different other devices at each tick. Where multiple + independent data channels exist between devices, this strategy + supplies a method of using them in parallel. + + Args: + num_workers: number of worker tasks + num_subchunks: number of subchunks into which to divide each per-GPU chunk. + gpu_perm: an array of integers in [0, num_gpus-1] giving the default + ring order of GPUs at each worker. Other permutations will be generated + by rotating this array and splicing together per-worker instances. + + Raises: + ValueError: the number of subchunks may not exceed the number of GPUs. + + Returns: + pred_by_s_d: list of lists that maps (by index) from (subchunk, dev) to + preceding device in the permutation for that subchunk. The + device index of GPU i at worker j is i + (j * num_gpus). + rank_by_s_d: list of lists that maps (by index) from (subchunk, dev) to + local rank of device d in the permutation for that subchunk. + """ + num_gpus = len(gpu_perm) + devices = num_workers * num_gpus + if devices == 0: + return [], [] + if num_subchunks > num_gpus: + raise ValueError( + "num_subchunks %d must be <= num_gpus %d" % (num_subchunks, num_gpus)) + rotation_interval = max(1, int(num_gpus / num_subchunks)) + perms_by_s = [] + for s in range(0, num_subchunks): + full_order = [] + offset = s * rotation_interval + for w in range(0, num_workers): + default_order = [(w * num_gpus) + i for i in gpu_perm] + dev_order = default_order[offset:] + default_order[:offset] + full_order += dev_order + perms_by_s.append(full_order) + pred_by_s_d = [[-1 for d in range(0, devices)] + for s in range(0, num_subchunks)] + rank_by_s_d = [[-1 for d in range(0, devices)] + for s in range(0, num_subchunks)] + for s in range(0, num_subchunks): + for d in range(0, devices): + for t in range(0, devices): + if d == perms_by_s[s][t]: + rank_by_s_d[s][d] = t + pred_by_s_d[s][d] = perms_by_s[s][(t + devices - 1) % devices] + break + return (pred_by_s_d, rank_by_s_d) + + +def build_ring_all_reduce(input_tensors, num_workers, num_subchunks, + gpu_perm, red_op, un_op=None): + """Construct a subgraph performing a ring-style all-reduce of input_tensors. + + Args: + input_tensors: a list of `tf.Tensor` objects, which must all + have the same shape and type. + num_workers: number of worker tasks spanned by input_tensors. + num_subchunks: number of subchunks each device should process in one tick. + gpu_perm: a list of ints giving a ring-wise rank ordering of GPUs at + each worker. All workers must have the same number of + GPUs with the same rank ordering. If NVLINK is available, this should + be a ring order supported by NVLINK edges. + red_op: a binary operator for elementwise reduction. + un_op: an optional unary operator to apply to fully reduced values. + + Raises: + ValueError: empty input_tensors or they don't all have same + size. + + Returns: + a list of `tf.Tensor` identical sum-reductions of input_tensors. + """ + if len(input_tensors) < 2: + raise ValueError("input_tensors must be length 2 or longer") + input_tensors, shape = _flatten_tensors(input_tensors) + devices = [t.device for t in input_tensors] + (pred_by_s_d, rank_by_s_d) = _ring_permutations( + num_workers, num_subchunks, gpu_perm) + chunks_by_dev, pad_len = _build_ring_gather( + input_tensors, devices, + num_subchunks, pred_by_s_d, rank_by_s_d, red_op) + if un_op: + chunks_by_dev = _apply_unary_to_chunks(un_op, chunks_by_dev) + output_tensors = _build_ring_scatter(pred_by_s_d, rank_by_s_d, + chunks_by_dev) + if pad_len > 0: + output_tensors = _strip_padding(output_tensors, pad_len) + if len(shape) != 1: + output_tensors = _reshape_tensors(output_tensors, shape) + return output_tensors + + +def _build_ring_gather(input_tensors, devices, num_subchunks, + pred_by_s_d, rank_by_s_d, red_op): + """Construct a subgraph for the first (reduction) pass of ring all-reduce. + + Args: + input_tensors: a list of `tf.Tensor` 1D input tensors of same + shape and type. + devices: array of device name strings + num_subchunks: number of subchunks each device should process in one tick. + pred_by_s_d: as produced by _ring_permutations + rank_by_s_d: as produced by _ring_permutations + red_op: a binary operator for elementwise reduction + + Raises: + ValueError: tensors must all be one dimensional. + + Returns: + list of list of `tf.Tensor` of (partially) reduced values where + exactly num_subchunks chunks at each device are fully reduced. + """ + num_devices = len(input_tensors) + if num_devices == 0: + return [] + if num_devices == 1: + return input_tensors + shape = input_tensors[0].shape + if 1 != len(shape): + raise ValueError("input tensors must be 1D") + num_chunks = num_devices * num_subchunks + num_ticks = num_devices - 1 + # Initialize chunks_by_dev with splits of the input tensors. + chunks_by_dev = [] + split_pad_len = 0 + for d in range(0, num_devices): + with ops.device(devices[d]): + splits, split_pad_len = _padded_split(input_tensors[d], num_chunks) + chunks_by_dev.append(splits) + # Reduction phase + for tick in range(0, num_ticks): + # One new partial reduction for every chunk + new_partial_reductions = [None for _ in range(0, num_chunks)] + # Compute reductions with respect to last tick's values + for d in range(0, num_devices): + with ops.device(devices[d]): + for s in range(0, num_subchunks): + rank = rank_by_s_d[s][d] + seg_index = (rank + num_devices - (2 + tick)) % num_devices + pred_dev = pred_by_s_d[s][d] + chunk_index = (seg_index * num_subchunks) + s + new_partial_reductions[chunk_index] = red_op( + chunks_by_dev[pred_dev][chunk_index], + chunks_by_dev[d][chunk_index]) + # Update chunks_by_dev with the new values at the end of the tick. + for d in range(0, num_devices): + for s in range(0, num_subchunks): + rank = rank_by_s_d[s][d] + seg_index = (rank + num_devices - (2 + tick)) % num_devices + chunk_index = (seg_index * num_subchunks) + s + chunks_by_dev[d][chunk_index] = new_partial_reductions[chunk_index] + return chunks_by_dev, split_pad_len + + +def _apply_unary_to_chunks(f, chunks_by_dev): + """Apply a unary op to each tensor in chunks_by_dev, on same device. + + Args: + f: a unary function over `tf.Tensor`. + chunks_by_dev: list of lists of `tf.Tensor`. + + Returns: + new list of lists of `tf.Tensor` with the same structure as + chunks_by_dev containing the derived tensors. + """ + output = [] + for x in chunks_by_dev: + with ops.colocate_with(x[0]): + output.append([f(t) for t in x]) + return output + + +def _build_ring_scatter(pred_by_s_d, rank_by_s_d, + chunks_by_dev): + """Construct subgraph for second (scatter) pass of ring all-reduce. + + Args: + pred_by_s_d: as produced by _ring_permutations + rank_by_s_d: as produced by _ring_permutations + chunks_by_dev: list of list of `tf.Tensor` indexed by ints + (device, chunk) + + Raises: + ValueError: chunks_by_dev is not well-formed + + Returns: + list of `tf.Tensor` which are the fully reduced tensors, one + at each device corresponding to the outer dimension of chunks_by_dev. + """ + num_devices = len(chunks_by_dev) + num_chunks = len(chunks_by_dev[0]) + if 0 != num_chunks % num_devices: + raise ValueError( + "Expect number of chunks per device to be divisible by num_devices") + num_subchunks = int(num_chunks / num_devices) + num_ticks = num_devices - 1 + for tick in range(0, num_ticks): + passed_values = [None for _ in range(0, num_chunks)] + for d in range(0, num_devices): + with ops.colocate_with(chunks_by_dev[d][0]): + for s in range(0, num_subchunks): + rank = rank_by_s_d[s][d] + seg_index = (rank + num_devices - (1 + tick)) % num_devices + pred_dev = pred_by_s_d[s][d] + chunk_index = (seg_index * num_subchunks) + s + passed_values[chunk_index] = array_ops.identity( + chunks_by_dev[pred_dev][chunk_index]) + for d in range(0, num_devices): + for s in range(0, num_subchunks): + rank = rank_by_s_d[s][d] + seg_index = (rank + num_devices - (1 + tick)) % num_devices + chunk_index = (seg_index * num_subchunks) + s + chunks_by_dev[d][chunk_index] = passed_values[chunk_index] + # Join chunks at each device. + output = [] + for x in chunks_by_dev: + with ops.colocate_with(x[0]): + output.append(array_ops.concat(x, 0)) + return output + + +def build_recursive_hd_all_reduce(input_tensors, red_op, un_op=None): + """Construct a subgraph for recursive halving-doubling all-reduce. + + The recursive halving-doubling algorithm is described in + (Thakur et al., 2015). + + The concept is to arrange the participating n devices in + a linear sequence where devices exchange data pairwise + with one other device in each round. During the gather + phase there are lg(n) rounds where devices exchange + increasingly smaller sub-tensors with another device + at increasingly greater distances, until at the top + each device has 1/n of the fully reduced values. During the + scatter phase each device exchanges its fully reduced + sub-tensor (which doubles in length at each round) + with one other device at increasingly smaller distances + until each device has all of the fully reduced values. + + Note: this preliminary version requires that len(input_tensors) be a + power of 2. TODO(tucker): relax this restriction. Also, the + number of elements in each tensor must be divisible by 2^h where h + is the number of hops in each phase. This will also be relaxed in + the future with edge-case specific logic. + + Args: + input_tensors: list of `tf.Tensor` to be elementwise reduced. + red_op: a binary elementwise reduction Op. + un_op: an optional unary elementwise Op to apply to reduced values. + + Returns: + list of `tf.Tensor` which are the fully reduced tensors, one + at each device of input_tensors. + + Raises: + ValueError: num_devices not a power of 2, or tensor len not divisible + by 2 the proper number of times. + + References: + Optimization of Collective Communication Operations in MPICH: + [Thakur et al., 2005] + (https://journals.sagepub.com/doi/abs/10.1177/1094342005051521) + ([pdf](http://wwwi10.lrr.in.tum.de/~gerndt/home/Teaching/HPCSeminar/mpich_multi_coll.pdf)) + """ + devices = [t.device for t in input_tensors] + input_tensors, shape = _flatten_tensors(input_tensors) + reduced_shards = _build_recursive_hd_gather(input_tensors, devices, red_op) + if un_op: + reduced_shards = [un_op(t) for t in reduced_shards] + output_tensors = _build_recursive_hd_scatter(reduced_shards, devices) + if len(shape) != 1: + output_tensors = _reshape_tensors(output_tensors, shape) + return output_tensors + + +def _build_recursive_hd_gather(input_tensors, devices, red_op): + """Construct the gather phase of recursive halving-doubling all-reduce. + + Args: + input_tensors: list of `tf.Tensor` to be elementwise reduced. + devices: a list of strings naming the devices hosting input_tensors, + which will also be used to host the (partial) reduction values. + red_op: a binary elementwise reduction Op. + + Returns: + list of `tf.Tensor` which are the fully reduced tensor shards. + + Raises: + ValueError: num_devices not a power of 2, or tensor len not divisible + by 2 the proper number of times. + """ + num_devices = len(devices) + num_hops = int(math.log(num_devices, 2)) + if num_devices != (2 ** num_hops): + raise ValueError("num_devices must be a power of 2") + chunks = input_tensors + for h in range(0, num_hops): + span = 2 ** h + group_size = span * 2 + new_chunks = [[] for _ in devices] + for d in range(0, num_devices): + if (d % group_size) >= (group_size / 2): + # skip right half of a pair + continue + left_dev = devices[d] + right_dev = devices[d + span] + left_split = array_ops.split(chunks[d], 2) + right_split = array_ops.split(chunks[d+span], 2) + with ops.device(left_dev): + new_chunks[d] = red_op(left_split[0], right_split[0]) + with ops.device(right_dev): + new_chunks[d + span] = red_op(left_split[1], right_split[1]) + chunks = new_chunks + return chunks + + +def _build_recursive_hd_scatter(input_tensors, devices): + """Construct the scatter phase of recursive halving-doubling all-reduce. + + Args: + input_tensors: list of `tf.Tensor` that are fully-reduced shards. + devices: a list of strings naming the devices on which the reconstituted + full tensors should be placed. + + Returns: + list of `tf.Tensor` which are the fully reduced tensors. + """ + num_devices = len(devices) + num_hops = int(math.log(num_devices, 2)) + assert num_devices == (2 ** num_hops), "num_devices must be a power of 2" + chunks = input_tensors + for h in reversed(range(0, num_hops)): + span = 2 ** h + group_size = span * 2 + new_chunks = [[] for _ in devices] + for d in range(0, num_devices): + if (d % group_size) >= (group_size / 2): + # skip right half of a pair + continue + left_idx = d + right_idx = d + span + left_dev = devices[left_idx] + right_dev = devices[right_idx] + with ops.device(left_dev): + new_chunks[left_idx] = array_ops.concat([chunks[left_idx], + chunks[right_idx]], 0) + with ops.device(right_dev): + new_chunks[right_idx] = array_ops.concat([chunks[left_idx], + chunks[right_idx]], 0) + chunks = new_chunks + return chunks + + +def build_shuffle_all_reduce(input_tensors, gather_devices, red_op, un_op=None): + """Construct a subgraph for shuffle all-reduce. + + Shuffle reduce is essentially the algorithm implemented when using + parameter servers. Suppose tensor length is n, there are d devices + and g gather shards. Each device sends a n/g length sub-tensor to + each gather shard. The gather shards perform a reduction across d + fragments, then broadcast the result back to each device. The + devices then join the g fully reduced fragments they receive from + the shards. The gather shards could perform d-1 pairwise + reductions, or one d-way reduction. The first is better where + reduction Op time is low compared to transmission time, the second + better in the other case. + + Args: + input_tensors: list of `tf.Tensor` values to be reduced. + gather_devices: list of names of devices on which reduction shards + should be placed. + red_op: an n-array elementwise reduction Op + un_op: optional elementwise unary Op to be applied to fully-reduced values. + + Returns: + list of `tf.Tensor` which are the fully reduced tensors. + """ + input_tensors, shape = _flatten_tensors(input_tensors) + dst_devices = [t.device for t in input_tensors] + reduced_shards = _build_shuffle_gather(input_tensors, gather_devices, + red_op, un_op) + output_tensors = _build_shuffle_scatter(reduced_shards, dst_devices) + if len(shape) != 1: + output_tensors = _reshape_tensors(output_tensors, shape) + return output_tensors + + +def _build_shuffle_gather(input_tensors, gather_devices, red_op, un_op=None): + """Construct the gather (concentrate and reduce) phase of shuffle all-reduce. + + Args: + input_tensors: list of `tf.Tensor` values to be reduced. + gather_devices: list of names of devices on which reduction shards + should be placed. + red_op: the binary reduction Op + un_op: optional elementwise unary Op to be applied to fully-reduced values. + + Returns: + list of `tf.Tensor` which are the fully reduced shards. + + Raises: + ValueError: inputs not well-formed. + """ + num_source_devices = len(input_tensors) + num_gather_devices = len(gather_devices) + shape = input_tensors[0].shape + if len(shape) != 1: + raise ValueError("input_tensors must be 1D") + shards_by_source = [] + for d in range(0, num_source_devices): + with ops.colocate_with(input_tensors[d]): + shards_by_source.append( + _ragged_split(input_tensors[d], num_gather_devices)) + reduced_shards = [] + for d in range(0, num_gather_devices): + with ops.device(gather_devices[d]): + values = [s[d] for s in shards_by_source] + red_shard = red_op(values) + if un_op: + red_shard = un_op(red_shard) + reduced_shards.append(red_shard) + return reduced_shards + + +def _build_shuffle_scatter(reduced_shards, dst_devices): + """Build the scatter phase of shuffle all-reduce. + + Args: + reduced_shards: list of `tf.Tensor` fully reduced shards + dst_devices: list of names of devices at which the fully-reduced value + should be reconstituted. + + Returns: + list of `tf.Tensor` scattered tensors. + """ + num_devices = len(dst_devices) + out_tensors = [] + for d in range(0, num_devices): + with ops.device(dst_devices[d]): + out_tensors.append(array_ops.concat(reduced_shards, 0)) + return out_tensors + + +def _split_by_task(devices, values): + """Partition devices and values by common task. + + Args: + devices: list of device name strings + values: list of `tf.Tensor` of same length as devices. + + Returns: + (per_task_devices, per_task_values) where both values are + lists of lists with isomorphic structure: the outer list is + indexed by task, and the inner list has length of the number + of values belonging to that task. per_task_devices contains + the specific devices to which the values are local, and + per_task_values contains the corresponding values. + + Raises: + ValueError: devices must be same length as values. + """ + num_devices = len(devices) + if num_devices != len(values): + raise ValueError("len(devices) must equal len(values)") + per_task_devices = collections.OrderedDict() + per_task_values = collections.OrderedDict() + for d in range(num_devices): + d_spec = device_lib.DeviceSpec.from_string(devices[d]) + if not hasattr(d_spec, "task") or d_spec.task is None: + assert False, "failed to parse device %s" % devices[d] + index = (d_spec.job or "localhost", d_spec.replica or 0, d_spec.task) + if index not in per_task_devices: + per_task_devices[index] = [] + per_task_values[index] = [] + per_task_devices[index].append(devices[d]) + per_task_values[index].append(values[d]) + + return (list(per_task_devices.values()), list(per_task_values.values())) + + +def build_nccl_all_reduce(input_tensors, red_op, un_op=None): + """Build a subgraph that does one full all-reduce, using NCCL. + + Args: + input_tensors: list of `tf.Tensor` of same-shape and type values to + be reduced. + red_op: binary elementwise reduction operator. Must be one of + {tf.add} + un_op: optional unary elementwise Op to apply to fully-reduce values. + + Returns: + list of `tf.Tensor` of reduced values. + + Raises: + ValueError: red_op not supported. + """ + if red_op == math_ops.add: + output_tensors = nccl_ops.all_sum(input_tensors) + else: + raise ValueError("red_op not supported by NCCL all-reduce: ", red_op) + if un_op: + un_op_wrapped = [] + for t in output_tensors: + with ops.colocate_with(t): + un_op_wrapped.append(un_op(t)) + output_tensors = un_op_wrapped + return output_tensors + + +def _build_nccl_hybrid(input_tensors, red_op, upper_level_f): + """Construct a subgraph for NCCL hybrid all-reduce. + + Args: + input_tensors: list of `tf.Tensor` of same-shape and type values to + be reduced. + red_op: binary elementwise reduction operator. + upper_level_f: function for reducing one value per worker, across + workers. + + Returns: + list of `tf.Tensor` of reduced values. + + Raises: + ValueError: inputs not well-formed. + """ + input_tensors, shape = _flatten_tensors(input_tensors) + devices = [t.device for t in input_tensors] + per_worker_devices, per_worker_values = _split_by_task(devices, input_tensors) + num_workers = len(per_worker_devices) + up_values = [None for w in range(0, num_workers)] + up_devices = up_values[:] + down_values = up_values[:] + # First stage: reduce within each worker using NCCL + for w in range(0, num_workers): + worker_values = build_nccl_all_reduce(per_worker_values[w], red_op) + # NOTE: these reductions will not run to completion unless + # every output value is used. Since we only need one, we + # need to put control dependencies on the rest. + with ops.control_dependencies(worker_values): + with ops.device(worker_values[0].device): + up_values[w] = array_ops.identity(worker_values[0]) + up_devices[w] = per_worker_devices[w][0] + # Second stage: Apply upper_level_f to reduce across first device at + # each worker + level_2_output = upper_level_f(up_values) + # Third stage: propagate within each worker using NCCL Broadcast + for w in range(0, num_workers): + dst_tensors = [] + with ops.device(per_worker_devices[w][0]): + broadcast_src = nccl_ops.broadcast(array_ops.identity(level_2_output[w])) + for d in per_worker_devices[w]: + with ops.device(d): + dst_tensors.append(array_ops.identity(broadcast_src)) + down_values[w] = dst_tensors + output_tensors = [v for sublist in down_values for v in sublist] + if len(shape) != 1: + output_tensors = _reshape_tensors(output_tensors, shape) + return output_tensors + + +def _reduce_non_singleton(input_tensors, red_f, un_op): + """If len(input_tensors) > 1, apply red_f, else apply un_op.""" + if len(input_tensors) > 1: + return red_f(input_tensors) + else: + if not un_op: + return input_tensors + output_tensors = [] + for t in input_tensors: + with ops.colocate_with(t): + output_tensors.append(un_op(t)) + return output_tensors + + +def build_nccl_then_ring(input_tensors, subdiv, red_op, un_op=None): + """Construct hybrid of NCCL within workers, Ring across workers.""" + def upper_builder(y): + return build_ring_all_reduce(y, len(y), subdiv, [0], red_op, un_op) + def upper_level_f(x): + return _reduce_non_singleton(x, upper_builder, un_op) + return _build_nccl_hybrid(input_tensors, red_op, upper_level_f) + + +def build_nccl_then_recursive_hd(input_tensors, red_op, un_op=None): + """Construct hybrid of NCCL within workers, Recursive-HD across workers.""" + upper_level_f = lambda x: build_recursive_hd_all_reduce(x, red_op, un_op) + return _build_nccl_hybrid(input_tensors, red_op, upper_level_f) + + +def build_nccl_then_shuffle(input_tensors, gather_devices, nccl_red_op, + shuffle_red_op, un_op=None): + """Construct hybrid of NCCL within workers, Shuffle across workers.""" + def upper_level_f(x): + return build_shuffle_all_reduce(x, gather_devices, shuffle_red_op, un_op) + + return _build_nccl_hybrid(input_tensors, nccl_red_op, upper_level_f) + + +def _build_shuffle_hybrid(input_tensors, gather_devices, red_op, upper_level_f): + """Construct a subgraph for Shuffle hybrid all-reduce. + + Args: + input_tensors: list of `tf.Tensor` of same-shape and type values to + be reduced. + gather_devices: list of device names on which to host gather shards. + red_op: binary elementwise reduction operator. + upper_level_f: function for reducing one value per worker, across + workers. + + Returns: + list of `tf.Tensor` of reduced values. + + Raises: + ValueError: inputs not well-formed. + """ + input_tensors, shape = _flatten_tensors(input_tensors) + # First stage, reduce across each worker using gather_devices. + devices = [t.device for t in input_tensors] + per_worker_devices, per_worker_values = _split_by_task(devices, input_tensors) + num_workers = len(per_worker_devices) + up_values = [] + if len(gather_devices) != num_workers: + raise ValueError("For shuffle hybrid, gather_devices must contain one " + "device per worker. ") + for w in range(0, num_workers): + reduced_shards = _build_shuffle_gather( + per_worker_values[w], [gather_devices[w]], red_op) + up_values.append(reduced_shards[0]) + # Second stage, apply upper_level_f. + level_2_output = upper_level_f(up_values) + # Third stage, apply shuffle scatter at each worker. + output_tensors = [] + for w in range(0, num_workers): + output_tensors += _build_shuffle_scatter( + [level_2_output[w]], per_worker_devices[w]) + if len(shape) != 1: + output_tensors = _reshape_tensors(output_tensors, shape) + return output_tensors + + +def build_shuffle_then_ring(input_tensors, gather_devices, subdiv, + red_n_op, red_op, un_op=None): + """Construct hybrid of Shuffle within workers, Ring across workers.""" + def upper_builder(tensors): + return build_ring_all_reduce(tensors, len(tensors), subdiv, [0], + red_op, un_op) + def upper_level_f(tensors): + return _reduce_non_singleton(tensors, upper_builder, un_op) + return _build_shuffle_hybrid( + input_tensors, gather_devices, red_n_op, upper_level_f) + + +def build_shuffle_then_shuffle(input_tensors, first_gather_devices, + second_gather_devices, red_op, un_op=None): + """Construct hybrid of Shuffle within workers, Shuffle across workers.""" + def upper_builder(tensors): + return build_shuffle_all_reduce(tensors, second_gather_devices, + red_op, un_op) + def upper_level_f(tensors): + return _reduce_non_singleton(tensors, upper_builder, un_op) + return _build_shuffle_hybrid( + input_tensors, first_gather_devices, red_op, upper_level_f) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/input_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/input_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..f1eb274a86c9dbb52087751ea18148f91f4be3d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/v1/input_lib.py @@ -0,0 +1,420 @@ +# 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. +# ============================================================================== +"""Various classes representing distributed inputs.""" + +from tensorflow.python.data.experimental.ops import cardinality as cardinality_lib +from tensorflow.python.data.ops import dataset_ops +from tensorflow.python.data.ops import multi_device_iterator_ops +from tensorflow.python.data.ops import optional_ops +from tensorflow.python.distribute import input_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.types import data as data_types +from tensorflow.python.util.deprecation import deprecated + + +class DistributedDatasetV1(input_lib.DistributedDataset): + """Distributed dataset that supports prefetching to multiple devices.""" + + def __init__(self, + dataset, + input_workers, + strategy, + num_replicas_in_sync=None, + input_context=None, + options=None): + self._input_workers = input_workers + super(DistributedDatasetV1, self).__init__( + input_workers, + strategy, + dataset, + num_replicas_in_sync=num_replicas_in_sync, + input_context=input_context, + options=options) + + def make_one_shot_iterator(self): + """Get a one time use iterator for DistributedDatasetV1. + + Note: This API is deprecated. Please use `for ... in dataset:` to iterate + over the dataset or `iter` to create an iterator. + + Returns: + A DistributedIteratorV1 instance. + """ + return self._make_one_shot_iterator() + + def _make_one_shot_iterator(self): + """Get an iterator for DistributedDatasetV1.""" + # Graph mode with one shot iterator is disabled because we have to call + # `initialize` on the iterator which is only required if we are using a + # tf.distribute strategy. + if not context.executing_eagerly(): + raise ValueError("Cannot create a one shot iterator. Please use " + "`make_initializable_iterator()` instead.") + return self._get_iterator() + + def make_initializable_iterator(self): + """Get an initializable iterator for DistributedDatasetV1. + + Note: This API is deprecated. Please use + `tf.compat.v1.data.make_initializable_iterator(dataset)` to create an + initializable iterator. + + Returns: + A DistributedIteratorV1 instance. + """ + return self._make_initializable_iterator() + + def _make_initializable_iterator(self, shared_name=None): # pylint: disable=unused-argument + """Get an initializable iterator for DistributedDatasetV1.""" + # Eager mode generates already initialized iterators. Hence we cannot create + # an initializable iterator. + if context.executing_eagerly(): + raise ValueError("Cannot create initializable iterator in Eager mode. " + "Please use `iter()` instead.") + return self._get_iterator() + + def _get_iterator(self): + worker_iterators = _create_iterators_per_worker(self._cloned_datasets, + self._input_workers, + self._options) + cardinality = input_lib._cardinality(self._cloned_datasets[0]) # pylint: disable=protected-access + iterator = DistributedIteratorV1(self._input_workers, worker_iterators, + self._strategy, cardinality, + self._enable_get_next_as_optional) + iterator._element_spec = self.element_spec # pylint: disable=protected-access + + # When async eager is enabled, sometimes the iterator may not finish + # initialization before passing to a multi device function, add a sync point + # here to make sure all underlying iterators are initialized. + if context.executing_eagerly(): + context.async_wait() + + return iterator + + # pylint: disable=non-iterator-returned + def __iter__(self): + if (ops.executing_eagerly_outside_functions() or + ops.get_default_graph().building_function): + return self._get_iterator() + + raise RuntimeError("__iter__() is only supported inside of tf.function " + "or when eager execution is enabled.") + + # pylint: enable=non-iterator-returned + + +class DistributedDatasetsFromFunctionV1( + input_lib.DistributedDatasetsFromFunction): + """Inputs created from dataset function.""" + + def _make_initializable_iterator(self, shared_name=None): + """Get an initializable iterator for DistributedDatasetsFromFunctionV1.""" + del shared_name # Unused + # Eager mode generates already initialized iterators. Hence we cannot create + # an initializable iterator. + if context.executing_eagerly(): + raise ValueError("Cannot create initializable iterator in Eager mode. " + "Please use `iter()` instead.") + return self._get_iterator() + + def _make_one_shot_iterator(self): + """Get an iterator for iterating over DistributedDatasetsFromFunctionV1.""" + # Graph mode with one shot iterator is disabled because we have to call + # `initialize` on the iterator which is only required if we are using a + # tf.distribute strategy. + if not context.executing_eagerly(): + raise ValueError("Cannot create a one shot iterator. Please use " + "`make_initializable_iterator()` instead.") + return self._get_iterator() + + def _get_iterator(self): + iterators = _create_iterators_per_worker(self._datasets, + self._input_workers, self._options) + cardinality = input_lib._cardinality(self._datasets[0]) # pylint: disable=protected-access + iterator = DistributedIteratorV1(self._input_workers, iterators, + self._strategy, cardinality, + self._enable_get_next_as_optional) + iterator._element_spec = self._element_spec # pylint: disable=protected-access + + # When async eager is enabled, sometimes the iterator may not finish + # initialization before passing to a multi device function, add a sync point + # here to make sure all underlying iterators are initialized. + if context.executing_eagerly(): + context.async_wait() + + return iterator + + # pylint: disable=non-iterator-returned + def __iter__(self): + if (ops.executing_eagerly_outside_functions() or + ops.get_default_graph().building_function): + return self._get_iterator() + + raise RuntimeError("__iter__() is only supported inside of tf.function " + "or when eager execution is enabled.") + + # pylint: enable=non-iterator-returned + + +class DistributedIteratorV1(input_lib.DistributedIteratorBase): + """Input Iterator for a distributed dataset.""" + + # We need a private initializer method for re-initializing multidevice + # iterators when used with Keras training loops. If we don't reinitialize the + # iterator we run into memory leak issues (b/123315763). + @property + def _initializer(self): + init_ops = [] + for it in self._iterators: + init_ops.extend(it.initialize()) + return control_flow_ops.group(init_ops) + + @deprecated(None, "Use the iterator's `initializer` property instead.") + def initialize(self): + """Initialize underlying iterators. + + Returns: + A list of any initializer ops that should be run. + """ + return self._initializer + + @property + def initializer(self): + """Returns a list of ops that initialize the iterator.""" + return self.initialize() + + # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs. + @property + def output_classes(self): + return self._iterators[0].output_classes + + # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs. + @property + def output_shapes(self): + return self._iterators[0].output_shapes + + # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs. + @property + def output_types(self): + return self._iterators[0].output_types + + # TODO(priyag): Remove when we switch to using `MultiDeviceIterator` for TPUs. + def get_iterator(self, worker): + for i, w in enumerate(self._input_workers.worker_devices): + if worker == w: + return self._iterators[i] + return None + + @property + def element_spec(self): + """The type specification of an element of this iterator.""" + return self._element_spec + + +class DatasetIterator(DistributedIteratorV1): + """Iterator created from input dataset.""" + + def __init__(self, + dataset, + input_workers, + strategy, + num_replicas_in_sync=None, + input_context=None): + """Make an iterator for the dataset on given devices. + + If `num_replicas_in_sync` is not None, we split each batch of the dataset + into `num_replicas_in_sync` smaller batches, to be distributed among that + worker's replicas, so that the batch size for a global step (across all + workers and replicas) is as expected. + + Args: + dataset: `tf.data.Dataset` that will be used as the input source. + input_workers: an `InputWorkers` object. + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + num_replicas_in_sync: Optional integer. If this is not None, the value is + used to decide how to rebatch datasets into smaller batches so that the + total batch size for each step (across all workers and replicas) adds up + to `dataset`'s batch size. + input_context: `InputContext` for sharding. Only pass this in for between + graph multi-worker cases where there is only one `input_worker`. In + these cases, we will shard based on the `input_pipeline_id` and + `num_input_pipelines` in the `InputContext`. + """ + dist_dataset = DistributedDatasetV1( + dataset, + input_workers, + strategy, + num_replicas_in_sync=num_replicas_in_sync, + input_context=input_context) + # pylint: disable=protected-access + worker_iterators = _create_iterators_per_worker( + dist_dataset._cloned_datasets, input_workers) + super(DatasetIterator, + self).__init__(input_workers, worker_iterators, strategy, + dist_dataset.cardinality, + dist_dataset._enable_get_next_as_optional) + self._element_spec = dist_dataset.element_spec + # pylint: enable=protected-access + + +class InputFunctionIterator(DistributedIteratorV1): + """Iterator created from input function.""" + + def __init__(self, input_fn, input_workers, input_contexts, strategy): + """Make an iterator for input provided via an input function. + + Currently implements PER_WORKER mode, in which the `input_fn` is called + once on each worker. + + TODO(priyag): Add other replication modes. + + Args: + input_fn: Input function that returns a `tf.data.Dataset` object. + input_workers: an `InputWorkers` object. + input_contexts: A list of `InputContext` instances to be passed to call(s) + to `input_fn`. Length and order should match worker order in + `worker_device_pairs`. + strategy: a `tf.distribute.Strategy` object, used to run all-reduce to + handle last partial batch. + """ + assert isinstance(input_workers, input_lib.InputWorkers) + if input_workers.num_workers != len(input_contexts): + raise ValueError("Number of input workers (%d) is not same as number of " + "input_contexts (%d)" % + (input_workers.num_workers, len(input_contexts))) + + iterators = [] + for i, ctx in enumerate(input_contexts): + worker = input_workers.worker_devices[i] + with ops.device(worker): + result = input_fn(ctx) + devices = input_workers.compute_devices_for_worker(i) + if isinstance(result, data_types.DatasetV2): + iterator = _SingleWorkerDatasetIterator(result, worker, devices) + elif callable(result): + iterator = _SingleWorkerCallableIterator(result, worker, devices) + else: + raise ValueError( + "input_fn must return a tf.data.Dataset or a callable.") + iterators.append(iterator) + + super(InputFunctionIterator, self).__init__( + input_workers, + iterators, + strategy, + cardinality=cardinality_lib.UNKNOWN, + enable_get_next_as_optional=False) + self._enable_get_next_as_optional = False + + +class _SingleWorkerDatasetIterator(input_lib._SingleWorkerDatasetIteratorBase): # pylint: disable=protected-access + """Iterator for a single DistributedDatasetV1 instance.""" + + def _make_iterator(self): + """Make appropriate iterator on the dataset.""" + with ops.device(self._worker): + if self._options is not None: + self._iterator = multi_device_iterator_ops.MultiDeviceIterator( + self._dataset, + self._devices, + max_buffer_size=self._options.experimental_per_replica_buffer_size, + prefetch_buffer_size=self._options + .experimental_per_replica_buffer_size) + else: + self._iterator = multi_device_iterator_ops.MultiDeviceIterator( + self._dataset, + self._devices, + ) + + def initialize(self): + """Initialize underlying iterator. + + In eager execution, this simply recreates the underlying iterator. + In graph execution, it returns the initializer ops for the underlying + iterator. + + Returns: + A list of any initializer ops that should be run. + """ + if ops.executing_eagerly_outside_functions(): + self._iterator._eager_reset() # pylint: disable=protected-access + return [] + else: + return [self._iterator.initializer] + + @property + def output_classes(self): + return dataset_ops.get_legacy_output_classes(self._iterator) + + @property + def output_shapes(self): + return dataset_ops.get_legacy_output_shapes(self._iterator) + + @property + def output_types(self): + return dataset_ops.get_legacy_output_types(self._iterator) + + +class _SingleWorkerCallableIterator(object): + """Iterator for a single tensor-returning callable.""" + + def __init__(self, fn, worker, devices): + self._fn = fn + self._worker = worker + self._devices = devices + + def get_next(self, device, name=None): + """Get next element for the given device from the callable.""" + del device, name + with ops.device(self._worker): + return self._fn() + + def get_next_as_list(self, name=None): + """Get next element from the callable.""" + del name + with ops.device(self._worker): + data_list = [self._fn() for _ in self._devices] + return data_list + + def get_next_as_optional_list(self): + with ops.device(self._worker): + data_list = [ + optional_ops.Optional.from_value(self._fn()) for _ in self._devices + ] + return data_list + + def initialize(self): + # TODO(petebu) Should this throw an exception instead? + return [] + + +def _create_iterators_per_worker(worker_datasets, input_workers, options=None): + """Create a multidevice iterator on each of the workers.""" + assert isinstance(input_workers, input_lib.InputWorkers) + assert len(worker_datasets) == len(input_workers.worker_devices) + iterators = [] + for i, worker in enumerate(input_workers.worker_devices): + with ops.device(worker): + worker_devices = input_workers.compute_devices_for_worker(i) + iterator = _SingleWorkerDatasetIterator( + worker_datasets[i], # pylint: disable=protected-access + worker, + worker_devices, + options) + iterators.append(iterator) + return iterators diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values.py new file mode 100644 index 0000000000000000000000000000000000000000..1a9ae9605438f12e7b7ab4bda61b2ef5deddb694 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values.py @@ -0,0 +1,1838 @@ +# 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. +# ============================================================================== +"""Various classes representing distributed values.""" + +import copy +from typing import Optional +import weakref + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import packed_distributed_variable as packed +from tensorflow.python.distribute import reduce_util +from tensorflow.python.distribute import values_util +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.ops import variables as variables_lib +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training.saving import saveable_object +from tensorflow.python.types import core +from tensorflow.python.types import distribute as ds_types +from tensorflow.python.types import trace + + +def _on_write_update_replica(var, update_fn, value, **kwargs): + """Updates variables with ON_WRITE synchronization in replica context.""" + if var.aggregation == vs.VariableAggregation.NONE: + return update_fn(var._get_on_device_or_primary(), value, **kwargs) # pylint: disable=protected-access + + if not distribute_lib.get_strategy().extended._use_merge_call(): # pylint: disable=protected-access + # Don't allow MEAN with non float dtype, since it may cause unexpected + # precision loss. Python3 and NumPy automatically upcast integers to + # float in division, but we should always preserve the type. + if var.aggregation == vs.VariableAggregation.MEAN and ( + not var.dtype.is_floating) and tensor_util.is_tf_type(value): + raise ValueError( + "Cannot update non-float variables with " + "tf.VariableAggregation.MEAN aggregation in replica context. " + "Either change the variable dtype to float or update it in " + "cross-replica context.") + + aggregated_value = apply_aggregation_replica_context( + value, var.aggregation, var) + values_util.mark_as_unsaveable() + + return distribute_lib.get_replica_context()._update( # pylint: disable=protected-access + var, + update_fn, + args=(aggregated_value,), + kwargs=kwargs, + group=True) + + else: + + def merge_fn(strategy, value, **kwargs): + """Aggregate values and update all variables in cross replica context.""" + # Don't allow MEAN with non float dtype, since it may cause unexpected + # precision loss. Python3 and NumPy automatically upcast integers to + # float in division, but we should always preserve the type. + # + # Note that to be backward compatible we allow the case when the value + # is *always* the same on each replica. I.E. value is not a + # PerReplica. Refer to regroup() to see how values are grouped. + if var.aggregation == vs.VariableAggregation.MEAN and ( + not var.dtype.is_floating) and isinstance(value, PerReplica): + raise ValueError( + "Cannot update non-float variables with " + "tf.VariableAggregation.MEAN aggregation in replica context. " + "Either change the variable dtype to float or update it in " + "cross-replica context.") + + assert strategy == var.distribute_strategy + v = values_util.apply_aggregation(strategy, value, var.aggregation, var) + return var._update_cross_replica(update_fn, v, **kwargs) # pylint: disable=protected-access + + return distribute_lib.get_replica_context().merge_call( + merge_fn, args=(value,), kwargs=kwargs) + + +def apply_aggregation_replica_context(value, aggregation, destinations): + """Aggregate `value` to `destinations` as specified by `aggregation`.""" + # if it is a python literal, return without aggregation + if isinstance(value, DistributedValues): + raise TypeError( + "Cannot use DistributedValues to update variables in replica context.") + if not tensor_util.is_tf_type(value): + return value + + if aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + # Switch to cross-replica context to broadcast + def merge_fn(strategy, value): + return strategy.extended.broadcast_to( + strategy.experimental_local_results(value)[0], + destinations=destinations) + + return distribute_lib.get_replica_context().merge_call( + merge_fn, args=(value,)) + + else: + reduce_op = reduce_util.ReduceOp.from_variable_aggregation(aggregation) + aggregated_value = distribute_lib.get_strategy( # pylint: disable=protected-access + ).extended._replica_ctx_all_reduce(reduce_op, value) + return aggregated_value + + +class DistributedValues(ds_types.DistributedValues): + """Base class for representing distributed values.""" + + def __init__(self, values): + """Should only be called by subclass __init__.""" + self._values = tuple(values) + + def _get(self): + """Returns the value for the current device or raises a ValueError.""" + replica_id = values_util.get_current_replica_id_as_int() + if replica_id is None: + return self._get_cross_replica() + else: + return self._values[replica_id] + + def _get_cross_replica(self): + raise NotImplementedError( + "DistributedValues._get_cross_replica should be implemented by " + "sub-classes which support cross-replica accesses. " + f"Type name is {type(self)}" + ) + + def _get_on_device_or_primary(self): + """Returns value in same replica or device if possible, else the _primary.""" + replica_id = values_util.get_current_replica_id_as_int() + if replica_id is None: + # Try to find a value on the current device. + current_device = device_util.canonicalize(device_util.current()) + for value in self._values: + if device_util.canonicalize(value.device) == current_device: + return value + return self._primary + else: + return self._values[replica_id] + + @property + def _primary(self): + """Returns a representative component.""" + return self._values[0] + + @property + def _devices(self): + return tuple(v.device for v in self._values) + + def __str__(self): + debug_str = ",\n".join( + " %d: %s" % (i, v) for i, v in enumerate(self._values)) + return "%s:{\n%s\n}" % (self.__class__.__name__, debug_str) + + def __repr__(self): + debug_repr = ",\n".join( + " %d: %r" % (i, v) for i, v in enumerate(self._values)) + return "%s:{\n%s\n}" % (self.__class__.__name__, debug_repr) + + +# NOTE(josh11b,apassos): It would be great if we could inspect the values this was +# initialized with and use that to generate the overloaded operators here. +# Unfortunately, Python's rules for special methods don't allow this, see +# https://docs.python.org/3/reference/datamodel.html#special-method-names +# "if a class defines a method named __getitem__(), and x is an instance of +# this class, then x[i] is roughly equivalent to type(x).__getitem__(x, i)." +# In particular, these special methods don't go through __getattr__, and +# it will only use those methods if they are defined in the class, not the +# object. +class DistributedDelegate(DistributedValues): + """A map from device to values; acts as the same type as the values.""" + + def __getattr__(self, name): + # The '_use_resource_variables' and the attrs starts with '_self' are used + # for restoring the saved_model proto, and '_attribute_sentinel' is used for + # Layer tracking. At the point these attrs are queried, the variable has not + # been initialized. Thus it should not query those of the underlying + # components. + if name.startswith("_self_") or name in ("_use_resource_variables", + "_attribute_sentinel", + "_distributed_container"): + return super(DistributedDelegate, self).__getattr__(name) + + # This allows copy.copy(DistributedDelegate). When copying an object, + # copy.copy doesn't invoke its __init__ method, instead it makes a new + # empty object, then copies the attributes over. copy.copy looks for + # attributes like "__getstate__" in case the object implements its custom + # copying. Since DistributedDelegate doesn't have those attributes defined, + # __getattr__ will be invoked, which tries to access "_values" attributes, + # but that doesn't exist either because this is an empty object, and again + # __getattr__ is invoked, leading to an infinite recursion. + if name == "_values": + raise AttributeError() + + # TODO(priyag): This needs to be made robust against pitfalls from mix use + # __getattr__ and @property. See b/120402273. + return getattr(self._get(), name) + + @property + def values(self): + """Returns the per replica values.""" + return self._values + + def _get_as_operand(self): + """Returns the value for operations for the current device. + + Some implementations, e.g. `TPUMirroredVariable`, are not able to return the + value type within a replica context. They can, however, return a value that + can be used by the operations below. + """ + return self._get() + + # pylint: disable=multiple-statements + def __add__(self, o): + return self._get_as_operand() + o + + def __radd__(self, o): + return o + self._get_as_operand() + + def __sub__(self, o): + return self._get_as_operand() - o + + def __rsub__(self, o): + return o - self._get_as_operand() + + def __mul__(self, o): + return self._get_as_operand() * o + + def __rmul__(self, o): + return o * self._get_as_operand() + + def __truediv__(self, o): + return self._get_as_operand() / o + + def __rtruediv__(self, o): + return o / self._get_as_operand() + + def __floordiv__(self, o): + return self._get_as_operand() // o + + def __rfloordiv__(self, o): + return o // self._get_as_operand() + + def __mod__(self, o): + return self._get_as_operand() % o + + def __rmod__(self, o): + return o % self._get_as_operand() + + def __lt__(self, o): + return self._get_as_operand() < o + + def __le__(self, o): + return self._get_as_operand() <= o + + def __gt__(self, o): + return self._get_as_operand() > o + + def __ge__(self, o): + return self._get_as_operand() >= o + + def __and__(self, o): + return self._get_as_operand() & o + + def __rand__(self, o): + return o & self._get_as_operand() + + def __or__(self, o): + return self._get_as_operand() | o + + def __ror__(self, o): + return o | self._get_as_operand() + + def __xor__(self, o): + return self._get_as_operand() ^ o + + def __rxor__(self, o): + return o ^ self._get_as_operand() + + def __getitem__(self, o): + return self._get_as_operand()[o] + + def __pow__(self, o, modulo=None): + return pow(self._get_as_operand(), o, modulo) + + def __rpow__(self, o): + return pow(o, self._get_as_operand()) + + def __invert__(self): + return ~self._get_as_operand() + + def __neg__(self): + return -self._get_as_operand() + + def __abs__(self): + return abs(self._get_as_operand()) + + def __div__(self, o): + try: + return self._get_as_operand().__div__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __rdiv__(self, o): + try: + return self._get_as_operand().__rdiv__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __matmul__(self, o): + try: + return self._get_as_operand().__matmul__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + def __rmatmul__(self, o): + try: + return self._get_as_operand().__rmatmul__(o) + except AttributeError: + # See https://docs.python.org/3/library/constants.html#NotImplemented + return NotImplemented + + # TODO(josh11b): Even more operator overloads. + + +class PerReplica(DistributedValues, composite_tensor.CompositeTensor, + ds_types.PerReplica): + """Holds a map from replica to unsynchronized values.""" + + @property + def _type_spec(self): + return PerReplicaSpec( + *(type_spec.type_spec_from_value(v) for v in self._values)) + + @property + def values(self): + """Returns the per replica values.""" + return self._values + + +def _per_replica_to_tensor(var, dtype=None, name=None, as_ref=False): + """Converts a `PerReplica` to a `Tensor`.""" + del name + if dtype is not None and not dtype.is_compatible_with(var.dtype): + raise ValueError( + "Incompatible type conversion requested to type {!r} for variable " + "of type {!r}".format(dtype.name, var.dtype.name)) + if as_ref: + raise NotImplementedError( + "PerReplica doesn't support being used as a reference.") + if (distribute_lib.in_cross_replica_context() or + not distribute_lib.has_strategy()): + raise ValueError("It looks like you are using a PerReplica object while " + "not inside a replica context, which is not supported. " + "Try running your op or function inside a replica context " + "by using `strategy.run`") + else: + replica_id = values_util.get_current_replica_id_as_int() + return var.values[replica_id] + +# Register a conversion function to provide a useful error message when users +# try to use PerReplica values in the wrong contexts +tensor_conversion_registry.register_tensor_conversion_function( + PerReplica, _per_replica_to_tensor) + + +class PerReplicaSpec(type_spec.TypeSpec): + """Type specification for a `PerReplica`.""" + + __slots__ = ["_value_specs"] + + value_type = property(lambda self: PerReplica) + + def __init__(self, *value_specs): + self._value_specs = tuple(value_specs) + + def _serialize(self): + return self._value_specs + + @property + def _component_specs(self): + return self._value_specs + + def _to_components(self, value): + replica_context = distribute_lib.get_replica_context() + if replica_context is not None and replica_context.num_replicas_in_sync > 1: + raise ValueError( + "Flattening a PerReplica to components is not supported in replica " + "context.") + return value._values # pylint: disable=protected-access + + def _from_components(self, tensor_list): + return PerReplica(tensor_list) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + PerReplicaSpec, struct_pb2.TypeSpecProto.PER_REPLICA_SPEC + ) +) + + +# Note that unlike PerReplica, Mirrored values inherit from +# DistributedDelegate and so can be used directly in cross-replica mode. +# TODO(tomhennigan) Should this extend CompositeTensor? +class Mirrored(DistributedDelegate, ds_types.Mirrored): + """Holds a map from replica to values which are kept in sync.""" + + def _get_cross_replica(self): + return self._get_on_device_or_primary() + + def _as_graph_element(self): + obj = self._get() + conv_fn = getattr(obj, "_as_graph_element", None) + if conv_fn and callable(conv_fn): + return conv_fn() + return obj + + def _is_mirrored(self): + return True + + +class DistributedVarOp(object): + """A class that looks like `tf.Operation`.""" + + def __init__(self, name, graph, traceback, typ): + self.name = name + self.graph = graph + self.traceback = traceback + self.type = typ + + def __eq__(self, o): + if not isinstance(o, self.__class__): + raise NotImplementedError + return (self.name == o.name and self.graph == o.graph and + self.traceback == o.traceback and self.type == o.type) + + def __hash__(self): + return hash((self.name, self.graph, tuple(self.traceback), self.type)) + + +# TODO(b/209081027): Remove this once Variable is a CompositeTensor. +class DistributedVariableTraceType(trace.TraceType): + """TraceType of DistributedVariable objects.""" + + def __init__(self, distributed_variable): + self.distributed_variable = distributed_variable + self.components = (tuple(distributed_variable.shape.as_list()), + distributed_variable.dtype) + + def is_subtype_of(self, other): + return self == other + + def most_specific_common_supertype(self, others): + return self if all(self == other for other in others) else None + + def placeholder_value(self, placeholder_context=None): + return self.distributed_variable + + def to_tensors(self, value): + return [] + + def cast(self, value, _): + return value + + def __hash__(self) -> int: + return hash(self.components) + + def __eq__(self, other) -> bool: + if not isinstance(other, DistributedVariableTraceType): + return False + + return self.components == other.components + + +class DistributedVariable(DistributedDelegate, variables_lib.Variable, + core.Tensor): + """Holds a map from replica to variables.""" + + def __init__(self, strategy, values, aggregation, var_policy=None): + if (aggregation == variables_lib.VariableAggregation.MEAN and + not values[0].dtype.is_floating): + raise ValueError( + "creating distributed tf.Variable with aggregation=MEAN and a " + "non-floating dtype is not supported, please use a different " + "aggregation or dtype") + self._distribute_strategy = strategy + self._aggregation = aggregation + super(DistributedVariable, self).__init__(values) + self._common_name = self._primary.name.split(":")[0] + # Use a weakref to make it easy to map from the contained values + # to the container without introducing a reference cycle. + for v in values: + # ResourceVariable is a CompositeTensor. Attributes added to + # CompositeTensors will get lost through tf.nest packing and unpacking. + if isinstance(v, composite_tensor.CompositeTensor) and hasattr( + v, "handle"): + v.handle._distributed_container = weakref.ref(self) # pylint: disable=protected-access + else: + v._distributed_container = weakref.ref(self) # pylint: disable=protected-access + + # Packed variable is used to reduce the overhead of function execution. + # For a DistributedVariable, only one variable handle is captured into a + # function graph. It's only supported in eager mode. + if ops.executing_eagerly_outside_functions() and getattr( + strategy, "_enable_packed_variable_in_eager_mode", False): + name = "%s/packed/" % self._common_name + if hasattr(values[0], "_vars"): + # Handle when the resource variables are "nested" underneath another + # layer of values, e.g., TPUReplicatedVariable, by packing all them + # together and pushing the packed var down a level + # pylint: disable=protected-access + packed_var = packed.PackedDistributedVariable( + sum((value._vars for value in values), []), name=name) + for value in values: + value._packed_var = packed_var + self._packed_var = None + # pylint: enable=protected-access + else: + self._packed_var = packed.PackedDistributedVariable(values, name=name) + else: + self._packed_var = None + + # tf.keras keeps track of variables initialized using this attribute. When + # tf.keras gets the default session, it initializes all uninitialized vars. + # We need to make _keras_initialized a member of DistributedVariable because + # without this it will use `__getattr__` which will delegate to a component + # variable. + self._keras_initialized = False + # Typically, a `DistributedVariable`'s initializer is composed of the + # initializers of the components variables. However, in some cases, such as + # when restoring from a checkpoint, we may set the _initializer_op + # property on the entire `DistributedVariable`. + self._initializer_op = None + # Set a VariablePolicy which decides how we replicate/aggregate the given + # variable. + self._policy = var_policy + + def __deepcopy__(self, memo): + """Perform a deepcopy of the `DistributedVariable`. + + Unlike the deepcopy of a regular tf.Variable, this keeps the original + strategy and devices of the `DistributedVariable`. To avoid confusion + with the behavior of deepcopy on a regular `Variable` (which does + copy into new devices), we only allow a deepcopy of a `DistributedVariable` + within its originating strategy scope. + + Args: + memo: The memoization object for `deepcopy`. + + Returns: + A deep copy of the current `DistributedVariable`. + + Raises: + RuntimeError: If trying to deepcopy into a different strategy. + """ + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + new_values = [] + + for value in self._values: + with ops.device(value.device): + new_values.append(copy.deepcopy(value, memo)) + + copied_variable = type(self)( + strategy=self._distribute_strategy, + values=new_values, + aggregation=self._aggregation, + var_policy=copy.deepcopy(self._policy, memo)) + + memo[id(self)] = copied_variable + + return copied_variable + + def _use_packed_variable(self): + # Don't use packed variable when under a SaveContext to avoid explicit + # device placement on variable consuming ops. + return self._packed_var is not None and ( + not values_util.is_saving_non_distributed()) + + def is_initialized(self, name=None): + """Identifies if all the component variables are initialized. + + Args: + name: Name of the final `logical_and` op. + + Returns: + The op that evaluates to True or False depending on if all the + component variables are initialized. + """ + if values_util.is_saving_non_distributed(): + return self._primary.is_initialized() + if self._use_packed_variable(): + return self._packed_var.is_initialized() + result = self._primary.is_initialized() + # We iterate through the list of values except the last one to allow us to + # name the final `logical_and` op the same name that is passed by the user + # to the `is_initialized` op. For distributed variables, the + # `is_initialized` op is a `logical_and` op. + for v in self._values[1:-1]: + result = math_ops.logical_and(result, v.is_initialized()) + result = math_ops.logical_and( + result, self._values[-1].is_initialized(), name=name) + return result + + @property + def initializer(self): + if values_util.is_saving_non_distributed(): + return self._primary.initializer + if self._initializer_op: + init_op = self._initializer_op + else: + # return grouped ops of all the var initializations of component values of + # the mirrored variable + init_op = control_flow_ops.group( + tuple(v.initializer for v in self._values)) + return init_op + + def initialized_value(self): + return self._get_on_device_or_primary().initialized_value() + + def _is_mirrored(self): + return (self._policy is not None) and (self._policy._is_mirrored()) # pylint: disable=protected-access + + @property + def initial_value(self): + return self._get_on_device_or_primary().initial_value + + @property + def constraint(self): + return self._primary.constraint + + @property + def graph(self): + return self._primary.graph + + @property + def _shared_name(self): + return self._common_name + + @property + def _unique_id(self): + return self._primary._unique_id # pylint: disable=protected-access + + @property + def _graph_key(self): + """Lets Optimizers know which graph this variable is from.""" + return self._primary._graph_key # pylint: disable=protected-access + + @property + def name(self): + return self._primary.name + + @property + def dtype(self): + return self._primary.dtype + + @property + def shape(self): + return self._primary.shape + + @property + def synchronization(self): + return self._primary.synchronization + + @property + def aggregation(self): + return self._aggregation + + @property + def _packed_variable(self): + if self._use_packed_variable(): + return self._packed_var + return None + + @property + def handle(self): + if values_util.is_saving_non_distributed(): + return self._primary.handle + replica_id = values_util.get_current_replica_id_as_int() + if replica_id is None: + raise ValueError( + "DistributedVariable.handle is not available outside the replica " + "context or a `tf.distribute.Strategy.update()` call.") + else: + if self._use_packed_variable(): + return self._packed_var.handle + return self._values[replica_id].handle + + def eval(self, session=None): + return self._get_on_device_or_primary().eval(session) + + @property + def _save_slice_info(self): + return self._primary._save_slice_info # pylint: disable=protected-access + + def _get_save_slice_info(self): + return self._primary._get_save_slice_info() # pylint: disable=protected-access + + def _set_save_slice_info(self, save_slice_info): + for v in self._values: + v._set_save_slice_info(save_slice_info) # pylint: disable=protected-access + + @property + def device(self): + return self._get_on_device_or_primary().device + + @property + def trainable(self): + return self._primary.trainable + + @property + def distribute_strategy(self): + return self._distribute_strategy + + def get_shape(self) -> tensor_shape.TensorShape: + return self._primary.get_shape() + + def to_proto(self, export_scope=None): + return self._primary.to_proto(export_scope=export_scope) + + @property + def op(self) -> ops.Operation: + if values_util.is_saving_non_distributed(): + return self._primary.op + # We want cross-replica code that does some var.op.X calls + # to work (even if the current device isn't in self._devices), but + # other uses of var.op in a cross-replica context to fail. + if distribute_lib.in_cross_replica_context(): + return DistributedVarOp(self._primary.op.name, self._primary.op.graph, + self._primary.op.traceback, self._primary.op.type) + return self._get().op + + @property + def _in_graph_mode(self): + return self._primary._in_graph_mode # pylint: disable=protected-access + + def _get_replica(self, replica_id): + """Returns the value on a device with the given replica_id.""" + value = self._values[replica_id] + if self._use_packed_variable(): + return self._packed_var.on_device(value.device) + else: + return value + + def _get(self): + """Returns the value for the current device or raises a ValueError.""" + if values_util.is_saving_non_distributed(): + return self._primary + replica_id = values_util.get_current_replica_id_as_int() + if replica_id is None: + return self._get_cross_replica() + else: + return self._get_replica(replica_id) + + def _get_on_device_or_primary(self): + """Returns value in same replica or device if possible, else the _primary.""" + if values_util.is_saving_non_distributed(): + return self._primary + replica_id = values_util.get_current_replica_id_as_int() + if replica_id is None: + # Try to find a value on the current device. + current_device = device_util.canonicalize(device_util.current()) + for i, value in enumerate(self._values): + if device_util.canonicalize(value.device) == current_device: + return self._get_replica(i) + return self._get_replica(0) + else: + return self._get_replica(replica_id) + + def read_value(self): + if values_util.is_saving_non_distributed(): + return self._primary.read_value() + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + return array_ops.identity(self._get()) + + def value(self): + if values_util.is_saving_non_distributed(): + return self._primary.value() + if self._policy: + return self._policy.value(self) + return self._get_on_device_or_primary().value() + + def numpy(self): + if context.executing_eagerly(): + return self.read_value().numpy() + else: + raise NotImplementedError("DistributedVariable.numpy() is only available " + "when eager execution is enabled.") + + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign_sub(value, use_locking, name, read_value) + if self._policy: + return self._policy.assign_sub( + self, + value, + use_locking=use_locking, + name=name, + read_value=read_value) + return values_util.on_write_assign_sub( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign_add(value, use_locking, name, read_value) + if self._policy: + return self._policy.assign_add( + self, + value, + use_locking=use_locking, + name=name, + read_value=read_value) + return values_util.on_write_assign_add( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign(value, use_locking, name, read_value) + if self._policy: + return self._policy.assign( + self, + value, + use_locking=use_locking, + name=name, + read_value=read_value) + return values_util.on_write_assign( + self, value, use_locking=use_locking, name=name, read_value=read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_sub(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_sub( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_sub( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_add(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_add( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_add( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_mul(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_mul( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_mul( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_div(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_div( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_div( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_min(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_min( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_min( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_max(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_max( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_max( + self, sparse_delta, use_locking=use_locking, name=name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_update(sparse_delta, use_locking, name) + if self._policy: + return self._policy.scatter_update( + self, sparse_delta, use_locking=use_locking, name=name) + return values_util.scatter_update( + self, sparse_delta, use_locking=use_locking, name=name) + + def __tf_tracing_type__(self, _): + return DistributedVariableTraceType(self) + + def _gather_saveables_for_checkpoint(self): + """Overrides Trackable method. + + This allows both name-based and object-based save and restore of + DistributedVariables. + + Returns: + A dictionary mapping attribute names to `SaveableObject` factories. + """ + + def _saveable_factory(name=self._common_name): + return _DistributedVariableSaveable(self, self._primary, name) + + return {trackable.VARIABLE_VALUE_KEY: _saveable_factory} + + def _as_graph_element(self): + if values_util.is_saving_non_distributed(): + return self._primary._as_graph_element() # pylint: disable=protected-access + if self._policy: + return self._policy._as_graph_element(self) # pylint: disable=protected-access + + raise NotImplementedError( + "DistributedVariable._as_graph_element requires a valid " + "VariablePolicy. Please set the policy via the `var_policy` argument " + "in the constructor, or override this method in sub-classes which " + "support cross-replica accesses. " + f"Type name is {type(self)}" + ) + + def _get_cross_replica(self): + if values_util.is_saving_non_distributed(): + return self._primary + if self._policy: + return self._policy._get_cross_replica(self) # pylint: disable=protected-access + + raise NotImplementedError( + "DistributedVariable._get_cross_replica requires a valid " + "VariablePolicy. Please set the policy via the `var_policy` argument " + "in the constructor, or override this method in sub-classes which " + "support cross-replica accesses. " + f"Type name is {type(self)}" + ) + + def _update_cross_replica(self, update_fn, value, **kwargs): + """Applies updates across replicas. + + Args: + update_fn: A callable to pass to `strategy.extended.update` to update the + variable. It should has the same signature as `Variable.assign()`. + value: value to be passed to `update_fn`. + **kwargs: remaining arguments to `update_fn`. + + Returns: + Updated variable or `tf.Operation`. + """ + values_util.mark_as_unsaveable() + return self.distribute_strategy.extended.update( + self, update_fn, args=(value,), kwargs=kwargs, group=True) + + def _update_replica(self, update_fn, value, **kwargs): + """Applies updates in one replica. + + Args: + update_fn: A callable to update the variable. It should has the same + signature as `Variable.assign()`. + value: value to be passed to `update_fn`. + **kwargs: remaining arguments to `update_fn`. + + Returns: + Updated variable or `tf.Operation`. + """ + if self._policy: + return self._policy._update_replica(self, update_fn, value, **kwargs) # pylint: disable=protected-access + raise NotImplementedError( + "DistributedVariable._update_replica requires a valid VariablePolicy. " + "Please set the policy via the `var_policy` argument in the " + "constructor, or override this method in sub-classes which support " + "cross-replica accesses. " + f"Type name is {type(self)}" + ) + + def _update(self, update_fn, value, **kwargs): + """Applies updates depending on the context. + + The method calls `_update_replica` in replica context, + `_update_cross_replica` in cross replica context, and `update_fn` in update + context. + + If `read_value` is True, the method returns the updated Variable. If + `read_value` is False, the method returns the update `tf.Operation`. + + Args: + update_fn: A callable to pass to `strategy.extended.update` to update the + variable. It should have the same signature as `Variable.assign()`. + value: value to be passed to `update_fn`. + **kwargs: keyword arguments to `update_fn`. + + Returns: + Updated variable or `tf.Operation`. + + """ + if values_util.is_saving_non_distributed(): + return update_fn(self._primary, value, **kwargs) + with distribute_lib.enter_or_assert_strategy(self.distribute_strategy): + if distribute_lib.in_cross_replica_context(): + update_replica_id = distribute_lib.get_update_replica_id() + if update_replica_id is not None: + replica_value = self._get_replica(update_replica_id) + return update_fn(replica_value, value, **kwargs) + return self._update_cross_replica(update_fn, value, **kwargs) + else: + values_util.assert_replica_context(self.distribute_strategy) + return self._update_replica(update_fn, value, **kwargs) + + def _should_act_as_resource_variable(self): + """Pass resource_variable_ops.is_resource_variable check.""" + pass + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + """Converts a variable to a tensor.""" + if values_util.is_saving_non_distributed(): + return ops.convert_to_tensor( + self._primary, dtype=dtype, name=name, as_ref=as_ref) + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + return ops.convert_to_tensor( + self._get(), dtype=dtype, name=name, as_ref=as_ref) + + def __tf_tensor__(self, + dtype: Optional[dtypes.DType] = None, + name: Optional[str] = None) -> tensor_lib.Tensor: + return self._dense_var_to_tensor(dtype, name) + + def _export_to_saved_model_graph(self, + object_map=None, + tensor_map=None, + options=None, + **kwargs): + # Initialize for self._primary first, so that obj_map[self._primary] and + # resource_map[self._primary.handle] contain mapped values. + resource_list = self._primary._export_to_saved_model_graph( # pylint:disable=protected-access + object_map=object_map, + tensor_map=tensor_map, + options=options, + **kwargs) + for v in [v for v in self._values if v != self._primary]: + if (options.experimental_variable_policy # pylint:disable=protected-access + ._expand_distributed_variables()): + resource_list.extend( + v._export_to_saved_model_graph( # pylint:disable=protected-access + object_map=object_map, + tensor_map=tensor_map, + options=options, + **kwargs)) # pylint:disable=protected-access + else: + object_map[v] = object_map[self._primary] + tensor_map[v.handle] = tensor_map[self._primary.handle] + resource_list.append(v.handle) + object_map[self] = object_map[self._primary] + tensor_map[self] = tensor_map[self._primary.handle] + resource_list.append(self) + if self._packed_var is not None: + tensor_map[self._packed_var.packed_handle] = tensor_map[ + self._primary.handle] + resource_list.append(self._packed_var.packed_handle) + return resource_list + + def _copy_trackable_to_cpu(self, object_map): + """For implementing `Trackable`.""" + if self not in object_map: + # If not populated, initialize the cpu copy first. + op_device = pydev.DeviceSpec.from_string(self.device).replace( + device_type="CPU", device_index=0).to_string() + with ops.device(op_device): + new_var = resource_variable_ops.UninitializedVariable( + trainable=self.trainable, + shape=self.shape, + dtype=self.dtype, + name=self._shared_name, + distribute_strategy=self._distribute_strategy, + aggregation=self._aggregation) # pylint: disable=protected-access + object_map[self] = new_var + + # Then copy value of self to the copy. + destination_var = object_map[self] + with ops.device(destination_var.device): + destination_var.assign(self.read_value()) + + def _write_object_proto(self, proto, options): + """Update a SavedObject proto for the caller. + + If a DistributedVariable object supports this method, it will be called when + saving with a pre-built `SavedObject` proto representing the object, plus an + instance of `SaveOptions`. This method is then free to modify that proto + instance. + + `DistributedVariable` with `AUTO` or `ON_WRITE` synchronization optionally + write out information about their components to the + `experimental_distributed_variable_components` field of a + `SavedVariable` (depending on the `SaveOptions` variable policy). + + Args: + proto: A pre-built `SavedObject` proto for this object. It is assumed this + will be a `SavedVariable` instance. + options: A `SaveOptions` instance. + """ + resource_variable_ops.write_object_proto_for_resource_variable( + self, proto, options) + # Set protos in the saved model such that distributed variables are + # correctly restored on COMPOSITE devices (otherwise, task:0/TPU:0). + values_util.write_object_proto(self, proto, options) + + @property + def is_distributed_variable(self): + return True + + def __tf_experimental_restore_capture__( + self, concrete_function, internal_capture): + graph = concrete_function.graph + # Add given distributed variable to captures with given placeholder. + graph.replace_capture(self, internal_capture) + record.record_operation( + "captured_value", [internal_capture], [self], + backward_function=lambda x: [x], + forward_function=lambda x: [x]) + return self + + +# We extend from `saveable_object.SaveableObject` instead of +# `saveable_object_util.ResourceVariableSaveable` since we need to read the +# value of ONREAD variables when saving. `SaveableObject` provides a way to +# specify the function to run to get the value of the variable or tensor at +# saving time. We can use this for both ON_READ and ON_WRITE variables. +# TODO(b/164586507): Consolidate ON_WRITE and ON_READ saving/restoring logic +# if possible. +class _DistributedVariableSaveable(saveable_object.SaveableObject): + """Class for defining how to restore a DistributedVariable.""" + + def __init__(self, distributed_variable, primary_variable, name): + self._distributed_variable = distributed_variable + if not self._distributed_variable._policy: + raise ValueError( + "The VariablePolicy of the argument `distributed_variable` must be " + "set to create a _DistributedVariableSaveable. Please set it via " + "the `var_policy` argument in the constructor of DistributedVariable." + ) + tensor, spec = distributed_variable._policy.get_saveable( + distributed_variable, primary_variable, name) + super(_DistributedVariableSaveable, self).__init__(tensor, spec, name) + + def restore(self, restored_tensors, restored_shapes): + """Restore the same value into all variables.""" + tensor, = restored_tensors + return self._distributed_variable._policy.get_restore_ops( # pylint: disable=protected-access + self._distributed_variable, tensor) + + +class _MirroredSaveable(saveable_object.SaveableObject): + """Class for defining how to restore a MirroredVariable.""" + + def __init__(self, mirrored_variable, primary_variable, name): + self._mirrored_variable = mirrored_variable + tensor, spec = values_util.get_on_write_saveable(self._mirrored_variable, + primary_variable, name) + super(_MirroredSaveable, self).__init__(tensor, spec, name) + + def restore(self, restored_tensors, restored_shapes): + """Restore the same value into all variables.""" + tensor, = restored_tensors + return values_util.get_on_write_restore_ops(self._mirrored_variable, tensor) + + +class MirroredVariable(DistributedVariable, Mirrored): + """Holds a map from replica to variables whose values are kept in sync.""" + + def _is_mirrored(self): + return Mirrored._is_mirrored(self) # Use correct parent class. + + def _update_replica(self, update_fn, value, **kwargs): + return _on_write_update_replica(self, update_fn, value, **kwargs) + + def scatter_min(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_min(*args, **kwargs) + if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and + self._aggregation != vs.VariableAggregation.NONE): + raise NotImplementedError( + values_util.scatter_error_msg.format( + op_name="scatter_min", aggregation=self._aggregation)) + return super(MirroredVariable, self).scatter_min(*args, **kwargs) + + def scatter_max(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_max(*args, **kwargs) + if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and + self._aggregation != vs.VariableAggregation.NONE): + raise NotImplementedError( + values_util.scatter_error_msg.format( + op_name="scatter_max", aggregation=self._aggregation)) + return super(MirroredVariable, self).scatter_max(*args, **kwargs) + + def scatter_update(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_update(*args, **kwargs) + if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and + self._aggregation != vs.VariableAggregation.NONE): + raise NotImplementedError( + values_util.scatter_error_msg.format( + op_name="scatter_update", aggregation=self._aggregation)) + return super(MirroredVariable, self).scatter_update(*args, **kwargs) + + def _get_cross_replica(self): + # Return identity, to avoid directly exposing the variable to the user and + # allowing it to be modified by mistake. + return array_ops.identity(Mirrored._get_cross_replica(self)) + + def _as_graph_element(self): + return self._get_on_device_or_primary()._as_graph_element() # pylint: disable=protected-access + + def _gather_saveables_for_checkpoint(self): + """Overrides Trackable method. + + This allows both name-based and object-based save and restore of + MirroredVariables. + + Returns: + A dictionary mapping attribute names to `SaveableObject` factories. + """ + + def _saveable_factory(name=self._common_name): + return _MirroredSaveable(self, self._primary, name) + + return {trackable.VARIABLE_VALUE_KEY: _saveable_factory} + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + """Converts a variable to a tensor.""" + # TODO(b/154017756): Make _dense_var_to_tensor consistent between ON_READ + # and ON_WRITE. + # Try to avoid assignments to and other mutations of MirroredVariable + # state except through a DistributionStrategy.extended.update() or any of + # the `assign*` and `scatter*` calls. + if as_ref: + # A TF 1.x case where the variable is a boolean variable and used like: + # tf.cond(v, true_fn, false_fn). + raise ValueError( + "You may be using variable created under distribute strategy in TF " + "1.x control flows. Try explicitly converting the variable to Tensor " + "using variable.read_value(), or switch to TF 2.x.") + return ops.convert_to_tensor( + self._get(), dtype=dtype, name=name, as_ref=as_ref) + + +class _SyncOnReadSaveable(saveable_object.SaveableObject): + """Class for defining how to restore a SyncOnReadVariable.""" + + def __init__(self, sync_on_read_variable, name): + self._sync_on_read_variable = sync_on_read_variable + tensor, spec = values_util.get_on_read_saveable( + sync_on_read_variable, sync_on_read_variable._primary, name) + + super(_SyncOnReadSaveable, self).__init__(tensor, spec, name) + + def restore(self, restored_tensors, restored_shapes): + """Restore the same value into all variables.""" + tensor, = restored_tensors + return values_util.get_on_read_restore_ops( + self._sync_on_read_variable, tensor, + self._sync_on_read_variable.aggregation) + + +class SyncOnReadVariable(DistributedVariable): + """Holds a map from replica to variables whose values are reduced on save.""" + + def _update_replica(self, update_fn, value, **kwargs): + return update_fn(self._get_on_device_or_primary(), value, **kwargs) + + def _get(self): + """Returns the value of SyncOnReadVariable based on surrounding context. + + If called under a non-default replica-context, returns the corresponding + variable on that replica. + If called under default replica-context or cross-replica context, returns + the synced value. + """ + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + return super(SyncOnReadVariable, self)._get() + + # TODO(b/154017756): Make assign behaivor in cross replica context consistent + # with MirroredVariable. + def assign_sub(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign_sub(value, use_locking, name, read_value) + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + values_util.mark_as_unsaveable() + return values_util.on_read_assign_sub_cross_replica( + self, value, read_value=read_value) + else: + return super(SyncOnReadVariable, + self).assign_sub(value, use_locking, name, read_value) + + def assign_add(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign_add(value, use_locking, name, read_value) + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + values_util.mark_as_unsaveable() + return values_util.on_read_assign_add_cross_replica( + self, value, read_value=read_value) + else: + return super(SyncOnReadVariable, + self).assign_add(value, use_locking, name, read_value) + + def assign(self, value, use_locking=False, name=None, read_value=True): + if values_util.is_saving_non_distributed(): + return self._primary.assign(value, use_locking, name, read_value) + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + values_util.mark_as_unsaveable() + return values_util.on_read_assign_cross_replica( + self, value, read_value=read_value) + else: + return super(SyncOnReadVariable, self).assign(value, use_locking, name, + read_value) + + def _scatter_not_implemented(self, method): + raise NotImplementedError( + f"Variables with `synchronization=ON_READ` doesn't support `{method}`") + + def scatter_sub(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_sub(*args, **kwargs) + self._scatter_not_implemented("scatter_sub") + + def scatter_add(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_add(*args, **kwargs) + self._scatter_not_implemented("scatter_add") + + def scatter_mul(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_mul(*args, **kwargs) + self._scatter_not_implemented("scatter_mul") + + def scatter_div(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_div(*args, **kwargs) + self._scatter_not_implemented("scatter_div") + + def scatter_min(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_min(*args, **kwargs) + self._scatter_not_implemented("scatter_min") + + def scatter_max(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_max(*args, **kwargs) + self._scatter_not_implemented("scatter_max") + + def scatter_update(self, *args, **kwargs): + if values_util.is_saving_non_distributed(): + return self._primary.scatter_update(*args, **kwargs) + self._scatter_not_implemented("scatter_update") + + def value(self): + if distribute_lib.in_variable_sync_on_read_context(): + raise NotImplementedError( + "call `variable.value()` inside variable_sync_on_read_context is not " + "supported") + if values_util.is_saving_non_distributed(): + return self._primary.value() + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + return self._get_replica(0).value() + return self._get_cross_replica() + else: + # _get_on_device_or_primary() returns a Variable. + return self._get_on_device_or_primary().value() + + def read_value(self): + if distribute_lib.in_variable_sync_on_read_context(): + raise NotImplementedError( + "call `variable.read_value()` inside variable_sync_on_read_context is" + " not supported") + return super().read_value() + + def _get_cross_replica(self): + if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + # Consider returning a tensor value here to make the return value of + # _get_cross_replica consistent. + return self._get_replica(0) + if self._aggregation == vs.VariableAggregation.SUM: + values_util.mark_as_unsaveable() + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + return self._distribute_strategy.reduce( + reduce_util.ReduceOp.from_variable_aggregation(self._aggregation), + self, + axis=None) + + def _as_graph_element(self): + if values_util.is_saving_non_distributed(): + return self._primary._as_graph_element() # pylint: disable=protected-access + # pylint: disable=protected-access + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + if distribute_lib.in_cross_replica_context(): + return ops.convert_to_tensor(self._get_cross_replica()) + return self._get()._as_graph_element() + + def _gather_saveables_for_checkpoint(self): + """Overrides Trackable method. + + This allows both name-based and object-based save and restore of + `SyncOnReadVariable`s. + + Returns: + A dictionary mapping attribute names to `SaveableObject` factories. + """ + + def _saveable_factory(name=self._common_name): + return _SyncOnReadSaveable(self, name) + + return {trackable.VARIABLE_VALUE_KEY: _saveable_factory} + + def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): + """Converts a SyncOnReadVariable to a tensor.""" + if values_util.is_saving_non_distributed(): + return ops.convert_to_tensor( + self._primary, dtype=dtype, name=name, as_ref=as_ref) + with distribute_lib.enter_or_assert_strategy(self._distribute_strategy): + replica_context = distribute_lib.get_replica_context() + if (replica_context is not None and + distribute_lib.in_variable_sync_on_read_context()): + if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + return ops.convert_to_tensor( + self._get_replica(0), dtype=dtype, name=name, as_ref=as_ref) + if self._aggregation == vs.VariableAggregation.SUM: + values_util.mark_as_unsaveable() + # pylint: disable=protected-access + reduced = ( + replica_context.strategy.extended._replica_ctx_all_reduce( + reduce_util.ReduceOp.from_variable_aggregation( + self._aggregation), + self._get().read_value())) + return ops.convert_to_tensor( + reduced, dtype=dtype, name=name, as_ref=as_ref) + + return ops.convert_to_tensor( + self._get(), dtype=dtype, name=name, as_ref=as_ref) + + +# Register a conversion functions which reads the value of the variable, +# allowing instances of the class to be used as tensors. +# DistributedVariable +def _tensor_conversion_distributed_var(var, + dtype=None, + name=None, + as_ref=False): + return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + DistributedVariable, _tensor_conversion_distributed_var) + + +# MirroredVariables +def _tensor_conversion_mirrored(var, dtype=None, name=None, as_ref=False): + return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + MirroredVariable, _tensor_conversion_mirrored) + + +# Mirrored Values +def _tensor_conversion_mirrored_val(value, dtype=None, name=None, as_ref=False): + return ops.convert_to_tensor( + value._get(), dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + Mirrored, _tensor_conversion_mirrored_val) + + +# SyncOnReadVariables +def _tensor_conversion_sync_on_read(var, dtype=None, name=None, as_ref=False): + return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access + + +tensor_conversion_registry.register_tensor_conversion_function( + SyncOnReadVariable, _tensor_conversion_sync_on_read) + + +class VariablePolicy(object): + """Policy defining synchronization and aggregation of a distributed variable. + + Given `synchronization` and `aggregation` parameters set on a `tf.Variable` + during variable creation within `tf.distribute` scope, `tf.distribute` creates + an appropriate policy object and assigns it to the distributed variable. All + variable operations are delegated to the respective policy object. + """ + + def __init__(self, aggregation): + self._aggregation = aggregation + + def value(self): + raise NotImplementedError( + "VariablePolicy.value should be overridden by sub-classes. " + f"Type name is {type(self)}" + ) + + def _is_mirrored(self): + raise NotImplementedError( + "VariablePolicy._is_mirrored should be overridden by sub-classes. " + f"Type name is {type(self)}" + ) + + def _as_graph_element(self, _): + raise NotImplementedError( + "VariablePolicy._as_graph_element should be overridden by sub-classes. " + f"Type name is {type(self)}" + ) + + def _get_cross_replica(self, var): + raise NotImplementedError( + "VariablePolicy._get_cross_replica should be overridden by" + f" sub-classes. Type name is {type(self)}" + ) + + def _update_replica(self, var, update_fn, value, **kwargs): + raise NotImplementedError( + "VariablePolicy._update_replica should be overridden by sub-classes. " + f"Type name is {type(self)}" + ) + + +class OnReadPolicy(VariablePolicy): + """Policy defined for `tf.VariableSynchronization.ON_READ` synchronization. + + This policy is created when `synchronization` is set to + `tf.VariableSynchronization.ON_READ` and `aggregation` is set to any of the + values allowed by the `tf.VariableAggregation` enum such as `NONE`, `SUM`, + `MEAN` or `ONLY_FIRST_REPLICA`when creating a `tf.Variable` in `tf.distribute` + scope. + """ + + def _is_mirrored(self): + return False + + def value(self, var): + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + return var._get_replica(0).value() # pylint: disable=protected-access + return var._get_cross_replica() # pylint: disable=protected-access + else: + return var._get_on_device_or_primary().value() # pylint: disable=protected-access + + def _as_graph_element(self, var): + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if distribute_lib.in_cross_replica_context(): + return ops.convert_to_tensor(var._get_cross_replica()) # pylint: disable=protected-access + return var._get()._as_graph_element() # pylint: disable=protected-access + + def _get_cross_replica(self, var): + if self._aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + return var._get_replica(0) # pylint: disable=protected-access + if self._aggregation == vs.VariableAggregation.SUM: + values_util.mark_as_unsaveable() + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + return var.distribute_strategy.reduce( + reduce_util.ReduceOp.from_variable_aggregation(self._aggregation), + var, + axis=None) + + def _update_replica(self, var, update_fn, value, **kwargs): + return update_fn(var._get_on_device_or_primary(), value, **kwargs) # pylint: disable=protected-access + + def _scatter_not_implemented(self, method): + raise NotImplementedError(f"ON_READ variables doesn't support `{method}` " + "in cross replica context") + + def assign_sub(self, + var, + value, + use_locking=False, + name=None, + read_value=True): + """Subtracts a value from this variable.""" + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + values_util.mark_as_unsaveable() + return values_util.on_read_assign_sub_cross_replica( + var, value, read_value=read_value) + else: + return values_util.on_write_assign_sub( + var, + value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def assign_add(self, + var, + value, + use_locking=False, + name=None, + read_value=True): + """Adds a value to this variable.""" + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + values_util.mark_as_unsaveable() + return values_util.on_read_assign_add_cross_replica( + var, value, read_value=read_value) + else: + return values_util.on_write_assign_add( + var, + value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def assign(self, var, value, use_locking=False, name=None, read_value=True): + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if (distribute_lib.in_cross_replica_context() and + not values_util.in_replica_update_context()): + values_util.mark_as_unsaveable() + return values_util.on_read_assign_cross_replica( + var, value, read_value=read_value) + else: + return values_util.on_write_assign( + var, + value, + use_locking=use_locking, + name=name, + read_value=read_value) + + def scatter_sub(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_sub") + + def scatter_add(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_add") + + def scatter_mul(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_mul") + + def scatter_div(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_div") + + def scatter_min(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_min") + + def scatter_max(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_max") + + def scatter_update(self, *args, **kwargs): + del args, kwargs + self._scatter_not_implemented("scatter_update") + + def get_saveable(self, var, primary_var, name): + """Create a saveable object for the given variable.""" + return values_util.get_on_read_saveable(var, primary_var, name) + + def get_restore_ops(self, var, tensor): + """Restore the same value into all variables.""" + return values_util.get_on_read_restore_ops(var, tensor, self._aggregation) + + +class OnWritePolicy(VariablePolicy): + """Policy defined for `tf.VariableSynchronization.ON_WRITE` synchronization. + + This policy is created when the following `synchronization` and `aggregation` + parameters are specified when creating a `tf.Variable` in `tf.distribute` + scope and `synchronization` is equal to `tf.VariableSynchronization.ON_WRITE` + or `tf.VariableSynchronization.AUTO`. + """ + + def _is_mirrored(self): + return True + + def value(self, var): + return var._get_on_device_or_primary().value() # pylint: disable=protected-access + + def _as_graph_element(self, var): + return var._get_on_device_or_primary()._as_graph_element() # pylint: disable=protected-access + + def _get_cross_replica(self, var): + # Return identity, to avoid directly exposing the variable to the user and + # allowing it to be modified by mistake. + return array_ops.identity(var._get_on_device_or_primary()) # pylint: disable=protected-access + + def _update_replica(self, var, update_fn, value, **kwargs): + if var.aggregation == variables_lib.VariableAggregation.NONE: + return update_fn(var._get_on_device_or_primary(), value, **kwargs) # pylint: disable=protected-access + return _on_write_update_replica(var, update_fn, value, **kwargs) + + def assign(self, var, value, use_locking=False, name=None, read_value=True): + return values_util.on_write_assign( + var, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign_add(self, + var, + value, + use_locking=False, + name=None, + read_value=True): + return values_util.on_write_assign_add( + var, value, use_locking=use_locking, name=name, read_value=read_value) + + def assign_sub(self, + var, + value, + use_locking=False, + name=None, + read_value=True): + return values_util.on_write_assign_sub( + var, value, use_locking=use_locking, name=name, read_value=read_value) + + def scatter_sub(self, var, sparse_delta, use_locking=False, name=None): + return values_util.scatter_sub( + var, sparse_delta, use_locking=use_locking, name=name) + + def scatter_add(self, var, sparse_delta, use_locking=False, name=None): + return values_util.scatter_add( + var, sparse_delta, use_locking=use_locking, name=name) + + def scatter_mul(self, var, sparse_delta, use_locking=False, name=None): + return values_util.scatter_mul( + var, sparse_delta, use_locking=use_locking, name=name) + + def scatter_div(self, var, sparse_delta, use_locking=False, name=None): + return values_util.scatter_div( + var, sparse_delta, use_locking=use_locking, name=name) + + def scatter_min(self, var, sparse_delta, use_locking=False, name=None): + if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and + self._aggregation != vs.VariableAggregation.NONE): + raise NotImplementedError( + values_util.scatter_error_msg.format( + op_name="scatter_min", aggregation=self._aggregation)) + return values_util.scatter_min( + var, sparse_delta, use_locking=use_locking, name=name) + + def scatter_max(self, var, sparse_delta, use_locking=False, name=None): + if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and + self._aggregation != vs.VariableAggregation.NONE): + raise NotImplementedError( + values_util.scatter_error_msg.format( + op_name="scatter_max", aggregation=self._aggregation)) + return values_util.scatter_max( + var, sparse_delta, use_locking=use_locking, name=name) + + def scatter_update(self, var, sparse_delta, use_locking=False, name=None): + if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and + self._aggregation != vs.VariableAggregation.NONE): + raise NotImplementedError( + values_util.scatter_error_msg.format( + op_name="scatter_update", aggregation=self._aggregation)) + return values_util.scatter_update( + var, sparse_delta, use_locking=use_locking, name=name) + + def get_saveable(self, var, primary_var, name): + """Saveable ops for AUTO variables.""" + return values_util.get_on_write_saveable(var, primary_var, name) + + def get_restore_ops(self, var, tensor): + return values_util.get_on_write_restore_ops(var, tensor) + + +class PerWorkerResource(): + """A per-worker CapturableResource class for non-ParameterServer strategy. + + Resources that populate `host_to_resources` should be instances of classes + subclassing CapturableResource, although currently it's only used and tested + for StaticHashTable with TPUStrategy. + """ + + def __init__(self, strategy, host_to_resources): + distribute_lib.distribution_strategy_input_api_counter.get_cell( + "PerWorkerResource", "TPUDistributedLookupTable").increase_by(1) + self._strategy = strategy + self._host_to_resources = host_to_resources + + def __getattribute__(self, name): + if name not in ("__init__", "__getattribute__", "_host_to_resources", + "_strategy", "local_resource"): + return getattr(self.local_resource(), name) + return super(PerWorkerResource, self).__getattribute__(name) + + def __setattr__(self, name, value): + if name not in ("_strategy", "_host_to_resources"): + return setattr(self.local_resource(), name, value) + return super(PerWorkerResource, self).__setattr__(name, value) + + def local_resource(self): + """Returns the resource on the local worker.""" + current_device = device_util.canonicalize(device_util.current()) + host_device = device_util.canonicalize( + device_util.get_host_for_device(current_device)) + return self._host_to_resources.get( + host_device, + self._host_to_resources[next(iter(self._host_to_resources))]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values_util.py new file mode 100644 index 0000000000000000000000000000000000000000..664e9405403c35d18e91c58cc6caea05a8c5a317 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values_util.py @@ -0,0 +1,388 @@ +# 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. +# ============================================================================== +"""Utility functions used by values.py and ps_values.py.""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import reduce_util +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.saved_model import save_context +from tensorflow.python.saved_model import save_options +from tensorflow.python.training.saving import saveable_object + + +def write_object_proto(var, proto, options): + """Update a SavedObject proto for the caller. + + If a DistributedVariable object supports this method, it will be called when + saving with a pre-built `SavedObject` proto representing the object, plus an + instance of `SaveOptions`. This method is then free to modify that proto + instance. + + `DistributedVariable` with `AUTO` or `ON_WRITE` synchronization optionally + write out information about their components to the + `experimental_distributed_variable_components` field of a + `SavedVariable` (depending on the `SaveOptions` variable policy). + + Args: + var: The DistributedVariable object. + proto: A pre-built `SavedObject` proto for this object. It is assumed this + will be a `SavedVariable` instance. + options: A `SaveOptions` instance. + """ + if options.experimental_variable_policy._expand_distributed_variables( # pylint: disable=protected-access + ): + for var in var.values: + var_proto = ( + proto.variable.experimental_distributed_variable_components.add()) + var_proto.name = var.name.split(":")[0] + var_proto.device = var.device + + +def get_on_write_saveable(var, primary_var, name): + """Return saveable spec for AUTO and ON_WRITE variables.""" + # We use a callable so that we don't have to evaluate this expression + # in the case where we are trying to restore instead of save. + def tensor(): + if context.executing_eagerly() and not primary_var.is_initialized(): + # A SaveSpec tensor value of `None` indicates that the variable is + # uninitialized. + return None + strategy = var.distribute_strategy + return strategy.extended.read_var(var) + + spec = saveable_object.SaveSpec( + tensor=tensor, + slice_spec="", + name=name, + dtype=var.dtype, + device=primary_var.device) + + return tensor, [spec] + + +def get_on_write_restore_ops(var, tensor): + """Return restore ops for AUTO and ON_WRITE variables.""" + packed_var = var._packed_variable # pylint: disable=protected-access + if packed_var is not None: + return control_flow_ops.group( + tuple( + assign_on_device(d, packed_var, tensor) + for d in packed_var.devices)) + return control_flow_ops.group( + tuple( + assign_on_device(v.device, v, tensor) + for v in var.values)) + + +def get_on_read_saveable(var, primary_var, name): + """Return saveables for ON_READ variable.""" + + # We use a callable so that we don't have to evaluate this expression + # in the case where we are trying to restore instead of save. + def tensor(): + return var._get_cross_replica() # pylint: disable=protected-access + + spec = saveable_object.SaveSpec( + tensor=tensor, + slice_spec="", + name=name, + dtype=var.dtype, + device=primary_var.device) + + return tensor, [spec] + + +def get_on_read_restore_ops(var, tensor, aggregation): + """Return restore ops for ON_READ variables.""" + # To preserve the sum across save and restore, we have to divide the + # total across all devices when restoring a variable that was summed + # when saving. + if aggregation == vs.VariableAggregation.SUM: + strategy = var.distribute_strategy + tensor = math_ops.cast(tensor / strategy.num_replicas_in_sync, + var.dtype) + return control_flow_ops.group( + tuple( + assign_on_device(v.device, v, tensor) + for v in var.values)) + + +# Utility function that indicates if you are in an UpdateContext when running +# in a replica fn. +def in_replica_update_context(): + return distribute_lib.get_update_replica_id() is not None + + +def on_write_assign(var, value, use_locking=False, name=None, read_value=True): + assign_fn = lambda var, *a, **kw: var.assign(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=assign_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + +def on_write_assign_add(var, value, use_locking=False, name=None, + read_value=True): + assign_add_fn = lambda var, *a, **kw: var.assign_add(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=assign_add_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + +def on_write_assign_sub(var, value, use_locking=False, name=None, + read_value=True): + assign_sub_fn = lambda var, *a, **kw: var.assign_sub(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=assign_sub_fn, + value=value, + use_locking=use_locking, + name=name, + read_value=read_value) + + +def assign_on_each_device(var, assign_func, value, read_value): + """Update the variable on each replica with the given assign_func and value.""" + if var._packed_variable is not None: # pylint: disable=protected-access + update = control_flow_ops.group( + tuple( + assign_func(d, var._packed_variable, value) for d in var._devices)) # pylint: disable=protected-access + else: + update = control_flow_ops.group( + tuple(assign_func(v.device, v, value) for v in var._values)) # pylint: disable=protected-access + if not read_value: + return update + with ops.control_dependencies([update] if update else []): + return var.read_value() + + +def on_read_assign_sub_cross_replica(var, value, read_value=True): + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if distribute_lib.in_cross_replica_context(): + if var.aggregation == vs.VariableAggregation.SUM: + raise ValueError( + "SyncOnReadVariable does not support `assign_sub` in " + "cross-replica context when aggregation is set to " + "`tf.VariableAggregation.SUM`.") + return assign_on_each_device(var, assign_sub_on_device, + value, read_value) + + +def on_read_assign_add_cross_replica(var, value, read_value=True): + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if distribute_lib.in_cross_replica_context(): + if var.aggregation == vs.VariableAggregation.SUM: + raise ValueError( + "SyncOnReadVariable does not support `assign_add` in " + "cross-replica context when aggregation is set to " + "`tf.VariableAggregation.SUM`.") + return assign_on_each_device(var, assign_add_on_device, + value, read_value) + + +def on_read_assign_cross_replica(var, value, read_value=True): + """Return the value of the variable in cross replica context.""" + with distribute_lib.enter_or_assert_strategy(var.distribute_strategy): + if distribute_lib.in_cross_replica_context(): + # To preserve the sum across save and restore, we have to divide the + # total across all devices when restoring a variable that was summed + # when saving. + tensor = value + if var.aggregation == vs.VariableAggregation.SUM: + strategy = var._distribute_strategy # pylint: disable=protected-access + tensor = math_ops.cast(tensor / strategy.num_replicas_in_sync, + var.dtype) + return assign_on_each_device(var, assign_on_device, tensor, + read_value) + + +def scatter_sub(var, sparse_delta, use_locking=False, name=None): + scatter_sub_fn = lambda var, *a, **kw: var.scatter_sub(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_sub_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def scatter_add(var, sparse_delta, use_locking=False, name=None): + scatter_add_fn = lambda var, *a, **kw: var.scatter_add(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_add_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def scatter_mul(var, sparse_delta, use_locking=False, name=None): + scatter_mul_fn = lambda var, *a, **kw: var.scatter_mul(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_mul_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def scatter_div(var, sparse_delta, use_locking=False, name=None): + scatter_div_fn = lambda var, *a, **kw: var.scatter_div(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_div_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def scatter_min(var, sparse_delta, use_locking=False, name=None): + scatter_min_fn = lambda var, *a, **kw: var.scatter_min(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_min_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def scatter_max(var, sparse_delta, use_locking=False, name=None): + scatter_max_fn = lambda var, *a, **kw: var.scatter_max(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_max_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def scatter_update(var, sparse_delta, use_locking=False, name=None): + scatter_update_fn = lambda var, *a, **kw: var.scatter_update(*a, **kw) + return var._update( # pylint: disable=protected-access + update_fn=scatter_update_fn, + value=sparse_delta, + use_locking=use_locking, + name=name) + + +def get_current_replica_id_as_int(): + """Returns the current replica ID as an integer, or `None`.""" + replica_context = distribute_lib.get_replica_context() + if replica_context: + replica_id = replica_context._replica_id # pylint: disable=protected-access + if not isinstance(replica_id, int): + replica_id = tensor_util.constant_value(replica_id) + else: + replica_id = distribute_lib.get_update_replica_id() + return replica_id + + +def assign_on_device(device, variable, tensor): + with ops.device(device): + return variable.assign(tensor) + + +def assign_add_on_device(device, variable, tensor): + with ops.device(device): + return variable.assign_add(tensor) + + +def assign_sub_on_device(device, variable, tensor): + with ops.device(device): + return variable.assign_sub(tensor) + + +def assert_replica_context(strategy): + replica_context = distribute_lib.get_replica_context() + if not replica_context: + raise RuntimeError( + "Replica-local variables may only be assigned in a replica context.") + if replica_context.strategy is not strategy: + raise RuntimeError( + "Replica-local variables may only be assigned in a replica context.") + + +def apply_aggregation(strategy, value, aggregation, destinations): + if aggregation == vs.VariableAggregation.ONLY_FIRST_REPLICA: + return strategy.extended.broadcast_to( + strategy.experimental_local_results(value)[0], + destinations=destinations) + reduce_op = reduce_util.ReduceOp.from_variable_aggregation(aggregation) + return strategy.extended.reduce_to(reduce_op, value, destinations) + + +aggregation_error_msg = ( + "You must specify an aggregation method to update a " + "{variable_type} in Replica Context. You can do so by passing " + "an explicit value for argument `aggregation` to tf.Variable(..)." + "e.g. `tf.Variable(..., aggregation=tf.VariableAggregation.SUM)`" + "`tf.VariableAggregation` lists the possible aggregation methods." + "This is required because {variable_type} should always be " + "kept in sync. When updating them or assigning to them in a " + "replica context, we automatically try to aggregate the values " + "before updating the variable. For this aggregation, we need to " + "know the aggregation method. " + "Another alternative is to not try to update such " + "{variable_type} in replica context, but in cross replica " + "context. You can enter cross replica context by calling " + "`tf.distribute.get_replica_context().merge_call(merge_fn, ..)`." + "Inside `merge_fn`, you can then update the {variable_type} " + "using `tf.distribute.StrategyExtended.update()`.") + + +scatter_error_msg = ("{op_name} is only supported for mirrored " + "variable (variable created within certain " + "`tf.distribute.Strategy` scope) with NONE or " + "`ONLY_FIRST_REPLICA` aggregation, got: {aggregation}.") + + +def is_saving_non_distributed(): + """Returns whether we're saving a non-distributed version of the model. + + It returns True iff we are in saving context and are saving a non-distributed + version of the model. That is, SaveOptions.experimental_variable_policy is + NONE. + + Returns: + A boolean. + """ + if not save_context.in_save_context(): + return False + options = save_context.get_save_options() + return (options.experimental_variable_policy != + save_options.VariablePolicy.EXPAND_DISTRIBUTED_VARIABLES) + + +def mark_as_unsaveable(): + """Marks the function as unsaveable if not inside save context.""" + if ops.inside_function() and not save_context.in_save_context(): + ops.get_default_graph().mark_as_unsaveable(""" +ConcreteFunction that uses distributed variables in certain way cannot be saved. +If you're saving with + +tf.saved_model.save(..., signatures=f.get_concrete_function()) + +do + +@tf.function(input_signature=...) +def f_with_input_signature(): + ... + +tf.saved_model.save(..., signatures=f_with_input_signature)` + +instead.""") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..f7ae4f469edda2f2dc2eb99dc283f0b0e81e51f4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/distribute/values_v2.py @@ -0,0 +1,268 @@ +# 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. +# ============================================================================== +"""Various classes representing distributed values.""" + +import copy +import weakref + +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute import tpu_util +from tensorflow.python.distribute import values_util +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables as variables_lib + + +# pylint: disable=protected-access + + +class DistributedVariable(resource_variable_ops.BaseResourceVariable): + """Represents variables that are replicated. + + It behaves exactly as a normal variable, but uses corresponding variable + handle based on the context. + - In each replica, it uses the handle from that replica. + - In tpu.replicate(), it uses the replicated handle. + - Otherwise, it uses the handle from the primary replica. + + Note that it doesn't synchronize automatically as the old DistributedVariable + in values.py. + """ + + def __init__(self, variables, *, enable_packed_handle=False): + if enable_packed_handle and not ops.executing_eagerly_outside_functions(): + raise ValueError( + "Argument `enable_packed_handle` is true, but packed handle is only " + "supported in eager mode. Please make sure eager execution is " + "enabled.") + self._variables = variables + if enable_packed_handle: + self._packed_handle = ops.pack_eager_tensors( + [v.handle for v in variables]) + else: + self._packed_handle = None + for v in variables: + v.handle._distributed_container = weakref.ref(self) # pylint: disable=protected-access + self._device_to_handle = {v.device: v.handle for v in variables} + self._primary_handle = variables[0].handle + with ops.init_scope(), \ + ops.name_scope("DistributedVariable", skip_on_eager=False) as name: + handle_name = ops.name_from_scope_name(name) + self._unique_id = "%s_%d" % (handle_name, ops.uid()) + if context.executing_eagerly(): + initial_value = None + initializer = None + else: + initial_value = variables[0].initial_value + initializer = control_flow_ops.group([v.initializer for v in variables]) + super().__init__( + trainable=variables[0].trainable, + shape=variables[0].shape, + dtype=variables[0].dtype, + handle=None, + synchronization=variables[0].synchronization, + constraint=variables[0].constraint, + aggregation=variables[0].aggregation, + distribute_strategy=variables[0]._distribute_strategy, + name=variables[0].name, + unique_id=self._unique_id, + handle_name=handle_name, + graph_element=variables[0]._graph_element, + initial_value=initial_value, + initializer_op=initializer, + is_initialized_op=None, + cached_value=None, + caching_device=None, + is_variables=True) + + @property + def handle(self): + if values_util.is_saving_non_distributed(): + return self._primary_handle + tpu_context = tpu_util.enclosing_tpu_context() + if tpu_context and not context.executing_eagerly(): + is_mirrored = ( + self._variables[0].synchronization != + variables_lib.VariableSynchronization.ON_READ) + if self._packed_handle is None: + handles = [v.handle for v in self._variables] + is_packed = False + else: + handles = [self._packed_handle] + is_packed = True + common_name = self._handle_name + # BaseResourceVariable appends ":0" to the handle name, which makes it not + # a valid root scope name. + if ":" in common_name: + common_name = common_name.split(":")[0] + return tpu_context.get_replicated_var_handle(common_name, self._unique_id, + handles, is_mirrored, + is_packed) + if self._packed_handle is not None and not context.executing_eagerly(): + return self._packed_handle + device = device_util.canonicalize(device_util.current()) + return self._device_to_handle.get(device, self._primary_handle) + + @property + def name(self): + if values_util.is_saving_non_distributed(): + return self._variables[0].name + return super().name + + @property + def initializer(self): + if values_util.is_saving_non_distributed(): + return self._variables[0].initializer + return super().initializer + + def _lazy_read(self, op): + # Lazy read is not supported. + with ops.control_dependencies([op]): + return self.read_value() + + # Begin overrides of read/write methods to satisfy the requirement of using + # packed handle, i.e. there must be explicit device annotations. + + def _device_scope(self): + if (self._packed_handle is None or + values_util.is_saving_non_distributed() or + tpu_util.enclosing_tpu_context() is not None): + return ops.NullContextmanager() + device = device_util.canonicalize(device_util.current()) + if device in self._device_to_handle: + return ops.NullContextmanager() + return ops.device(self._primary_handle.device) + + def value(self): + # We always force a read_value() instead of using the cached_value, as + # value() can be called on different devices. + return self.read_value() + + def read_value(self): + with self._device_scope(): + return super().read_value() + + def assign_sub(self, delta, use_locking=None, name=None, read_value=True): + with self._device_scope(): + return super().assign_sub(delta, use_locking, name, read_value) + + def assign_add(self, delta, use_locking=None, name=None, read_value=True): + with self._device_scope(): + return super().assign_add(delta, use_locking, name, read_value) + + def assign(self, value, use_locking=None, name=None, read_value=True): + with self._device_scope(): + return super().assign(value, use_locking, name, read_value) + + def scatter_sub(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_sub(sparse_delta, use_locking, name) + + def scatter_add(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_add(sparse_delta, use_locking, name) + + def scatter_mul(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_mul(sparse_delta, use_locking, name) + + def scatter_div(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_div(sparse_delta, use_locking, name) + + def scatter_min(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_min(sparse_delta, use_locking, name) + + def scatter_max(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_max(sparse_delta, use_locking, name) + + def scatter_update(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().scatter_update(sparse_delta, use_locking, name) + + def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): + with self._device_scope(): + return super().batch_scatter_update(sparse_delta, use_locking, name) + + def scatter_nd_sub(self, indices, updates, name=None): + with self._device_scope(): + return super().scatter_nd_sub(indices, updates, name) + + def scatter_nd_add(self, indices, updates, name=None): + with self._device_scope(): + return super().scatter_nd_add(indices, updates, name) + + def scatter_nd_update(self, indices, updates, name=None): + with self._device_scope(): + return super().scatter_nd_update(indices, updates, name) + + def sparse_read(self, indices, name=None): + with self._device_scope(): + return super().sparse_read(indices, name) + + def gather_nd(self, indices, name=None): + with self._device_scope(): + return super().gather_nd(indices, name) + + def to_proto(self, export_scope=None): + del self + raise TypeError("DistributedVariable doesn't support to_proto") + + @staticmethod + def from_proto(variable_def, import_scope=None): + raise TypeError("DistributedVariable doesn't support from_proto") + + def _as_graph_element(self): + if ops.get_default_graph().finalized: + return self._variables[0]._graph_element + return self.read_value() + + def _strided_slice_assign(self, *args, **kwargs): + with self._device_scope(): + return super()._strided_slice_assign(*args, **kwargs) + + def __str__(self): + debug_str = ",\n".join( + " %d: %s" % (i, v) for i, v in enumerate(self._variables)) + return "%s:{\n%s\n}" % (self.__class__.__name__, debug_str) + + def __repr__(self): + debug_repr = ",\n".join( + " %d: %r" % (i, v) for i, v in enumerate(self._variables)) + return "%s:{\n%s\n}" % (self.__class__.__name__, debug_repr) + + def __deepcopy__(self, memo): + copied_variables = copy.deepcopy(self._variables, memo) + return DistributedVariable( + copied_variables, enable_packed_handle=self._packed_handle is not None) + + +def _tensor_conversion(var, dtype=None, name=None, as_ref=False): + if as_ref: + raise ValueError( + "You may be using variable created under distribute strategy in TF " + "1.x control flows. Try explicitly converting the variable to Tensor " + "using variable.read_value(), or switch to TF 2.x.") + return ops.convert_to_tensor( + var.read_value(), dtype=dtype, name=name, as_ref=as_ref) + + +tensor_conversion_registry.register_tensor_conversion_function( + DistributedVariable, _tensor_conversion) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/dlpack/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/dlpack/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/dlpack/dlpack.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/dlpack/dlpack.py new file mode 100644 index 0000000000000000000000000000000000000000..fb1f258ea43b8f1b39ba2a76336218500ccb0974 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/dlpack/dlpack.py @@ -0,0 +1,63 @@ +# 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. +# ============================================================================== +"""DLPack modules for Tensorflow.""" + +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import context +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("experimental.dlpack.to_dlpack", v1=[]) +def to_dlpack(tf_tensor): + """Returns the dlpack capsule representing the tensor. + + This operation ensures the underlying data memory is ready when returns. + + ```python + a = tf.tensor([1, 10]) + dlcapsule = tf.experimental.dlpack.to_dlpack(a) + # dlcapsule represents the dlpack data structure + ``` + + Args: + tf_tensor: Tensorflow eager tensor, to be converted to dlpack capsule. + + Returns: + A PyCapsule named as dltensor, which shares the underlying memory to other + framework. This PyCapsule can be consumed only once. + """ + return pywrap_tfe.TFE_ToDlpackCapsule(tf_tensor) + + +@tf_export("experimental.dlpack.from_dlpack", v1=[]) +def from_dlpack(dlcapsule): + """Returns the Tensorflow eager tensor. + + The returned tensor uses the memory shared by dlpack capsules from other + framework. + + ```python + a = tf.experimental.dlpack.from_dlpack(dlcapsule) + # `a` uses the memory shared by dlpack + ``` + + Args: + dlcapsule: A PyCapsule named as dltensor + + Returns: + A Tensorflow eager tensor + """ + context.context().ensure_initialized() + return pywrap_tfe.TFE_FromDlpackCapsule(dlcapsule, context.context()._handle) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/backprop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/backprop.py new file mode 100644 index 0000000000000000000000000000000000000000..57593eac09b26dd2936c5e356f9b80373421c444 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/backprop.py @@ -0,0 +1,1345 @@ +# 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. +# ============================================================================== +"""Code for backpropagation using the tape utilities.""" + +# TODO(b/159343581): Properly support CompositeTensor in all functions in this +# file. + +import functools +import operator + +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import backprop_util +from tensorflow.python.eager import context +from tensorflow.python.eager import execute +from tensorflow.python.eager import imperative_grad +from tensorflow.python.eager import tape +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gradients_impl # pylint: disable=unused-import +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops.parallel_for import control_flow_ops as pfor_ops +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import nest +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +_op_attr_type_cache = {} + + +def op_attr_type(op_type, attr_name): + try: + return _op_attr_type_cache[(op_type, attr_name)] + except KeyError: + context.ensure_initialized() + h = context.context()._handle # pylint: disable=protected-access + attr_type = pywrap_tfe.TFE_OpNameGetAttrType(h, op_type, attr_name) + _op_attr_type_cache[(op_type, attr_name)] = attr_type + return attr_type + + +def make_attr(attr_type, value): + # pybind11 enums do not return the raw value like SWIG enums do. They are + # useful when comparing amongst each other but not direct integers as we are + # doing in most tests. + # https://pybind11.readthedocs.io/en/stable/classes.html#enumerations-and-internal-types + # TODO(amitpatankar): After all SWIG transitions, convert the enum comparisons + # from integer value to class. + if attr_type == int(pywrap_tfe.TF_ATTR_TYPE): + return dtypes.as_dtype(value) + if attr_type == [int(pywrap_tfe.TF_ATTR_TYPE)]: + return [dtypes.as_dtype(v) for v in value] + if attr_type == int(pywrap_tfe.TF_ATTR_SHAPE): + return tensor_shape.as_shape(value).as_proto() + if attr_type == [int(pywrap_tfe.TF_ATTR_SHAPE)]: + return [tensor_shape.as_shape(v).as_proto() for v in value] + return nest.map_structure( + lambda v: v.encode() if isinstance(v, str) else v, + value) + + +class _MockOp(object): + """Pretends to be a tf.Operation for the gradient functions.""" + + def __init__(self, attrs, inputs, outputs, typ, skip_input_indices): + self.attrs = attrs + self.inputs = inputs + self.outputs = outputs + self.type = typ + self.skip_input_indices = skip_input_indices + + def get_attr(self, attr): + typ = op_attr_type(self.type, attr) + for i in range(0, len(self.attrs), 2): + if self.attrs[i] == attr: + return make_attr(typ, self.attrs[i + 1]) + raise KeyError(attr) + + def _get_control_flow_context(self): + raise NotImplementedError( + "tf.GradientTape.gradients() does not support graph control flow " + "operations like tf.cond or tf.while at this time. Use tf.gradients() " + "instead. If you need this feature, please file a feature request at " + "https://github.com/tensorflow/tensorflow/issues/new" + ) + + +def _gradient_function(op_name, attr_tuple, num_inputs, inputs, outputs, + out_grads, skip_input_indices, forward_pass_name_scope): + """Calls the gradient function of the op. + + Args: + op_name: the name of the op to be differentiated. + attr_tuple: the attrs, as a tuple. + num_inputs: the number of inputs to the op. + inputs: inputs to the original operation. + outputs: outputs to the original operation. + out_grads: gradients of the operation wrt its outputs. + skip_input_indices: a tuple that is passed to the gradient function, + indicating which inputs to skip calculating the gradient for + forward_pass_name_scope: the namescope of the op in the forward pass. + + Returns: + The gradients with respect to the inputs of the function, as a list. + """ + mock_op = _MockOp(attr_tuple, inputs, outputs, op_name, skip_input_indices) + grad_fn = ops._gradient_registry.lookup(op_name) # pylint: disable=protected-access + if grad_fn is None: + return [None] * num_inputs + + # This does not work with v1 TensorArrays. + if ops.executing_eagerly_outside_functions( + ) or control_flow_util.EnableControlFlowV2(ops.get_default_graph()): + gradient_name_scope = "gradient_tape/" + if forward_pass_name_scope: + gradient_name_scope += forward_pass_name_scope + "/" + with ops.name_scope(gradient_name_scope): + return grad_fn(mock_op, *out_grads) + else: + return grad_fn(mock_op, *out_grads) + + +pywrap_tfe.TFE_Py_RegisterGradientFunction(_gradient_function) + + +def _must_record_gradient(): + return not pywrap_tfe.TFE_Py_TapeSetIsEmpty() + + +@tf_export("__internal__.record_gradient", v1=[]) +def record_gradient(op_name, inputs, attrs, outputs): + """Explicitly record the gradient for a given op. + + Args: + op_name: The op name as listed in the `OpDef` for the op. + inputs: A list of tensor inputs to the op. + attrs: The op attributes as a flattened list of alternating attribute names + and attribute values. + outputs: A list of tensor outputs from the op. + """ + pywrap_tfe.TFE_Py_RecordGradient(op_name, inputs, attrs, outputs, + ops.get_name_scope()) + + +execute.must_record_gradient = _must_record_gradient +execute.record_gradient = record_gradient + + +def implicit_val_and_grad(f): + """Returns a function which differentiates f with respect to variables. + + The wrapped function returns the value and the gradient of f when called with + the same arguments. The gradient is with respect to all trainable TFE + variables accessed by `f`. + + This function is useful when the exact set of variables to differentiate with + is not known ahead of time. + + Example: + + ```python + dense_layer = tf.compat.v1.layers.Dense(1) + def loss(x, y): + return tf.reduce_sum(tf.square(dense_layer(x) - y)) + + # Obtain the gradient function. + val_grad_fn = tfe.implicit_value_and_gradients(loss) + + # Invoke the gradient function with concrete values of x and y. + x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) + y = tf.constant([[10.0], [20.0]]) + value, grads_and_vars = val_grad_fn(x, y) + print('Value of loss: %s' % value) + + # Apply the gradients to Variables. + optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) + optimizer.apply_gradients(grads_and_vars) + ``` + + Args: + f: function to be differentiated. If `f` returns a scalar, this scalar will + be differentiated. If `f` returns a tensor or list of tensors, by default + a scalar will be computed by adding all their values to produce a single + scalar. + + Returns: + A function which, when called, returns a tuple pair. + Its first element is the value to which the function evaluates. + Its second element is list of (gradient, variable) pairs. + + Raises: + ValueError: if `f` returns None. + """ + # TODO(cais): Remove calls to tf.constant() once the gradients functions + # accept lists and np.ndarrays. + + def grad_fn(*args, **kwds): + """Computes the gradient of the wrapped function.""" + this_tape = tape.push_new_tape() + try: + end_node = f(*args, **kwds) + if end_node is None: + raise ValueError("Cannot differentiate a function that returns None; " + "did you forget to return a value from {}?".format( + f.__name__)) + finally: + tape.pop_tape(this_tape) + # Note: variables are returned in construction order. This ensures unique + # order across executions. + variables = this_tape.watched_variables() + if not variables: + raise ValueError("No trainable variables were accessed while the " + "function was being computed.") + + sources = [v.handle for v in variables] + for s in sources: + if getattr(s, "is_packed", False): + raise ValueError( + "GradientTape.gradient is not supported on packed EagerTensors yet." + ) + grad = imperative_grad.imperative_grad(this_tape, nest.flatten(end_node), + sources) + return end_node, list(zip(grad, variables)) + + return grad_fn + + +def implicit_grad(f): + """Returns a function which differentiates f with respect to variables. + + The wrapped function returns the gradient of f when called with the same + arguments. The gradient is with respect to all trainable TFE variables + accessed by `f`. + + This function is useful when the exact set of variables to differentiate with + is not known ahead of time. + + Example: + + ```python + dense_layer = tf.compat.v1.layers.Dense(1) + def loss(x, y): + return tf.reduce_sum(tf.square(dense_layer(x) - y)) + + # Obtain the gradient function. + grad_fn = tfe.implicit_gradients(loss) + + # Invoke the gradient function with concrete values of x and y. + x = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) + y = tf.constant([[10.0], [20.0]]) + grads_and_vars = grad_fn(x, y) + + # Apply the gradients to Variables. + optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1) + optimizer.apply_gradients(grads_and_vars) + ``` + + Args: + f: function to be differentiated. If `f` returns a scalar, this scalar will + be differentiated. If `f` returns a tensor or list of tensors, by default + a scalar will be computed by adding all their values to produce a single + scalar. + + Returns: + A function which, when called, returns a list of (gradient, variable) pairs. + """ + # TODO(cais): Remove calls to tf.constant() once the gradients functions + # accept lists and np.ndarrays. + + def grad_fn(*args, **kwds): + """Computes the gradient of the wrapped function.""" + return implicit_val_and_grad(f)(*args, **kwds)[1] + + return grad_fn + + +def _get_arg_spec(f, params, param_args): + """The positions of the parameters of f to be differentiated in param_args.""" + try: + args = tf_inspect.getfullargspec(f).args + except TypeError as e: + # TypeError can happen when f is a callable object. + if params is None: + return range(len(param_args)) + elif all(isinstance(x, int) for x in params): + return params + raise ValueError("Either callable provided is not a function or could not " + "inspect its arguments by name: %s. Original error: %s" + % (f, e)) + if params is None: + if not args: + return range(len(param_args)) + if args[0] == "self": + return range(len(args) - 1) + else: + return range(len(args)) + elif all(isinstance(x, str) for x in params): + return [args.index(n) for n in params] + elif all(isinstance(x, int) for x in params): + return params + else: + raise ValueError( + "params must be all strings or all integers; got %s." % params) + + +def gradients_function(f, params=None): + """Returns a function which differentiates f with respect to params. + + Example: + ```python + # f(x, y) = (x ^ 3) * y - x * (y ^ 2) + # Therefore, the 1st order derivatives are: + # df / dx = 3 * (x ^ 2) * y - y ^ 2 + # df / dy = x ^ 3 - 2 * x * y + # The 2nd order derivatives with respect to x is: + # d^2 f / (dx)^2 = 6 * x * y + def f(x, y): + return x * x * x * y - x * y * y + + # Obtain a function that returns 1st order gradients. + grad_fn = tfe.gradients_function(f) + + x = 2.0 + y = 3.0 + + # Invoke the 1st order gradient function. + x_grad, y_grad = grad_fn(x, y) + assert x_grad.numpy() == 3 * (2 ** 2) * 3 - 3 ** 2 + assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3 + + # Obtain a function that returns the 2nd order gradient with respect to x. + gradgrad_fn = tfe.gradients_function(lambda x, y: grad_fn(x, y)[0]) + + # Invoke the 2nd order gradient function. + x_gradgrad = gradgrad_fn(x, y)[0] + assert x_gradgrad.numpy() == 6 * 2 * 3 + + # To obtain a callable that returns the gradient(s) of `f` with respect to a + # subset of its inputs, use the `params` keyword argument with + # `gradients_function()`. + ygrad_fn = tfe.gradients_function(f, params=[1]) + + (y_grad,) = ygrad_fn(x, y) + assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3 + ``` + + Note that only tensors with real or complex dtypes are differentiable. + + Args: + f: function to be differentiated. If `f` returns a scalar, this scalar will + be differentiated. If `f` returns a tensor or list of tensors, by default + a scalar will be computed by adding all their values to produce a single + scalar. If desired, the tensors can be elementwise multiplied by the + tensors passed as the `dy` keyword argument to the returned gradient + function. + params: list of parameter names of f or list of integers indexing the + parameters with respect to which we'll differentiate. Passing None + differentiates with respect to all parameters. + + Returns: + function which, when called, returns the value of f and the gradient + of `f` with respect to all of `params`. The function takes an extra optional + keyword argument `dy`. Setting it allows computation of vector jacobian + products for vectors other than the vector of ones. + + Raises: + ValueError: if the params are not all strings or all integers. + """ + + def decorated(*args, **kwds): + """Computes the gradient of the decorated function.""" + + _, grad = val_and_grad_function(f, params=params)(*args, **kwds) + return grad + + return decorated + + +def _ensure_unique_tensor_objects(parameter_positions, args): + """Make each of the parameter_positions in args a unique tensor_lib.Tensor object. + + Ensure that each parameter is treated independently. + For example: + + def f(x, y): return x * y + g = gradients_function(f) + one = tf.constant(1.) + + g(one, one) should return [1., 1.] + (even though the two arguments are the same Tensor object). + + Args: + parameter_positions: List of indices into args defining the arguments to + differentiate against. + args: A list of arguments to the function to be differentiated. + + Returns: + args, possibly edited in-place. + """ + s = set() + for (i, t) in enumerate(args): + if i in parameter_positions: + tid = ops.tensor_id(t) + if tid in s: + args[i] = gen_array_ops.identity(args[i]) + else: + s.add(tid) + return args + + +def val_and_grad_function(f, params=None): + """Returns a function that computes f and its derivative w.r.t. params. + + Example: + ```python + # f(x, y) = (x ^ 3) * y - x * (y ^ 2) + # Therefore, the 1st order derivatives are: + # df / dx = 3 * (x ^ 2) * y - y ^ 2 + # df / dy = x ^ 3 - 2 * x * y + def f(x, y): + return x * x * x * y - x * y * y + + # Obtain a function that returns the function value and the 1st order + # gradients. + val_grads_fn = tfe.value_and_gradients_function(f) + + x = 2.0 + y = 3.0 + + # Invoke the value-and-gradients function. + f_val, (x_grad, y_grad) = val_grads_fn(x, y) + assert f_val.numpy() == (2 ** 3) * 3 - 2 * (3 ** 2) + assert x_grad.numpy() == 3 * (2 ** 2) * 3 - 3 ** 2 + assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3 + + # To obtain a callable that returns the value of `f` and the gradient(s) of + # `f` with respect to a subset of its inputs, use the `params` keyword + # argument with `value_and_gradients_function()`. + val_ygrad_fn = tfe.value_and_gradients_function(f, params=[1]) + + f_val, (y_grad,) = val_ygrad_fn(x, y) + assert f_val.numpy() == (2 ** 3) * 3 - 2 * (3 ** 2) + assert y_grad.numpy() == (2 ** 3) - 2 * 2 * 3 + ``` + + Args: + f: function to be differentiated. If `f` returns a scalar, this scalar will + be differentiated. If `f` returns a tensor or list of tensors, by default + a scalar will be computed by adding all their values to produce a single + scalar. If desired, the tensors can be elementwise multiplied by the + tensors passed as the `dy` keyword argument to the returned gradient + function. + params: list of parameter names of f or list of integers indexing the + parameters with respect to which we'll differentiate. Passing `None` + differentiates with respect to all parameters. + + Returns: + function which, when called, returns the value of f and the gradient + of f with respect to all of `params`. The function takes an extra optional + keyword argument "dy". Setting it allows computation of vector jacobian + products for vectors other than the vector of ones. + + Raises: + ValueError: if the params are not all strings or all integers. + """ + + def decorated(*args, **kwds): + """Computes the value and gradient of the decorated function.""" + dy = kwds.pop("dy", None) + if kwds: + raise ValueError("Functions to be differentiated cannot " + "receive keyword arguments.") + val, vjp = make_vjp(f, params)(*args, **kwds) + return val, vjp(dy=dy) + + return decorated + + +def make_vjp(f, params=None, persistent=True): + """Returns a function that computes f and its vjp w.r.t. + + params. + + The term "vjp" here is an abbreviation for vector-jacobian product. + + Args: + f: the function to be differentiated. + params: the parameters (numbers or names) to differentiate with respect to. + A value of None will differentiate with respect to all parameters. + persistent: Boolean controlling whether the VJP function can be re-used. + Must be True or False. + + Returns: + A function, which when called, returns a tuple (value, vjp), where: + - value is the result of calling f. + - vjp is a function, which takes a vector as an argument and + returns the product of that vector with the Jacobian of f. + Providing no argument to vjp is equivalent to providing a + vector of ones. + + For example, + ```python + def f(x): + return x * x + + wrapped_fn = tfe.make_vjp(f) + result, vjp = wrapped_fn(tf.constant(3.0)) + # result is 9.0 + vjp() # the vjp function returns 6.0 + + Raises: + ValueError: if `f` returns None. + """ + + def decorated(*args, **kwds): + """Computes the value and gradient of the decorated function.""" + parameter_positions = _get_arg_spec(f, params, args) + assert not kwds, "The gradient function can't take keyword arguments." + this_tape = tape.push_new_tape(persistent=persistent) + try: + sources = [] + args = [ + ops.convert_to_tensor(arg) if i in parameter_positions else arg + for i, arg in enumerate(args) + ] + args = _ensure_unique_tensor_objects(parameter_positions, args) + for i in parameter_positions: + if getattr(args[i], "is_packed", False): + raise ValueError( + "GradientTape.gradient is not supported on packed EagerTensors" + "yet.") + sources.append(args[i]) + tape.watch(this_tape, args[i]) + result = f(*args) + if result is None: + raise ValueError("Cannot differentiate a function that returns None; " + "did you forget to return a value from {}?".format( + f.__name__)) + flat_result = nest.flatten(result) + flat_result = [gen_array_ops.identity(x) for x in flat_result] + result = nest.pack_sequence_as(result, flat_result) + finally: + tape.pop_tape(this_tape) + def vjp(dy=None): + if dy is not None: + dy = [ops.convert_to_tensor(x) for x in nest.flatten(dy)] + return imperative_grad.imperative_grad( + this_tape, nest.flatten(result), sources, output_gradients=dy) + + return result, vjp + + return decorated + + +def _aggregate_grads(gradients): + """Aggregate gradients from multiple sources. + + Args: + gradients: A list of 'Tensor' or 'IndexedSlices' gradients. + + Returns: + If 'gradients' only has 'Tensor', returns an aggregated 'Tensor'. + Otherwise returns an aggregated 'IndexedSlices'. + """ + assert gradients, "No gradients to aggregate" + + if len(gradients) == 1: + return gradients[0] + if all(isinstance(g, tensor_lib.Tensor) for g in gradients): + return gen_math_ops.add_n(gradients) + else: + assert all( + isinstance(g, (tensor_lib.Tensor, indexed_slices.IndexedSlices)) + for g in gradients) + return backprop_util.AggregateIndexedSlicesGradients(gradients) + + +def _num_elements(grad): + """The number of elements in the `grad` tensor.""" + if isinstance(grad, tensor_lib.Tensor): + shape_tuple = grad._shape_tuple() # pylint: disable=protected-access + elif isinstance(grad, indexed_slices.IndexedSlices): + shape_tuple = grad.values._shape_tuple() # pylint: disable=protected-access + else: + raise ValueError("`grad` not a Tensor or IndexedSlices.") + if shape_tuple is None or None in shape_tuple: + return 0 + return functools.reduce(operator.mul, shape_tuple, 1) + + +def _fast_fill(value, shape, dtype): + return array_ops.fill( + constant_op.constant(shape, dtype=dtypes.int32), + constant_op.constant(value, dtype=dtype)) + + +def _zeros(shape, dtype): + """Helper to return (possibly cached) zero tensors in eager mode.""" + # Note: variants will use _zeros_like + if dtype == dtypes.string or dtype == dtypes.resource: + return None + + ctx = context.context() + if not ctx.executing_eagerly(): + return array_ops.zeros(shape, dtype) + + device = ctx.device_name + + if tensor_util.is_tf_type(shape): + shape_key = shape.ref() + else: + shape_key = shape + cache_key = shape_key, dtype, device + cached = ctx.zeros_cache().get(cache_key) + if cached is None: + if dtypes.as_dtype(dtype).is_bool: + value = False + else: + value = 0 + cached = _fast_fill(value, shape, dtype) + ctx.zeros_cache().put(cache_key, cached) + return cached + + +def _ones(shape, dtype): + as_dtype = dtypes.as_dtype(dtype) + if as_dtype == dtypes.string: + return None + + if not context.executing_eagerly(): + return array_ops.ones(shape, dtype) + + if as_dtype.is_bool: + value = True + else: + value = 1 + + if shape == (): # pylint: disable=g-explicit-bool-comparison + return constant_op.constant(value, dtype=dtype) + return _fast_fill(value, shape, dtype) + + +_default_vspace = imperative_grad.VSpace( + num_elements_fn=_num_elements, + aggregate_fn=_aggregate_grads, + zeros_fn=_zeros, + ones_fn=_ones, + zeros_like_fn=default_gradient.zeros_like, + ones_like_fn=default_gradient.ones_like, + graph_shape_fn=gen_array_ops.shape) +pywrap_tfe.TFE_Py_RegisterVSpace(_default_vspace) + + +def _handle_or_self(x): + """Unwrap resource variable/ndarray to return tensors.""" + if resource_variable_ops.is_resource_variable(x): + return x.handle + return x + + +def _extract_tensors_and_variables(tensor): + """Extracts tensors and variables from the input object.""" + for obj in nest.flatten(tensor): + if _pywrap_utils.IsTensor(obj) or _pywrap_utils.IsVariable(obj): + yield obj + elif isinstance(obj, composite_tensor.CompositeTensor): + components = type_spec.type_spec_from_value(obj)._to_components(obj) # pylint: disable=protected-access + yield from _extract_tensors_and_variables(components) + else: + raise ValueError(f"Passed in object {obj} of type {type(obj).__name__!r}" + f", not tf.Tensor or tf.Variable or ExtensionType.") + + +@tf_export("GradientTape", "autodiff.GradientTape", v1=["GradientTape"]) +class GradientTape: + """Record operations for automatic differentiation. + + Operations are recorded if they are executed within this context manager and + at least one of their inputs is being "watched". + + Trainable variables (created by `tf.Variable` or `tf.compat.v1.get_variable`, + where `trainable=True` is default in both cases) are automatically watched. + Tensors can be manually watched by invoking the `watch` method on this context + manager. + + For example, consider the function `y = x * x`. The gradient at `x = 3.0` can + be computed as: + + >>> x = tf.constant(3.0) + >>> with tf.GradientTape() as g: + ... g.watch(x) + ... y = x * x + >>> dy_dx = g.gradient(y, x) + >>> print(dy_dx) + tf.Tensor(6.0, shape=(), dtype=float32) + + GradientTapes can be nested to compute higher-order derivatives. For example, + + >>> x = tf.constant(5.0) + >>> with tf.GradientTape() as g: + ... g.watch(x) + ... with tf.GradientTape() as gg: + ... gg.watch(x) + ... y = x * x + ... dy_dx = gg.gradient(y, x) # dy_dx = 2 * x + >>> d2y_dx2 = g.gradient(dy_dx, x) # d2y_dx2 = 2 + >>> print(dy_dx) + tf.Tensor(10.0, shape=(), dtype=float32) + >>> print(d2y_dx2) + tf.Tensor(2.0, shape=(), dtype=float32) + + By default, the resources held by a GradientTape are released as soon as + GradientTape.gradient() method is called. To compute multiple gradients over + the same computation, create a persistent gradient tape. This allows multiple + calls to the gradient() method as resources are released when the tape object + is garbage collected. For example: + + >>> x = tf.constant(3.0) + >>> with tf.GradientTape(persistent=True) as g: + ... g.watch(x) + ... y = x * x + ... z = y * y + >>> dz_dx = g.gradient(z, x) # (4*x^3 at x = 3) + >>> print(dz_dx) + tf.Tensor(108.0, shape=(), dtype=float32) + >>> dy_dx = g.gradient(y, x) + >>> print(dy_dx) + tf.Tensor(6.0, shape=(), dtype=float32) + + By default GradientTape will automatically watch any trainable variables that + are accessed inside the context. If you want fine grained control over which + variables are watched you can disable automatic tracking by passing + `watch_accessed_variables=False` to the tape constructor: + + >>> x = tf.Variable(2.0) + >>> w = tf.Variable(5.0) + >>> with tf.GradientTape( + ... watch_accessed_variables=False, persistent=True) as tape: + ... tape.watch(x) + ... y = x ** 2 # Gradients will be available for `x`. + ... z = w ** 3 # No gradients will be available as `w` isn't being watched. + >>> dy_dx = tape.gradient(y, x) + >>> print(dy_dx) + tf.Tensor(4.0, shape=(), dtype=float32) + >>> # No gradients will be available as `w` isn't being watched. + >>> dz_dw = tape.gradient(z, w) + >>> print(dz_dw) + None + + Note that when using models you should ensure that your variables exist when + using `watch_accessed_variables=False`. Otherwise it's quite easy to make your + first iteration not have any gradients: + + ```python + a = tf.keras.layers.Dense(32) + b = tf.keras.layers.Dense(32) + + with tf.GradientTape(watch_accessed_variables=False) as tape: + tape.watch(a.variables) # Since `a.build` has not been called at this point + # `a.variables` will return an empty list and the + # tape will not be watching anything. + result = b(a(inputs)) + tape.gradient(result, a.variables) # The result of this computation will be + # a list of `None`s since a's variables + # are not being watched. + ``` + + Note that only tensors with real or complex dtypes are differentiable. + """ + + def __init__(self, persistent=False, watch_accessed_variables=True): + """Creates a new GradientTape. + + Args: + persistent: Boolean controlling whether a persistent gradient tape + is created. False by default, which means at most one call can + be made to the gradient() method on this object. + watch_accessed_variables: Boolean controlling whether the tape will + automatically `watch` any (trainable) variables accessed while the tape + is active. Defaults to True meaning gradients can be requested from any + result computed in the tape derived from reading a trainable `Variable`. + If False users must explicitly `watch` any `Variable`s they want to + request gradients from. + """ + self._tape = None + self._persistent = persistent + self._watch_accessed_variables = watch_accessed_variables + self._watched_variables = () + self._recording = False + + def __enter__(self): + """Enters a context inside which operations are recorded on this tape.""" + self._push_tape() + return self + + def __exit__(self, typ, value, traceback): + """Exits the recording context, no further operations are traced.""" + if self._recording: + self._pop_tape() + + def _push_tape(self): + """Pushes a new tape onto the tape stack.""" + if self._recording: + raise ValueError("Tape is still recording, This can happen if you try to " + "re-enter an already-active tape.") + if self._tape is None: + self._tape = tape.push_new_tape( + persistent=self._persistent, + watch_accessed_variables=self._watch_accessed_variables) + else: + tape.push_tape(self._tape) + self._recording = True + + def _pop_tape(self): + if not self._recording: + raise ValueError("Tape is not recording.") + tape.pop_tape(self._tape) + self._recording = False + + @tf_contextlib.contextmanager + def _ensure_recording(self): + """Ensures that this tape is recording.""" + if not self._recording: + try: + self._push_tape() + yield + finally: + self._pop_tape() + else: + yield + + # TODO(b/209081027): Add a variable in composite tensor test case after + # variables become composite tensors. + def watch(self, tensor): + """Ensures that `tensor` is being traced by this tape. + + Args: + tensor: a Tensor/Variable or list of Tensors/Variables. + + Raises: + ValueError: if it encounters something that is not a tensor. + """ + for t in _extract_tensors_and_variables(tensor): + if not backprop_util.IsTrainable(t): + logging.log_first_n( + logging.WARN, "The dtype of the watched tensor must be " + "floating (e.g. tf.float32), got %r", 5, t.dtype) + if hasattr(t, "handle"): + # There are many variable-like objects, all of them currently have + # `handle` attribute that points to a tensor. If this changes, + # internals of watch_variable need to change as well. + tape.watch_variable(self._tape, t) + else: + tape.watch(self._tape, t) + + @tf_contextlib.contextmanager + def stop_recording(self): + """Temporarily stops recording operations on this tape. + + Operations executed while this context manager is active will not be + recorded on the tape. This is useful for reducing the memory used by tracing + all computations. + + For example: + + >>> x = tf.constant(4.0) + >>> with tf.GradientTape() as tape: + ... with tape.stop_recording(): + ... y = x ** 2 + >>> dy_dx = tape.gradient(y, x) + >>> print(dy_dx) + None + + Yields: + None + Raises: + RuntimeError: if the tape is not currently recording. + """ + if self._tape is None: + raise RuntimeError( + "Trying to stop recording a tape which is not recording.") + self._pop_tape() + try: + yield + finally: + self._push_tape() + + def reset(self): + """Clears all information stored in this tape. + + Equivalent to exiting and reentering the tape context manager with a new + tape. For example, the two following code blocks are equivalent: + + ``` + with tf.GradientTape() as t: + loss = loss_fn() + with tf.GradientTape() as t: + loss += other_loss_fn() + t.gradient(loss, ...) # Only differentiates other_loss_fn, not loss_fn + + + # The following is equivalent to the above + with tf.GradientTape() as t: + loss = loss_fn() + t.reset() + loss += other_loss_fn() + t.gradient(loss, ...) # Only differentiates other_loss_fn, not loss_fn + ``` + + This is useful if you don't want to exit the context manager for the tape, + or can't because the desired reset point is inside a control flow construct: + + ``` + with tf.GradientTape() as t: + loss = ... + if loss > k: + t.reset() + ``` + """ + self._pop_tape() + self._tape = None + self._push_tape() + + def watched_variables(self): + """Returns variables watched by this tape in order of construction.""" + if self._tape is not None: + self._watched_variables = self._tape.watched_variables() + return self._watched_variables + + def gradient(self, + target, + sources, + output_gradients=None, + unconnected_gradients=UnconnectedGradients.NONE): + """Computes the gradient using operations recorded in context of this tape. + + Note: Unless you set `persistent=True` a GradientTape can only be used to + compute one set of gradients (or jacobians). + + In addition to Tensors, gradient also supports RaggedTensors. For example, + + >>> x = tf.ragged.constant([[1.0, 2.0], [3.0]]) + >>> with tf.GradientTape() as g: + ... g.watch(x) + ... y = x * x + >>> g.gradient(y, x) + + + Args: + target: a list or nested structure of Tensors or Variables or + CompositeTensors to be differentiated. + sources: a list or nested structure of Tensors or Variables or + CompositeTensors. `target` will be differentiated against elements in + `sources`. + output_gradients: a list of gradients, one for each differentiable + element of target. Defaults to None. + unconnected_gradients: a value which can either hold 'none' or 'zero' and + alters the value which will be returned if the target and sources are + unconnected. The possible values and effects are detailed in + 'UnconnectedGradients' and it defaults to 'none'. + + Returns: + a list or nested structure of Tensors (or IndexedSlices, or None, or + CompositeTensor), one for each element in `sources`. Returned structure + is the same as the structure of `sources`. + + Raises: + RuntimeError: If called on a used, non-persistent tape. + RuntimeError: If called inside the context of the tape. + TypeError: If the target is a None object. + ValueError: If the target is a variable or if unconnected gradients is + called with an unknown value. + """ + if self._tape is None: + raise RuntimeError("A non-persistent GradientTape can only be used to " + "compute one set of gradients (or jacobians)") + if self._recording: + if not self._persistent: + self._pop_tape() + else: + logging.log_first_n( + logging.WARN, "Calling GradientTape.gradient on a persistent " + "tape inside its context is significantly less " + "efficient than calling it outside the context (it " + "causes the gradient ops to be recorded on the " + "tape, leading to increased CPU and memory usage). " + "Only call GradientTape.gradient inside the " + "context if you actually want to trace the " + "gradient in order to compute higher order " + "derivatives.", 1) + + if target is None: + raise TypeError("Argument `target` should be a list or nested structure" + " of Tensors, Variables or CompositeTensors to be " + "differentiated, but received None.") + + flat_targets = composite_tensor_gradient.get_flat_tensors_for_gradients( + nest.flatten(target)) + # TODO(b/246997907): Remove this once + # ResourceVariableGradient.get_gradient_components returns the handle. + flat_targets = nest.map_structure(_handle_or_self, flat_targets) + + for t in flat_targets: + if not backprop_util.IsTrainable(t): + logging.vlog( + 1, "The dtype of the target tensor must be " + "floating (e.g. tf.float32) when calling GradientTape.gradient, " + "got %r", t.dtype) + + flat_sources_raw = nest.flatten(sources) + flat_sources = [] + for t in flat_sources_raw: + flat_sources.append(_handle_or_self(t)) + flat_sources = composite_tensor_gradient.get_flat_tensors_for_gradients( + flat_sources) + for t in flat_sources: + if not backprop_util.IsTrainable(t): + logging.vlog( + 1, "The dtype of the source tensor must be " + "floating (e.g. tf.float32) when calling GradientTape.gradient, " + "got %r", t.dtype) + if getattr(t, "is_packed", False): + raise ValueError( + "GradientTape.gradient is not supported on packed EagerTensors yet." + ) + + if output_gradients is not None: + output_gradients = nest.flatten( + variable_utils.convert_variables_to_tensors(output_gradients)) + output_gradients = ( + composite_tensor_gradient.get_flat_tensors_for_gradients( + output_gradients)) + output_gradients = [None if x is None else ops.convert_to_tensor(x) + for x in output_gradients] + + flat_grad = imperative_grad.imperative_grad( + self._tape, + flat_targets, + flat_sources, + output_gradients=output_gradients, + sources_raw=flat_sources_raw, + unconnected_gradients=unconnected_gradients) + + if not self._persistent: + # Keep track of watched variables before setting tape to None + self._watched_variables = self._tape.watched_variables() + self._tape = None + + flat_sources_raw = nest.map_structure(_handle_or_self, flat_sources_raw) + flat_grad = composite_tensor_gradient.replace_flat_tensors_for_gradients( + flat_sources_raw, flat_grad) + grad = nest.pack_sequence_as(sources, flat_grad) + return grad + + def jacobian(self, + target, + sources, + unconnected_gradients=UnconnectedGradients.NONE, + parallel_iterations=None, + experimental_use_pfor=True): + """Computes the jacobian using operations recorded in context of this tape. + + Note: Unless you set `persistent=True` a GradientTape can only be used to + compute one set of gradients (or jacobians). + + Note: By default the jacobian implementation uses parallel for (pfor), which + creates a tf.function under the hood for each jacobian call. For better + performance, and to avoid recompilation and vectorization rewrites on each + call, enclose GradientTape code in @tf.function. + + See[wikipedia + article](http://en.wikipedia.org/wiki/jacobian_matrix_and_determinant) + for the definition of a Jacobian. + + Example usage: + + ```python + with tf.GradientTape() as g: + x = tf.constant([1.0, 2.0]) + g.watch(x) + y = x * x + jacobian = g.jacobian(y, x) + # jacobian value is [[2., 0.], [0., 4.]] + ``` + + Args: + target: Tensor to be differentiated. + sources: a list or nested structure of Tensors or Variables. `target` + will be differentiated against elements in `sources`. + unconnected_gradients: a value which can either hold 'none' or 'zero' and + alters the value which will be returned if the target and sources are + unconnected. The possible values and effects are detailed in + 'UnconnectedGradients' and it defaults to 'none'. + parallel_iterations: A knob to control how many iterations are dispatched + in parallel. This knob can be used to control the total memory usage. + experimental_use_pfor: If true, vectorizes the jacobian computation. Else + falls back to a sequential while_loop. Vectorization can sometimes fail + or lead to excessive memory usage. This option can be used to disable + vectorization in such cases. + + Returns: + A list or nested structure of Tensors (or None), one for each element in + `sources`. Returned structure is the same as the structure of `sources`. + Note if any gradient is sparse (IndexedSlices), jacobian function + currently makes it dense and returns a Tensor instead. This may change in + the future. + + + Raises: + RuntimeError: If called on a used, non-persistent tape. + RuntimeError: If called on a non-persistent tape with eager execution + enabled and without enabling experimental_use_pfor. + ValueError: If vectorization of jacobian computation fails. + """ + if self._tape is None: + raise RuntimeError("A non-persistent GradientTape can only be used to " + "compute one set of gradients (or jacobians)") + + flat_sources = nest.flatten(sources) + target_static_shape = target.shape + target_shape = array_ops.shape(target) + # Note that we push and pop the tape here and below. This is needed since we + # need gradients through the enclosed operations. + with self._ensure_recording(): + target = array_ops.reshape(target, [-1]) + + def loop_fn(i): + with self._ensure_recording(): + y = array_ops.gather(target, i) + return self.gradient(y, flat_sources, + unconnected_gradients=unconnected_gradients) + + try: + target_size = int(target.shape[0]) + except TypeError: + target_size = array_ops.shape(target)[0] + + if experimental_use_pfor: + try: + output = pfor_ops.pfor(loop_fn, target_size, + parallel_iterations=parallel_iterations) + except ValueError as err: + raise ValueError( + "Encountered an exception while vectorizing the " + "jacobian computation. Vectorization can be disabled by setting" + " experimental_use_pfor to False.") from err + else: + if context.executing_eagerly() and not self._persistent: + raise RuntimeError( + "GradientTape must be created with persistent=True" + " to compute the jacobian with eager execution enabled and with " + " experimental_use_pfor set to False.") + output = pfor_ops.for_loop( + loop_fn, [target.dtype] * len(flat_sources), target_size, + parallel_iterations=parallel_iterations) + + for i, out in enumerate(output): + if out is not None: + new_shape = array_ops.concat( + [target_shape, array_ops.shape(out)[1:]], axis=0) + out = array_ops.reshape(out, new_shape) + if context.executing_eagerly(): + out.set_shape(target_static_shape.concatenate(flat_sources[i].shape)) + output[i] = out + + return nest.pack_sequence_as(sources, output) + + def batch_jacobian(self, + target, + source, + unconnected_gradients=UnconnectedGradients.NONE, + parallel_iterations=None, + experimental_use_pfor=True): + """Computes and stacks per-example jacobians. + + See [wikipedia article](http://en.wikipedia.org/wiki/jacobian_matrix_and_determinant) + for the definition of a Jacobian. This function is essentially an efficient + implementation of the following: + + `tf.stack([self.jacobian(y[i], x[i]) for i in range(x.shape[0])])`. + + Note that compared to `GradientTape.jacobian` which computes gradient of + each output value w.r.t each input value, this function is useful when + `target[i,...]` is independent of `source[j,...]` for `j != i`. This + assumption allows more efficient computation as compared to + `GradientTape.jacobian`. The output, as well as intermediate activations, + are lower dimensional and avoid a bunch of redundant zeros which would + result in the jacobian computation given the independence assumption. + + Note: Unless you set `persistent=True` a GradientTape can only be used to + compute one set of gradients (or jacobians). + + Note: By default the batch_jacobian implementation uses parallel for (pfor), + which creates a tf.function under the hood for each batch_jacobian call. + For better performance, and to avoid recompilation and vectorization + rewrites on each call, enclose GradientTape code in @tf.function. + + + Example usage: + + ```python + with tf.GradientTape() as g: + x = tf.constant([[1., 2.], [3., 4.]], dtype=tf.float32) + g.watch(x) + y = x * x + batch_jacobian = g.batch_jacobian(y, x) + # batch_jacobian is [[[2, 0], [0, 4]], [[6, 0], [0, 8]]] + ``` + + Args: + target: A tensor with rank 2 or higher and with shape [b, y1, ..., y_n]. + `target[i,...]` should only depend on `source[i,...]`. + source: A tensor with rank 2 or higher and with shape [b, x1, ..., x_m]. + unconnected_gradients: a value which can either hold 'none' or 'zero' and + alters the value which will be returned if the target and sources are + unconnected. The possible values and effects are detailed in + 'UnconnectedGradients' and it defaults to 'none'. + parallel_iterations: A knob to control how many iterations are dispatched + in parallel. This knob can be used to control the total memory usage. + experimental_use_pfor: If true, uses pfor for computing the Jacobian. Else + uses a tf.while_loop. + + Returns: + A tensor `t` with shape [b, y_1, ..., y_n, x1, ..., x_m] where `t[i, ...]` + is the jacobian of `target[i, ...]` w.r.t. `source[i, ...]`, i.e. stacked + per-example jacobians. + + Raises: + RuntimeError: If called on a used, non-persistent tape. + RuntimeError: If called on a non-persistent tape with eager execution + enabled and without enabling experimental_use_pfor. + ValueError: If vectorization of jacobian computation fails or if first + dimension of `target` and `source` do not match. + """ + if self._tape is None: + raise RuntimeError("A non-persistent GradientTape can only be used to" + "compute one set of gradients (or jacobians)") + target_shape = target.shape + if target_shape.rank is None: + dim = tensor_shape.Dimension(None) + else: + dim = target_shape.dims[0] + if not (target_shape.with_rank_at_least(2) and + source.shape.with_rank_at_least(2) and + dim.is_compatible_with(source.shape[0])): + raise ValueError( + "Need first dimension of target shape (%s) and " + "source shape (%s) to match." % (target.shape, source.shape)) + if target_shape.is_fully_defined(): + batch_size = int(target_shape[0]) + target_row_size = target_shape.num_elements() // batch_size + else: + target_shape = array_ops.shape(target) + batch_size = target_shape[0] + target_row_size = array_ops.size(target) // batch_size + source_shape = array_ops.shape(source) + # Flatten target to 2-D. + # Note that we push and pop the tape here and below. This is needed since we + # need gradients through the enclosed operations. + with self._ensure_recording(): + with ops.control_dependencies( + [check_ops.assert_equal(batch_size, source_shape[0])]): + target = array_ops.reshape(target, [batch_size, target_row_size]) + + run_once = False + + def loop_fn(i): + nonlocal run_once + if run_once and not self._persistent: + if parallel_iterations is not None: + raise RuntimeError( + "GradientTape must be created with persistent=True" + " to compute the batch_jacobian with parallel_iterations.") + else: + raise RuntimeError( + "GradientTape must be created with persistent=True" + " to compute the batch_jacobian.") + run_once = True + + with self._ensure_recording(): + y = array_ops.gather(target, i, axis=1) + return self.gradient(y, source, + unconnected_gradients=unconnected_gradients) + + if experimental_use_pfor: + try: + output = pfor_ops.pfor(loop_fn, target_row_size, + parallel_iterations=parallel_iterations) + except ValueError as err: + raise ValueError( + "Encountered an exception while vectorizing the " + "batch_jacobian computation. Vectorization can be disabled by " + "setting experimental_use_pfor to False.") from err + else: + if context.executing_eagerly() and not self._persistent: + raise RuntimeError( + "GradientTape must be created with persistent=True" + " to compute the batch_jacobian with eager execution enabled and " + " with experimental_use_pfor set to False.") + output = pfor_ops.for_loop(loop_fn, target.dtype, target_row_size, + parallel_iterations=parallel_iterations) + new_shape = array_ops.concat([target_shape, source_shape[1:]], axis=0) + if output is None: + # Note that this block is returning zeros when it could use `None` to + # represent unconnected gradients. This is to maintain compatibility with + # the previous behavior, which ignored `unconnected_gradients`. + output = array_ops.zeros(new_shape, target.dtype) + return output + else: + output = array_ops.reshape(output, + [target_row_size, batch_size, -1]) + output = array_ops.transpose(output, [1, 0, 2]) + + output = array_ops.reshape(output, new_shape) + return output diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/backprop_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/backprop_util.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fe1158dc3c8e35ed9f1dfcc0f654d4c9285b86 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/backprop_util.py @@ -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. +# ============================================================================== +"""Shared utilities related to backprop.""" + +from tensorflow.core.config import flags +from tensorflow.core.framework import types_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import math_ops + + +def _DTypeFromTensor(tensor): + """Extract either `tensor.dtype` or the unanimous sub-type of a variant.""" + dtype = tensor.dtype + if dtype.base_dtype == dtypes.variant: + # If we know statically that the data a variant points to is non-trainable + # then the variant itself is non-trainable. + if isinstance(tensor, ops.EagerTensor): + handle_data = tensor._handle_data # pylint: disable=protected-access + else: + handle_data = handle_data_util.get_resource_handle_data(tensor) + if (handle_data is not None + and handle_data.is_set + and handle_data.shape_and_type): + first_type = handle_data.shape_and_type[0].dtype + # Some variants have statically unknown dtypes; we can't make inferences + # about trainability, so we conservatively assume they're trainable + # (which may waste memory passing zeros around, but will be correct). + if (first_type != types_pb2.DT_INVALID + and all(shape_and_type.dtype == first_type + for shape_and_type in handle_data.shape_and_type)): + return first_type + return dtype + + +def IsTrainable(tensor_or_dtype): + """Determines whether a tensor or dtype supports infinitesimal changes.""" + if tensor_util.is_tf_type(tensor_or_dtype): + dtype = _DTypeFromTensor(tensor_or_dtype) + else: + dtype = tensor_or_dtype + dtype = dtypes.as_dtype(dtype) + trainable_dtypes = [dtypes.float16, dtypes.float32, dtypes.float64, + dtypes.complex64, dtypes.complex128, dtypes.resource, + dtypes.variant, dtypes.bfloat16] + if flags.config().enable_quantized_dtypes_training.value(): + trainable_dtypes.extend([dtypes.qint8, dtypes.qint16, dtypes.qint32, + dtypes.quint8, dtypes.quint16]) + return dtype.base_dtype in trainable_dtypes + + +def FlattenNestedIndexedSlices(grad): + assert isinstance(grad, indexed_slices.IndexedSlices) + if isinstance(grad.values, tensor_lib.Tensor): + return grad + else: + assert isinstance(grad.values, indexed_slices.IndexedSlices) + g = FlattenNestedIndexedSlices(grad.values) + return indexed_slices.IndexedSlices( + g.values, array_ops.gather(grad.indices, g.indices), g.dense_shape) + + +def AggregateIndexedSlicesGradients(grads): + """Aggregates gradients containing `IndexedSlices`s.""" + if len(grads) < 1: + return None + if len(grads) == 1: + return grads[0] + grads = [g for g in grads if g is not None] + # If any gradient is a `Tensor`, sum them up and return a dense tensor + # object. + if any(isinstance(g, tensor_lib.Tensor) for g in grads): + return math_ops.add_n(grads) + + # The following `_as_indexed_slices_list` casts ids of IndexedSlices into + # int64. It is to make sure the inputs of `concat` all have same the data + # type. + grads = math_ops._as_indexed_slices_list(grads) # pylint: disable=protected-access + + grads = [FlattenNestedIndexedSlices(x) for x in grads] + # Form IndexedSlices out of the concatenated values and indices. + concat_grad = indexed_slices.IndexedSlices( + array_ops.concat([x.values for x in grads], axis=0), + array_ops.concat([x.indices for x in grads], axis=0), + grads[0].dense_shape) + + return concat_grad + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/benchmarks_test_base.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/benchmarks_test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..14ccf1578f62ec9603468df06d2772d640451ff0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/benchmarks_test_base.py @@ -0,0 +1,77 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +r"""Benchmark base to run and report benchmark results.""" + +import os +import uuid + +from tensorflow.python.eager import test +from tensorflow.python.platform import flags +from tensorflow.python.profiler import profiler_v2 as profiler + +flags.DEFINE_bool("xprof", False, "Run and report benchmarks with xprof on") +flags.DEFINE_string("logdir", "/tmp/xprof/", "Directory to store xprof data") + + +class MicroBenchmarksBase(test.Benchmark): + """Run and report benchmark results. + + The first run is without any profilng. + Second run is with xprof and python trace. Third run is with xprof without + python trace. Note: xprof runs are with fewer iterations. + """ + + def run_with_xprof(self, enable_python_trace, run_benchmark, func, + num_iters_xprof, execution_mode, suid): + if enable_python_trace: + options = profiler.ProfilerOptions(python_tracer_level=1) + logdir = os.path.join(flags.FLAGS.logdir, suid + "_with_python") + else: + options = profiler.ProfilerOptions(python_tracer_level=0) + logdir = os.path.join(flags.FLAGS.logdir, suid) + with profiler.Profile(logdir, options): + total_time = run_benchmark(func, num_iters_xprof, execution_mode) + us_per_example = float("{0:.3f}".format(total_time * 1e6 / num_iters_xprof)) + return logdir, us_per_example + + def run_report(self, run_benchmark, func, num_iters, execution_mode=None): + """Run and report benchmark results.""" + total_time = run_benchmark(func, num_iters, execution_mode) + mean_us = total_time * 1e6 / num_iters + extras = { + "examples_per_sec": float("{0:.3f}".format(num_iters / total_time)), + "us_per_example": float("{0:.3f}".format(total_time * 1e6 / num_iters)) + } + + if flags.FLAGS.xprof: + suid = str(uuid.uuid4()) + # Re-run with xprof and python trace. + num_iters_xprof = min(100, num_iters) + xprof_link, us_per_example = self.run_with_xprof(True, run_benchmark, + func, num_iters_xprof, + execution_mode, suid) + extras["xprof link with python trace"] = xprof_link + extras["us_per_example with xprof and python"] = us_per_example + + # Re-run with xprof but no python trace. + xprof_link, us_per_example = self.run_with_xprof(False, run_benchmark, + func, num_iters_xprof, + execution_mode, suid) + extras["xprof link"] = xprof_link + extras["us_per_example with xprof"] = us_per_example + + benchmark_name = self._get_benchmark_name() + self.report_benchmark( + iters=num_iters, wall_time=mean_us, extras=extras, name=benchmark_name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/cancellation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/cancellation.py new file mode 100644 index 0000000000000000000000000000000000000000..a8956d7a683507d3d90eab8f59d60fe9ed638b69 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/cancellation.py @@ -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. +# ============================================================================== +"""Cancellation support for eager execution.""" + +from tensorflow.python import pywrap_tfe + + +class CancellationManager(object): + """A mechanism for cancelling blocking computation.""" + + __slots__ = ["_impl"] + + def __init__(self): + self._impl = pywrap_tfe.TFE_NewCancellationManager() + + @property + def is_cancelled(self): + """Returns `True` if `CancellationManager.start_cancel` has been called.""" + return pywrap_tfe.TFE_CancellationManagerIsCancelled(self._impl) + + def start_cancel(self): + """Cancels blocking operations that have been registered with this object.""" + pywrap_tfe.TFE_CancellationManagerStartCancel(self._impl) + + def get_cancelable_function(self, concrete_function): + def cancellable(*args, **kwargs): + with CancellationManagerContext(self): + return concrete_function(*args, **kwargs) + return cancellable + +_active_context = None + + +def context(): + return _active_context + + +class CancellationManagerContext: + """A Python context for wrapping a cancellable ConcreteFunction.""" + + def __init__(self, cancellation_manager): + self._cancellation_manager = cancellation_manager + + def __enter__(self): + global _active_context + _active_context = self._cancellation_manager + + def __exit__(self, exc_type, exc_value, exc_tb): + global _active_context + _active_context = None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/context.py new file mode 100644 index 0000000000000000000000000000000000000000..fa0a41ea550451ece35d0eec306c03668e10fb7d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/context.py @@ -0,0 +1,2934 @@ +# 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. +# ============================================================================== +"""State management for eager execution.""" + +import collections +import contextlib +import copy +import gc +import itertools +import os +import random +import threading + +from absl import logging +import numpy as np + +from tensorflow.core.framework import function_pb2 +from tensorflow.core.framework import graph_debug_info_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python import pywrap_tfe +from tensorflow.python import tf2 +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.eager import cancellation +from tensorflow.python.eager import execute +from tensorflow.python.eager import executor +from tensorflow.python.eager import monitoring +from tensorflow.python.framework import c_api_util +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import tfrt_utils +from tensorflow.python.util import compat +from tensorflow.python.util import function_utils +from tensorflow.python.util import is_in_graph_mode +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.deprecation import deprecated +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tsl.protobuf import coordination_config_pb2 + + +GRAPH_MODE = 0 +EAGER_MODE = 1 + +default_execution_mode = EAGER_MODE if tf2.enabled() else GRAPH_MODE + +# Cache from (old_device_name, partial_new_device_name) -> (new_device_name, +# new_device_spec). +# Note that we do not protect this with a lock and instead rely on python's GIL +# and the idempotent nature of writes to provide thread safety. +_device_parsing_cache = {} +_starting_device_spec = pydev.DeviceSpec.from_string("") + +_MAXINT32 = 2**31 - 1 + +DEVICE_PLACEMENT_EXPLICIT = pywrap_tfe.TFE_DEVICE_PLACEMENT_EXPLICIT +DEVICE_PLACEMENT_WARN = pywrap_tfe.TFE_DEVICE_PLACEMENT_WARN +DEVICE_PLACEMENT_SILENT = pywrap_tfe.TFE_DEVICE_PLACEMENT_SILENT +DEVICE_PLACEMENT_SILENT_FOR_INT32 = ( + pywrap_tfe.TFE_DEVICE_PLACEMENT_SILENT_FOR_INT32) + +SYNC = 0 +ASYNC = 1 + +_KEEP_ALIVE_SECS = 600 + +_python_eager_context_create_counter = monitoring.Counter( + "/tensorflow/api/python/eager_context_create_counter", + "Counter for number of eager contexts created in Python.") + +# Re-exporting through context. +is_tfrt_enabled = tfrt_utils.enabled + +# This flag and the associated environment var are transient and will eventually +# be removed, once this experiment is enabled by default. +_JIT_COMPILE_REWRITE_ENABLED = os.getenv("TF_JIT_COMPILE_REWRITE") == "1" + + +def run_eager_op_as_function_enabled(): + return True + + +# This method should only be called after the context has beein initialized. +def enable_jit_compile_rewrite(): + """Run jit_compile functions through rewrite pass. + + This runs jit_compile functions through all of the multidevice function + rewrite passes. + """ + global _JIT_COMPILE_REWRITE_ENABLED + _JIT_COMPILE_REWRITE_ENABLED = True + if context_safe() is not None: + context_safe().jit_compile_rewrite = True + + +# This method should only be called after the context has been initialized. +def disable_jit_compile_rewrite(): + global _JIT_COMPILE_REWRITE_ENABLED + _JIT_COMPILE_REWRITE_ENABLED = False + if context_safe() is not None: + context_safe().jit_compile_rewrite = False + + +def jit_compile_rewrite_enabled(): + if context_safe() is not None: + return context_safe().jit_compile_rewrite + return _JIT_COMPILE_REWRITE_ENABLED + + +# Expose it as internally public APIs for Keras use cases in b/171080602. +tf_export("__internal__.is_tfrt_enabled", v1=[])(is_tfrt_enabled) + + +class _EagerTensorCache(object): + """Simple cache which evicts items based on length in a FIFO manner.""" + + __slots__ = ["_data", "_max_items", "_max_tensor_size"] + + def __init__(self, max_items=256, max_tensor_size=10000): + self._data = collections.OrderedDict() + self._max_items = max_items + self._max_tensor_size = max_tensor_size + + def put(self, key, value): + if value._num_elements() > self._max_tensor_size: # pylint: disable=protected-access + return + + self._data[key] = value + + if len(self._data) > self._max_items: + self._data.popitem(last=False) + + def get(self, key): + return self._data.get(key, None) + + def flush(self): + self._data.clear() + + +class FunctionCallOptions: + """Options applied at call sites of eager functions. + + Eager functions are functions decorated with tf.contrib.eager.defun. + """ + + __slots__ = ["_config_proto_serialized", "_executor_type"] + + def __init__(self, executor_type=None, config_proto=None): + """Constructor. + + Args: + executor_type: (optional) name of the executor to be used to execute the + eager function. If None or an empty string, the default Tensorflow + executor will be used. + config_proto: (optional) a `config_pb2.ConfigProto` proto or a serialized + string of that proto. The config used by Grappler when optimizing the + function graph. Each concrete function is optimized the first time is + called. Changing config_proto after the first call has no effect. If + config_proto is None, an empty RewriterConfig will be used. + """ + self.config_proto_serialized = config_proto + self.executor_type = executor_type + + @property + def executor_type(self): + return self._executor_type + + @executor_type.setter + def executor_type(self, executor_type): + self._executor_type = executor_type + + @property + def config_proto_serialized(self): + return self._config_proto_serialized + + @config_proto_serialized.setter + def config_proto_serialized(self, config): + if isinstance(config, config_pb2.ConfigProto): + self._config_proto_serialized = config.SerializeToString( + deterministic=True) + elif isinstance(config, str): + self._config_proto_serialized = config + elif config is None: + self._config_proto_serialized = ( + config_pb2.ConfigProto().SerializeToString()) + else: + raise ValueError("the rewriter config must be either a " + "config_pb2.ConfigProto, or a serialized string of that " + "proto or None. got: {}".format(type(config))) + + def as_attrs(self): + if self.config_proto_serialized is None: + config = function_utils.get_disabled_rewriter_config() + else: + config = self.config_proto_serialized + executor_type = self.executor_type or "" + + return {"executor_type": executor_type, "config_proto": config} + + +# Map from context_id (an int) to _TensorCaches. +# Dicts are thread safe in CPython. +# TODO(iga): Remove this once TensorCaches are moved to C++. +_tensor_caches_map = {} + + +class _TensorCaches(threading.local): + """Thread local tensor caches.""" + + __slots__ = ["_ones_rank_cache", "_zeros_cache"] + + def __init__(self): + super().__init__() + self._ones_rank_cache = None + self._zeros_cache = None + + @property + def ones_rank_cache(self): + if not self._ones_rank_cache: + self._ones_rank_cache = _EagerTensorCache() + return self._ones_rank_cache + + @property + def zeros_cache(self): + if not self._zeros_cache: + self._zeros_cache = _EagerTensorCache() + return self._zeros_cache + + +ContextSwitch = collections.namedtuple( + "ContextSwitch", + ["is_building_function", "enter_context_fn", "device_stack"]) + + +# `_ContextSwitchStack` is a `threading.local` to match the semantics of +# ``DefaultGraphStack`, which is also a `threading.local`. +class _ContextSwitchStack(threading.local): + """A thread-local stack of context switches.""" + + def __init__(self, eager): + super().__init__() + self.stack = [] + if eager: + # Initialize the stack with a pointer to enter the eager context; this + # ensures that the fact that eager execution was enabled is propagated + # across threads, since (1) `enable_eager_execution` modifies a + # process-level flag (`default_execution_mode`) and (2) `__init__` is + # called each time a threading.local object is used in a separate thread. + self.push( + is_building_function=False, + enter_context_fn=eager_mode, + device_stack=None) + + def push(self, is_building_function, enter_context_fn, device_stack): + """Push metadata about a context switch onto the stack. + + A context switch can take any one of the two forms: installing a graph as + the default graph, or entering the eager context. For each context switch, + we record whether or not the entered context is building a function. + + Args: + is_building_function: (bool.) Whether the context is building a function. + enter_context_fn: (function.) A callable that executes the context switch. + For example, `graph.as_default` or `eager_mode`. + device_stack: If applicable, the device function stack for this graph. + When breaking out of graphs in init_scope, the innermost nonempty device + stack is used. Eager contexts put `None` here and the value is never + used. + """ + + self.stack.append( + ContextSwitch(is_building_function, enter_context_fn, device_stack)) + + def pop(self): + """Pop the stack.""" + + self.stack.pop() + + +@tf_export("config.LogicalDevice") +class LogicalDevice( + collections.namedtuple("LogicalDevice", ["name", "device_type"])): + """Abstraction for a logical device initialized by the runtime. + + A `tf.config.LogicalDevice` corresponds to an initialized logical device on a + `tf.config.PhysicalDevice` or a remote device visible to the cluster. Tensors + and operations can be placed on a specific logical device by calling + `tf.device` with a specified `tf.config.LogicalDevice`. + + Fields: + name: The fully qualified name of the device. Can be used for Op or function + placement. + device_type: String declaring the type of device such as "CPU" or "GPU". + """ + pass + + +@tf_export("config.LogicalDeviceConfiguration", + "config.experimental.VirtualDeviceConfiguration") +class LogicalDeviceConfiguration( + collections.namedtuple("LogicalDeviceConfiguration", [ + "memory_limit", "experimental_priority", "experimental_device_ordinal" + ])): + """Configuration class for a logical devices. + + The class specifies the parameters to configure a `tf.config.PhysicalDevice` + as it is initialized to a `tf.config.LogicalDevice` during runtime + initialization. Not all fields are valid for all device types. + + See `tf.config.get_logical_device_configuration` and + `tf.config.set_logical_device_configuration` for usage examples. + + Fields: + memory_limit: (optional) Maximum memory (in MB) to allocate on the virtual + device. Currently only supported for GPUs. + experimental_priority: (optional) Priority to assign to a virtual device. + Lower values have higher priorities and 0 is the default. + Within a physical GPU, the GPU scheduler will prioritize ops on virtual + devices with higher priority. Currently only supported for Nvidia GPUs. + experimental_device_ordinal: (optional) Ordinal number to order the virtual + device. + LogicalDevice with lower ordinal number will receive a lower device id. + Physical device id and location in the list is used to break ties. + Currently only supported for Nvidia GPUs. + """ + + def __new__(cls, + memory_limit=None, + experimental_priority=None, + experimental_device_ordinal=None): + return super().__new__(cls, memory_limit, experimental_priority, + experimental_device_ordinal) + + +@tf_export("config.PhysicalDevice") +class PhysicalDevice( + collections.namedtuple("PhysicalDevice", ["name", "device_type"])): + """Abstraction for a locally visible physical device. + + TensorFlow can utilize various devices such as the CPU or multiple GPUs + for computation. Before initializing a local device for use, the user can + customize certain properties of the device such as it's visibility or memory + configuration. + + Once a visible `tf.config.PhysicalDevice` is initialized one or more + `tf.config.LogicalDevice` objects are created. Use + `tf.config.set_visible_devices` to configure the visibility of a physical + device and `tf.config.set_logical_device_configuration` to configure multiple + `tf.config.LogicalDevice` objects for a `tf.config.PhysicalDevice`. This is + useful when separation between models is needed or to simulate a multi-device + environment. + + Fields: + name: Unique identifier for device. + device_type: String declaring the type of device such as "CPU" or "GPU". + """ + pass + + +class _AtomicCounter(object): + """A simple atomic counter.""" + + __slots__ = ["_value", "_lock"] + + def __init__(self): + self._value = 0 + self._lock = threading.Lock() + + def increment_and_get(self): + with self._lock: + self._value += 1 + return self._value + + +_context_id_counter = _AtomicCounter() + + +class _TensorCacheDeleter(object): + """Deletes tensor caches for a given context.""" + + __slots__ = ["_context_id"] + + def __init__(self, context_id): + self._context_id = context_id + + def __del__(self): + if _tensor_caches_map is None: + return + if self._context_id in _tensor_caches_map: + del _tensor_caches_map[self._context_id] + + +# TODO(agarwal): rename to EagerContext / EagerRuntime ? +# TODO(agarwal): consider keeping the corresponding Graph here. +class Context: + """Environment in which eager operations execute.""" + + # TODO(agarwal): create and link in some documentation for `execution_mode`. + # pylint: disable=redefined-outer-name + def __init__(self, + config=None, + device_policy=None, + execution_mode=None, + server_def=None): + """Creates a new Context. + + Args: + config: (Optional.) A `ConfigProto` protocol buffer with configuration + options for the Context. Note that a lot of these options may be + currently unimplemented or irrelevant when eager execution is enabled. + device_policy: (Optional.) What policy to use when trying to run an + operation on a device with inputs which are not on that device. When set + to None, an appropriate value will be picked automatically. The value + picked may change between TensorFlow releases. Defaults to + DEVICE_PLACEMENT_SILENT. + Valid values: + - DEVICE_PLACEMENT_EXPLICIT: raises an error if the placement is not + correct. + - DEVICE_PLACEMENT_WARN: copies the tensors which are not on the right + device but raises a warning. + - DEVICE_PLACEMENT_SILENT: silently copies the tensors. This might hide + performance problems. + - DEVICE_PLACEMENT_SILENT_FOR_INT32: silently copies int32 tensors, + raising errors on the other ones. + execution_mode: (Optional.) Policy controlling how operations dispatched + are actually executed. When set to None, an appropriate value will be + picked automatically. The value picked may change between TensorFlow + releases. + Valid values: + - SYNC: executes each operation synchronously. + - ASYNC: executes each operation asynchronously. These operations may + return "non-ready" handles. + server_def: (Optional.) A tensorflow::ServerDef proto. Enables execution + on remote devices. GrpcServers need to be started by creating an + identical server_def to this, and setting the appropriate task_indexes, + so that the servers can communicate. It will then be possible to execute + operations on remote devices. + + Raises: + ValueError: If execution_mode is not valid. + """ + # This _id is used only to index the tensor caches. + # TODO(iga): Remove this when tensor caches are moved to C++. + self._id = _context_id_counter.increment_and_get() + self._tensor_cache_deleter = _TensorCacheDeleter(self._id) + _tensor_caches_map[self._id] = _TensorCaches() + + self._config = config + self._thread_local_data = pywrap_tfe.EagerContextThreadLocalData( + self, + is_eager=lambda: default_execution_mode == EAGER_MODE, + device_spec=_starting_device_spec) + self._context_switches = _ContextSwitchStack(self.executing_eagerly()) + self._context_handle = None + self._context_devices = None + self._seed = None + self._initialize_lock = threading.Lock() + self._initialized = False + if device_policy is None: + device_policy = DEVICE_PLACEMENT_SILENT + self._device_policy = device_policy + self._mirroring_policy = None + if execution_mode not in (None, SYNC, ASYNC): + raise ValueError("execution_mode should be None/SYNC/ASYNC. Got %s" % + execution_mode) + if execution_mode is None: + execution_mode = SYNC + self._default_is_async = execution_mode == ASYNC + self._use_tfrt = is_tfrt_enabled() + self._jit_compile_rewrite = jit_compile_rewrite_enabled() + self._server_def = server_def + self._collective_ops_server_def = None + self._collective_leader = None + self._collective_scoped_allocator_enabled_ops = None + self._collective_use_nccl_communication = None + self._collective_device_filters = None + self._coordination_service_config = None + + self._device_lock = threading.Lock() + self._physical_devices = None + self._physical_device_to_index = None + self._pluggable_devices = None + self._visible_device_list = [] + self._memory_growth_map = None + self._virtual_device_map = {} + + # Values set after construction + self._optimizer_jit = None + self._intra_op_parallelism_threads = None + self._inter_op_parallelism_threads = None + self._soft_device_placement = None + self._log_device_placement = None + self._operation_timeout_in_ms = None + self._enable_mlir_graph_optimization = None + self._optimizer_experimental_options = {} + + _python_eager_context_create_counter.get_cell().increase_by(1) + + self._is_global_context = False + + # Number of retries to give the SetServerDef step. This is useful for fault + # tolerant initial connection in high-preemption settings like + # ParameterServerStrategy training. + self._set_server_def_retries = 0 + + # pylint: enable=redefined-outer-name + + def _set_global_seed(self, seed): + """Set a global eager mode seed for random ops.""" + self._seed = seed + # `random.Random(seed)` needs `seed` to be hashable, while values of type + # e.g. `np.int64` or `np.ndarray` are not. We use `int(...)` to convert them + # to int. + try: + hash(seed) + self._rng = random.Random(seed) + except TypeError: + seed = int(np.array(seed)) + self._rng = random.Random(seed) + # Also clear the kernel cache, to reset any existing seeds + if self._context_handle is not None: + pywrap_tfe.TFE_ContextClearCaches(self._context_handle) + + def _internal_operation_seed(self): + """Returns a fake operation seed. + + In eager mode, user shouldn't set or depend on operation seed. + Here, we generate a random seed based on global seed to make + operation's randomness different and depend on the global seed. + + Returns: + A fake operation seed based on global seed. + """ + return self._rng.randint(0, _MAXINT32) + + def _initialize_logical_devices(self): + """Helper to initialize devices.""" + # Store list of devices + logical_devices = [] + context_devices = [] + device_list = pywrap_tfe.TFE_ContextListDevices(self._context_handle) + try: + self._num_gpus = 0 + current_job, current_task = None, None + server_def = self._server_def or self._collective_ops_server_def + if server_def is not None: + current_job, current_task = server_def.job_name, server_def.task_index + for i in range(pywrap_tfe.TF_DeviceListCount(device_list)): + dev_name = pywrap_tfe.TF_DeviceListName(device_list, i) + context_devices.append(pydev.canonical_name(dev_name)) + spec = pydev.DeviceSpec.from_string(dev_name) + # If the job is localhost, we assume that the cluster has not yet been + # configured and thus clear the job, replica & task. + if spec.job == "localhost": + spec = spec.replace(job=None, replica=None, task=None) + logical_devices.append( + LogicalDevice(name=spec.to_string(), device_type=spec.device_type)) + dev_type = pywrap_tfe.TF_DeviceListType(device_list, i) + if (dev_type == "GPU" and spec.job == current_job and + spec.task == current_task): + self._num_gpus += 1 + + finally: + self._logical_devices = logical_devices + self._context_devices = context_devices + pywrap_tfe.TF_DeleteDeviceList(device_list) + + def ensure_initialized(self): + """Initialize handle and devices if not already done so.""" + if self._initialized: + return + with self._initialize_lock: + if self._initialized: + return + assert self._context_devices is None + opts = pywrap_tfe.TFE_NewContextOptions() + try: + config_str = self.config.SerializeToString() + pywrap_tfe.TFE_ContextOptionsSetConfig(opts, config_str) + if self._device_policy is not None: + pywrap_tfe.TFE_ContextOptionsSetDevicePlacementPolicy( + opts, self._device_policy) + if self._mirroring_policy is not None: + pywrap_tfe.TFE_ContextOptionsSetMirroringPolicy( + opts, self._mirroring_policy) + if self._default_is_async == ASYNC: + pywrap_tfe.TFE_ContextOptionsSetAsync(opts, True) + if self._use_tfrt is not None: + pywrap_tfe.TFE_ContextOptionsSetTfrt(opts, self._use_tfrt) + pywrap_tfe.TFE_ContextOptionsSetRunEagerOpAsFunction(opts, True) + pywrap_tfe.TFE_ContextOptionsSetJitCompileRewrite( + opts, self._jit_compile_rewrite) + context_handle = pywrap_tfe.TFE_NewContext(opts) + finally: + pywrap_tfe.TFE_DeleteContextOptions(opts) + assert not (self._server_def and self._collective_ops_server_def), ( + "Cannot enable remote execution as well as collective ops at the " + "moment. If this is important to you, please file an issue.") + if self._server_def is not None: + server_def_str = self._server_def.SerializeToString() + timeout = 0 # Indicates no timeout. + pywrap_tfe.TFE_ContextSetServerDefWithTimeoutAndRetries( + context_handle, _KEEP_ALIVE_SECS, server_def_str, timeout, + self._set_server_def_retries) + elif self._collective_ops_server_def is not None: + server_def_str = self._collective_ops_server_def.SerializeToString() + pywrap_tfe.TFE_EnableCollectiveOps(context_handle, server_def_str) + + self._context_handle = context_handle + self._initialize_logical_devices() + self._initialized = True + + if self._is_global_context: + pywrap_tfe.TFE_Py_SetCEagerContext(self._context_handle) + + def ensure_uninitialized(self): + """Uninitialize handle and devices if not already done so.""" + with self._initialize_lock: + if not self._initialized: + return + self._context_devices = None + self._logical_devices = None + self._server_def = None + self._initialized = False + + if self._is_global_context: + pywrap_tfe.TFE_Py_SetCEagerContext(None) + + self._context_handle = None + + def mark_as_global_context(self): + # If the context was already initialized, publish it. Otherwise wait with + # publication until it's initialized. + if self._initialized: + pywrap_tfe.TFE_Py_SetCEagerContext(self._context_handle) + self._is_global_context = True + + def _clear_caches(self): + self.ones_rank_cache().flush() + self.zeros_cache().flush() + pywrap_tfe.TFE_ClearScalarCache() + + def get_server_def(self): + return self._server_def + + def set_server_def(self, server_def, keep_alive_secs=_KEEP_ALIVE_SECS): + """Allow setting a server_def on the context. + + When a server def is replaced, it effectively clears a bunch of caches + within the context. If you attempt to use a tensor object that was pointing + to a tensor on the remote device, it will raise an error. + + Args: + server_def: A tensorflow::ServerDef proto. Enables execution on remote + devices. + keep_alive_secs: Num. seconds after which the remote end will hang up. As + long as the client is still alive, the server state for the context will + be kept alive. If the client is killed (or there is some failure), the + server will clean up its context keep_alive_secs after the final RPC it + receives. + + Raises: + ValueError: if server_def is None. + """ + if not server_def: + raise ValueError("server_def is None.") + + self._server_def = server_def + + if self._context_handle: + server_def_str = server_def.SerializeToString() + pywrap_tfe.TFE_ContextSetServerDef(self._context_handle, keep_alive_secs, + server_def_str) + self._initialize_logical_devices() + + # Clear all the caches in case there are remote tensors in them. + self._clear_caches() + + def update_server_def(self, server_def, keep_alive_secs=_KEEP_ALIVE_SECS): + """Update a server_def on the context. + + Args: + server_def: A tensorflow::ServerDef proto. Enables execution on remote + devices. + keep_alive_secs: Num. seconds after which the remote end will hang up. As + long as the client is still alive, the server state for the context will + be kept alive. If the client is killed (or there is some failure), the + server will clean up its context keep_alive_secs after the final RPC it + receives. + + Raises: + ValueError: if server_def is None. + """ + if not server_def: + raise ValueError("server_def is None.") + + self._server_def = server_def + + if self._context_handle: + server_def_str = server_def.SerializeToString() + pywrap_tfe.TFE_ContextUpdateServerDef(self._context_handle, + keep_alive_secs, server_def_str) + self._initialize_logical_devices() + + self._clear_caches() + + def check_alive(self, worker_name): + """Checks whether a remote worker is alive or not. + + Args: + worker_name: a string representing the remote worker. It must be a fully + specified name like "/job:worker/replica:0/task:0". + + Returns: + a boolean indicating whether the remote worker is alive or not. + + Raises: + ValueError: if context is not initialized. + """ + # TODO(yuefengz): support checking multiple workers. + if self._context_handle: + return pywrap_tfe.TFE_ContextCheckAlive(self._context_handle, worker_name) + else: + raise ValueError("Context is not initialized.") + + def sync_executors(self): + """Sync both local executors and the ones on remote workers. + + In async execution mode, local function calls can return before the + corresponding remote op/function execution requests are completed. Calling + this method creates a synchronization barrier for remote executors. It only + returns when all remote pending nodes are finished, potentially with errors + if any remote executors are in error state. + + Raises: + ValueError: if context is not initialized. + """ + if self._context_handle: + pywrap_tfe.TFE_ContextSyncExecutors(self._context_handle) + else: + raise ValueError("Context is not initialized.") + + def clear_executor_errors(self): + """Clear errors in both local executors and remote workers. + + After receiving errors from remote workers, additional requests on the fly + could further taint the status on the remote workers due to the async nature + of remote execution. Calling this method block on waiting for all pending + nodes in remote executors to finish and clear their error statuses. + + Raises: + ValueError: if context is not initialized. + """ + if self._context_handle: + pywrap_tfe.TFE_ContextClearExecutors(self._context_handle) + else: + raise ValueError("Context is not initialized.") + + def configure_coordination_service(self, + service_type, + service_leader="", + enable_health_check=True, + cluster_register_timeout_in_ms=0, + heartbeat_timeout_in_ms=0, + shutdown_barrier_timeout_in_ms=0, + coordinated_jobs=None, + allow_new_incarnation_to_reconnect=False): + """Enable distributed coordination service with specified configs.""" + if self._context_handle: + logging.warning("Configuring coordination service type may not be " + "effective because the context is already initialized.") + config = coordination_config_pb2.CoordinationServiceConfig() + config.service_type = service_type + if service_leader: + config.service_leader = pydev.canonical_name(service_leader) + config.enable_health_check = enable_health_check + config.cluster_register_timeout_in_ms = cluster_register_timeout_in_ms + config.heartbeat_timeout_in_ms = heartbeat_timeout_in_ms + config.shutdown_barrier_timeout_in_ms = shutdown_barrier_timeout_in_ms + config.allow_new_incarnation_to_reconnect = ( + allow_new_incarnation_to_reconnect) + if coordinated_jobs is not None: + if isinstance(coordinated_jobs, list): + config.coordinated_job_list.extend(coordinated_jobs) + else: + raise ValueError("`coordinated_jobs` must be list[CoordinatedJob] or " + "None, but got: %s" % (coordinated_jobs,)) + self._coordination_service_config = config + + @property + def coordination_service(self): + return self._coordination_service_config + + def set_config_key_value(self, key, value): + ensure_initialized() + pywrap_tfe.TFE_InsertConfigKeyValue(self._context_handle, key, value) + + # If `timeout_in_ms=0`, this will block until the key-value is set or the + # worker shuts down. + def get_config_key_value(self, key, timeout_in_ms=0): + ensure_initialized() + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_GetConfigKeyValue(self._context_handle, key, + timeout_in_ms, buffer_) + value = pywrap_tf_session.TF_GetBuffer(buffer_).decode("utf-8") + return value + + def delete_config_key_value(self, key): + ensure_initialized() + pywrap_tfe.TFE_DeleteConfigKeyValue(self._context_handle, key) + + def report_error_to_cluster(self, error_code, error_message): + """Report error to other members in a multi-client cluster. + + Args: + error_code: a `tf.errors` error code. + error_message: a string. The error message. + """ + if self._context_handle: + pywrap_tfe.TFE_ReportErrorToCluster(self._context_handle, error_code, + error_message) + else: + raise ValueError("Context is not initialized.") + + def get_task_states(self, job_configs): + """Get task states from the Coordination Service. + + Args: + job_configs: A list of tuples of job name and task number. + + Returns: + A list of TF_Status. + """ + if self._context_handle: + job_names, task_nums = zip(*job_configs) + return pywrap_tfe.TFE_GetTaskStates(self._context_handle, job_names, + task_nums) + else: + raise ValueError("Context is not initialized.") + + def wait_at_barrier(self, barrier_id, timeout_in_ms): + """Blocks until all coordinated tasks are at the barrier. + + The barrier may fail if it times out or if one of the tasks is unhealthy. + + Args: + barrier_id: Unique string identifying the barrier. + timeout_in_ms: Duration before the barrier times out and fails. + """ + ensure_initialized() + pywrap_tfe.TFE_WaitAtBarrier(self._context_handle, barrier_id, + timeout_in_ms) + + def clear_kernel_cache(self): + """Clear kernel cache and reset all stateful kernels.""" + if self._context_handle is not None: + pywrap_tfe.TFE_ContextClearCaches(self._context_handle) + + def enable_collective_ops(self, server_def): + """Enable distributed collective ops with an appropriate server_def. + + Args: + server_def: A tensorflow::ServerDef proto. Enables execution on remote + devices. + + Raises: + ValueError: if server_def is None. + RuntimeError: if this method is not called at program startup. + """ + if not server_def: + raise ValueError("server_def is None.") + + self._collective_ops_server_def = server_def + + # TODO(b/129298253): Allow creating datasets/tensors before enabling + # collective ops. + if self._context_handle is not None: + logging.warning("Enabling collective ops after program startup may cause " + "error when accessing previously created tensors.") + with self._initialize_lock: + assert self._initialized + server_def_str = self._collective_ops_server_def.SerializeToString() + pywrap_tfe.TFE_EnableCollectiveOps(self._context_handle, server_def_str) + self._initialize_logical_devices() + self._clear_caches() + + def configure_collective_ops( + self, + collective_leader="", + scoped_allocator_enabled_ops=("CollectiveReduce",), + use_nccl_communication=False, + device_filters=None): + """Configure collective ops. + + Collective group leader is necessary for collective ops to run, other + configurations are mainly for the purpose of performance. + + Args: + collective_leader: a device string for collective leader, e.g. + "/job:worker/replica:0/task:0"; empty string means local execution of + collective ops. + scoped_allocator_enabled_ops: a tuple or a list of op names for scoped + allocator to run with. + use_nccl_communication: whether to use nccl communication for collective + ops. + device_filters: a tuple or a list of device strings. If set, corresponding + task can only see the devices filtered by these device filters. + + Raises: + RuntimeError: if this method is not called at program startup. + """ + if self._collective_leader is not None: + if (self._collective_leader != collective_leader or + self._collective_scoped_allocator_enabled_ops != + scoped_allocator_enabled_ops or + self._collective_use_nccl_communication != use_nccl_communication or + self._collective_device_filters != device_filters): + raise ValueError("Collective ops are already configured.") + else: + return + + if self._context_handle is not None: + raise RuntimeError("Collective ops must be configured at program startup") + + self._collective_leader = collective_leader + self._collective_scoped_allocator_enabled_ops = scoped_allocator_enabled_ops + self._collective_use_nccl_communication = use_nccl_communication + self._collective_device_filters = device_filters + + def abort_collective_ops(self, code, message): + """Abort the collective ops. + + This is intended to be used when a peer failure is detected, which allows + the user to handle the case instead of hanging. This aborts all on-going + collectives. After all subsequent collectives error immediately, and you + need to reset_context() to use collectives again. + + Args: + code: a `tf.errors` error code. + message: a string. The error message. + """ + self.ensure_initialized() + pywrap_tfe.TFE_AbortCollectiveOps(self._handle, code, message) + + def check_collective_ops_peer_health(self, task, timeout_in_ms): + """Check collective peer health. + + This probes each task to see if they're still alive. Note that restarted + tasks are considered a different one, and they're considered not healthy. + + This should only be used in multi client multi worker training. + + Args: + task: a task string, must be in the format of /job:xxx/replica:0/task:N. + timeout_in_ms: an integer, the timeout. If zero, there's no timeout. + + Raises: + tf.errors.UnavailableError: when a peer is down. + tf.errors.FailedPreconditionError: when a peer is a different one from the + one this task has talked to, e.g. the peer has restarted. + tf.errors.InvalidArgumentError: when the task string is invalid. + """ + self.ensure_initialized() + pywrap_tfe.TFE_CollectiveOpsCheckPeerHealth(self._handle, task, + timeout_in_ms) + + @property + def _handle(self): + if self._context_handle is None: + raise AssertionError("Context must be initialized first.") + + return self._context_handle + + @property + def _devices(self): + if self._context_devices is None: + raise AssertionError("Context must be initialized first.") + + return self._context_devices + + def __str__(self): + if self._context_handle is None: + return "Eager TensorFlow Context. Devices currently uninitialized." + else: + devices = self._devices + lines = ["Eager TensorFlow Context with %d devices" % (len(devices))] + for i, d in enumerate(devices): + lines.append(" Device %d: %s" % (i, d)) + return "\n".join(lines) + + @tf_contextlib.contextmanager + def _mode(self, mode): + """A context manager to allow setting the mode to EAGER/GRAPH.""" + ctx = self._thread_local_data + old_is_eager = ctx.is_eager + ctx.is_eager = mode == EAGER_MODE + if mode == EAGER_MODE: + # Entering graph mode does not provide us with sufficient information to + # record a context switch; graph-based context switches are only logged + # when a graph is registered as the default graph. + self.context_switches.push(False, eager_mode, None) + try: + yield + finally: + ctx.is_eager = old_is_eager + if mode == EAGER_MODE: + self.context_switches.pop() + + def executing_eagerly(self): + """Returns True if current thread has eager executing enabled.""" + return self._thread_local_data.is_eager + + def ones_rank_cache(self): + """Per-device cache for scalars.""" + return _tensor_caches_map[self._id].ones_rank_cache + + def zeros_cache(self): + """Per-device cache for scalars.""" + return _tensor_caches_map[self._id].zeros_cache + + @property + def scope_name(self): + """Returns scope name for the current thread.""" + return self._thread_local_data.scope_name + + @scope_name.setter + def scope_name(self, s): + """Sets scope name for the current thread.""" + self._thread_local_data.scope_name = s + + @property + def device_name(self): + """Returns the device name for the current thread.""" + return self._thread_local_data.device_name + + @property + def device_spec(self): + """Returns the device spec for the current thread.""" + return self._thread_local_data.device_spec + + def _set_device(self, device_name, device_spec): + self._thread_local_data.device_name = device_name + self._thread_local_data.device_spec = device_spec + + def device(self, name): + """Context-manager to force placement of operations and Tensors on a device. + + Args: + name: Name of the device or None to get default placement. + + Returns: + Context manager that forces device placement. + + Raises: + ValueError: If name is not a string or is an invalid device name. + RuntimeError: If device scopes are not properly nested. + """ + if isinstance(name, LogicalDevice): + name = name.name + elif pydev.is_device_spec(name): + name = name.to_string() + return _EagerDeviceContext(self, name) + + def devices(self): + """List of the names of devices available to execute operations.""" + return self._devices + + def host_address_space(self): + self.ensure_initialized() + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_HostAddressSpace(self._context_handle, buffer_) + address_space = pywrap_tf_session.TF_GetBuffer(buffer_).decode("utf-8") + return address_space + + # TODO(fishx): remove this property. + @property + def execution_mode(self): + """Gets execution mode for current thread.""" + return ASYNC if self.is_async() else SYNC + + @execution_mode.setter + def execution_mode(self, mode): + """Sets execution mode for current thread.""" + if mode not in (None, SYNC, ASYNC): + raise ValueError("Execution mode should be None/SYNC/ASYNC. Got %s" % + mode) + + if mode is None: + mode = SYNC + + enable_async = (mode == ASYNC) + if self.is_async() != enable_async: + # Only set the execution mode if the context has already been initialized + if self._context_handle is not None: + self.executor.wait() + executor_new = executor.new_executor(enable_async) + self._thread_local_data.executor = executor_new + pywrap_tfe.TFE_ContextSetExecutorForThread(self._context_handle, + executor_new.handle()) + else: + self._default_is_async = enable_async + + def is_async(self): + if self._context_handle is not None: + return self.executor.is_async() + else: + return self._default_is_async + + @property + def executor(self): + self.ensure_initialized() + return executor.Executor( + pywrap_tfe.TFE_ContextGetExecutorForThread(self._context_handle)) + + @executor.setter + def executor(self, e): + self.ensure_initialized() + pywrap_tfe.TFE_ContextSetExecutorForThread(self._context_handle, e.handle()) + + @property + def config(self): + """Return the ConfigProto with all runtime deltas applied.""" + # Ensure physical devices have been discovered and config has been imported + self._initialize_physical_devices() + + config = config_pb2.ConfigProto() + if self._config is not None: + config.CopyFrom(self._config) + + if self._optimizer_jit is not None: + config.graph_options.optimizer_options.global_jit_level = ( + config_pb2.OptimizerOptions.ON_1 + if self._optimizer_jit else config_pb2.OptimizerOptions.OFF) + if self._intra_op_parallelism_threads is not None: + config.intra_op_parallelism_threads = self._intra_op_parallelism_threads + if self._inter_op_parallelism_threads is not None: + config.inter_op_parallelism_threads = self._inter_op_parallelism_threads + + if self._soft_device_placement is not None: + config.allow_soft_placement = self._soft_device_placement + else: + config.allow_soft_placement = self.executing_eagerly() + + if self._log_device_placement is not None: + config.log_device_placement = self._log_device_placement + + if self._operation_timeout_in_ms is not None: + config.operation_timeout_in_ms = self._operation_timeout_in_ms + + is_mlir_bridge_enabled = pywrap_tfe.TF_IsMlirBridgeEnabled() + config.experimental.mlir_bridge_rollout = is_mlir_bridge_enabled + if (is_mlir_bridge_enabled == + config_pb2.ConfigProto.Experimental.MLIR_BRIDGE_ROLLOUT_ENABLED): + config.experimental.enable_mlir_bridge = True + + if self._enable_mlir_graph_optimization is not None: + config.experimental.enable_mlir_graph_optimization = ( + self._enable_mlir_graph_optimization) + + def rewriter_toggle(option): + toggle = self._optimizer_experimental_options.get(option, None) + if toggle is None: + return + + setattr(config.graph_options.rewrite_options, option, + (rewriter_config_pb2.RewriterConfig.ON + if toggle else rewriter_config_pb2.RewriterConfig.OFF)) + + def rewriter_bool(option): + toggle = self._optimizer_experimental_options.get(option, None) + if toggle is None: + return + + setattr(config.graph_options.rewrite_options, option, toggle) + + rewriter_toggle("layout_optimizer") + rewriter_toggle("constant_folding") + rewriter_toggle("shape_optimization") + rewriter_toggle("remapping") + rewriter_toggle("arithmetic_optimization") + rewriter_toggle("dependency_optimization") + rewriter_toggle("loop_optimization") + rewriter_toggle("function_optimization") + rewriter_toggle("debug_stripper") + rewriter_bool("disable_model_pruning") + rewriter_toggle("scoped_allocator_optimization") + rewriter_toggle("pin_to_host_optimization") + rewriter_toggle("implementation_selector") + rewriter_toggle("auto_mixed_precision") + rewriter_toggle("use_plugin_optimizers") + rewriter_bool("disable_meta_optimizer") + rewriter_toggle("auto_mixed_precision_onednn_bfloat16") + rewriter_toggle("auto_mixed_precision_mkl") + nodes = self._optimizer_experimental_options.get("min_graph_nodes", None) + if nodes is not None: + config.graph_options.rewrite_options.min_graph_nodes = nodes + + # Compute device counts + config.device_count["CPU"] = 0 + config.device_count["GPU"] = 0 + for dev in self._physical_devices: + if dev not in self._visible_device_list: + continue + + virtual_devices = self._virtual_device_map.get(dev) + if virtual_devices is None: + config.device_count[dev.device_type] += 1 + else: + config.device_count[dev.device_type] += len(virtual_devices) + + # Configure gpu_options + gpu_options = self._compute_gpu_options() + config.gpu_options.MergeFrom(gpu_options) + + # Configure collective ops + if self._collective_leader: + config.experimental.collective_group_leader = self._collective_leader + if self._collective_scoped_allocator_enabled_ops: + rewrite_options = config.graph_options.rewrite_options + rewrite_options.scoped_allocator_optimization = ( + rewriter_config_pb2.RewriterConfig.ON) + del rewrite_options.scoped_allocator_opts.enable_op[:] + for op in self._collective_scoped_allocator_enabled_ops: + rewrite_options.scoped_allocator_opts.enable_op.append(op) + if self._collective_use_nccl_communication: + config.experimental.collective_nccl = True + if self._collective_device_filters: + del config.device_filters[:] + for f in self._collective_device_filters: + config.device_filters.append(f) + + # Configure coordination service + if self._coordination_service_config: + config.experimental.coordination_config.CopyFrom( + self._coordination_service_config) + + return config + + def _compute_gpu_options(self): + """Build the GPUOptions proto.""" + visible_device_list = [] + virtual_devices = [] + gpu_index = -1 + memory_growths = set() + gpu_devices = self.list_physical_devices("GPU") + pluggable_devices = self._pluggable_devices + compatible_devices = gpu_devices + for dev in pluggable_devices: + if dev not in gpu_devices: + compatible_devices.append(dev) + for dev in compatible_devices: + gpu_index += 1 + + if dev not in self._visible_device_list: + continue + + growth = self._memory_growth_map[dev] + memory_growths.add(growth) + visible_device_list.append(str(gpu_index)) + + if self._virtual_device_map: + vdevs = self._virtual_device_map.get(dev, []) + device_ordinals = [] + device_limits = [] + priority = [] + for virt_dev in vdevs: + if virt_dev.experimental_device_ordinal is not None: + device_ordinals.append(virt_dev.experimental_device_ordinal) + device_limits.append(virt_dev.memory_limit) + if virt_dev.experimental_priority is not None: + priority.append(virt_dev.experimental_priority) + # If priority is specified, it must be specified for all virtual + # devices. + if priority and len(device_limits) != len(priority): + raise ValueError("priority must be specified for all virtual devices") + # If device_ordinals is specified, it must be specified for all virtual + # devices. + if device_ordinals and len(device_limits) != len(device_ordinals): + raise ValueError( + "device_ordinals must be specified for all virtual devices") + + virtual_devices.append( + config_pb2.GPUOptions.Experimental.VirtualDevices( + memory_limit_mb=device_limits, + priority=priority, + device_ordinal=device_ordinals)) + + # Only compute growth if virtual devices have not been configured and we + # have GPUs + if not virtual_devices and memory_growths: + if len(memory_growths) > 1: + raise ValueError("Memory growth cannot differ between GPU devices") + allow_growth = memory_growths.pop() + else: + allow_growth = None + + return config_pb2.GPUOptions( + allow_growth=allow_growth, + visible_device_list=",".join(visible_device_list), + experimental=config_pb2.GPUOptions.Experimental( + virtual_devices=virtual_devices)) + + @property + def function_call_options(self): + """Returns function call options for current thread. + + Note that the returned object is still referenced by the eager context. + + Returns: the FunctionCallOptions for current thread. + """ + if self._thread_local_data.function_call_options is None: + config = self.config + + # Default to soft placement for functions unless specified + if self._soft_device_placement is None: + config.allow_soft_placement = True + self._thread_local_data.function_call_options = FunctionCallOptions( + config_proto=config) + + return self._thread_local_data.function_call_options + + @function_call_options.setter + def function_call_options(self, options): + """Returns function call options for current thread.""" + self._thread_local_data.function_call_options = options + + def num_gpus(self): + """The number of GPUs available to execute operations.""" + self.ensure_initialized() + return self._num_gpus + + def add_c_function(self, c_func): + """Add a C API TF_Function to the context. + + Once added, the function (identified by its name) can be executed like any + other operation. + + Args: + c_func: A wrapped TF_Function (returned from TF_GraphToFunction_wrapper). + """ + self.ensure_initialized() + pywrap_tfe.TFE_ContextAddFunction(self._handle, c_func) + + def get_c_function(self, name): + """Get a C API TF_Function from the context. + + Args: + name: Name of the function to get. + + Returns: + A ScopedTFFunction wrapping the C API TF_Function. + """ + self.ensure_initialized() + return c_api_util.ScopedTFFunction( + pywrap_tfe.TFE_ContextGetFunction(self._handle, name), name + ) + + def add_function_def(self, fdef): + """Add a function definition to the context. + + Once added, the function (identified by its name) can be executed like any + other operation. + + Args: + fdef: A FunctionDef protocol buffer message. + """ + self.ensure_initialized() + fdef_string = fdef.SerializeToString() + pywrap_tfe.TFE_ContextAddFunctionDef(self._handle, fdef_string, + len(fdef_string)) + + def get_function_def(self, name): + """Get a function definition from the context. + + Args: + name: function signature name. + + Returns: + The requested FunctionDef. + + Raises: + tf.errors.NotFoundError: if name is not the name of a registered function. + """ + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_ContextGetFunctionDef(self._handle, name, buffer_) + proto_data = pywrap_tf_session.TF_GetBuffer(buffer_) + function_def = function_pb2.FunctionDef() + function_def.ParseFromString(proto_data) + + return function_def + + def get_graph_debug_info(self, name): + """Get GraphDebugInfo associated with a function from the context. + + Args: + name: function signature name. + + Returns: + The requested GraphDebugInfo. + + Raises: + tf.errors.NotFoundError: if name is not the name of a registered function. + """ + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_ContextGetGraphDebugInfo(self._handle, name, buffer_) + proto_data = pywrap_tf_session.TF_GetBuffer(buffer_) + graph_debug_info = graph_debug_info_pb2.GraphDebugInfo() + graph_debug_info.ParseFromString(proto_data) + + return graph_debug_info + + def is_custom_device(self, device_name): + """Calls TFE_IsCustomDevice. See the non-member function.""" + self.ensure_initialized() + return pywrap_tfe.TFE_Py_IsCustomDevice(self._handle, device_name) + + def register_custom_device(self, device_capsule, device_name, + device_info_capsule): + """Calls TFE_RegisterCustomDevice. See the non-member function.""" + self.ensure_initialized() + pywrap_tfe.TFE_Py_RegisterCustomDevice(self._handle, device_capsule, + device_name, device_info_capsule) + + def pack_eager_tensors(self, tensors): + """Pack multiple `EagerTensor`s of the same dtype and shape. + + Args: + tensors: a list of EagerTensors to pack. + + Returns: + A packed EagerTensor. + """ + self.ensure_initialized() + return pywrap_tfe.TFE_Py_PackEagerTensors(self._handle, tensors) + + def list_function_names(self): + """Get a list of names of registered functions. + + Returns: + A set of names of all registered functions for the context. + """ + self.ensure_initialized() + return set(pywrap_tfe.TFE_ContextListFunctionNames(self._handle)) + + def remove_function(self, name): + """Remove a function from the context. + + Once removed, the function cannot be executed anymore. + + Args: + name: function signature name. + """ + self.ensure_initialized() + pywrap_tfe.TFE_ContextRemoveFunction(self._handle, name) + + def has_function(self, name): + """Check if a function `name` is registered.""" + self.ensure_initialized() + return bool(pywrap_tfe.TFE_ContextHasFunction(self._handle, name)) + + @property + def function_scope_id(self): + """Returns an id that is unique to each scope holding functions.""" + return id(self._context_handle) + + def call_function(self, name, tensor_inputs, num_outputs): + """Calls the function associated with the given name.""" + attrs = tuple( + itertools.chain( + *self.function_call_options.as_attrs().items() + ) + ) + + cancellation_context = cancellation.context() + if cancellation_context is None: + outputs = execute.execute( + name.decode("utf-8"), + num_outputs=num_outputs, + inputs=tensor_inputs, + attrs=attrs, + ctx=self, + ) + else: + outputs = execute.execute_with_cancellation( + name.decode("utf-8"), + num_outputs=num_outputs, + inputs=tensor_inputs, + attrs=attrs, + ctx=self, + cancellation_manager=cancellation_context, + ) + # Empty list means no function outputs so return None + outputs = outputs or None + + return outputs + + def add_op_callback(self, callback): + """Add a post-op callback to the context. + + A post-op callback is invoked immediately after an eager operation or + function has finished execution or after a op has been added to a graph, + providing access to the op's type, name input and output tensors. Multiple + op callbacks can be added, in which case the callbacks will be invoked in + the order in which they are added. + + Args: + callback: a callable of the signature `f(op_type, inputs, attrs, outputs, + op_name=None, graph=None)`. See doc strings in `op_callbacks.py` for + details on the function signature and its semantics. + """ + if callback not in self._thread_local_data.op_callbacks: + self._thread_local_data.op_callbacks.append(callback) + + def remove_op_callback(self, callback): + """Remove an already-registered op callback. + + Args: + callback: The op callback to be removed. + + Raises: + KeyError: If `callback` is not already registered. + """ + if callback not in self._thread_local_data.op_callbacks: + raise KeyError("The specified op callback has not been registered, " + "and hence cannot be removed.") + del self._thread_local_data.op_callbacks[ + self._thread_local_data.op_callbacks.index(callback)] + + @property + def op_callbacks(self): + return self._thread_local_data.op_callbacks + + @property + def invoking_op_callbacks(self): + return self._thread_local_data.invoking_op_callbacks + + @invoking_op_callbacks.setter + def invoking_op_callbacks(self, value): + self._thread_local_data.invoking_op_callbacks = value + + def _initialize_physical_devices(self, reinitialize=False): + """Gets local devices visible to the system. + + Args: + reinitialize: If True, reinitializes self._physical_devices so that + dynamic registered devices will also be visible to the python front-end. + """ + # We lazy initialize self._physical_devices since we do not want to do this + # the constructor since the backend may not be initialized yet. + with self._device_lock: + if not reinitialize and self._physical_devices is not None: + return + + devs = pywrap_tfe.TF_ListPhysicalDevices() + self._physical_devices = [ + PhysicalDevice(name=d.decode(), device_type=d.decode().split(":")[1]) + for d in devs + ] + self._physical_device_to_index = { + p: i for i, p in enumerate(self._physical_devices) + } + # We maintain a separate list just so we can check whether the device in + # _physical_devices is a PluggableDevice. + pluggable_devs = pywrap_tfe.TF_ListPluggablePhysicalDevices() + self._pluggable_devices = [ + PhysicalDevice(name=d.decode(), device_type=d.decode().split(":")[1]) + for d in pluggable_devs + ] + + self._visible_device_list = list(self._physical_devices) + self._memory_growth_map = { + d: None + for d in self._physical_devices + if d.device_type == "GPU" or d in self._pluggable_devices + } + + # Import device settings that may have been passed into the constructor + self._import_config() + + def reinitialize_physical_devices(self): + """Gets local devices visible to the system.""" + # Reinitialize the physical device list after registering + # the pluggable device. + self._initialize_physical_devices(True) + + def list_physical_devices(self, device_type=None): + """List local devices visible to the system. + + This API allows a client to query the devices before they have been + initialized by the eager runtime. Additionally a user can filter by device + type, to get only CPUs or GPUs. + + Args: + device_type: Optional device type to limit results to + + Returns: + List of PhysicalDevice objects. + """ + self._initialize_physical_devices() + + if device_type is None: + return list(self._physical_devices) + + return [d for d in self._physical_devices if d.device_type == device_type] + + def get_device_details(self, device): # pylint: disable=redefined-outer-name + """Returns details about a physical devices. + + Args: + device: A `tf.config.PhysicalDevice` returned by + `tf.config.list_physical_devices` or `tf.config.get_visible_devices`. + + Returns: + A dict with string keys. + """ + if not isinstance(device, PhysicalDevice): + raise ValueError("device must be a tf.config.PhysicalDevice, but got: " + "%s" % (device,)) + if (self._physical_device_to_index is None or + device not in self._physical_device_to_index): + raise ValueError("The PhysicalDevice must be one obtained from " + "calling `tf.config.list_physical_devices`, but got: " + "%s" % (device,)) + index = self._physical_device_to_index[device] + details = pywrap_tfe.TF_GetDeviceDetails(index) + + # Change compute_capability from a string to a tuple + if "compute_capability" in details: + try: + major, minor = details["compute_capability"].split(".") + details["compute_capability"] = (int(major), int(minor)) + except ValueError: + raise RuntimeError("Device returned compute capability an in invalid " + "format: %s" % details["compute_capability"]) + return details + + def _import_config(self): + """Import config if passed in during construction. + + If Context was created with a ConfigProto such as when calling + tf.compat.v1.enable_eager_execution(), then we need to pull out the + various pieces we might be replacing and import then into our internal + class representation. + """ + if self._config is None: + return + + num_cpus = self._config.device_count.get("CPU", 1) + if num_cpus != 1: + cpus = [d for d in self._physical_devices if d.device_type == "CPU"] + if num_cpus == 0: + self.set_visible_devices([], "CPU") + elif num_cpus > 1: + self.set_logical_device_configuration( + cpus[0], [LogicalDeviceConfiguration() for _ in range(num_cpus)]) + + # Parse GPU options + gpus = [d for d in self._physical_devices if d.device_type == "GPU"] + + # If there are no GPUs detected, simply ignore all the GPU options passed in + # rather than doing any validation checks. + if not gpus: + return + + gpu_count = self._config.device_count.get("GPU", None) + + visible_gpus = [] + # TODO(gjn): Handle importing existing virtual GPU configuration + visible_indices = self._config.gpu_options.visible_device_list + if visible_indices: + for index in visible_indices.split(","): + if int(index) >= len(gpus): + raise ValueError("Invalid visible device index: %s" % index) + visible_gpus.append(gpus[int(index)]) + else: + visible_gpus = gpus + + if gpu_count is not None: + visible_gpus = visible_gpus[:gpu_count] + + self.set_visible_devices(visible_gpus, "GPU") + + def list_logical_devices(self, device_type=None): + """Return logical devices.""" + self.ensure_initialized() + if device_type is None: + return list(self._logical_devices) + + return [d for d in self._logical_devices if d.device_type == device_type] + + def get_visible_devices(self, device_type=None): + """Get the list of visible devices.""" + self._initialize_physical_devices() + + if device_type is None: + return list(self._visible_device_list) + + return [ + d for d in self._visible_device_list if d.device_type == device_type + ] + + def set_visible_devices(self, devices, device_type=None): + """Set the list of visible devices.""" + self._initialize_physical_devices() + + if not isinstance(devices, list): + devices = [devices] + + for d in devices: + if d not in self._physical_devices: + raise ValueError("Unrecognized device: %s" % repr(d)) + if device_type is not None and d.device_type != device_type: + raise ValueError("Unrecognized device: %s" % repr(d)) + + visible_device_list = [] + if device_type is not None: + visible_device_list = [ + d for d in self._visible_device_list if d.device_type != device_type + ] + + visible_device_list += devices + + if self._visible_device_list == visible_device_list: + return + + if self._context_handle is not None: + raise RuntimeError( + "Visible devices cannot be modified after being initialized") + + self._visible_device_list = visible_device_list + + def get_memory_info(self, dev): + """Returns a dict of memory info for the device.""" + self._initialize_physical_devices() + self.ensure_initialized() + return pywrap_tfe.TFE_GetMemoryInfo(self._context_handle, dev) + + def reset_memory_stats(self, dev): + """Resets the tracked memory stats for the device.""" + self._initialize_physical_devices() + self.ensure_initialized() + pywrap_tfe.TFE_ResetMemoryStats(self._context_handle, dev) + + def get_memory_growth(self, dev): + """Get if memory growth is enabled for a PhysicalDevice.""" + self._initialize_physical_devices() + + if dev not in self._physical_devices: + raise ValueError("Unrecognized device: %s" % repr(dev)) + + return self._memory_growth_map[dev] + + def set_memory_growth(self, dev, enable): + """Set if memory growth should be enabled for a PhysicalDevice.""" + self._initialize_physical_devices() + + if dev not in self._physical_devices: + raise ValueError("Unrecognized device: %s" % repr(dev)) + + if dev in self._virtual_device_map: + raise ValueError( + "Cannot set memory growth on device when virtual devices configured") + + if dev.device_type != "GPU" and dev not in self._pluggable_devices: + raise ValueError( + "Cannot set memory growth on non-GPU and non-Pluggable devices") + + if self._memory_growth_map.get(dev) == enable: + return + + if self._context_handle is not None: + raise RuntimeError( + "Physical devices cannot be modified after being initialized") + + self._memory_growth_map[dev] = enable + + def get_logical_device_configuration(self, dev): + """Get the virtual device configuration for a PhysicalDevice.""" + self._initialize_physical_devices() + + if dev not in self._physical_devices: + raise ValueError("Unrecognized device: %s" % repr(dev)) + + return self._virtual_device_map.get(dev) + + def set_logical_device_configuration(self, dev, virtual_devices): + """Set the virtual device configuration for a PhysicalDevice.""" + self._initialize_physical_devices() + + if dev not in self._physical_devices: + raise ValueError("Unrecognized device: %s" % repr(dev)) + + if dev.device_type == "CPU": + for vdev in virtual_devices: + if vdev.memory_limit is not None: + raise ValueError("Setting memory limit on CPU virtual devices is " + "currently not supported") + if vdev.experimental_priority is not None: + raise ValueError("Setting experimental_priority on CPU virtual " + " devices is currently not supported") + if vdev.experimental_device_ordinal is not None: + raise ValueError("Setting experimental_device_ordinal on CPU virtual " + " devices is currently not supported") + elif dev.device_type == "GPU": + for vdev in virtual_devices: + if vdev.memory_limit is None: + raise ValueError( + "Setting memory limit is required for GPU virtual devices") + else: + raise ValueError("Virtual devices are not supported for %s" % + dev.device_type) + + if self._virtual_device_map.get(dev) == virtual_devices: + return + + if self._context_handle is not None: + raise RuntimeError( + "Virtual devices cannot be modified after being initialized") + + self._virtual_device_map[dev] = virtual_devices + + def set_logical_cpu_devices(self, num_cpus, prefix=""): + """Set virtual CPU devices in context. + + If virtual CPU devices are already configured at context initialization + by tf.config.set_logical_device_configuration(), this method should not be + called. + + Args: + num_cpus: Number of virtual CPUs. + prefix: Device name prefix. + + Raises: + RuntimeError: If virtual CPUs are already configured at context + initialization. + """ + server_def = self._server_def or self._collective_ops_server_def + local_prefix = ["/device"] + if server_def is not None: + local_prefix.append("/job:%s/replica:0/task:%d" % (server_def.job_name, + server_def.task_index)) + logical_local_devices = [d for d in self.list_logical_devices("CPU") if + d.name.startswith(tuple(local_prefix))] + self.ensure_initialized() + # Error out if there are already multiple logical CPU in the context. + if len(logical_local_devices) > 1: + raise RuntimeError("Virtual CPUs already set, cannot modify again.") + + pywrap_tfe.TFE_SetLogicalCpuDevices(self._context_handle, num_cpus, prefix) + self._initialize_logical_devices() + + def get_compiler_ir( + self, + device_name, + function_name, + flat_args, + captured_inputs, + stage="hlo", + ): + return pywrap_tfe.TF_GetCompilerIr( + self._context_handle, + function_name, + stage, + device_name, + flat_args, + captured_inputs, + ) + + @deprecated( + None, "XLA:CPU and XLA:GPU devices are deprecated", warn_once=True) + def enable_xla_devices(self): + """Enables XLA:CPU and XLA:GPU devices registration.""" + pywrap_tfe.TF_EnableXlaDevices() + + @property + def enable_mlir_bridge(self): + return pywrap_tfe.TF_IsMlirBridgeEnabled() + + @property + def enable_mlir_graph_optimization(self): + return self._enable_mlir_graph_optimization + + @enable_mlir_bridge.setter + def enable_mlir_bridge(self, enabled): + pywrap_tfe.TF_EnableMlirBridge(enabled) + self._thread_local_data.function_call_options = None + + @enable_mlir_graph_optimization.setter + def enable_mlir_graph_optimization(self, enabled): + self._enable_mlir_graph_optimization = enabled + self._thread_local_data.function_call_options = None + + @property + def optimizer_jit(self): + level = self.config.graph_options.optimizer_options.global_jit_level + return (level == config_pb2.OptimizerOptions.ON_1 or + level == config_pb2.OptimizerOptions.ON_2) + + @optimizer_jit.setter + def optimizer_jit(self, enabled): + self._optimizer_jit = enabled + + self._thread_local_data.function_call_options = None + + def get_optimizer_experimental_options(self): + """Get experimental options for the optimizer. + + Returns: + Dictionary of current option values + """ + rewrite_options = self.config.graph_options.rewrite_options + options = {} + + def rewriter_toggle(option): + attr = getattr(rewrite_options, option) + if attr != 0: + options[option] = (attr == rewriter_config_pb2.RewriterConfig.ON) + + def rewriter_bool(option): + options[option] = getattr(rewrite_options, option) + + rewriter_toggle("layout_optimizer") + rewriter_toggle("constant_folding") + rewriter_toggle("shape_optimization") + rewriter_toggle("remapping") + rewriter_toggle("arithmetic_optimization") + rewriter_toggle("dependency_optimization") + rewriter_toggle("loop_optimization") + rewriter_toggle("function_optimization") + rewriter_toggle("debug_stripper") + rewriter_bool("disable_model_pruning") + rewriter_toggle("scoped_allocator_optimization") + rewriter_toggle("pin_to_host_optimization") + rewriter_toggle("implementation_selector") + rewriter_toggle("auto_mixed_precision") + rewriter_toggle("use_plugin_optimizers") + rewriter_bool("disable_meta_optimizer") + rewriter_toggle("auto_mixed_precision_onednn_bfloat16") + rewriter_toggle("auto_mixed_precision_mkl") + + if rewrite_options.min_graph_nodes != 0: + options["min_graph_nodes"] = rewrite_options.min_graph_nodes + + return options + + def set_optimizer_experimental_options(self, options): + """Set experimental options for the optimizer. + + Args: + options: Dictionary of options to modify + """ + self._optimizer_experimental_options.update(options) + + self._thread_local_data.function_call_options = None + + @property + def intra_op_parallelism_threads(self): + return self.config.intra_op_parallelism_threads + + @intra_op_parallelism_threads.setter + def intra_op_parallelism_threads(self, num_threads): + if self._intra_op_parallelism_threads == num_threads: + return + + if self._context_handle is not None: + raise RuntimeError( + "Intra op parallelism cannot be modified after initialization.") + + self._intra_op_parallelism_threads = num_threads + + @property + def inter_op_parallelism_threads(self): + return self.config.inter_op_parallelism_threads + + @inter_op_parallelism_threads.setter + def inter_op_parallelism_threads(self, num_threads): + if self._inter_op_parallelism_threads == num_threads: + return + + if self._context_handle is not None: + raise RuntimeError( + "Inter op parallelism cannot be modified after initialization.") + + self._inter_op_parallelism_threads = num_threads + + @property + def soft_device_placement(self): + return self.config.allow_soft_placement + + @soft_device_placement.setter + def soft_device_placement(self, enable): + if self._context_handle is not None: + pywrap_tfe.TFE_ContextSetSoftDevicePlacement(self._handle, enable) + + self._soft_device_placement = enable + self._thread_local_data.function_call_options = None + + @property + def log_device_placement(self): + return self.config.log_device_placement + + @log_device_placement.setter + def log_device_placement(self, enable): + if self._context_handle is not None: + pywrap_tfe.TFE_ContextSetLogDevicePlacement(self._handle, enable) + + self._log_device_placement = enable + self._thread_local_data.function_call_options = None + + @property + def jit_compile_rewrite(self): + return self._jit_compile_rewrite + + @jit_compile_rewrite.setter + def jit_compile_rewrite(self, enable): + if self._context_handle is not None: + pywrap_tfe.TFE_ContextSetJitCompileRewrite(self._handle, enable) + self._jit_compile_rewrite = enable + + @property + def device_policy(self): + # Only get the policy from the context if it has already been initialized + if self._context_handle is not None: + return pywrap_tfe.TFE_ContextGetDevicePlacementPolicy(self._handle) + + return self._device_policy + + @device_policy.setter + def device_policy(self, policy): + if policy is None: + policy = DEVICE_PLACEMENT_SILENT + + if self._device_policy != policy: + self._device_policy = policy + + # Only set the policy if the context has already been initialized + if self._context_handle is not None: + pywrap_tfe.TFE_ContextSetThreadLocalDevicePlacementPolicy( + self._handle, self._device_policy) + + @property + def use_tfrt(self): + return self._use_tfrt + + @use_tfrt.setter + def use_tfrt(self, tfrt): + """Sets whether to use TFRT.""" + if not isinstance(tfrt, bool): + raise ValueError("Expecting a boolean but got %s" % type(tfrt)) + + if self._use_tfrt != tfrt: + if self._initialized: + raise ValueError("use_tfrt should be set before being initialized.") + self._use_tfrt = tfrt + + @property + def operation_timeout_in_ms(self): + return self.config.operation_timeout_in_ms + + @operation_timeout_in_ms.setter + def operation_timeout_in_ms(self, timeout_in_ms): + if self._operation_timeout_in_ms == timeout_in_ms: + return + + if self._context_handle is not None: + raise RuntimeError( + "Operation timeout cannot be modified after initialization.") + + self._operation_timeout_in_ms = timeout_in_ms + + def enable_run_metadata(self): + """Enables tracing of op execution via RunMetadata. + + To retrieve the accumulated metadata call context.export_run_metadata() + and to stop tracing call context.disable_run_metadata(). + """ + self.ensure_initialized() + pywrap_tfe.TFE_ContextEnableRunMetadata(self._handle) + + def disable_run_metadata(self): + """Disables tracing of op execution via RunMetadata.""" + if not self._context_handle: + return + pywrap_tfe.TFE_ContextDisableRunMetadata(self._context_handle) + + def enable_graph_collection(self): + """Enables graph collection of executed functions. + + To retrieve the accumulated graphs call context.export_run_metadata() + and to stop collecting graphs call context.disable_graph_collection(). + """ + self.ensure_initialized() + pywrap_tfe.TFE_ContextEnableGraphCollection(self._handle) + + def disable_graph_collection(self): + """Disables graph collection of executed functions.""" + if not self._context_handle: + return + pywrap_tfe.TFE_ContextDisableGraphCollection(self._context_handle) + + def export_run_metadata(self): + """Returns a RunMetadata proto with accumulated information. + + The returned protocol buffer contains information since the most recent call + to either enable_run_metadata or export_run_metadata. + + Returns: + A RunMetadata protocol buffer. Or None if not enabled. + """ + if not self._context_handle: + return None + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_ContextExportRunMetadata(self._context_handle, buffer_) + proto_data = pywrap_tf_session.TF_GetBuffer(buffer_) + run_metadata = config_pb2.RunMetadata() + run_metadata.ParseFromString(compat.as_bytes(proto_data)) + return run_metadata + + def set_server_def_retries(self, retries): + """Set the number of retries to use when calling SetServerDef. + + In cases where many servers run in high-preemption environments, jobs could + be preempted during startup and initial connection via SetServerDef. Retries + allow for more robust connection in these environments. + + Args: + retries: int specifying the number of connection retries before failing. + Retries follow an exponential backoff waiting period with min value 1ms, + max value 10s, and exponent 1.3. + """ + self._set_server_def_retries = retries + + @property + def context_switches(self): + """Returns a stack of context switches.""" + return self._context_switches + + +class _EagerDeviceContext(object): + """Context-manager forcing placement of ops and Tensors on a device.""" + + __slots__ = ["_device_name", "_ctx", "_stack"] + + def __init__(self, ctx, device_name): + self._device_name = device_name + self._ctx = ctx + self._stack = [] + + # TODO(b/189233748): Consolidate the device string parsing logic with + # tensorflow/core/util/device_name_utils.cc. + def __enter__(self): + ctx = self._ctx + old_device_name = ctx.device_name + old_device_spec = ctx.device_spec + new_device_name = self._device_name + cache_key = (old_device_name, new_device_name) + try: + new_device_name, new_device_spec = _device_parsing_cache[cache_key] + except TypeError: + # Error while trying to compute the cache key. + raise ValueError("Expecting a string device name. Got %s(%s)" % + (type(new_device_name), new_device_name)) + except KeyError: + # Handle a cache miss. + if new_device_name is not None: + if not isinstance(new_device_name, str): + raise ValueError("Expecting a string device name. Got %s(%s)" % + (type(new_device_name), new_device_name)) + device_spec = pydev.DeviceSpec.from_string(new_device_name) + if old_device_name: + new_device_spec = copy.copy(old_device_spec) + else: + ctx.ensure_initialized() + new_device_spec = pydev.DeviceSpec.from_string( + ctx._context_devices[0]) # pylint: disable=protected-access + new_device_spec = new_device_spec.make_merged_spec(device_spec) + else: + new_device_spec = pydev.DeviceSpec.from_string("") + new_device_name = new_device_spec.to_string() + _device_parsing_cache[cache_key] = (new_device_name, new_device_spec) + + ctx._set_device(new_device_name, new_device_spec) # pylint: disable=protected-access + self._stack.append((old_device_name, old_device_spec, new_device_spec)) + + def __exit__(self, *ex_info): + ctx = self._ctx + old_device_name, old_device_spec, new_device_spec = self._stack[-1] + if ctx.device_spec is not new_device_spec: + raise RuntimeError("Exiting device scope without proper scope nesting") + del self._stack[-1] + ctx._set_device(old_device_name, old_device_spec) # pylint: disable=protected-access + + +# Do not change directly. +_context = None +_context_lock = threading.Lock() + + +def _set_context_locked(ctx): + global _context + pywrap_tfe.TFE_Py_SetEagerContext(ctx) + ctx.mark_as_global_context() + _context = ctx + + +def _set_context(ctx): + with _context_lock: + _set_context_locked(ctx) + + +def _create_context(): + with _context_lock: + if _context is None: + ctx = Context() + _set_context_locked(ctx) + + +def _reset_context(): + """Clears and re-initializes the singleton context. + + Should only be used for testing. + """ + global _context + global _device_parsing_cache + + # Garbage collect and clear scalar cache to avoid Tensor from current context + # polluting next context. + gc.collect() + pywrap_tfe.TFE_ClearScalarCache() + with _context_lock: + if _context is not None: + _context._clear_caches() + _context = None + _create_context() + _device_parsing_cache = {} + + +def _reset_jit_compiler_flags(): + """Clears and re-initializes the TF JIT compiler flags. + + Should only be used for testing. + """ + pywrap_tfe.TF_ResetJitCompilerFlags() + + +def context() -> Context: + """Returns a singleton context object.""" + if _context is None: + _create_context() + return _context + + +def context_safe(): + """Returns current context (or None if one hasn't been initialized).""" + return _context + + +def ensure_initialized(): + """Initialize the context.""" + context().ensure_initialized() + + +def initialize_logical_devices(): + """Initialize the virtual devices.""" + context()._initialize_logical_devices() # pylint: disable=protected-access + + +def set_global_seed(seed): + """Sets the eager mode seed.""" + context()._set_global_seed(seed) # pylint: disable=protected-access + + +def global_seed(): + """Returns the eager mode seed.""" + return context()._seed # pylint: disable=protected-access + + +def internal_operation_seed(): + """Returns the operation seed generated based on global seed.""" + return context()._internal_operation_seed() # pylint: disable=protected-access + + +@tf_export("executing_eagerly", v1=[]) +def executing_eagerly(): + """Checks whether the current thread has eager execution enabled. + + Eager execution is enabled by default and this API returns `True` + in most of cases. However, this API might return `False` in the following use + cases. + + * Executing inside `tf.function`, unless under `tf.init_scope` or + `tf.config.run_functions_eagerly(True)` is previously called. + * Executing inside a transformation function for `tf.dataset`. + * `tf.compat.v1.disable_eager_execution()` is called. + + General case: + + >>> print(tf.executing_eagerly()) + True + + Inside `tf.function`: + + >>> @tf.function + ... def fn(): + ... with tf.init_scope(): + ... print(tf.executing_eagerly()) + ... print(tf.executing_eagerly()) + >>> fn() + True + False + + Inside `tf.function` after `tf.config.run_functions_eagerly(True)` is called: + + >>> tf.config.run_functions_eagerly(True) + >>> @tf.function + ... def fn(): + ... with tf.init_scope(): + ... print(tf.executing_eagerly()) + ... print(tf.executing_eagerly()) + >>> fn() + True + True + >>> tf.config.run_functions_eagerly(False) + + Inside a transformation function for `tf.dataset`: + + >>> def data_fn(x): + ... print(tf.executing_eagerly()) + ... return x + >>> dataset = tf.data.Dataset.range(100) + >>> dataset = dataset.map(data_fn) + False + + Returns: + `True` if the current thread has eager execution enabled. + """ + ctx = context_safe() + if ctx is None: + return default_execution_mode == EAGER_MODE + + return ctx.executing_eagerly() + + +@tf_export(v1=["executing_eagerly"]) +def executing_eagerly_v1(): + """Checks whether the current thread has eager execution enabled. + + Eager execution is typically enabled via + `tf.compat.v1.enable_eager_execution`, but may also be enabled within the + context of a Python function via tf.contrib.eager.py_func. + + When eager execution is enabled, returns `True` in most cases. However, + this API might return `False` in the following use cases. + + * Executing inside `tf.function`, unless under `tf.init_scope` or + `tf.config.run_functions_eagerly(True)` is previously called. + * Executing inside a transformation function for `tf.dataset`. + * `tf.compat.v1.disable_eager_execution()` is called. + + >>> tf.compat.v1.enable_eager_execution() + + General case: + + >>> print(tf.executing_eagerly()) + True + + Inside `tf.function`: + + >>> @tf.function + ... def fn(): + ... with tf.init_scope(): + ... print(tf.executing_eagerly()) + ... print(tf.executing_eagerly()) + >>> fn() + True + False + + Inside `tf.function` + after `tf.config.run_functions_eagerly(True)` is called: + + >>> tf.config.run_functions_eagerly(True) + >>> @tf.function + ... def fn(): + ... with tf.init_scope(): + ... print(tf.executing_eagerly()) + ... print(tf.executing_eagerly()) + >>> fn() + True + True + >>> tf.config.run_functions_eagerly(False) + + Inside a transformation function for `tf.dataset`: + + >>> def data_fn(x): + ... print(tf.executing_eagerly()) + ... return x + >>> dataset = tf.data.Dataset.range(100) + >>> dataset = dataset.map(data_fn) + False + + Returns: + `True` if the current thread has eager execution enabled. + """ + return executing_eagerly() + + +def in_eager_mode(): + """Use executing_eagerly() instead. This function will be removed.""" + return executing_eagerly() + + +def anonymous_name(): + """Returns the anonymous shared name. + + In eager mode we create anonymous resources to avoid spurious sharing issues. + The runtime generates a unique name on our behalf when the reserved + anonymous shared name is used as a shared name. + + Returns: + The anonymous shared name. + """ + + # The magic value is defined as + # `tensorflow::ResourceHandle::ANONYMOUS_NAME` in C++. + return "cd2c89b7-88b7-44c8-ad83-06c2a9158347" + + +def graph_mode(): + """Context-manager to disable eager execution for the current thread.""" + return context()._mode(GRAPH_MODE) # pylint: disable=protected-access + + +# Used by b/167638505 for keras backend API and Lambda layer. +@tf_export("__internal__.eager_context.eager_mode", v1=[]) +def eager_mode(): + """Context-manager to enable eager execution for the current thread.""" + return context()._mode(EAGER_MODE) # pylint: disable=protected-access + + +def scope_name(): + """Name of the current scope.""" + return context().scope_name + + +def device(name): + """Context-manager to force placement of operations and Tensors on a device. + + Example: + ```python + with tf.device('gpu:0'): + with tf.device('cpu:0'): + shape = tf.constant([], dtype=tf.int32) + x = tf.random.truncated_normal(shape, tf.float32) + ``` + will ensure that the `shape` Tensor is on CPU but the `truncated_normal` + operation runs on GPU 0. + + Args: + name: Name of the device (see context().devices()), or None to perform + automatic placement. + + Returns: + Context manager for setting the device. + """ + ensure_initialized() + return context().device(name) + + +# Expose some properties of Context as internally public APIs (b/160348781). +@tf_export("__internal__.eager_context.get_config", v1=[]) +def get_config(): + """Get the ConfigProto of Context. + + Returns: + The ConfigProto of Context. + """ + return context().config + + +@tf_export("__internal__.eager_context.get_device_name", v1=[]) +def get_device_name(): + """Get the device name for the current thread. + + Returns: + The device name for the current thread. + """ + return context().device_name + + +@tf_export("__internal__.eager_context.set_soft_device_placement", v1=[]) +def set_soft_device_placement(enabled): + """Set if soft device placements should be allowed. + + Args: + enabled: Whether to enable soft device placement. + """ + context().soft_device_placement = enabled + + +@tf_export("__internal__.eager_context.get_executor", v1=[]) +def get_executor(): + """Get the Executor of the current thread. + + Returns: + The Executor of the current thread. + """ + return context().executor + + +@tf_export("debugging.get_log_device_placement") +def get_log_device_placement(): + """Get if device placements are logged. + + Returns: + If device placements are logged. + """ + return context().log_device_placement + + +@tf_export("debugging.set_log_device_placement") +def set_log_device_placement(enabled): + """Turns logging for device placement decisions on or off. + + Operations execute on a particular device, producing and consuming tensors on + that device. This may change the performance of the operation or require + TensorFlow to copy data to or from an accelerator, so knowing where operations + execute is useful for debugging performance issues. + + For more advanced profiling, use the [TensorFlow + profiler](https://www.tensorflow.org/guide/profiler). + + Device placement for operations is typically controlled by a `tf.device` + scope, but there are exceptions, for example operations on a `tf.Variable` + which follow the initial placement of the variable. Turning off soft device + placement (with `tf.config.set_soft_device_placement`) provides more explicit + control. + + >>> tf.debugging.set_log_device_placement(True) + >>> tf.ones([]) + >>> # [...] op Fill in device /job:localhost/replica:0/task:0/device:GPU:0 + >>> with tf.device("CPU"): + ... tf.ones([]) + >>> # [...] op Fill in device /job:localhost/replica:0/task:0/device:CPU:0 + >>> tf.debugging.set_log_device_placement(False) + + Turning on `tf.debugging.set_log_device_placement` also logs the placement of + ops inside `tf.function` when the function is called. + + Args: + enabled: Whether to enabled device placement logging. + """ + context().log_device_placement = enabled + + +@tf_contextlib.contextmanager +def device_policy(policy): + """Context manager for setting device placement policy for current thread.""" + ctx = context() + old_policy = ctx.device_policy + try: + ctx.device_policy = policy + yield + finally: + ctx.device_policy = old_policy + + +def set_execution_mode(mode): + """Sets execution mode for the current thread.""" + context().execution_mode = mode + + +# TODO(fishx): remove this method. +@tf_contextlib.contextmanager +def execution_mode(mode): + """Context manager for setting execution mode for current thread.""" + if mode is None: + yield + else: + ctx = context() + executor_new = executor.new_executor(mode == ASYNC) + executor_old = ctx.executor + try: + executor_old.wait() + ctx.executor = executor_new + yield + finally: + ctx.executor = executor_old + executor_new.wait() + + +@tf_contextlib.contextmanager +def executor_scope(e): + """Context manager for changing executor for current thread. + + Args: + e: A Executor to execute eager ops under this scope. Setting it to None will + switch back to use the default executor for the context. + + Yields: + Context manager for setting the executor for current thread. + """ + ctx = context() + executor_old = ctx.executor + try: + ctx.executor = e + yield + finally: + ctx.executor = executor_old + + +@tf_export("experimental.function_executor_type") +@tf_contextlib.contextmanager +def function_executor_type(executor_type): + """Context manager for setting the executor of eager defined functions. + + Eager defined functions are functions decorated by tf.contrib.eager.defun. + + Args: + executor_type: a string for the name of the executor to be used to execute + functions defined by tf.contrib.eager.defun. + + Yields: + Context manager for setting the executor of eager defined functions. + """ + current_options = context().function_call_options + old_options = copy.copy(current_options) + try: + current_options.executor_type = executor_type + yield + finally: + context().function_call_options = old_options + + +def is_async(): + """Returns true if current thread is in async mode.""" + return context().is_async() + + +def num_gpus(): + """Get the number of available GPU devices. + + Returns: + The number of available GPU devices. + """ + return context().num_gpus() + + +def enable_run_metadata(): + """Enables tracing of op execution via RunMetadata. + + To retrieve the accumulated metadata call context.export_run_metadata() + and to stop tracing call context.disable_run_metadata(). + """ + context().enable_run_metadata() + + +def disable_run_metadata(): + """Disables tracing of op execution via RunMetadata.""" + context().disable_run_metadata() + + +def enable_graph_collection(): + """Enables graph collection of executed functions. + + To retrieve the accumulated graphs call context.export_run_metadata() + and to stop collecting graphs call context.disable_graph_collection(). + """ + context().enable_graph_collection() + + +def disable_graph_collection(): + """Disables graph collection of executed functions.""" + context().disable_graph_collection() + + +def export_run_metadata(): + """Returns a RunMetadata proto with accumulated information. + + The returned protocol buffer contains information since the most recent call + to either enable_run_metadata or export_run_metadata. + + Returns: + A RunMetadata protocol buffer. + """ + return context().export_run_metadata() + + +@contextlib.contextmanager +def collect_graphs(optimized=True): + """Collects a flat list of pre- or post-optimization graphs. + + The collected graphs include device placements, which can be useful for + testing. + + Usage: + + ``` + @def_function.function + def f(x): + return x + constant_op.constant(1.) + + with context.collect_graphs() as graphs: + with ops.device("CPU:0"): + f(constant_op.constant(1.)) + + graph, = graphs # `graph` contains a single GraphDef for inspection + ``` + + Args: + optimized: whether to collect optimized graphs or non-optimized graphs + + Yields: + A list of GraphDefs, populated when the context manager exits. + """ + ctx = context() + ctx.enable_graph_collection() + try: + graphs = [] + yield graphs + metadata = ctx.export_run_metadata() + finally: + ctx.disable_graph_collection() + for graph in metadata.function_graphs: + if optimized: + graphs.append(graph.post_optimization_graph) + else: + graphs.append(graph.pre_optimization_graph) + + +def get_server_def(): + return context().get_server_def() + + +def set_server_def(server_def): + context().set_server_def(server_def) + + +def set_server_def_retries(retries): + """Set the number of retries to use when calling SetServerDef. + + In cases where many servers run in high-preemption environments, jobs could + be preempted during startup and initial connection via SetServerDef. Retries + allow for more robust connection in these environments. + + + Args: + retries: int specifying the number of connection retries before failing. + Retries follow an exponential backoff waiting period with min value 1ms, + max value 10s, and exponent 1.3. + """ + context().set_server_def_retries(retries) + + +def update_server_def(server_def): + context().update_server_def(server_def) + + +def check_alive(worker_name): + return context().check_alive(worker_name) + + +@tf_export("experimental.async_scope") +@tf_contextlib.contextmanager +def async_scope(): + """Context manager for grouping async operations. + + Ops/function calls inside the scope can return before finishing the actual + execution. When exiting the async scope, a synchronization barrier will be + automatically added to ensure the completion of all async op and function + execution, potentially raising exceptions if async execution results in + an error state. + + Users may write the following code to asynchronously invoke `train_step_fn` + and log the `loss` metric for every `num_steps` steps in a training loop. + `train_step_fn` internally consumes data using `iterator.get_next()`, and may + throw OutOfRangeError when running out of data. In the case: + + ``` + try: + with tf.experimental.async_scope(): + for _ in range(num_steps): + # Step function updates the metric `loss` internally + train_step_fn() + except tf.errors.OutOfRangeError: + tf.experimental.async_clear_error() + logging.info('loss = %s', loss.numpy()) + ``` + + Yields: + Context manager for grouping async operations. + """ + # TODO(haoyuzhang): replace env var once we have a config method to turn on + # and off async streaming RPC + remote_async_env_var = "TF_ENABLE_EAGER_CLIENT_STREAMING_ENQUEUE" + old_policy = os.environ.get(remote_async_env_var) + try: + os.environ[remote_async_env_var] = str(True) + yield + # Note: sync local and remote executors iff the async block does not raise + # an exception. Triggering sync after an exception may lead to derived + # runtime errors and unexpected exception types. + context().sync_executors() + finally: + if old_policy is None: + del os.environ[remote_async_env_var] + else: + os.environ[remote_async_env_var] = old_policy + + +def async_wait(): + """Sync all async operations and raise any errors during execution. + + In async execution mode, an op/function call can return before finishing the + actual execution. Calling this method creates a synchronization barrier for + all async op and function execution. It only returns when all pending nodes + are finished, potentially raising exceptions if async execution results in + an error state. It is a no-op if the context is not initialized. + """ + disable_async_executor_env_var = "TF_PS_DISABLE_ASYNC_EXECUTOR_GLOBALLY" + if os.environ.get(disable_async_executor_env_var) == str(True): + return + if context()._context_handle is not None: # pylint: disable=protected-access + context().sync_executors() + + +@tf_export("experimental.async_clear_error") +def async_clear_error(): + """Clear pending operations and error statuses in async execution. + + In async execution mode, an error in op/function execution can lead to errors + in subsequent ops/functions that are scheduled but not yet executed. Calling + this method clears all pending operations and reset the async execution state. + + Example: + + ``` + while True: + try: + # Step function updates the metric `loss` internally + train_step_fn() + except tf.errors.OutOfRangeError: + tf.experimental.async_clear_error() + break + logging.info('loss = %s', loss.numpy()) + ``` + """ + context().clear_executor_errors() + + +def add_c_function(c_func): + """Add a C API TF_Function to the context.""" + context().add_c_function(c_func) + + +def get_c_function(name): + """Get a C API TF_Function from the context.""" + return context().get_c_function(name) + + +def remove_function(name): + """Remove a function from the context.""" + context().remove_function(name) + + +def get_function_def(name): + return context().get_function_def(name) + + +def is_custom_device(device_name): + """Calls TFE_IsCustomDevice. + + Enables using C extensions specifying a custom device from Python. See the + experimental eager C API in tensorflow/c/eager/c_api_experimental.h for + details. + + Args: + device_name: A string indicating the name to check whether it is a + registered custom device. + + Returns: + A boolean. + """ + return context().is_custom_device(device_name) + + +def register_custom_device(device_capsule, device_name, device_info_capsule): + """Calls TFE_RegisterCustomDevice to register a custom device with Python. + + Enables using C extensions specifying a custom device from Python. See the + experimental eager C API in tensorflow/c/eager/c_api_experimental.h for + details. + + Note that custom devices are not currently supported inside `tf.function`s. + + Args: + device_capsule: A PyCapsule with the name set to 'TFE_CustomDevice' + containing a pointer to a TFE_CustomDevice struct. The capsule retains + ownership of the memory. + device_name: A string indicating the name to register the custom device + under, e.g. '/job:localhost/replica:0/task:0/device:CUSTOM:0'. It may + subsequently be passed to `with tf.device(...):`. + device_info_capsule: A PyCapsule with the name set to + 'TFE_CustomDevice_DeviceInfo' containing a pointer to a device-specific + struct with the initial state of the custom device (the void* device_info + argument to TFE_RegisterCustomDevice). This method takes ownership of the + memory and clears the capsule destructor. + """ + context().register_custom_device(device_capsule, device_name, + device_info_capsule) + + +# Not every user creates a Context via context.context() +# (for example, enable_eager_execution in python/framework/ops.py), +# but they do all import this file. Note that IS_IN_GRAPH_MODE and +# in_graph_mode are both parameterless functions. +def _tmp_in_graph_mode(): + if context_safe() is None: + # Context not yet initialized. Assume graph mode following the + # default implementation in `is_in_graph_mode`. + return True + return not executing_eagerly() + + +is_in_graph_mode.IS_IN_GRAPH_MODE = _tmp_in_graph_mode diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/core.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/core.py new file mode 100644 index 0000000000000000000000000000000000000000..9519fdc0000848561b9f9afb97c9c386b17c53fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/core.py @@ -0,0 +1,78 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Experimental API for TensorFlow's "Eager" mode of execution.""" + +from tensorflow.python import pywrap_tfe +from tensorflow.python.framework import errors +from tensorflow.python.platform import tf_logging as logging + +# Trace of execution and memory usage. +_active_trace = None + + +def _status_to_exception(status): + try: + error_class = errors.exception_type_from_error_code(status.code) + e = error_class(None, None, status.message, status.payloads) + logging.error_log("%s: %s" % (e.__class__.__name__, e)) + return e + except KeyError: + e = errors.UnknownError( + None, None, status.message, status.code, status.payloads + ) + logging.error_log("%s: %s" % (e.__class__.__name__, e)) + return e + + +class _NotOkStatusException(Exception): + """Exception class to handle not ok Status.""" + + def __init__(self, message, code, payloads): + super(_NotOkStatusException, self).__init__() + self.message = message + self.code = code + self.payloads = payloads + + def __str__(self): + e = _status_to_exception(self) + return "%s: %s" % (e.__class__.__name__, e) + + +pywrap_tfe.TFE_Py_RegisterExceptionClass(_NotOkStatusException) + + +class _FallbackException(Exception): + """Exception class to handle fallback from the fastpath. + + The fastpath that we refer to here is the one implemented to reduce per-op + overheads (TFE_Py_FastPathExecute_C). If the conditions for executing the op + on the fastpath are not met, we fallback to a safer (and more complete) + slowpath, and this Exception is raised to signal that transition. + """ + pass + + +class _SymbolicException(Exception): + """Exception class to handle use of symbolic tensors when executing eagerly. + + `keras.Input()` creates symbolic tensors (in a FuncGraph managed by the + Keras backend) while in eager execution. This exception is used to + identify this case (raised in `convert_to_tensor` cause generated functions + for ops to construct graphs instead of executing the kernel). + """ + pass + + +pywrap_tfe.TFE_Py_RegisterFallbackExceptionClass(_FallbackException) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/def_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/def_function.py new file mode 100644 index 0000000000000000000000000000000000000000..07d85f0f4bee86ed25e88231b8a78e1a8c9bf78f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/def_function.py @@ -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. +# ============================================================================== +"""Supports old symbols supplied by this file while the code is refactored.""" + +# pylint:disable=unused-import,g-bad-import-order + +# Config Options +from tensorflow.python.eager.polymorphic_function.eager_function_run import run_functions_eagerly +from tensorflow.python.eager.polymorphic_function.eager_function_run import functions_run_eagerly + +# tf.function Classes +from tensorflow.python.eager.polymorphic_function.polymorphic_function import Function +from tensorflow.python.eager.polymorphic_function.polymorphic_function import function + +# Private attributes +from tensorflow.python.eager.polymorphic_function.polymorphic_function import _tf_function_counter diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/execute.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/execute.py new file mode 100644 index 0000000000000000000000000000000000000000..94236fa66fdfccf9d765e3ad2f48635fa91db970 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/execute.py @@ -0,0 +1,329 @@ +# 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. +# ============================================================================== +"""Functions called by the generated code to execute an eager-mode op.""" + +from google.protobuf import text_format +from tensorflow.core.framework import tensor_pb2 +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import core +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.types import core as core_types +from tensorflow.python.util import compat + + +def quick_execute(op_name, num_outputs, inputs, attrs, ctx, name=None): + """Execute a TensorFlow operation. + + Args: + op_name: Name of the TensorFlow operation (see REGISTER_OP in C++ code) to + execute. + num_outputs: The number of outputs of the operation to fetch. (Explicitly + provided instead of being inferred for performance reasons). + inputs: A list of inputs to the operation. Each entry should be a Tensor, or + a value which can be passed to the Tensor constructor to create one. + attrs: A tuple with alternating string attr names and attr values for this + operation. + ctx: The value of context.context(). + name: Customized name for the operation. + + Returns: + List of output Tensor objects. The list is empty if there are no outputs + + Raises: + An exception on error. + """ + device_name = ctx.device_name + # pylint: disable=protected-access + try: + ctx.ensure_initialized() + tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, + inputs, attrs, num_outputs) + except core._NotOkStatusException as e: + if name is not None: + e.message += " name: " + name + raise core._status_to_exception(e) from None + except TypeError as e: + keras_symbolic_tensors = [x for x in inputs if _is_keras_symbolic_tensor(x)] + if keras_symbolic_tensors: + raise core._SymbolicException( + "Inputs to eager execution function cannot be Keras symbolic " + "tensors, but found {}".format(keras_symbolic_tensors)) + raise e + # pylint: enable=protected-access + return tensors + + +def execute_with_cancellation(op_name, + num_outputs, + inputs, + attrs, + ctx, + cancellation_manager, + name=None): + """Execute a TensorFlow operation. + + Args: + op_name: Name of the TensorFlow operation (see REGISTER_OP in C++ code) to + execute. + num_outputs: The number of outputs of the operation to fetch. (Explicitly + provided instead of being inferred for performance reasons). + inputs: A list of inputs to the operation. Each entry should be a Tensor, or + a value which can be passed to the Tensor constructor to create one. + attrs: A tuple with alternating string attr names and attr values for this + operation. + ctx: The value of context.context(). + cancellation_manager: a `CancellationManager` object that can be used to + cancel the operation. + name: Customized name for the operation. + + Returns: + List of output Tensor objects. The list is empty if there are no outputs + + Raises: + An exception on error. + """ + device_name = ctx.device_name + # pylint: disable=protected-access + try: + ctx.ensure_initialized() + tensors = pywrap_tfe.TFE_Py_ExecuteCancelable(ctx._handle, device_name, + op_name, inputs, attrs, + cancellation_manager._impl, + num_outputs) + except core._NotOkStatusException as e: + if name is not None: + e.message += " name: " + name + raise core._status_to_exception(e) from None + except TypeError as e: + keras_symbolic_tensors = [x for x in inputs if _is_keras_symbolic_tensor(x)] + if keras_symbolic_tensors: + raise core._SymbolicException( + "Inputs to eager execution function cannot be Keras symbolic " + "tensors, but found {}".format(keras_symbolic_tensors)) + raise e + # pylint: enable=protected-access + return tensors + + +def execute_with_callbacks(op_name, num_outputs, inputs, attrs, ctx, name=None): + """Monkey-patch to execute to enable execution callbacks.""" + tensors = quick_execute(op_name, num_outputs, inputs, attrs, ctx, name) + for callback in ctx.op_callbacks: + callback(op_name, tuple(inputs), attrs, tensors, name) + + return tensors + + +execute = quick_execute + + +def must_record_gradient(): + """Import backprop if you want gradients recorded.""" + return False + + +def record_gradient(unused_op_name, unused_inputs, unused_attrs, + unused_outputs): + """Import backprop if you want gradients recorded.""" + pass + + +def make_float(v, arg_name): + if not isinstance(v, compat.real_types): + raise TypeError("Expected float for argument '%s' not %s." % + (arg_name, repr(v))) + return float(v) + + +def make_int(v, arg_name): + if isinstance(v, str): + raise TypeError("Expected int for argument '%s' not %s." % + (arg_name, repr(v))) + try: + return int(v) + except (ValueError, TypeError): + raise TypeError("Expected int for argument '%s' not %s." % + (arg_name, repr(v))) + + +def make_str(v, arg_name): + if not isinstance(v, compat.bytes_or_text_types): + raise TypeError("Expected string for argument '%s' not %s." % + (arg_name, repr(v))) + return compat.as_bytes(v) # Convert unicode strings to bytes. + + +def make_bool(v, arg_name): + if not isinstance(v, bool): + raise TypeError("Expected bool for argument '%s' not %s." % + (arg_name, repr(v))) + return v + + +def make_type(v, arg_name): + try: + v = dtypes.as_dtype(v).base_dtype + except TypeError: + raise TypeError("Expected DataType for argument '%s' not %s." % + (arg_name, repr(v))) + i = v.as_datatype_enum + return i + + +def make_shape(v, arg_name): + """Convert v into a list.""" + # Args: + # v: A TensorShapeProto, a list of ints, or a tensor_shape.TensorShape. + # arg_name: String, for error messages. + + # Returns: + # None if the rank is unknown, otherwise a list of ints (or Nones in the + # position where the dimension is unknown). + try: + shape = tensor_shape.as_shape(v) + except TypeError as e: + raise TypeError("Error converting %s to a TensorShape: %s." % (arg_name, e)) + except ValueError as e: + raise ValueError("Error converting %s to a TensorShape: %s." % + (arg_name, e)) + if shape.ndims is None: + return None + else: + return shape.as_list() + + +def make_tensor(v, arg_name): + """Ensure v is a TensorProto.""" + if isinstance(v, tensor_pb2.TensorProto): + return v + elif isinstance(v, str): + pb = tensor_pb2.TensorProto() + text_format.Merge(v, pb) + return pb + raise TypeError( + "Don't know how to convert %s to a TensorProto for argument '%s'." % + (repr(v), arg_name)) + + +def args_to_matching_eager(l, ctx, allowed_dtypes, default_dtype=None): + """Convert sequence `l` to eager same-type Tensors.""" + del ctx # Unused + if (not l) and (default_dtype is not None): + return default_dtype, [] # List is empty; assume default dtype. + for x in l: + if not isinstance(x, core_types.Value): + break + else: # note: intentional for-else + return l[0]._datatype_enum(), l # pylint: disable=protected-access + + # Is some input already a Tensor with a dtype? + dtype = None + for t in l: + if isinstance(t, core_types.Value): + dtype = t.dtype + break + + if dtype is None: + # Infer a dtype based on the first value, and use that dtype for the + # remaining values. + + ret = [] + for t in l: + tensor = None + # First see if we can get a valid dtype with the default conversion + # and see if it matches an allowed dtypes. Some ops like ConcatV2 may + # not list allowed dtypes, in which case we should skip this. + if dtype is None and allowed_dtypes: + tensor = tensor_conversion_registry.convert(t) + # If we did not match an allowed dtype, try again with the default + # dtype. This could be because we have an empty tensor and thus we + # picked the wrong type. + if tensor.dtype not in allowed_dtypes: + tensor = None + + if tensor is None: + tensor = tensor_conversion_registry.convert( + t, dtype, preferred_dtype=default_dtype + ) + + ret.append(tensor) + if dtype is None: + dtype = tensor.dtype + else: + ret = [tensor_conversion_registry.convert(t, dtype) for t in l] + + # TODO(slebedev): consider removing this as it leaks a Keras concept. + # pylint: disable=protected-access + keras_symbolic_tensors = [x for x in ret if _is_keras_symbolic_tensor(x)] + if keras_symbolic_tensors: + raise core._SymbolicException( + "Using symbolic output of a Keras layer during eager execution " + "{}".format(keras_symbolic_tensors)) + # pylint: enable=protected-access + return dtype.as_datatype_enum, ret + + +def convert_to_mixed_eager_tensors(values, ctx): + del ctx # Unused + v = [tensor_conversion_registry.convert(t) for t in values] + types = [t._datatype_enum() for t in v] # pylint: disable=protected-access + return types, v + + +def args_to_mixed_eager_tensors(lists, ctx): + """Converts a list of same-length lists of values to eager tensors.""" + del ctx # Unused + assert len(lists) > 1 + + # Generate an error if len(lists[i]) is not the same for all i. + lists_ret = [[]] + for l in lists[1:]: + if len(l) != len(lists[0]): + raise ValueError( + "Expected list arguments to be the same length: %d != %d (%r vs. %r)." + % (len(lists[0]), len(l), lists[0], l)) + lists_ret.append([]) + + # Convert the first element of each list first, then the second element, etc. + types = [] + for i in range(len(lists[0])): + dtype = None + # If any list has a Tensor, use that dtype + for l in lists: + if isinstance(l[i], core_types.Value): + dtype = l[i].dtype + break + if dtype is None: + # Convert the first one and use its dtype. + lists_ret[0].append(tensor_conversion_registry.convert(lists[0][i])) + dtype = lists_ret[0][i].dtype + for j in range(1, len(lists)): + lists_ret[j].append( + tensor_conversion_registry.convert(lists[j][i], dtype=dtype) + ) + else: + # Convert everything to the found dtype. + for j in range(len(lists)): + lists_ret[j].append( + tensor_conversion_registry.convert(lists[j][i], dtype=dtype) + ) + types.append(dtype.as_datatype_enum) + return types, lists_ret + + +def _is_keras_symbolic_tensor(x): + return hasattr(x, "graph") and getattr(x.graph, "name", None) == "keras_graph" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/executor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..4d01f8e9cab010ca6bf37325d06b47728baeda12 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/executor.py @@ -0,0 +1,77 @@ +# 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. +# ============================================================================== +"""Executor for eager execution.""" + +from tensorflow.python import pywrap_tfe + + +class Executor(object): + """A class for handling eager execution. + + The default behavior for asynchronous execution is to serialize all ops on + a single thread. Having different `Executor` objects in different threads + enables executing ops asynchronously in parallel: + + ```python + def thread_function(): + executor = executor.Executor(enable_async=True): + context.set_executor(executor) + + a = threading.Thread(target=thread_function) + a.start() + b = threading.Thread(target=thread_function) + b.start() + ``` + """ + + __slots__ = ["_handle"] + + def __init__(self, handle): + self._handle = handle + + def __del__(self): + try: + self.wait() + pywrap_tfe.TFE_DeleteExecutor(self._handle) + except TypeError: + # Suppress some exceptions, mainly for the case when we're running on + # module deletion. Things that can go wrong include the pywrap module + # already being unloaded, self._handle. no longer being + # valid, and so on. Printing warnings in these cases is silly + # (exceptions raised from __del__ are printed as warnings to stderr). + pass # 'NoneType' object is not callable when the handle has been + # partially unloaded. + + def is_async(self): + return pywrap_tfe.TFE_ExecutorIsAsync(self._handle) + + def handle(self): + return self._handle + + def wait(self): + """Waits for ops dispatched in this executor to finish.""" + pywrap_tfe.TFE_ExecutorWaitForAllPendingNodes(self._handle) + + def clear_error(self): + """Clears errors raised in this executor during execution.""" + pywrap_tfe.TFE_ExecutorClearError(self._handle) + + +def new_executor(enable_async, + enable_streaming_enqueue=True, + in_flight_nodes_limit=0): + handle = pywrap_tfe.TFE_NewExecutor(enable_async, enable_streaming_enqueue, + in_flight_nodes_limit) + return Executor(handle) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/forwardprop.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/forwardprop.py new file mode 100644 index 0000000000000000000000000000000000000000..1a02be97bd6bfc866cbfd7c8d0cac2f6383133f8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/forwardprop.py @@ -0,0 +1,487 @@ +# 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. +# ============================================================================== +"""Utilities for forward-mode automatic differentiation.""" + +import functools +import threading + +from tensorflow.core.function.polymorphism import function_cache +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import backprop +from tensorflow.python.eager import backprop_util +from tensorflow.python.eager import execute +from tensorflow.python.eager import forwardprop_util +from tensorflow.python.eager.polymorphic_function import tracing_compilation +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops.parallel_for import control_flow_ops +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +# Dictionary mapping from op names to special-cased jvp functions. Otherwise +# backward functions are transposed on the tape. +_SPECIAL_CASES = {} + + +def _identity_jvp(attr_tuple, inputs, outputs, tangents): + # Special-cased mostly for resource handles, where creating ones Tensors from + # handle data for transposing the backward function on the tape is error-prone + # (even if we get good handle data, partially defined shapes are an issue). + del attr_tuple, inputs, outputs + return [array_ops.identity(t) for t in tangents] + + +_SPECIAL_CASES["Identity"] = _identity_jvp + + +def _read_variable_jvp(attr_tuple, inputs, outputs, tangents): + # Like for Identity, this special case means we don't need to create + # variable-shaped Tensors from resource handles. + del attr_tuple, inputs, outputs + return [array_ops.identity(t) for t in tangents] + + +_SPECIAL_CASES["ReadVariableOp"] = _read_variable_jvp + + +_TRACE_COUNT_CONSISTENCY_LOCK = threading.Lock() +# Map from op names to number of traces of _jvp_helper. Used to cap the number +# of traces due to shape differences while still specializing where possible. +_TRACE_COUNT = {} + + +def _jvp_helper(op_name, attr_tuple, inputs, outputs, tangents): + """Computes a Jacobian-vector product for an op. + + Note that this function would be wasteful if executed eagerly. It runs the + backward gradient function and throws away the result just to record its + operations on a GradientTape. These unused ops are pruned away when this + function is traced. + + Args: + op_name: A string, the type of operation being executed. + attr_tuple: Attributes of the operation. + inputs: A flat list of input Tensors to the operation. + outputs: A flat list of output Tensors from the operation. + tangents: A flat list of Tensors, same shape as `inputs`. + + Returns: + A flat list of tangents corresponding to `outputs`. + """ + with _TRACE_COUNT_CONSISTENCY_LOCK: + # Just make sure writes don't clobber each other's increments; reads in + # _jvp_dispatch do not lock. + _TRACE_COUNT[op_name] = _TRACE_COUNT.get(op_name, 0) + 1 + + special_case = _SPECIAL_CASES.get(op_name, None) + if special_case is not None: + return special_case(attr_tuple, inputs, outputs, tangents) + if not outputs: + # tape.gradients([], inputs) doesn't make much sense + return [] + # Generally inner GradientTapes won't function while outer accumulators are + # recording. We temporarily reset forwardprop state to allow GradientTapes to + # function here. + with forwardprop_util.push_forwardprop_state(): + trainable_inputs = [] + trainable_indices = [] + nontrivial_tangents = [] + for input_index, tensor in enumerate(inputs): + if backprop_util.IsTrainable(tensor): + trainable_inputs.append(tensor) + trainable_indices.append(input_index) + nontrivial_tangents.append(tangents[input_index]) + + with backprop.GradientTape() as transpose_tape: + with backprop.GradientTape() as backfunc_tape: + backfunc_tape.watch(trainable_inputs) + execute.record_gradient(op_name, inputs, attr_tuple, outputs) + + forwardprop_aids = [] + trainable_outputs = [] + nontrivial_output_indices = [] + for output_index, output in enumerate(outputs): + if backprop_util.IsTrainable(output): + forwardprop_aids.append( + array_ops.ones_like(output, name="unused_forwardprop_aid")) + trainable_outputs.append(output) + nontrivial_output_indices.append(output_index) + + transpose_tape.watch(forwardprop_aids) + grads = backfunc_tape.gradient( + trainable_outputs, + trainable_inputs, + forwardprop_aids, + unconnected_gradients=UnconnectedGradients.ZERO) + nontrivial_output_tangents = transpose_tape.gradient( + grads, forwardprop_aids, output_gradients=nontrivial_tangents) + output_tangents = [None] * len(outputs) + for index, tangent in zip(nontrivial_output_indices, + nontrivial_output_tangents): + output_tangents[index] = tangent + return output_tangents + + +def _jvp_helper_wrapper(op_name, attr_tuple, inputs, outputs, tangents, + use_batch): + """Computes a batch of Jacobian-vector product for an op. + + Args: + op_name: A string, the type of operation being executed. + attr_tuple: Attributes of the operation. + inputs: A flat list of input Tensors to the operation. + outputs: A flat list of output Tensors from the operation. + tangents: A flat list of Tensors, compatible with shape `[None] + + input_shape`. + use_batch: A bool, True to vetorize over batch of tangents of shape `[None] + + input_shape`. + + Returns: + A flat list of tangents compatible with `outputs` + or `[None] + output_shape`. + + Raises: + ValueError: if tangent shapes are not compatible with input shapes. + """ + if use_batch: + for primal, tangent in zip(inputs, tangents): + if not tangent.shape.is_compatible_with([None] + primal.shape): + raise ValueError("Tangent {} was expected to be of shape " + "{} but is instead of shape {}".format( + tangent, [None] + primal.shape, tangent.shape)) + + return control_flow_ops.vectorized_map( + functools.partial(_jvp_helper, op_name, attr_tuple, inputs, outputs), + tangents, + ) + return _jvp_helper(op_name, attr_tuple, inputs, outputs, tangents) + + +# TODO(allenl): reduce_retracing for gradients which rely on static +# shape information are underspecialized. We may want hand-written forward +# implementations, or a more satisfying story about how we re-specialize +# gradients which were traced with relaxed shapes (e.g. use conds instead of +# trace-time Python logic). +# +# Using function.defun rather than def_function.function avoids +# tf.config.run_functions_eagerly(True). `_jvp_helper` doesn't successfully run +# eagerly (infinite recursion), and even if it did it would use extra memory and +# run unnecessary computation. The function does not create variables, so the +# two symbols are otherwise equivalent. +_jvp_function_cache = function_cache.FunctionCache() +_jvp_relaxed_config = tracing_compilation.TracingOptions( + _jvp_helper_wrapper, + name="_jvp_relaxed_shapes", + reduce_retracing=True, + function_cache=_jvp_function_cache, +) + +_jvp_exact_config = tracing_compilation.TracingOptions( + _jvp_helper_wrapper, + name="_jvp_exact_shapes", + reduce_retracing=False, + function_cache=_jvp_function_cache, +) + +# The maximum number of exact-shape traces to perform for a single op before +# switching to shape relaxation. +_TRACE_COUNT_LIMIT = 32 + + +def _jvp_dispatch(op_name, + attr_tuple, + inputs, + outputs, + tangents, + use_batch=False): + """Determine which forwardprop function to call.""" + # Note that this _TRACE_COUNT read races with writes. That's fine, it just + # means we may trace a few more exact shapes before moving on to relaxation. + if _TRACE_COUNT.get(op_name, 0) < _TRACE_COUNT_LIMIT: + config = _jvp_exact_config + else: + config = _jvp_relaxed_config + return tracing_compilation.call_function( + (op_name, attr_tuple, inputs, outputs, tangents, use_batch), + tracing_options=config, + ) + + +pywrap_tfe.TFE_Py_RegisterJVPFunction(_jvp_dispatch) + + +@tf_export("autodiff.ForwardAccumulator", v1=[]) +class ForwardAccumulator(): + """Computes Jacobian-vector products ("JVP"s) using forward-mode autodiff. + + Compare to `tf.GradientTape` which computes vector-Jacobian products ("VJP"s) + using reverse-mode autodiff (backprop). Reverse mode is more attractive when + computing gradients of a scalar-valued function with respect to many inputs + (e.g. a neural network with many parameters and a scalar loss). Forward mode + works best on functions with many outputs and few inputs. Since it does not + hold on to intermediate activations, it is much more memory efficient than + backprop where it is applicable. + + Consider a simple linear regression: + + >>> x = tf.constant([[2.0, 3.0], [1.0, 4.0]]) + >>> targets = tf.constant([[1.], [-1.]]) + >>> dense = tf.keras.layers.Dense(1) + >>> dense.build([None, 2]) + >>> with tf.autodiff.ForwardAccumulator( + ... primals=dense.kernel, + ... tangents=tf.constant([[1.], [0.]])) as acc: + ... loss = tf.reduce_sum((dense(x) - targets) ** 2.) + >>> acc.jvp(loss) + + + The example has two variables containing parameters, `dense.kernel` (2 + parameters) and `dense.bias` (1 parameter). Considering the training data `x` + as a constant, this means the Jacobian matrix for the function mapping from + parameters to loss has one row and three columns. + + With forwardprop, we specify a length-three vector in advance which multiplies + the Jacobian. The `primals` constructor argument is the parameter (a + `tf.Tensor` or `tf.Variable`) we're specifying a vector for, and the + `tangents` argument is the "vector" in Jacobian-vector product. If our goal is + to compute the entire Jacobian matrix, forwardprop computes one column at a + time while backprop computes one row at a time. Since the Jacobian in the + linear regression example has only one row, backprop requires fewer + invocations: + + >>> x = tf.constant([[2.0, 3.0], [1.0, 4.0]]) + >>> targets = tf.constant([[1.], [-1.]]) + >>> dense = tf.keras.layers.Dense(1) + >>> dense.build([None, 2]) + >>> loss_fn = lambda: tf.reduce_sum((dense(x) - targets) ** 2.) + >>> kernel_fprop = [] + >>> with tf.autodiff.ForwardAccumulator( + ... dense.kernel, tf.constant([[1.], [0.]])) as acc: + ... kernel_fprop.append(acc.jvp(loss_fn())) + >>> with tf.autodiff.ForwardAccumulator( + ... dense.kernel, tf.constant([[0.], [1.]])) as acc: + ... kernel_fprop.append(acc.jvp(loss_fn())) + >>> with tf.autodiff.ForwardAccumulator(dense.bias, tf.constant([1.])) as acc: + ... bias_fprop = acc.jvp(loss_fn()) + >>> with tf.GradientTape() as tape: + ... loss = loss_fn() + >>> kernel_grad, bias_grad = tape.gradient(loss, (dense.kernel, dense.bias)) + >>> np.testing.assert_allclose( + ... kernel_grad, tf.stack(kernel_fprop)[:, tf.newaxis]) + >>> np.testing.assert_allclose(bias_grad, bias_fprop[tf.newaxis]) + + Implicit in the `tape.gradient` call is a length-one vector which + left-multiplies the Jacobian, a vector-Jacobian product. + + `ForwardAccumulator` maintains JVPs corresponding primal tensors it is + watching, derived from the original `primals` specified in the constructor. As + soon as a primal tensor is deleted, `ForwardAccumulator` deletes the + corresponding JVP. + + `acc.jvp(x)` retrieves `acc`'s JVP corresponding to the primal tensor `x`. It + does not perform any computation. `acc.jvp` calls can be repeated as long as + `acc` is accessible, whether the context manager is active or not. New JVPs + are only computed while the context manager is active. + + Note that `ForwardAccumulator`s are always applied in the order their context + managers were entered, so inner accumulators will not see JVP computation from + outer accumulators. Take higher-order JVPs from outer accumulators: + + >>> primal = tf.constant(1.1) + >>> with tf.autodiff.ForwardAccumulator(primal, tf.constant(1.)) as outer: + ... with tf.autodiff.ForwardAccumulator(primal, tf.constant(1.)) as inner: + ... primal_out = primal ** tf.constant(3.5) + >>> inner_jvp = inner.jvp(primal_out) + >>> inner_jvp # 3.5 * 1.1 ** 2.5 + + >>> outer.jvp(inner_jvp) # 3.5 * 2.5 * 1.1 ** 1.5 + + + Reversing the collection in the last line to instead retrieve + `inner.jvp(outer.jvp(primal_out))` will not work. + + Strict nesting also applies to combinations of `ForwardAccumulator` and + `tf.GradientTape`. More deeply nested `GradientTape` objects will ignore the + products of outer `ForwardAccumulator` objects. This allows (for example) + memory-efficient forward-over-backward computation of Hessian-vector products, + where the inner `GradientTape` would otherwise hold on to all intermediate + JVPs: + + >>> v = tf.Variable([1., 2.]) + >>> with tf.autodiff.ForwardAccumulator( + ... v, + ... # The "vector" in Hessian-vector product. + ... tf.constant([1., 0.])) as acc: + ... with tf.GradientTape() as tape: + ... y = tf.reduce_sum(v ** 3.) + ... backward = tape.gradient(y, v) + >>> backward # gradient from backprop + + >>> acc.jvp(backward) # forward-over-backward Hessian-vector product + + """ + + def __init__(self, primals, tangents): + """Specify tensors to watch and their Jacobian-vector products. + + Mathematically, `tangents` is a vector right-multiplying the Jacobian matrix + (a Jacobian-vector product) for the function computed while this accumulator + is active. Since JVPs are computed in forward mode as the computation + happens, this vector must be supplied in advance. + + Listing a single tensor multiple times in `primals` raises an + exception. Excluding a tensor from `primals` is equivalent to watching it + with a tangent tensor of zeros. + + Args: + primals: A tensor or nested structure of tensors to watch. + tangents: A tensor or nested structure of tensors, with the same nesting + structure as `primals`, with each element being a vector with the same + size as the corresponding primal element. + + Raises: + ValueError: If the same tensor or variable is specified multiple times in + `primals`. + """ + self._accumulator = pywrap_tfe.TFE_Py_ForwardAccumulatorNew(False) + self._recording = False + primal_ids = set() + for primal in nest.flatten(primals): + if id(primal) in primal_ids: + raise ValueError( + "Tensor {} was specified as a primal multiple times. This may " + "indicate an error. If it was intended, please sum the " + "corresponding tangents.") + primal_ids.add(id(primal)) + self._watch(primals, tangents) + + def __enter__(self): + self._push_accumulator() + return self + + def __exit__(self, typ, value, traceback): + if self._recording: + self._pop_accumulator() + + def _push_accumulator(self): + if self._recording: + raise ValueError("Accumulator is already recording.") + pywrap_tfe.TFE_Py_ForwardAccumulatorSetAdd(self._accumulator) + self._recording = True + + def _pop_accumulator(self): + if not self._recording: + raise ValueError("Accumulator is not recording.") + pywrap_tfe.TFE_Py_ForwardAccumulatorSetRemove(self._accumulator) + self._recording = False + + def _watch(self, primals, tangents): + """Ensures that `primals` are being traced by this accumulator. + + Mathematically, `tangents` is a vector right-multiplying the Jacobian matrix + (a Jacobian-vector product) for the function computed while this accumulator + is active. Since JVPs are computed in forward mode as the computation + happens, this vector must be supplied in advance. + + Watching a single tensor multiple times sums each of its `tangents`. Any + un-watched tensor has zeros for its tangent vector. + + Args: + primals: A Tensor or list of Tensors. + tangents: A Tensor or list of Tensors matching `primals`. + """ + + def _watch(primal, tangent): + if not primal.dtype.is_floating: + logging.log_first_n( + logging.WARN, "The dtype of the watched primal must be " + "floating (e.g. tf.float32), got %r", 5, primal.dtype) + tangent = ops.convert_to_tensor(tangent, dtype=primal.dtype) + if hasattr(primal, "handle"): + # Run convert_to_tensor to get the captured handle from whichever + # function we're running if necessary. + primal = ops.convert_to_tensor(primal.handle) + pywrap_tfe.TFE_Py_ForwardAccumulatorWatch(self._accumulator, primal, + tangent) + + nest.map_structure(_watch, primals, tangents) + + def jvp(self, primals, unconnected_gradients=UnconnectedGradients.NONE): + """Fetches the Jacobian-vector product computed for `primals`. + + Note that this method performs no computation, and simply looks up a JVP + that was already computed (unlike backprop using a `tf.GradientTape`, where + the computation happens on the call to `tape.gradient`). + + Args: + primals: A watched Tensor or structure of Tensors to fetch the JVPs for. + unconnected_gradients: A value which can either hold 'none' or 'zero' and + alters the value which will be returned if no JVP was computed for + `primals`. The possible values and effects are detailed in + 'tf.UnconnectedGradients' and it defaults to 'none'. + + Returns: + Tensors with the same shapes and dtypes as `primals`, or None if no JVP + is available. + """ + unconnected_gradients = UnconnectedGradients(unconnected_gradients) + if self._accumulator is None: + raise ValueError("Called jvp() without first tracing anything.") + + def _fetch_jvp(tensor): + if hasattr(tensor, "handle"): + unwrapped_tensor = ops.convert_to_tensor(tensor.handle) + else: + unwrapped_tensor = tensor + result = pywrap_tfe.TFE_Py_ForwardAccumulatorJVP(self._accumulator, + unwrapped_tensor) + if result is None and unconnected_gradients == UnconnectedGradients.ZERO: + result = array_ops.zeros_like(tensor) + return result + + return nest.map_structure(_fetch_jvp, primals) + + @classmethod + def _batch_accumulator(cls, primals, tangents): + """Factory constructor to test accumulator on batches of tangents. + + Args: + primals: A tensor or nested structure of tensors to watch. + tangents: A tensor or nested structure of tensors, with the same nesting + structure as `primals`, with each element being a vector with compatible + shape `[None] + primal.shape` of the corresponding primal element. + + Returns: + A batch accumulator object. + """ + acc = super(ForwardAccumulator, cls).__new__(cls, primals, tangents) + acc._recording = False + acc._accumulator = pywrap_tfe.TFE_Py_ForwardAccumulatorNew(True) + primal_ids = set() + for primal, tangent in zip(nest.flatten(primals), nest.flatten(tangents)): + tangent.shape.assert_is_compatible_with( + tensor_shape.TensorShape([None]) + primal.shape) + if id(primal) in primal_ids: + raise ValueError( + "Tensor {} was specified as a primal multiple times. This may " + "indicate an error. If it was intended, please sum the " + "corresponding tangents.") + primal_ids.add(id(primal)) + acc._watch(primals, tangents) + return acc diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/forwardprop_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/forwardprop_util.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea224192acf6fe6fc8cb95f1fd299a7646f08b5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/forwardprop_util.py @@ -0,0 +1,74 @@ +# 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. +# ============================================================================== +"""Utilities for managing forward accumulators. + +A separate file from forwardprop.py so that functions can use these utilities. +""" + +import collections +import contextlib + +from tensorflow.python import pywrap_tfe + + +class TangentInfo( + collections.namedtuple("TangentInfo", ["indices", "tangents"])): + """Packed forward accumulator state. The return value of `pack_tangents`.""" + + def __new__(cls, indices=None, tangents=None): + if indices is None: + indices = () + if tangents is None: + tangents = [] + return super(TangentInfo, cls).__new__(cls, indices, tangents) + + +def pack_tangents(tensors): + """Packs forward accumulator state into a TangentInfo tuple. + + Args: + tensors: A flat list of Tensors to pack forward accumulator state for. + + Returns: + A tuple of (indices, tangents): + indices: A sequence of sequences of two-element tuples. Each forward + accumulator is represented as a sequence of tuples with (primal_index, + jvp_index). Both integers index into the concatenated `tensors + jvps` + array. + tangents: A flat list of Tensors. Best interpreted as a sequence to be + appended to `tensors`. + """ + return TangentInfo(*pywrap_tfe.TFE_Py_PackJVPs(tensors)) + + +@contextlib.contextmanager +def push_forwardprop_state(): + """Temporarily push or pop transient state for accumulators in the active set. + + Allows an accumulator which is currently processing an operation to + temporarily reset its state. This is useful when building forwardprop versions + of functions, where an accumulator will trigger function building and then + must process captured symbolic tensors while building it. Without pushing and + popping, accumulators ignore operations executed as a direct result of their + own jvp computations. + + Yields: + None (used for its side effect). + """ + try: + pywrap_tfe.TFE_Py_ForwardAccumulatorPushState() + yield + finally: + pywrap_tfe.TFE_Py_ForwardAccumulatorPopState() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/function.py new file mode 100644 index 0000000000000000000000000000000000000000..c4df3b680314dedcef57ff6802181cbd64ed38d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/function.py @@ -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. +# ============================================================================== +"""Supports old symbols supplied by this file while the code is refactored.""" + +# pylint:disable=unused-import,g-bad-import-order + +# TODO(b/243822285): Reduce this list as much as possible. +# Constants +from tensorflow.python.eager.polymorphic_function.concrete_function import _BACKWARD_PREFIX +from tensorflow.python.eager.polymorphic_function.concrete_function import _FORWARD_PREFIX +from tensorflow.python.eager.polymorphic_function.concrete_function import _INFERENCE_PREFIX + +# Function Classes +from tensorflow.python.eager.polymorphic_function.concrete_function import ConcreteFunction +from tensorflow.python.eager.polymorphic_function.atomic_function import from_func_graph +from tensorflow.python.eager.polymorphic_function.atomic_function import AtomicFunction + +# Utilities +from tensorflow.python.eager.polymorphic_function.tf_method_target import TfMethodTarget +from tensorflow.python.eager.polymorphic_function.concrete_function import _inference_name + +# TODO(b/244360504): Remove in favor of graph transformation API. +# QUARANTINED - Function Callback Modification API +from tensorflow.python.eager.polymorphic_function.transform import FUNC_GRAPH_TRANSFORMS +from tensorflow.python.eager.polymorphic_function.transform import CONCRETE_FUNCTION_CALLBACKS diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/graph_only_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/graph_only_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2d5c557fdeb423a8e38f3acc40a16fa30bcf3d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/graph_only_ops.py @@ -0,0 +1,46 @@ +# 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. +# ============================================================================== +"""Graph-only versions of a few op functions, for internal use only.""" + +# Must be separate from array_ops to avoid a cyclic dependency. + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape + + +def graph_placeholder(dtype, shape, name=None): + """Graph-only version of tf.compat.v1.placeholder(), for internal use only.""" + dtype = dtype.base_dtype + dtype_value = attr_value_pb2.AttrValue(type=dtype.as_datatype_enum) + if isinstance(shape, (list, tuple)): + shape = tensor_shape.TensorShape(shape) + shape = attr_value_pb2.AttrValue(shape=shape.as_proto()) + g = ops.get_default_graph() + attrs = {"dtype": dtype_value, "shape": shape} + op = g._create_op_internal( # pylint: disable=protected-access + "Placeholder", [], [dtype], input_types=[], + attrs=attrs, name=name) + result, = op.outputs + if op_callbacks.should_invoke_op_callbacks(): + # TODO(b/147670703): Once the special-op creation code paths + # are unified. Remove this `if` block. + callback_outputs = op_callbacks.invoke_op_callbacks( + "Placeholder", tuple(), attrs, tuple(op.outputs), + op_name=name, graph=g) + if callback_outputs is not None: + result, = callback_outputs + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/imperative_grad.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/imperative_grad.py new file mode 100644 index 0000000000000000000000000000000000000000..86d6e78b7fc316522ddc790318f9960485da7d7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/imperative_grad.py @@ -0,0 +1,73 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Code for backpropagation using the tape utilities.""" + +import collections + +from tensorflow.python import pywrap_tfe +from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients +from tensorflow.python.util import compat + +VSpace = collections.namedtuple("VSpace", [ + "aggregate_fn", "num_elements_fn", "zeros_fn", "ones_fn", + "zeros_like_fn", "ones_like_fn", "graph_shape_fn" +]) + + +def imperative_grad(tape, + target, + sources, + output_gradients=None, + sources_raw=None, + unconnected_gradients=UnconnectedGradients.NONE): + """Computes gradients from the imperatively defined tape on top of the stack. + + Works by filtering the tape, computing how many downstream usages are of each + tensor and entry, and repeatedly applying backward functions until we have + gradients for all sources. + + Args: + tape: the gradient tape which stores the trace. + target: either a Tensor or list of Tensors to be differentiated. + sources: list of Tensors for which we want gradients + output_gradients: if not None, a list of gradient provided for each Target, + or None if we are to use the target's computed downstream gradient. + sources_raw: if not None, a list of the source python objects from which the + sources were generated. Should have the same length as sources. Only needs + to be populated if unconnected_gradients is 'zero'. + unconnected_gradients: determines the value returned if the target and + sources are unconnected. When 'none' the value returned is None wheras when + 'zero' a zero tensor in the same shape as the sources is returned. + + Returns: + the gradient wrt each of the sources. + + Raises: + ValueError: if the arguments are invalid. + RuntimeError: if something goes wrong. + """ + try: + unconnected_gradients = UnconnectedGradients(unconnected_gradients) + except ValueError: + raise ValueError( + "Unknown value for unconnected_gradients: %r" % unconnected_gradients) + + return pywrap_tfe.TFE_Py_TapeGradient( + tape._tape, # pylint: disable=protected-access + target, + sources, + output_gradients, + sources_raw, + compat.as_str(unconnected_gradients.value)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/lift_to_graph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/lift_to_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..7d7ac1b8e0dff20a420f699175fac5c33ab79b05 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/lift_to_graph.py @@ -0,0 +1,365 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""Utility to lift subgraphs.""" + +import collections + +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import op_selector +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.util import compat +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +UnliftableError = op_selector.UnliftableError + + +def _as_operation(op_or_tensor): + if isinstance(op_or_tensor, tensor_lib.Tensor): + return op_or_tensor.op + return op_or_tensor + + +def _constant_inputs(op_or_tensor): + return all(_as_operation(i).type == u"Const" + and not _as_operation(i).control_inputs + for i in op_selector.graph_inputs(_as_operation(op_or_tensor))) + + +# Represents an input to `copied_op` which must be updated once +# `old_graph_tensor` has been copied. +_InputMutation = collections.namedtuple( + "_InputMutation", + ["copied_op", "input_index", "old_graph_tensor"]) + + +# Represents a control input to `copied_op` which must be added once +# `old_graph_op` has been copied. +_ControlMutation = collections.namedtuple( + "_ControlMutation", + ["copied_op", "old_graph_op"]) + + +def _copy_non_source(op, graph, op_map, base_graph): + """Copy an op directly to a given graph. + + Generally `op`'s inputs should already have been copied. If this is not the + case, for example with v1 while_loops, then `_copy_non_source` inserts + placeholders for the unavailable Tensors and returns a list of required + mutations. + + Args: + op: The op to be copied. + graph: The destination graph. + op_map: A dict mapping ops and tensors in the old graph to the new one. + base_graph: The graph we're copying from, for any necessary functions. + Returns: + A tuple of (required_inputs, required_control_inputs): + required_inputs: + A list of `_InputMutation` tuples containing inputs to `copied_op` which + must be updated once `old_graph_tensor` has been copied. + required_control_inputs: + A list of `_ControlMutation` tuples containing control inputs to + `copied_op` which must be added once `old_graph_op` has been copied. + """ + input_mutations = [] + control_mutations = [] + copied_inputs = [] + for input_index, original_input in enumerate(op.inputs): + copied_input = op_map.get(original_input, None) + if copied_input is None: + # An input for this op is missing due to a loop in the graph. We'll insert + # a placeholder for now and return information about the required post-hoc + # mutation. + copied_input = array_ops.placeholder( + name="unused_control_flow_input", + shape=original_input.shape, + dtype=original_input.dtype) + input_mutations.append( + # `copied_op` is filled in below, after we've created it. + _InputMutation(copied_op=None, + input_index=input_index, + old_graph_tensor=original_input)) + copied_inputs.append(copied_input) + + copied_control_inputs = [] + for original_control_input in op.control_inputs: + copied_control_input = op_map.get(original_control_input, None) + if copied_control_input is None: + control_mutations.append( + _ControlMutation(copied_op=None, + old_graph_op=original_control_input)) + else: + copied_control_inputs.append(copied_control_input) + + # Don't copy over nodes with _tpu_replicate attribute. This attributed is used + # to signal that the op was built inside a tpu_replicate context; if we're + # lifting it to another graph we're similarly lifting it into another context. + with ops.control_dependencies(copied_control_inputs), ops.device(op.device): + # pylint: disable=protected-access + f = base_graph._functions.get(op.type, None) + if f is not None and compat.as_str(f.name) not in graph._functions: + f.add_to_graph(graph) + # pylint: enable=protected-access + + # Create a new op in the destination graph if it doesn't exist before. + copied_op = graph.create_op( + op_type=op.type, + inputs=copied_inputs, + dtypes=[x.dtype for x in op.outputs], + attrs={ + key: value for key, value in op.node_def.attr.items() + if not key.startswith("_class") and + not key.startswith("_tpu_replicate") + }, # b/128981532. + name=op.name) + op_map[op] = copied_op + for i, o in enumerate(op.outputs): + op_map[o] = copied_op.outputs[i] + + return ([mutation._replace(copied_op=copied_op) + for mutation in input_mutations], + [mutation._replace(copied_op=copied_op) + for mutation in control_mutations]) + + +def _copy_source(s, graph, op_map, handle_captures, inverse_captures, + base_graph): + """Create a source in a graph based on a Tensor from a different graph. + + This function creates a placeholder analog of `s` in a graph with the + following behavior: + + 1) If s is a captured Tensor or Variable and handle_captures is set to True, + simply capture it in the new graph as well. + + 2) If s is a PlaceholderWithDefault whose default is a constant, preserve + said default in the new graph. + + 3) When applicable, copy resource variable metadata from `s` to the newly + created placeholder. + + Args: + s: The source of interest. + graph: The destination graph. + op_map: A dict mapping ops and tensors in the old graph to the new one. + handle_captures: A boolean indicating whether to re-capture s in the new + graph or simply create a vanilla placeholder. + inverse_captures: A dict mapping s back to the Tensor or Variable that it + captures. + base_graph: The graph being copied from. + """ + if handle_captures and s in inverse_captures: + copied_placeholder = graph.capture(inverse_captures[s], name=s.op.name) + elif s.op.type == "PlaceholderWithDefault" and _constant_inputs(s): + # Copy the default value to the graph. + default_value = s.op.inputs[0] + unavailable_inputs, unavailable_control_inputs = _copy_non_source( + op=default_value.op, graph=graph, op_map=op_map, + base_graph=base_graph) + if unavailable_inputs or unavailable_control_inputs: + raise AssertionError( + "Could not copy source node {} because it has inputs." + .format(default_value)) + + with ops.device(s.op.device): + copied_placeholder = array_ops.placeholder_with_default( + input=op_map[default_value], shape=s.shape, name=s.op.name) + else: + with ops.device(s.op.device): + copied_placeholder = array_ops.placeholder( + dtype=s.dtype, shape=s.shape, name=s.op.name) + + base_handle = resource_variable_ops.get_resource_handle_data(s) + if base_handle.shape_and_type: + resource_variable_ops._set_handle_shapes_and_types( # pylint: disable=protected-access + copied_placeholder, + base_handle, + graph_mode=True) + + op_map[s] = copied_placeholder + # Add an entry for the op of the source tensor so that if there are any nodes + # depending on that op via control dependencies it can work correctly. + op_map[s.op] = copied_placeholder.op + + +@tf_export("__internal__.lift_to_graph", v1=[]) +def lift_to_graph(tensors, + graph, + sources=None, + disallowed_placeholders=None, + add_sources=False, + handle_captures=False, + base_graph=None, + op_map=None): + """Copies the tensor and all its inputs recursively to the outer graph. + + Args: + tensors: The Tensors to lift. + graph: The graph to lift to. + sources: Optional sequence of nodes to start from. If omitted the whole + subgraph which feeds into `init_tensor` is lifted. + disallowed_placeholders: An optional set of ops which may not appear in the + lifted graph. Defaults to all placeholders. + add_sources: A boolean indicating whether placeholders which are not in + sources should be allowed. + handle_captures: A boolean indicating whether to re-capture s in the new + graph or simply create a vanilla placeholder. + base_graph: The graph from which to lift ops. This will be inferred if not + specified. + op_map: A map contains all the existing nodes that have been lifted to the + destination graph, so they won't be lifted and copied again. + + Returns: + A mapping from ops in the current default graph to ops in `graph`. + + Raises: + UnliftableError: If a placeholder blocks lifting. + """ + variable_init_tensors = [] + init_tensors = [] + for tensor in tensors: + if isinstance(tensor, resource_variable_ops.ResourceVariable): + variable_init_tensors.append(tensor) + else: + init_tensors.append(tensor) + base_graph = base_graph or init_tensors[0].graph + op_map = op_map or object_identity.ObjectIdentityDictionary() + + # Check that the initializer does not depend on any placeholders. + sources = object_identity.ObjectIdentitySet(sources or []) + visited_ops = set(x.op for x in sources) + op_outputs = collections.defaultdict(set) + + # First we extract the subgraph between init_tensors and sources. + for init_tensor in init_tensors: + sources.update(op_selector.map_subgraph( + init_tensor=init_tensor, + sources=sources, + disallowed_placeholders=disallowed_placeholders, + visited_ops=visited_ops, + op_outputs=op_outputs, + add_sources=add_sources)) + + # Try to topologically sort the nodes we've extracted. Now we know how many of + # their outputs are part of this subgraph. + ops_to_copy = [] + marked_ops = set([]) + ops_to_visit = [_as_operation(t) for t in init_tensors + if not op_outputs[_as_operation(t)]] + unvisited_ops = set(ops_to_visit) + while unvisited_ops: + while ops_to_visit: + op = ops_to_visit.pop() + if op in marked_ops: + continue + marked_ops.add(op) + ops_to_copy.append(op) + for inp in op_selector.graph_inputs(op): + # Don't lift the TPUReplicateMetadata nodes out of the function, because + # it has no registered kernels. + if inp.type == "TPUReplicateMetadata": + continue + unvisited_ops.add(inp) + if (all(x in marked_ops for x in op_outputs[inp]) and + inp not in sources): + ops_to_visit.append(inp) + unvisited_ops.difference_update(marked_ops) + if unvisited_ops: + # `unvisited_ops` should only have elements if the graph has a loop. In + # this case we want to keep copying and there's no topological ordering; + # we'll do ugly post-hoc mutations instead. + ops_to_visit.append(next(iter(unvisited_ops))) + + # When the topological sort fails due to loops, it can result in exceptions + # later when copying a node which inputs haven't been copied yet. We can + # improve that pseudo-topological order slightly by putting the ops without + # inputs, such as constants, at the start of the topological order (i.e at + # the end of ops_to_copy). + ops_to_copy.sort(key=(lambda op: len(op_selector.graph_inputs(op)) == 0)) + + # When lifting from one FuncGraph to another, we will need to capture the + # relevant tensors as well. + captures = [] + inverse_captures = object_identity.ObjectIdentityDictionary() + internal_captures = [] + if (isinstance(base_graph, func_graph.FuncGraph) and + isinstance(graph, func_graph.FuncGraph)): + captures = base_graph.captures + for external_capture, internal_capture in captures: + inverse_captures[internal_capture] = external_capture + internal_captures = base_graph.internal_captures + + # ops_to_copy now holds a reverse topologically sorted list of ops which + # ends in the initializer. We copy those to the outermost graph and + # build the initialization op there. + with graph.as_default(): + for i in variable_init_tensors: + op_map[i] = i + source_ops = set() + # Add the sources in the same order as the original graph. + for s in internal_captures: + if s in sources: + sources.remove(s) + source_ops.add(s.op) + _copy_source( + s=s, + graph=graph, + op_map=op_map, + handle_captures=handle_captures, + inverse_captures=inverse_captures, + base_graph=base_graph) + for s in sources: + source_ops.add(s.op) + _copy_source( + s=s, + graph=graph, + op_map=op_map, + handle_captures=handle_captures, + inverse_captures=inverse_captures, + base_graph=base_graph) + + input_mutations = [] + control_mutations = [] + for op in reversed(ops_to_copy): + if op in source_ops or op in op_map: + continue + new_input_mutations, new_control_mutations = _copy_non_source( + op=op, graph=graph, op_map=op_map, base_graph=base_graph) + input_mutations.extend(new_input_mutations) + control_mutations.extend(new_control_mutations) + + # Mutate the new graph to insert any loops which existed in the source + # graph due to v1 while_loops. + # + # pylint: disable=protected-access + with graph._mutation_lock(): + for mutation in input_mutations: + mutation.copied_op._update_input( + mutation.input_index, op_map[mutation.old_graph_tensor]) + for mutation in control_mutations: + # Don't lift the TPUReplicateMetadata nodes out of the function, because + # it has no registered kernels. + if mutation.old_graph_op.type == "TPUReplicateMetadata": + continue + mutation.copied_op._add_control_input(op_map[mutation.old_graph_op]) + # pylint: enable=protected-access + + return op_map diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/memory_tests/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/memory_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/memory_tests/memory_test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/memory_tests/memory_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..7d584661b342b7efa4590d2a41811433d75abd72 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/memory_tests/memory_test_util.py @@ -0,0 +1,73 @@ +# 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. +# ============================================================================== +"""Utils for memory tests.""" + +import collections +import gc +import time + +from tensorflow.python.eager import context + +# memory_profiler might not be available in the OSS version of TensorFlow. +try: + import memory_profiler # pylint:disable=g-import-not-at-top +except ImportError: + memory_profiler = None + + +def _instance_count_by_class(): + counter = collections.Counter() + + for obj in gc.get_objects(): + try: + counter[obj.__class__.__name__] += 1 + except Exception: # pylint:disable=broad-except + pass + + return counter + + +def assert_no_leak(f, num_iters=100000, increase_threshold_absolute_mb=25): + """Assert memory usage doesn't increase beyond given threshold for f.""" + + with context.eager_mode(): + # Warm up. + f() + + # Wait for background threads to start up and take over memory. + # FIXME: The nature of this test leaves few other options. Maybe there + # is a better way to do this. + time.sleep(4) + + gc.collect() + initial = memory_profiler.memory_usage(-1)[0] + instance_count_by_class_before = _instance_count_by_class() + + for _ in range(num_iters): + f() + + gc.collect() + increase = memory_profiler.memory_usage(-1)[0] - initial + + assert increase < increase_threshold_absolute_mb, ( + "Increase is too high. Initial memory usage: %f MB. Increase: %f MB. " + "Maximum allowed increase: %f MB. " + "Instance count diff before/after: %s") % ( + initial, increase, increase_threshold_absolute_mb, + _instance_count_by_class() - instance_count_by_class_before) + + +def memory_profiler_is_available(): + return memory_profiler is not None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/monitoring.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/monitoring.py new file mode 100644 index 0000000000000000000000000000000000000000..b4d5d4e610f1b375f0d8a0a46d3ff6991406afea --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/monitoring.py @@ -0,0 +1,542 @@ +# 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. +# ============================================================================== +"""TensorFlow monitoring APIs.""" + +import collections +import functools +import time + +from tensorflow.core.framework import summary_pb2 +from tensorflow.python import pywrap_tfe +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.framework import c_api_util +from tensorflow.python.util import compat +from tensorflow.python.util.tf_export import tf_export + +_MetricMethod = collections.namedtuple('MetricMethod', 'create delete get_cell') +_counter_methods = [ + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewCounter0, + delete=pywrap_tfe.TFE_MonitoringDeleteCounter0, + get_cell=pywrap_tfe.TFE_MonitoringGetCellCounter0), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewCounter1, + delete=pywrap_tfe.TFE_MonitoringDeleteCounter1, + get_cell=pywrap_tfe.TFE_MonitoringGetCellCounter1), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewCounter2, + delete=pywrap_tfe.TFE_MonitoringDeleteCounter2, + get_cell=pywrap_tfe.TFE_MonitoringGetCellCounter2), +] +_int_gauge_methods = [ + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewIntGauge0, + delete=pywrap_tfe.TFE_MonitoringDeleteIntGauge0, + get_cell=pywrap_tfe.TFE_MonitoringGetCellIntGauge0), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewIntGauge1, + delete=pywrap_tfe.TFE_MonitoringDeleteIntGauge1, + get_cell=pywrap_tfe.TFE_MonitoringGetCellIntGauge1), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewIntGauge2, + delete=pywrap_tfe.TFE_MonitoringDeleteIntGauge2, + get_cell=pywrap_tfe.TFE_MonitoringGetCellIntGauge2), +] +_string_gauge_methods = [ + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewStringGauge0, + delete=pywrap_tfe.TFE_MonitoringDeleteStringGauge0, + get_cell=pywrap_tfe.TFE_MonitoringGetCellStringGauge0), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewStringGauge1, + delete=pywrap_tfe.TFE_MonitoringDeleteStringGauge1, + get_cell=pywrap_tfe.TFE_MonitoringGetCellStringGauge1), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewStringGauge2, + delete=pywrap_tfe.TFE_MonitoringDeleteStringGauge2, + get_cell=pywrap_tfe.TFE_MonitoringGetCellStringGauge2), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewStringGauge3, + delete=pywrap_tfe.TFE_MonitoringDeleteStringGauge3, + get_cell=pywrap_tfe.TFE_MonitoringGetCellStringGauge3), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewStringGauge4, + delete=pywrap_tfe.TFE_MonitoringDeleteStringGauge4, + get_cell=pywrap_tfe.TFE_MonitoringGetCellStringGauge4), +] +_bool_gauge_methods = [ + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewBoolGauge0, + delete=pywrap_tfe.TFE_MonitoringDeleteBoolGauge0, + get_cell=pywrap_tfe.TFE_MonitoringGetCellBoolGauge0), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewBoolGauge1, + delete=pywrap_tfe.TFE_MonitoringDeleteBoolGauge1, + get_cell=pywrap_tfe.TFE_MonitoringGetCellBoolGauge1), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewBoolGauge2, + delete=pywrap_tfe.TFE_MonitoringDeleteBoolGauge2, + get_cell=pywrap_tfe.TFE_MonitoringGetCellBoolGauge2), +] +_sampler_methods = [ + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewSampler0, + delete=pywrap_tfe.TFE_MonitoringDeleteSampler0, + get_cell=pywrap_tfe.TFE_MonitoringGetCellSampler0), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewSampler1, + delete=pywrap_tfe.TFE_MonitoringDeleteSampler1, + get_cell=pywrap_tfe.TFE_MonitoringGetCellSampler1), + _MetricMethod( + create=pywrap_tfe.TFE_MonitoringNewSampler2, + delete=pywrap_tfe.TFE_MonitoringDeleteSampler2, + get_cell=pywrap_tfe.TFE_MonitoringGetCellSampler2), +] + + +class Metric(object): + """The base class of metric.""" + + __slots__ = ["_metric", "_metric_name", "_metric_methods", "_label_length"] + + def __init__(self, metric_name, metric_methods, label_length, *args): + """Creates a new metric. + + Args: + metric_name: name of the metric class. + metric_methods: list of swig metric methods. + label_length: length of label args. + *args: the arguments to call create method. + """ + self._metric_name = metric_name + self._metric_methods = metric_methods + self._label_length = label_length + + if label_length >= len(self._metric_methods): + raise ValueError('Cannot create {} metric with label >= {}'.format( + self._metric_name, len(self._metric_methods))) + + self._metric = self._metric_methods[self._label_length].create(*args) + + def __del__(self): + try: + deleter = self._metric_methods[self._label_length].delete + metric = self._metric + except AttributeError: + return + + if deleter is not None: + deleter(metric) + + def get_cell(self, *labels): + """Retrieves the cell.""" + if len(labels) != self._label_length: + raise ValueError('The {} expects taking {} labels'.format( + self._metric_name, self._label_length)) + return self._metric_methods[self._label_length].get_cell( + self._metric, *labels) + + +class CounterCell(object): + """CounterCell stores each value of a Counter.""" + + __slots__ = ["_cell"] + + def __init__(self, cell): + """Creates a new CounterCell. + + Args: + cell: A c pointer of TFE_MonitoringCounterCell. + """ + self._cell = cell + + def increase_by(self, value): + """Atomically increments the value. + + Args: + value: non-negative value. + """ + pywrap_tfe.TFE_MonitoringCounterCellIncrementBy(self._cell, value) + + def value(self): + """Retrieves the current value.""" + return pywrap_tfe.TFE_MonitoringCounterCellValue(self._cell) + + +class Counter(Metric): + """A stateful class for updating a cumulative integer metric. + + This class encapsulates a set of values (or a single value for a label-less + metric). Each value is identified by a tuple of labels. The class allows the + user to increment each value. + """ + + __slots__ = [] + + def __init__(self, name, description, *labels): + """Creates a new Counter. + + Args: + name: name of the new metric. + description: description of the new metric. + *labels: The label list of the new metric. + """ + super(Counter, self).__init__('Counter', _counter_methods, len(labels), + name, description, *labels) + + def get_cell(self, *labels): + """Retrieves the cell.""" + return CounterCell(super(Counter, self).get_cell(*labels)) + + +class IntGaugeCell(object): + """A single integer value stored in an `IntGauge`.""" + + __slots__ = ["_cell"] + + def __init__(self, cell): + """Creates a new IntGaugeCell. + + Args: + cell: A c pointer of TFE_MonitoringIntGaugeCell. + """ + self._cell = cell + + def set(self, value): + """Atomically set the value. + + Args: + value: integer value. + """ + pywrap_tfe.TFE_MonitoringIntGaugeCellSet(self._cell, value) + + def value(self): + """Retrieves the current value.""" + return pywrap_tfe.TFE_MonitoringIntGaugeCellValue(self._cell) + + +class IntGauge(Metric): + """A stateful class for updating a gauge-like integer metric. + + This class encapsulates a set of integer values (or a single value for a + label-less metric). Each value is identified by a tuple of labels. The class + allows the user to set each value. + """ + + __slots__ = [] + + def __init__(self, name, description, *labels): + """Creates a new IntGauge. + + Args: + name: name of the new metric. + description: description of the new metric. + *labels: The label list of the new metric. + """ + super(IntGauge, self).__init__('IntGauge', _int_gauge_methods, len(labels), + name, description, *labels) + + def get_cell(self, *labels): + """Retrieves the cell.""" + return IntGaugeCell(super(IntGauge, self).get_cell(*labels)) + + +class StringGaugeCell(object): + """A single string value stored in an `StringGauge`.""" + + __slots__ = ["_cell"] + + def __init__(self, cell): + """Creates a new StringGaugeCell. + + Args: + cell: A c pointer of TFE_MonitoringStringGaugeCell. + """ + self._cell = cell + + def set(self, value): + """Atomically set the value. + + Args: + value: string value. + """ + pywrap_tfe.TFE_MonitoringStringGaugeCellSet(self._cell, value) + + def value(self): + """Retrieves the current value.""" + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_MonitoringStringGaugeCellValue(self._cell, buffer_) + value = pywrap_tf_session.TF_GetBuffer(buffer_).decode('utf-8') + return value + + +class StringGauge(Metric): + """A stateful class for updating a gauge-like string metric. + + This class encapsulates a set of string values (or a single value for a + label-less metric). Each value is identified by a tuple of labels. The class + allows the user to set each value. + """ + + __slots__ = [] + + def __init__(self, name, description, *labels): + """Creates a new StringGauge. + + Args: + name: name of the new metric. + description: description of the new metric. + *labels: The label list of the new metric. + """ + super(StringGauge, self).__init__('StringGauge', _string_gauge_methods, + len(labels), name, description, *labels) + + def get_cell(self, *labels): + """Retrieves the cell.""" + return StringGaugeCell(super(StringGauge, self).get_cell(*labels)) + + +class BoolGaugeCell(object): + """A single boolean value stored in an `BoolGauge`.""" + + __slots__ = ["_cell"] + + def __init__(self, cell): + """Creates a new BoolGaugeCell. + + Args: + cell: A c pointer of TFE_MonitoringBoolGaugeCell. + """ + self._cell = cell + + def set(self, value): + """Atomically set the value. + + Args: + value: bool value. + """ + pywrap_tfe.TFE_MonitoringBoolGaugeCellSet(self._cell, value) + + def value(self): + """Retrieves the current value.""" + return pywrap_tfe.TFE_MonitoringBoolGaugeCellValue(self._cell) + + +@tf_export("__internal__.monitoring.BoolGauge", v1=[]) +class BoolGauge(Metric): + """A stateful class for updating a gauge-like bool metric. + + This class encapsulates a set of boolean values (or a single value for a + label-less metric). Each value is identified by a tuple of labels. The class + allows the user to set each value. + """ + + __slots__ = [] + + def __init__(self, name, description, *labels): + """Creates a new BoolGauge. + + Args: + name: name of the new metric. + description: description of the new metric. + *labels: The label list of the new metric. + """ + super(BoolGauge, self).__init__('BoolGauge', _bool_gauge_methods, + len(labels), name, description, *labels) + + def get_cell(self, *labels): + """Retrieves the cell.""" + return BoolGaugeCell(super(BoolGauge, self).get_cell(*labels)) + + +class SamplerCell(object): + """SamplerCell stores each value of a Sampler.""" + + __slots__ = ["_cell"] + + def __init__(self, cell): + """Creates a new SamplerCell. + + Args: + cell: A c pointer of TFE_MonitoringSamplerCell. + """ + self._cell = cell + + def add(self, value): + """Atomically add a sample. + + Args: + value: float value. + """ + pywrap_tfe.TFE_MonitoringSamplerCellAdd(self._cell, value) + + def value(self): + """Retrieves the current distribution of samples. + + Returns: + A HistogramProto describing the distribution of samples. + """ + with c_api_util.tf_buffer() as buffer_: + pywrap_tfe.TFE_MonitoringSamplerCellValue(self._cell, buffer_) + proto_data = pywrap_tf_session.TF_GetBuffer(buffer_) + histogram_proto = summary_pb2.HistogramProto() + histogram_proto.ParseFromString(compat.as_bytes(proto_data)) + return histogram_proto + + +class Buckets(object): + """Bucketing strategies for the samplers.""" + + __slots__ = ["buckets"] + + def __init__(self, buckets): + """Creates a new Buckets. + + Args: + buckets: A c pointer of TFE_MonitoringBuckets. + """ + self.buckets = buckets + + def __del__(self): + pywrap_tfe.TFE_MonitoringDeleteBuckets(self.buckets) + + +class ExponentialBuckets(Buckets): + """Exponential bucketing strategy. + + Sets up buckets of the form: + [-DBL_MAX, ..., scale * growth^i, + scale * growth_factor^(i + 1), ..., DBL_MAX]. + """ + + __slots__ = [] + + def __init__(self, scale, growth_factor, bucket_count): + """Creates a new exponential Buckets. + + Args: + scale: float + growth_factor: float + bucket_count: integer + """ + super(ExponentialBuckets, self).__init__( + pywrap_tfe.TFE_MonitoringNewExponentialBuckets(scale, growth_factor, + bucket_count)) + + +class Sampler(Metric): + """A stateful class for updating a cumulative histogram metric. + + This class encapsulates a set of histograms (or a single histogram for a + label-less metric) configured with a list of increasing bucket boundaries. + Each histogram is identified by a tuple of labels. The class allows the + user to add a sample to each histogram value. + """ + + __slots__ = [] + + def __init__(self, name, buckets, description, *labels): + """Creates a new Sampler. + + Args: + name: name of the new metric. + buckets: bucketing strategy of the new metric. + description: description of the new metric. + *labels: The label list of the new metric. + """ + super(Sampler, self).__init__('Sampler', _sampler_methods, len(labels), + name, buckets.buckets, description, *labels) + + def get_cell(self, *labels): + """Retrieves the cell.""" + return SamplerCell(super(Sampler, self).get_cell(*labels)) + + +# Keeping track of current MonitoredTimer sections to prevent repetitive +# counting. +MonitoredTimerSections = [] + + +class MonitoredTimer(object): + """A context manager to measure the walltime and increment a Counter cell.""" + + __slots__ = [ + "cell", + "t", + "monitored_section_name", + "_counting", + "_avoid_repetitive_counting", + ] + + def __init__( + self, cell, monitored_section_name=None, avoid_repetitive_counting=False + ): + """Creates a new MonitoredTimer. + + Args: + cell: the cell associated with the time metric that will be inremented. + monitored_section_name: name of action being monitored here. + avoid_repetitive_counting: when set to True, if already in a monitored + timer section with the same monitored_section_name, skip counting. + """ + self.cell = cell + self.monitored_section_name = monitored_section_name + self._avoid_repetitive_counting = avoid_repetitive_counting + self._counting = True + + def __enter__(self): + if ( + self._avoid_repetitive_counting + and self.monitored_section_name + and self.monitored_section_name in MonitoredTimerSections + ): + self._counting = False + return self + + self.t = time.time() + if self.monitored_section_name: + MonitoredTimerSections.append(self.monitored_section_name) + + return self + + def __exit__(self, exception_type, exception_value, traceback): + del exception_type, exception_value, traceback + if self._counting: + micro_seconds = (time.time() - self.t) * 1000000 + self.cell.increase_by(int(micro_seconds)) + if self.monitored_section_name: + MonitoredTimerSections.remove(self.monitored_section_name) + + +def monitored_timer(cell): + """A function decorator for adding MonitoredTimer support. + + Args: + cell: the cell associated with the time metric that will be inremented. + Returns: + A decorator that measure the function runtime and increment the specified + counter cell. + """ + + def actual_decorator(func): + + @functools.wraps(func) + def wrapper(*args, **kwargs): + with MonitoredTimer(cell): + return func(*args, **kwargs) + + return wrapper + + return actual_decorator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/atomic_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/atomic_function.py new file mode 100644 index 0000000000000000000000000000000000000000..3493fff2541ee07cd60e37837232b5123f39600e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/atomic_function.py @@ -0,0 +1,693 @@ +# 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. +# ============================================================================== +"""Implementation for AtomicFunction.""" + +import dataclasses +import traceback +import typing +from typing import Any, Dict, List, Optional, Sequence, Union + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import function_pb2 +from tensorflow.core.framework import graph_debug_info_pb2 +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.eager import context +from tensorflow.python.eager import record +from tensorflow.python.eager.polymorphic_function import attributes as attributes_lib +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.framework import auto_control_deps_utils as acd +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import error_interpolation +from tensorflow.python.framework import errors +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import function_def_to_graph +from tensorflow.python.framework import ops +from tensorflow.python.ops import handle_data_util +from tensorflow.python.types import core +from tensorflow.python.util import compat +from tensorflow.python.util import function_utils +from tensorflow.python.util import tf_stack + + +# TODO(fmuham): Should be lowered to FunctionDef/FunctionRecord. +@dataclasses.dataclass(frozen=True) +class CallOptions: + """Specifies additional configuration for an AtomicFunction call.""" + + # Used by ACD to identify the CollectiveManager this function is scoped in. + collective_manager_ids_used: List[int] = dataclasses.field( + default_factory=list + ) + + # Used by ACD to list Ops/Tensors/Callables that must be called in advance. + control_captures: List[Any] = dataclasses.field(default_factory=list) + + # Determines what kind of partitoned call is used for this function. + is_stateful: bool = False + + +# Maps the (scope_id, name) in runtime to associated AtomicFunctions. +RUNTIME_FUNCTION_REFS = {} + + +class AtomicFunction(core.AtomicFunction): + """A Python callable for functions in the TF Runtime. + + Provides core functionality for tf.function including: + - automatic lifecycle management of runtime functions + - structured inputs (including captures) and structured outputs + - calls from both eager and graph mode + - dependency tracking of children functions + - runtime error interpolation to identify user code stack traces + - control dependencies (including automatic) + """ + + __slots__ = [ + "_name", + "_bound_context", + "_function_type", + "_children", + "_call_options", + "_cached_definition", + "_cached_graph", + "_generated_graph", + ] + + def __init__( + self, + name: Union[str, bytes], + bound_context: context.Context, + function_type: function_type_lib.FunctionType, + children: Optional[List["AtomicFunction"]] = None, + call_options: CallOptions = CallOptions(), + cached_graph: Optional[func_graph_module.FuncGraph] = None, + ): + """Construct a new AtomicFunction. + + Args: + name: str/bytes name of the runtime function in the bound context. + bound_context: interface to the runtime for the AtomicFunction. + function_type: input/output contract for the AtomicFunction + children: list of AtomicFunctions that are needed to call this one. + call_options: extra configuration options for the call. + cached_graph: FuncGraph that this AtomicFunction was generated from (if + known). Otherwise it will lazily construct a new corresponding FuncGraph + if ever needed. + """ + self._name = compat.as_bytes(name) + self._bound_context = bound_context + self._function_type = function_type + self._children = children if children else [] + self._call_options = call_options + self._cached_definition = None + + self._cached_graph = cached_graph + self._generated_graph = None + + ref_key = (self._bound_context.function_scope_id, self.name) + if ref_key not in RUNTIME_FUNCTION_REFS: + RUNTIME_FUNCTION_REFS[ref_key] = 1 + else: + RUNTIME_FUNCTION_REFS[ref_key] += 1 + + @property + def name(self) -> bytes: + """Name represented in UTF-8 encoded bytes.""" + return self._name + + @property + def function_type(self) -> function_type_lib.FunctionType: + """Represents the input/output contract of this function.""" + return self._function_type + + @property + def children(self) -> List["AtomicFunction"]: + """AtomicFunctions needed as dependencies for this one.""" + return self._children + + @property + def definition(self) -> function_pb2.FunctionDef: + """Current FunctionDef in the Runtime.""" + return self._bound_context.get_function_def(self.name) + + @property + def attributes(self) -> Any: + """Returns FunctionDef attributes in the Runtime.""" + attrs = self.definition.attr + # Remove construction context since it is specific to runtime and this fn. + attrs.pop(attributes_lib.EAGER_RUNTIME_CONSTRUCTION_CONTEXT, None) + return attrs + + @property + def graph_debug_info(self) -> graph_debug_info_pb2.GraphDebugInfo: + """A GraphDebugInfo proto mapping nodes to corresponding stack traces.""" + return self._bound_context.get_graph_debug_info(self.name) + + @property + def call_options(self) -> CallOptions: + """Call options declared for this AtomicFunction.""" + return self._call_options + + @property + def graph_call_attrs(self) -> Dict[str, Any]: + """Returns a dictionary of attributes needed to add a call in graph.""" + attrs = { + "is_stateful": self.call_options.is_stateful, + "tout": [ + o.dtype.as_datatype_enum for o in self.function_type.flat_outputs + ], + "xla_compile_attr": self.cached_definition.attr.get( + attributes_lib.XLA_COMPILE, None + ), + } + attrs.update(self._bound_context.function_call_options.as_attrs()) + return attrs + + @property + def _c_func(self) -> Any: + """Returns a scoped pybind object containing FunctionRecord in runtime.""" + return self._bound_context.get_c_function(self.name) + + # TODO(fmuham): Move caching to dependent code and remove method. + @property + def cached_definition(self) -> function_pb2.FunctionDef: + """Cached FunctionDef (not guaranteed to be fresh).""" + if self._cached_definition is None: + self._cached_definition = self.definition + + return self._cached_definition + + @property + def graph(self) -> func_graph_module.FuncGraph: + """Returns a FuncGraph corresponding to the AtomicFunction.""" + if self._cached_graph: + return self._cached_graph + + # Lazily generate the graph if one is not specified. + if not self._generated_graph: + self._generated_graph = to_func_graph(self) + + return self._generated_graph + + def call_with_captures( + self, args: Sequence[Any], kwargs: Dict[str, Any], captures: Sequence[Any] + ) -> Any: + """Calls with args, kwargs, captures and returns structured output.""" + bound_parameters = self.function_type.bind(*args, **kwargs) + tensor_inputs = self.function_type.unpack_inputs(bound_parameters) + capture_inputs = self.function_type.unpack_captures(captures) + return self.call_preflattened(tensor_inputs + capture_inputs) + + def call_preflattened(self, args: Sequence[core.Tensor]) -> Any: + """Calls with flattened tensor inputs and returns the structured output.""" + flat_outputs = self.call_flat(*args) + return self.function_type.pack_output(flat_outputs) + + def call_flat(self, *args: core.Tensor) -> Sequence[core.Tensor]: + """Calls with flat tensor inputs and returns flat tensor outputs. + + Args: + *args: arguments to call this function with. + + Returns: + The outputs of the function call. + + Raises: + ValueError: if the number of arguments is incorrect. + FunctionAlreadyGarbageCollectedError: if the function is no longer + available to be called because it has been garbage collected. + """ + expected_len = len(self.cached_definition.signature.input_arg) + if len(args) != expected_len: + raise ValueError( + f"Signature specifies {expected_len} arguments, got: {len(args)}." + f" Expected inputs: {self.cached_definition.signature.input_arg}." + f" Received inputs: {args}." + f" Function Type: {self.function_type!r}" + ) + + with InterpolateRuntimeError(self): + with ops.control_dependencies(self._call_options.control_captures): + # The caller must use record_operation to record this operation in the + # eager case, so we enforce the same requirement for the non-eager + # case by explicitly pausing recording. We don't have a gradient + # registered for PartitionedCall, so recording this operation confuses + # forwardprop code (GradientTape manages to ignore it). + with record.stop_recording(): + if self._bound_context.executing_eagerly(): + outputs = self._bound_context.call_function( + self.name, + list(args), + len(self.function_type.flat_outputs), + ) + else: + outputs = make_call_op_in_graph( + self, + list(args), + self._bound_context.function_call_options.as_attrs(), + ) + + for i, output_type in enumerate(self.function_type.flat_outputs): + handle_data = output_type.dtype._handle_data # pylint: disable=protected-access + if handle_data: + handle_data_util.set_handle_data( + outputs[i], handle_data.shape_inference + ) + + # TODO(fmuham): Use FunctionType cast here for all cases. + if not self._bound_context.executing_eagerly(): + for i, output_type in enumerate(self.function_type.flat_outputs): + outputs[i].set_shape(output_type.shape) + + return outputs + + def __call__(self, *args, **kwargs) -> Any: + if self.function_type.captures: + raise ValueError( + "The FunctionType defines captured inputs. Use call_with_captures" + " instead." + ) + + return self.call_with_captures(args, kwargs, []) + + def __del__(self): + if self._generated_graph: + func_graph_module.dismantle_func_graph(self._generated_graph) + + key = (self._bound_context.function_scope_id, self.name) + RUNTIME_FUNCTION_REFS[key] -= 1 + if RUNTIME_FUNCTION_REFS[key] < 0: + raise RuntimeError( + f"AtomicFunction Refcounting for {self.name} is invalid." + ) + + if RUNTIME_FUNCTION_REFS[key] == 0: + try: + self._bound_context.remove_function(self.name) + RUNTIME_FUNCTION_REFS.pop(key) + except TypeError: + # Suppress some exceptions, mainly for the case when we're running on + # module deletion. Things that can go wrong include the context module + # already being unloaded, self._handle._handle_data no longer being + # valid, and so on. Printing warnings in these cases is silly + # (exceptions raised from __del__ are printed as warnings to stderr). + pass # 'NoneType' object is not callable when the handle has been + # partially unloaded. + except AttributeError: + pass # 'NoneType' object has no attribute 'eager_mode' when context has + # been unloaded. Will catch other module unloads as well. + + def __str__(self): + return f" {compat.as_str(self.name)}{self.function_type}" + + def __repr__(self): + return ( + f"AtomicFunction(name={self.name},\n" + f"bound_context={self._bound_context},\n" + f"function_type={self.function_type!r},\n" + f"children={self._children!s},\n" + f"call_options={self._call_options},\n" + f"cached_graph={self._cached_graph})" + ) + + +def _set_read_only_resource_inputs_attr( + op: ops.Operation, func_graph: func_graph_module.FuncGraph +): + """Sets the list of resource inputs which are read-only. + + This is used by AutomaticControlDependencies. + + Args: + op: PartitionedCall Operation. + func_graph: FuncGraph. + """ + read_only_indices = acd.get_read_only_resource_input_indices_graph(func_graph) + ops.set_int_list_attr( + op, acd.READ_ONLY_RESOURCE_INPUTS_ATTR, read_only_indices + ) + + +def partitioned_call_op( + name: str, + args: Sequence[core.Tensor], + is_stateful: bool, + tout: Sequence[Any], + config: Any = None, + executor_type: Optional[str] = None, + xla_compile_attr: Any = None, +) -> ops.Operation: + """Generates a function call op respecting device annotations. + + Args: + name: Name of the function to call. + args: The arguments of the function, including captured inputs. + is_stateful: If the function is stateful. + tout: a list containing the output dtypes enums + config: (Optional) A `tensorflow::ConfigProto` proto, serialized. If `None`, + all optimizations are disabled. Currently only handled for eager defined + functions. + executor_type: (Optional) A string for the name of the executor to be used + in the function call. If not set, or set to an empty string, the default + tensorflow executor will be used. + xla_compile_attr: (Optional) value of the XLA compilation attribute. + + Returns: + Returns the operation. + """ + if config is None: + config = function_utils.get_disabled_rewriter_config() + + if executor_type is None: + executor_type = "" + + # The generated binding returns an empty list for functions that don't + # return any Tensors, hence the need to use `create_op` directly. + args = [ops.convert_to_tensor(x) for x in args] + tin_attr = attr_value_pb2.AttrValue( + list=attr_value_pb2.AttrValue.ListValue( + type=[x.dtype.as_datatype_enum for x in args] + ) + ) + tout_attr = attr_value_pb2.AttrValue( + list=attr_value_pb2.AttrValue.ListValue(type=tout) + ) + func_attr = attr_value_pb2.AttrValue( + func=attr_value_pb2.NameAttrList(name=name) + ) + executor_type_attr = attr_value_pb2.AttrValue( + s=compat.as_bytes(executor_type) + ) + + # When running in graph mode, the graph and function graphs are optimized + # (i.e. run through grappler) per the session options, so we can disable any + # eager-specific rewriting. + config_proto = attr_value_pb2.AttrValue(s=config) + + op_name = "StatefulPartitionedCall" if is_stateful else "PartitionedCall" + + # Propagate the attribute indicating the need to compile from function to the + # call itself. + op_attrs = { + "Tin": tin_attr, + "Tout": tout_attr, + "f": func_attr, + "config_proto": config_proto, + "executor_type": executor_type_attr, + } + if xla_compile_attr is not None: + op_attrs[attributes_lib.XLA_COMPILE] = xla_compile_attr + + op = ops.get_default_graph().create_op( + op_name, args, tout, name=op_name, attrs=op_attrs + ) + return op + + +def make_call_op_in_graph( + atomic: AtomicFunction, + tensor_inputs: Sequence[core.Tensor], + context_call_attrs: Dict[str, Any], +): + """Adds an AtomicFunction to graph.""" + graph = ops.get_default_graph() + graph._add_function_recursive(atomic) # pylint: disable=protected-access + + op = partitioned_call_op( + name=atomic.name, + args=tensor_inputs, + is_stateful=atomic.call_options.is_stateful, + tout=[ + o.dtype.as_datatype_enum for o in atomic.function_type.flat_outputs + ], + config=context_call_attrs["config_proto"], + executor_type=context_call_attrs["executor_type"], + xla_compile_attr=atomic.cached_definition.attr.get( + attributes_lib.XLA_COMPILE, None + ), + ) + _set_read_only_resource_inputs_attr(op, atomic.graph) + + ops.set_int_list_attr( + op, + acd.COLLECTIVE_MANAGER_IDS, + atomic._call_options.collective_manager_ids_used, # pylint: disable=protected-access + ) + + return op.outputs + + +def from_function_def( + function_def: function_pb2.FunctionDef, + function_type: function_type_lib.FunctionType, +) -> AtomicFunction: + """Create a new AtomicFunction from FunctionDef + FunctionType.""" + bound_context = context.context() + if bound_context.has_function(compat.as_bytes(function_def.signature.name)): + raise ValueError("Function already registered in context.") + + bound_context.add_function_def(function_def) + return AtomicFunction( + function_def.signature.name, bound_context, function_type + ) + + +def from_func_graph( + name: Union[str, bytes], + graph: func_graph_module.FuncGraph, + attrs: Dict[str, attr_value_pb2.AttrValue], + function_type: Optional[function_type_lib.FunctionType] = None, + overwrite: bool = False, +) -> AtomicFunction: + """Initializes an AtomicFunction from FuncGraph. + + Args: + name: str, the name for the created function. + graph: Graph, the graph containing the operations in the function + attrs: dict mapping names of attributes to their AttrValue values + function_type: known FunctionType to use, otherwise one is derived. + overwrite: overwrites function definition in the current context if needed + + Returns: + An AtomicFunction instance. + """ + if attrs and attributes_lib.IMPLEMENTS in attrs: + # The alternative is to silently drop "implements" tag + # but it seems likely it would lead to hard to catch bugs. + # Another alternative is to make func_body to preserve the order + # of arguments if variables are present. Yet another option + # is to automatically replace variables as arguments to functions + # to v.read_value() whenever "implements" tag is present + # Anytime we annotate existing function we probably want to wrap + # it with safe read_value for backward compatibility. + has_resource_vars = any( + inp.dtype == dtypes.resource for inp in graph.inputs + ) + + captured_inputs = graph.external_captures + graph.deferred_external_captures + assert not any( + (has_resource_vars, captured_inputs) + ), ( + 'Function {name} has "{attr}={value}" attribute and thus can not ' + "depend on any tensors outside of its signature or modify variables. " + "\n\nNote: variables are always captured and cause function " + "re-tracing for every variable called.\n" + " inputs: {inputs}\n captures: {captured}\n\n" + "To pass a variable to such function use " + "use variable.read_value().".format( + name=graph.name, + attr=attributes_lib.IMPLEMENTS, + value=attrs[attributes_lib.IMPLEMENTS], + inputs=graph.inputs, + captured=captured_inputs, + ) + ) + + input_ops = set(arg.op for arg in graph.inputs) + operations = [op for op in graph.get_operations() if op not in input_ops] + + graph_output_names = graph._output_names # pylint: disable=protected-access + if graph_output_names is not None and all( + ops.tensor_id(t) in graph_output_names for t in graph.outputs + ): + output_names = [ + compat.as_bytes(graph_output_names[ops.tensor_id(t)]) + for t in graph.outputs + ] + if len(set(output_names)) != len(output_names): + # There are duplicate names for some reason, probably an invalid + # signature. Revert to auto-naming. + output_names = [] + else: + output_names = [] + with graph._c_graph.get() as c_graph: # pylint: disable=protected-access + fn = pywrap_tf_session.TF_GraphToFunction_wrapper( + c_graph, + compat.as_str(name), + False, + [o._c_op for o in operations], # pylint: disable=protected-access + [t._as_tf_output() for t in graph.inputs], # pylint: disable=protected-access + [t._as_tf_output() for t in graph.outputs], # pylint: disable=protected-access + output_names, + [o._c_op for o in graph.control_outputs], # pylint: disable=protected-access + [], # control_output_names + None, + compat.as_str(""), + ) + + attrs = attributes_lib.parse_func_attrs(attrs or {}) + for attr_name, attr_value in attrs.items(): + serialized = attr_value.SerializeToString() + pywrap_tf_session.TF_FunctionSetAttrValueProto( + fn, compat.as_str(attr_name), serialized + ) + + name = compat.as_bytes(name) + bound_context = context.context() + + if overwrite and bound_context.has_function(name): + bound_context.remove_function(name) + + bound_context.add_c_function(fn) + pywrap_tf_session.TF_DeleteFunction(fn) + + call_options = CallOptions( + collective_manager_ids_used=getattr( + graph, "collective_manager_ids_used", [] + ), + control_captures=graph.function_captures.control, + is_stateful=any(op._is_stateful for op in operations), # pylint: disable=protected-access + ) + + if not function_type: + function_type = function_type_utils.derive_from_graph(graph) + + return AtomicFunction( + name, + bound_context, + function_type, + list(graph._functions.values()), # pylint: disable=protected-access, + call_options, + cached_graph=graph, + ) + + +def to_func_graph(atomic: AtomicFunction) -> func_graph_module.FuncGraph: + """Generate a FuncGraph from an AtomicFunction.""" + # pylint: disable=protected-access + input_signature, output_signature = function_type_lib.to_structured_signature( + atomic.function_type + ) + + with ops.Graph().as_default(): + # Insert dependencies in the default graph so the new graph can pull them. + for f in atomic.children: + ops.get_default_graph()._add_function(f) + + result = function_def_to_graph.function_def_to_graph( + atomic.definition, + structured_input_signature=input_signature, + structured_outputs=output_signature, + propagate_device_spec=True, + include_library_functions=False, + ) + for f in atomic.children: + result._add_function(f) + + # Set input shapes and handle data + for i, input_type in enumerate(atomic.function_type.flat_inputs): + handle_data = input_type.dtype._handle_data + if handle_data: + handle_data_util.set_handle_data( + result.inputs[i], handle_data.shape_inference + ) + result.inputs[i].set_shape(input_type.shape) + + # Set output shapes and handle data + for i, output_type in enumerate(atomic.function_type.flat_outputs): + handle_data = output_type.dtype._handle_data + if handle_data: + handle_data_util.set_handle_data( + result.outputs[i], handle_data.shape_inference + ) + result.outputs[i].set_shape(output_type.shape) + + result.collective_manager_ids_used = ( + atomic.call_options.collective_manager_ids_used, + ) + + # pylint: enable=protected-access + return result + + +class InterpolateRuntimeError(object): + """Context Manager that interpolates exceptions received by AtomicFunction.""" + + DENY_LIST_PHRASES = ["") + + error_message.append(message.strip()) + return "\n".join(error_message) + + def __enter__(self): + pass + + def __exit__(self, typ, exc, tb): + if not exc or not isinstance(exc, errors.OpError): + return False + exc = typing.cast(errors.OpError, exc) + message = compat.as_text(exc.message) + parsed_message, func_tags, node_tags = error_interpolation.parse_message( + message + ) + deepest_func = None + for func_tag in func_tags: + if func_tag.name == compat.as_str(self._func.name): + deepest_func = self._func + elif deepest_func: + next_func = None + for child_func in deepest_func.children: + if func_tag.name == compat.as_str(child_func.name): + next_func = child_func + break + if next_func is not None and isinstance(next_func, AtomicFunction): + deepest_func = next_func + if deepest_func: + exc._message = self.interpolate( + parsed_message, + [t.name for t in node_tags], + deepest_func.graph_debug_info, + ) + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/attributes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..2e9be8a94c9c98c3fc926ad66e915c60b6566f5f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/attributes.py @@ -0,0 +1,182 @@ +# 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. +# ============================================================================== + +"""This file lists FunctionDef attributes and corresponding allowlists.""" + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.util import compat + +# IMPORTANT: The usage of all the attributes below should be considered tech +# debt and new additions to this list are discouraged. +# +# Historically, attributes have been used as means to pipe extra information +# down to runtime that is not related to the actual function definition itself. +# +# This information is better layered independently and future work is encouraged +# to pursue that direction instead. + +API_IMPLEMENTS = "api_implements" +API_PREFERRED_DEVICE = "api_preferred_device" +BACKWARD_FUNCTION = "backward_function_name" +DISABLE_ACD = "_disable_acd" +DISABLE_CALL_SHAPE_INFERENCE = "_disable_call_shape_inference" +DISABLE_SUMMARIES_AT_RUNTIME = "disable_summaries_at_runtime" +EAGER_RUNTIME_CONSTRUCTION_CONTEXT = "_construction_context" +FORWARD_FUNCTION = "forward_function_name" +GO_BACKWARDS = "go_backwards" +IMPLEMENTS = "_implements" +INPUT_SHAPES = "_input_shapes" +INTS_ON_DEVICE = "experimental_ints_on_device" +NO_INLINE = "_noinline" +ORIGINAL_FUNCTION_NAME = "_original_func_name" +OUTPUTS_ON_OP_DEVICE = "_OutputsOnOpDevice" +QUANTIZED_COMPOSITE_FUNCTION = "tf_quant.composite_function" +QUANTIZED_OPS = "tf_quant.quantized_ops" +RUNTIME_CONSTANT_OPTIMIZATION = "runtime_constant_optimization" +SHARED_RENDEZVOUS = "shared_rendezvous" +TF_DATA_FUNCTION = "_tf_data_function" +TFTRT_ALLOW_BUILD_AT_RUNTIME = "_tftrt_allow_build_at_runtime" +TFTRT_CONVERT_FUNCTION = "_tftrt_convert_function" +TFTRT_IS_DYN_OP = "_tftrt_is_dyn_op" +TFTRT_LOGGER = "_tftrt_trt_logger_name" +TFTRT_MAX_BATCH_SIZE = "_tftrt_max_batch_size" +TFTRT_MAX_CACHED_ENGINES = "_tftrt_max_cached_engines" +TFTRT_MAX_WORKSPACE_SIZE = "_tftrt_max_workspace_size_bytes" +TFTRT_MIN_SEGMENT_SIZE = "_tftrt_minimum_segment_size" +TFTRT_PRECISION_MODE = "_tftrt_precision_mode" +TFTRT_PROFILE_STRATEGY = "_tftrt_profile_strategy" +TFTRT_USE_CALIBRATION = "_tftrt_use_calibration" +TFTRT_USE_IMPLICIT_BATCH = "_tftrt_use_implicit_batch" +TIME_MAJOR = "time_major" +XLA_COMPILE = "_XlaMustCompile" +XLA_COMPILE_OPTIONAL = "_XlaCompile" +XLA_SCOPE = "_XlaScope" +XLA_SEPERATE_COMPILED_GRADIENTS = "_XlaSeparateCompiledGradients" + +POLYMORPHIC_FUNCTION_ALLOWLIST = frozenset({ + API_IMPLEMENTS, + API_PREFERRED_DEVICE, + DISABLE_ACD, + DISABLE_SUMMARIES_AT_RUNTIME, + GO_BACKWARDS, + IMPLEMENTS, + INTS_ON_DEVICE, + NO_INLINE, + RUNTIME_CONSTANT_OPTIMIZATION, + TF_DATA_FUNCTION, + TIME_MAJOR, + OUTPUTS_ON_OP_DEVICE, +}) + +TRACING_COMPILATION_ALLOWLIST = frozenset().union( + POLYMORPHIC_FUNCTION_ALLOWLIST, + { + SHARED_RENDEZVOUS, + XLA_COMPILE, + }, +) + +MONOMORPHIC_FUNCTION_ALLOWLIST = frozenset().union( + TRACING_COMPILATION_ALLOWLIST, + { + BACKWARD_FUNCTION, + DISABLE_CALL_SHAPE_INFERENCE, + EAGER_RUNTIME_CONSTRUCTION_CONTEXT, + FORWARD_FUNCTION, + INPUT_SHAPES, + ORIGINAL_FUNCTION_NAME, + QUANTIZED_COMPOSITE_FUNCTION, + QUANTIZED_OPS, + TFTRT_ALLOW_BUILD_AT_RUNTIME, + TFTRT_CONVERT_FUNCTION, + TFTRT_IS_DYN_OP, + TFTRT_LOGGER, + TFTRT_MAX_BATCH_SIZE, + TFTRT_MAX_CACHED_ENGINES, + TFTRT_MAX_WORKSPACE_SIZE, + TFTRT_MIN_SEGMENT_SIZE, + TFTRT_PRECISION_MODE, + TFTRT_PROFILE_STRATEGY, + TFTRT_USE_CALIBRATION, + TFTRT_USE_IMPLICIT_BATCH, + XLA_COMPILE_OPTIONAL, + XLA_SCOPE, + XLA_SEPERATE_COMPILED_GRADIENTS, + }, +) + + +def _parse_func_attr_value(key, value): + """Converts a python object to an attr_value_pb2.AttrValue object.""" + if isinstance(value, attr_value_pb2.AttrValue): + return value + # bool type check has to happen before int since bool is a subclass of int. + elif isinstance(value, bool): + return attr_value_pb2.AttrValue(b=value) + elif isinstance(value, int): + return attr_value_pb2.AttrValue(i=value) + elif isinstance(value, float): + return attr_value_pb2.AttrValue(f=value) + elif isinstance(value, (str, bytes)): + return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) + elif isinstance(value, list): + list_value = attr_value_pb2.AttrValue.ListValue() + for v in value: + if isinstance(v, bool): + list_value.b.append(v) + elif isinstance(v, int): + list_value.i.append(v) + elif isinstance(v, float): + list_value.f.append(v) + elif isinstance(v, (str, bytes)): + list_value.s.append(compat.as_bytes(v)) + else: + raise ValueError( + f"Attributes for {key} must be bool, int, float, or string. " + f"Got {type(v)}." + ) + return attr_value_pb2.AttrValue(list=list_value) + else: + raise ValueError( + f"Attribute {key} must be bool, int, float, string, list, or " + f"AttrValue. Got {type(value)}." + ) + + +def parse_func_attrs(attributes, allowlist=None): + """Convert the keyword arguments into function_def attributes. + + Currently only support primitive types: bool, int, float and string. + + Args: + attributes: the dictionary of attributes. + allowlist: set of attribute names allowed. + Returns: + A dict of attributes where the key is the name of attribute and the value + is the AttrValue proto. + Raises: + ValueError: If the kwargs contains unallowlisted name or unsupported value + types. + """ + if not allowlist: + allowlist = MONOMORPHIC_FUNCTION_ALLOWLIST + + attrs = {} + for key, value in attributes.items(): + if key not in allowlist: + raise ValueError( + f"Allowlist does not support `{key}` as an attribute.") + attrs[key] = _parse_func_attr_value(key, value) + return attrs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/autograph_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/autograph_util.py new file mode 100644 index 0000000000000000000000000000000000000000..958dea68e694e1dae728effcb4d4521b0d17078e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/autograph_util.py @@ -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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""Autograph utility functions for polymorphic_function.""" + +from tensorflow.python.autograph.core import converter +from tensorflow.python.autograph.impl import api +from tensorflow.python.util import tf_decorator + + +def py_func_from_autograph( + python_func, + autograph_options=None, +): + """Compile a python function using autograph, for use with FuncGraph. + + Args: + python_func: the Python function to compile. + autograph_options: additional knobs to control when `autograph=True`. + See https://www.tensorflow.org/guide/autograph for more information. + Returns: + python_func, converted using autograph. + """ + _, original_func = tf_decorator.unwrap(python_func) + + def autograph_handler(*args, **kwargs): + """Calls a converted version of original_func.""" + try: + return api.converted_call( + original_func, + args, + kwargs, + options=converter.ConversionOptions( + recursive=True, + optional_features=autograph_options, + user_requested=True, + )) + except Exception as e: # pylint:disable=broad-except + if hasattr(e, "ag_error_metadata"): + raise e.ag_error_metadata.to_exception(e) + else: + raise + + # Wrapping around a decorator allows checks like tf_inspect.getargspec + # to be accurate. + converted_func = tf_decorator.make_decorator(original_func, autograph_handler) + return tf_decorator.rewrap(python_func, original_func, converted_func) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/compiler_ir.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/compiler_ir.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca5b126667accb97a3ebd3d72ca1f8f25a7ac9a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/compiler_ir.py @@ -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. +# ============================================================================== +"""Implmentation for defining get_compiler_ir.""" +from typing import List, Optional + +from tensorflow.core.function import trace_type +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import random_ops + +from tensorflow.python.util import nest + + +def maybe_get_device_name(device_name): + # TODO(cheshire): This is a hack to get the current "preferred" device, + # there is no current API to get it otherwise. + if device_name is None: + device_name = random_ops.random_normal([]).device + return device_name + + +# TODO(fmuham): Use trace_type._flatten here instead when available +def make_handledata_tensor_specs(resource_vars): + """Convert tf.Variable list to its corresponding TensorSpec list.""" + if not all(x.dtype is dtypes.resource for x in resource_vars): + raise RuntimeError("Resource_vars must be tf.resource list.") + inner_context = trace_type.InternalTracingContext() + trace_type_inputs = trace_type.from_value( + tuple(resource_vars), inner_context + ).components + + def to_resource_spec(traced_input): + try: + handle_data = traced_input.dtype._handle_data.shape_inference # pylint: disable=protected-access + shape_and_type = handle_data.shape_and_type[0] + spec = tensor_spec.TensorSpec( + shape=shape_and_type.shape, dtype=shape_and_type.dtype + ) + return spec + except Exception as e: + raise ValueError( + "Fail to convert tf.Variable list to TensorSpec list. The error" + " is: %s" % e + ) from e + + return [to_resource_spec(trace_type) for trace_type in trace_type_inputs] + + +def from_concrete_function( + concrete_fn, + specialized_flat_specs: Optional[List[tensor_spec.TensorSpec]] = None, +): + """Generate the Compiler Ir from tf concrete function with TensorSpec. + + Args: + concrete_fn: returned by using get_concrete_function. + specialized_flat_specs: specialized flat tf.TensorSpecs for function args. + + Returns: + Function callable that generate the HLO text. + + Raises: + ValueError: if concrete_fn is not "compilable" without concrete + inputs. + """ + context.ensure_initialized() + fn_name = concrete_fn.name + filtered_flat_specs = specialized_flat_specs or list( + nest.flatten(concrete_fn.structured_input_signature) + ) + + if not all(s.shape.is_fully_defined() for s in filtered_flat_specs): + raise ValueError( + f"Only support static input shape but got inputs = {concrete_fn.inputs}" + ) + + def compiler_ir_generator(stage="hlo", device_name=None): + device_name = maybe_get_device_name(device_name) + res_bytes = context.context().get_compiler_ir( + device_name=device_name, + function_name=fn_name, + flat_args=filtered_flat_specs, + captured_inputs=concrete_fn.captured_inputs, + stage=stage, + ) + if stage in ( + "hlo_serialized", + "optimized_hlo_serialized", + "optimized_hlo_proto_serialized", + ): + return res_bytes + else: + return res_bytes.decode("utf-8") + + return compiler_ir_generator diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/composite_tensor_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/composite_tensor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f0523e9da3431174d6faa0b6c12e3c7217daf1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/composite_tensor_utils.py @@ -0,0 +1,39 @@ +# 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. +# ============================================================================== +"""Utility to manipulate CompositeTensors in tf.function.""" + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import nest + + +# TODO(b/240337581, b/240337099): Remove this function when we de-alias +# dt_resource tensors or tf.nest support is_leaf. +def flatten_with_variables(inputs): + """Flattens `inputs` but don't expand `ResourceVariable`s.""" + # We assume that any CompositeTensors have already converted their components + # from numpy arrays to Tensors, so we don't need to expand composites here for + # the numpy array conversion. Instead, we do so because the flattened inputs + # are eventually passed to ConcreteFunction()._call_flat, which requires + # expanded composites. + flat_inputs = [] + for value in nest.flatten(inputs): + if (isinstance(value, composite_tensor.CompositeTensor) and + not _pywrap_utils.IsResourceVariable(value)): + components = value._type_spec._to_components(value) # pylint: disable=protected-access + flat_inputs.extend(flatten_with_variables(components)) + else: + flat_inputs.append(value) + return flat_inputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/concrete_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/concrete_function.py new file mode 100644 index 0000000000000000000000000000000000000000..3bbc4deeca4aaf9d188bbd47e958cc882d316eb6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/concrete_function.py @@ -0,0 +1,1777 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""Implementation for ConcreteFunction.""" + +import collections + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.python import pywrap_tfe +from tensorflow.python.eager import backprop_util +from tensorflow.python.eager import context +from tensorflow.python.eager import forwardprop_util +from tensorflow.python.eager import record +from tensorflow.python.eager.graph_only_ops import graph_placeholder +from tensorflow.python.eager.polymorphic_function import atomic_function +from tensorflow.python.eager.polymorphic_function import attributes as attributes_lib +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.eager.polymorphic_function import saved_model_exported_concrete +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import default_gradient +from tensorflow.python.ops import gradients_util +from tensorflow.python.ops import handle_data_util +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import core +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity + + +def _is_type_subset(a, b): + """Returns true if `b` is a subset of type `a` (or if a is not a TypeSpec.)""" + if isinstance(a, type_spec.TypeSpec): + return a.most_specific_compatible_type(b) == a + return True + + +_FORWARD_PREFIX = "__forward_" +_BACKWARD_PREFIX = "__backward_" +_INFERENCE_PREFIX = "__inference_" + + +def _forward_name(n): + """The name of a generated forward defun named n.""" + return "%s%s_%s" % (_FORWARD_PREFIX, n, ops.uid()) + + +def _backward_name(n): + """The name of a generated backward defun named n.""" + return "%s%s_%s" % (_BACKWARD_PREFIX, n, ops.uid()) + + +def _inference_name(n): + """The name of a forward-but-no-gradient defun named n.""" + return "%s%s_%s" % (_INFERENCE_PREFIX, n, ops.uid()) + + +def _create_forward_backward_with_graph( + attrs, forward_graph, backwards_graph: func_graph_module.FuncGraph +): + """Creates forward and backward functions from the function graphs.""" + forward_function_name = _forward_name(forward_graph.name) + common_attributes = dict(attrs) + # NB: forward and backward function need to drop "_implements". + # attribute, because their signature contains all the intermediate tensors + # that they compute. Thus they don't have a stable signature which can + # be directly optimized downstream. + # See for more details: + # https://github.com/tensorflow/community/blob/master/rfcs/20190610-standardizing-composite_ops.md#appendix-future-support-for-optimizing-gradient-functions + common_attributes.pop(attributes_lib.IMPLEMENTS, None) + backward_function_attr = attributes_lib.parse_func_attrs( + {attributes_lib.FORWARD_FUNCTION: forward_function_name}) + backward_function_attr.update(common_attributes) + # TODO(fmuham): Include inputs as well. + function_type = function_type_lib.from_structured_signature( + ((), {}), + backwards_graph.structured_outputs, + backwards_graph.function_captures.capture_types, + ) + backward_function = ConcreteFunction.from_func_graph( + backwards_graph, function_type, attrs=backward_function_attr + ) + forward_function_attr = attributes_lib.parse_func_attrs( + {attributes_lib.BACKWARD_FUNCTION: backward_function.name} + ) + forward_function_attr.update(common_attributes) + forward_function = atomic_function.from_func_graph( + forward_function_name, forward_graph, forward_function_attr + ) + return forward_function, backward_function + + +class _DelayedRewriteGradientFunctions(object): + """Caches forward/backward functions with a delayed forward rewrite.""" + + def __init__( + self, atomic_fn: atomic_function.AtomicFunction, func_graph_deleter + ): + """Construct an inference function and initialize caches.""" + # A map from the number of forward function outputs with accepted gradients + # to forward and backward functions, used to cache non-tape backward + # function generation. + self._cached_function_pairs = {} + self._func_graph = atomic_fn.graph + self._inference_function = atomic_fn + self._attrs = atomic_fn.attributes + self._gradient_name = None + # Note that the FuncGraph is mutated later, so we need to inspect it now to + # figure out the user-specified outputs of the inference function. + self._num_inference_outputs = len(self._func_graph.outputs) + self._func_graph_deleter = func_graph_deleter + + def forward_backward(self, num_doutputs=None): + """A possibly-cached pair of forward and backward functions.""" + if num_doutputs is None: + num_doutputs = self._num_inference_outputs + forward_backward = self._cached_function_pairs.get(num_doutputs) + if forward_backward is not None: + return forward_backward + forward, backward = self._construct_forward_backward(num_doutputs) + self._cached_function_pairs[num_doutputs] = (forward, backward) + return forward, backward + + def _construct_forward_backward(self, num_doutputs): + """Constructs a pair of forward and backward functions. + + Args: + num_doutputs: The constructed backprop function will take output gradients + for the first `num_doutputs` outputs of the forward function. Defaults + to the number of outputs for the inference function, but when + higher-order gradients are computed this will increase to include side + outputs. + + Returns: + A pair of (forward_function, backward_function): + forward_function: A re-generated inference function (an + AtomicFunction) to account for new side outputs, if any extra + were required when building the backward pass. + backward_function: A ConcreteFunction that Takes `num_doutputs` + arguments and returns gradients with respect to inputs of the forward + function. + """ + trainable_outputs = [ + output for output in self._func_graph.outputs[:num_doutputs] + if backprop_util.IsTrainable(output)] + + signature = [] + for t in trainable_outputs: + signature.append( + tensor_lib.TensorSpec(*default_gradient.shape_and_dtype(t))) + + def _backprop_function(*grad_ys): + with ops.device(None): + return gradients_util._GradientsHelper( # pylint: disable=protected-access + trainable_outputs, + self._func_graph.inputs, + grad_ys=grad_ys, + src_graph=self._func_graph) + + with self._func_graph.as_default(): + backwards_graph = func_graph_module.FuncGraph( + _backward_name(self._func_graph.name)) + func_graph_module.func_graph_from_py_func( + name=backwards_graph.name, + python_func=_backprop_function, + args=[], kwargs={}, + signature=signature, + func_graph=backwards_graph) + backwards_graph_captures = backwards_graph.external_captures + captures_from_forward = [ + c for c in backwards_graph_captures if + not isinstance(c, ops.EagerTensor) and c.graph is self._func_graph] + + existing_outputs = object_identity.ObjectIdentitySet( + self._func_graph.outputs) + for capture in captures_from_forward: + if capture not in existing_outputs: + existing_outputs.add(capture) + self._func_graph.outputs.append(capture) + + forward_function, backward_function = _create_forward_backward_with_graph( + self._attrs, self._func_graph, backwards_graph) + return forward_function, backward_function + + def _rewrite_forward_and_call_backward(self, op: ops.Operation, *doutputs): + """Add outputs to the forward call and feed them to the grad function.""" + forward_function, backwards_function = self.forward_backward(len(doutputs)) + if not backwards_function.outputs: + return backwards_function.structured_outputs + + op.graph._add_function_recursive(forward_function) # pylint: disable=protected-access + + # pylint: disable=protected-access + # Rewrite an inference call op to be a forward call op + op._set_func_attr("f", forward_function.name) + op._set_type_list_attr( + "Tout", + [ + o.dtype.as_datatype_enum + for o in forward_function.function_type.flat_outputs + ], + ) + truncated_outputs = forward_function.function_type.flat_outputs[ + len(op.outputs) : + ] + op._add_outputs( + [o.dtype.as_datatype_enum for o in truncated_outputs], + [o.shape for o in truncated_outputs], + ) + for i in range(len(op.outputs)): + output_type = forward_function.function_type.flat_outputs[i] + handle_data = output_type.dtype._handle_data + if handle_data: + handle_data_util.set_handle_data( + op.outputs[i], handle_data.shape_inference + ) + # pylint: enable=protected-access + + capture_mapping = dict( + zip((ops.tensor_id(t) for t in self._func_graph.outputs), op.outputs)) + remapped_captures = [ + capture_mapping.get(ops.tensor_id(capture), capture) + for capture in backwards_function.captured_inputs + ] + + # Replace Nones with zeros since we're calling a graph function which + # expects numeric inputs. + cleaned_doutputs = [] + for doutput, placeholder in zip(doutputs, self._func_graph.outputs): + if backprop_util.IsTrainable(placeholder): + if isinstance(doutput, indexed_slices.IndexedSlices): + # Gradient passed to a backward ConcreteFunction must be tf.Tensor, + # so we convert tf.IndexedSlices to tf.Tensor. + cleaned_doutputs.append(ops.convert_to_tensor(doutput)) + elif doutput is not None: + cleaned_doutputs.append(doutput) + else: + cleaned_doutputs.append(default_gradient.zeros_like(placeholder)) + + # Compute the gradients using the side outputs + return backwards_function._call_flat( # pylint: disable=protected-access + cleaned_doutputs, remapped_captures) + + def get_gradient_function(self): + """Returns gradient function. + + The gradient rewrites an inference call op to a forward call op, but does + not modify a pre-existing forward call op. It then computes the gradient + from the output's gradients and the side outputs of the forward op. + """ + return self._rewrite_forward_and_call_backward + + def forward(self, inference_args=None, input_tangents=None): + """A forward function with only user-specified outputs. + + The call operation for the returned inference function can be rewritten into + a forward function. This only happens if the backward function (from the + `backward` method) ends up being used to compute gradients. + + This approach avoids constructing unnecessary graphs, but it only works if + we are calling this function when not executing eagerly. + + Args: + inference_args: A flat list of Tensors, arguments to the inference + function. Unused, but taken for compatibility with + _TapeGradientFunctions. + input_tangents: A flat list of Tensors, jvps associated with + `inference_args`. Unused; if required, tape functions must be used + instead. + + Returns: + An atomic_function.AtomicFunction. + """ + del inference_args # unused + if input_tangents: + # This class does not support special-cased forwardprop. The arguments are + # here for compatibility with _TapeGradientFunctions. + raise errors.InternalError("unexpectedly got forwardprop information in " + "a class that does not support forwardprop.") + return self._inference_function + + def _backward(self, outputs): + """Fetch a backward function for `outputs` from the forward function.""" + def _backward_function(*args): + call_op = outputs[0].op + return self._rewrite_forward_and_call_backward(call_op, *args) + return _backward_function, outputs + + def record(self, flat_outputs, inference_args, input_tangents): + """Record the function call operation. + + _DelayedRewriteGradientFunctions supports only first-order backprop tape + gradients (and then only when graph building). It does not work with + higher-order tape gradients or forward autodiff, but does work with + higher-order symbolic gradients (tf.gradients). + + Args: + flat_outputs: The result of running `forward`. + inference_args: A flat list of Tensors with inference inputs to the + operation. + input_tangents: A flat list of Tensors with input tangents consumed by the + operation. + """ + backward_function, to_record = self._backward(flat_outputs) + record.record_operation( + self._inference_function.cached_definition.signature.name, + to_record, + inference_args + input_tangents, + backward_function, + ) + + +# Contains information about a forward function wrapped to compute jvps. +_ForwardWrapper = collections.namedtuple( + "_ForwardWrapper", ( + # The wrapper Graph. + "graph", + # A flat list of non-tangent Tensor outputs from the wrapped forward + # function. + "outputs", + # Indices for output tangents, same format as + # forwardprop_util.pack_tangents. + "output_indices", + # A flat list of tangents for `outputs`. + "output_tangents")) + + +class _TapeGradientFunctions(object): + """Caches forward and backward functions compatible with eager gradients. + + In contrast to the delayed-rewrite approach in + `_DelayedRewriteGradientFunctions` which only works with delayed execution, + the forward function generated by this class has a fixed set of outputs which + may be preserved by a tape in order to compute gradients later. + + This class is abstract; its child classes differ in how many side outputs of + the forward function their backward function accepts gradients for, which + determines whether higher-order tape gradients are possible. + """ + + def __init__( + self, + func_graph: func_graph_module.FuncGraph, + attrs, + func_graph_deleter, + forwardprop_input_indices, + delayed_rewrite_functions, + need_gradients_for_jvps, + ): + self._func_graph = func_graph + self._forward_graph = None + self._attrs = attrs + self._forward = None + self._backward = None + self._num_outputs = len(func_graph.outputs) + self._func_graph_deleter = func_graph_deleter + self._forwardprop_input_indices = forwardprop_input_indices + self._forwardprop_output_indices = None + self._num_forwardprop_outputs = 0 + self._num_inference_outputs = len(func_graph.outputs) + self._num_trainable_inference_outputs = len( + [t for t in func_graph.outputs if backprop_util.IsTrainable(t)]) + self._delayed_rewrite_functions = delayed_rewrite_functions + self._need_gradients_for_jvps = need_gradients_for_jvps + + def _build_functions_for_outputs( + self, outputs, inference_args, input_tangents): + """Forward+backward functions where the backward function sees `outputs`.""" + # First figure out which of `outputs` are trainable. We'll accept gradients + # for each of these in the backward function. + trainable_outputs = [] + trainable_indices = [] + for index, output in enumerate(outputs): + + if backprop_util.IsTrainable(output): + trainable_outputs.append(output) + trainable_indices.append(index) + + backwards_graph = func_graph_module.FuncGraph( + _backward_name(self._func_graph.name)) + with backwards_graph.as_default(): + gradients_wrt_outputs = [] + for output in trainable_outputs: + gradient_shape, gradient_dtype = default_gradient.shape_and_dtype( + output) + gradient_placeholder = graph_placeholder(gradient_dtype, gradient_shape) + handle_data_util.copy_handle_data(output, gradient_placeholder) + gradients_wrt_outputs.append(gradient_placeholder) + with ops.device(None): + gradients_wrt_inputs = gradients_util._GradientsHelper( # pylint: disable=protected-access + trainable_outputs, + self._func_graph.inputs, + grad_ys=gradients_wrt_outputs, + src_graph=self._func_graph) + + if input_tangents: + # Convert IndexedSlices to dense tensors (as we do elsewhere for + # function gradients). Our C++ bindings don't know how to handle them + # currently. + gradients_wrt_inputs = nest.map_structure( + lambda x: ops.convert_to_tensor(x) if x is not None else None, + gradients_wrt_inputs) + captures_from_forward = [ + c for c in backwards_graph.external_captures + if not isinstance(c, ops.EagerTensor) and c.graph is self._func_graph + ] + existing_outputs = object_identity.ObjectIdentitySet( + self._func_graph.outputs) + for capture in captures_from_forward: + if capture not in existing_outputs: + existing_outputs.add(capture) + self._func_graph.outputs.append(capture) + + # The ordering of `backwards_graph.inputs` is important: inputs of + # `backward_function` correspond to outputs (including + # side outputs) of `self._tape_forward_function`. + backwards_graph.inputs = ( + gradients_wrt_outputs + backwards_graph.internal_captures) + backwards_graph.outputs.extend( + grad + for grad in nest.flatten(gradients_wrt_inputs, expand_composites=True) + if grad is not None) + backwards_graph.structured_outputs = gradients_wrt_inputs + + forward_function, backward_function = _create_forward_backward_with_graph( + self._attrs, self._func_graph, backwards_graph) + + if not input_tangents: + # There is no need to special-case forwardprop, so we can return the + # forward+backward pair we've created without further wrapping. + return (forward_function, self._func_graph, backward_function, + # No forwardprop outputs. + None, 0) + forward_wrapper = self._wrap_forward_function_with_jvps( + forward_function, backward_function, inference_args, input_tangents) + (wrapped_backwards_graph, + forward_wrapper) = self._wrap_backward_function_with_jvp_backprop( + backward_function, gradients_wrt_outputs, forward_wrapper) + # Now that we've added new captures, we need to make sure forward outputs + # are in the same order the backward function expects them to be in: + # [inference outputs] + [jvps] + [side outputs] + [captures]. + forward_wrapper = self._shuffle_forward_outputs(forward_wrapper) + (wrapped_forward_function, + wrapped_backward_function) = _create_forward_backward_with_graph( + self._attrs, forward_wrapper.graph, wrapped_backwards_graph) + if (len(inference_args) + len(input_tangents) + != len(forward_wrapper.graph.inputs)): + raise errors.InternalError( + f"The forward graph had {len(forward_wrapper.graph.inputs)} inputs, " + f"but we expected {len(inference_args) + len(input_tangents)} " + f"({len(inference_args)} inference inputs and " + f"{len(input_tangents)} input tangents).") + return (wrapped_forward_function, forward_wrapper.graph, + wrapped_backward_function, forward_wrapper.output_indices, + len(forward_wrapper.output_tangents)) + + def _wrap_forward_function_with_jvps( + self, forward_function, backward_function, + inference_args, input_tangents): + """Adds inline JVP computation to a forward function.""" + forward_wrapper_graph = func_graph_module.FuncGraph( + _forward_name(self._func_graph.name)) + with forward_wrapper_graph.as_default(): + # Tell forward accumulators to free up space for new JVP computations, + # since one may be in the process of computing a JVP (if that computation + # triggered this function building). + # + # We'll make symbolic versions of input JVPs, run the forward function + # under forward accumulators to get symbolic output JVPs, then set those + # as outputs of the new wrapped forward function. + with forwardprop_util.push_forwardprop_state(): + forward_captures = { + ops.tensor_id(internal): external + for external, internal in self._func_graph.captures} + for input_index, real_input in enumerate(self._func_graph.inputs): + # This loop is more or less equivalent to running tf.identity on each + # of self._func_graph.inputs. However, doing that also captures jvps + # for resource handles, which confuses the jvp capturing code below + # (since primal inputs are interwoven with jvp inputs). + input_placeholder = array_ops.placeholder( + dtype=real_input.dtype, + shape=real_input.shape) + capture = forward_captures.get(ops.tensor_id(real_input)) + if capture is not None: + forward_wrapper_graph.add_capture(capture, input_placeholder) + if capture.dtype == dtypes.resource: + handle_data_util.copy_handle_data(capture, input_placeholder) + else: + forward_wrapper_graph.inputs.append(input_placeholder) + for inp, arg in zip(forward_wrapper_graph.inputs, inference_args): + record.record_operation( + "captured_value", [inp], [arg], + backward_function=lambda x: [x], + forward_function=lambda x: [x]) + num_inference_inputs = len(inference_args) + for tape_indices in self._forwardprop_input_indices: + for input_index, jvp_index in tape_indices: + input_placeholder = forward_wrapper_graph.inputs[input_index] + if len(forward_wrapper_graph.inputs) != jvp_index: + raise errors.InternalError( + f"Expected {jvp_index} forward graph inputs, " + f"got {len(forward_wrapper_graph.inputs)}.") + gradient_shape, gradient_dtype = default_gradient.shape_and_dtype( + input_placeholder) + jvp_placeholder = graph_placeholder(gradient_dtype, gradient_shape) + external_jvp = input_tangents[jvp_index - num_inference_inputs] + forward_wrapper_graph.add_capture(external_jvp, jvp_placeholder) + tensor_shape.TensorShape( + external_jvp.shape).assert_is_compatible_with( + jvp_placeholder.shape) + record.record_operation( + "captured_value", + [jvp_placeholder], + [external_jvp], + backward_function=lambda x: [x], + forward_function=lambda x: [x]) + forward_inputs = forward_wrapper_graph.inputs[:num_inference_inputs] + gradient_function = ( + self._delayed_rewrite_functions._rewrite_forward_and_call_backward) # pylint: disable=protected-access + with ops.get_default_graph()._override_gradient_function( # pylint: disable=protected-access + {"PartitionedCall": gradient_function, + "StatefulPartitionedCall": gradient_function}): + forward_outputs = forward_function.call_flat(*forward_inputs) + if isinstance(forward_outputs, ops.Operation): + # _wrapped_backward_function expects a list, but if the function has + # no outputs its call() returns an Operation. We need to undo that + # so we don't cause problems later. + forward_outputs = [] + py_backward, _ = self._wrap_backward_function( + self._func_graph, backward_function, forward_outputs) + # We will never request backward tape gradients for this operation + # directly since we're wrapping the call; forwardprop will call the + # backward function (and nested forward accumulators may build + # higher-order gradients), but any watching GradientTapes should ignore + # it. + # + # TODO(allenl): It might be better to explicitly stop backward recording + # so we don't use the second-order tape cases unnecessarily. + record.record_operation_forwardprop_only( + forward_function.cached_definition.signature.name, + forward_outputs, forward_inputs, py_backward, None) + output_indices, output_tangents = ( + pywrap_tfe.TFE_Py_PackJVPs(forward_outputs)) + output_tangents = [forward_wrapper_graph.capture(t) + for t in output_tangents] + return _ForwardWrapper( + graph=forward_wrapper_graph, outputs=forward_outputs, + output_indices=output_indices, output_tangents=output_tangents) + + def _wrap_backward_function_with_jvp_backprop( + self, backward_function, gradients_wrt_outputs, forward_wrapper): + """Wraps `backward_function` to include gradients for JVPs.""" + wrapped_backwards_graph = func_graph_module.FuncGraph( + _backward_name(self._func_graph.name)) + with wrapped_backwards_graph.as_default(): + py_backward, recorded_outputs = self._wrap_backward_function( + self._func_graph, backward_function, forward_wrapper.outputs) + trainable_index = 0 + forward_doutputs = [] + doutput_args = [] + for output in recorded_outputs: + if backprop_util.IsTrainable(output): + doutput = gradients_wrt_outputs[trainable_index] + doutput_placeholder = graph_placeholder(doutput.dtype, doutput.shape) + doutput_args.append(doutput_placeholder) + forward_doutputs.append(doutput_placeholder) + trainable_index += 1 + else: + doutput_args.append(None) + + dinputs = py_backward(*doutput_args) + existing_outputs = object_identity.ObjectIdentitySet( + forward_wrapper.outputs + forward_wrapper.output_tangents) + num_processed_output_tangents = 0 + gradients_wrt_output_tangents = [] + tangent_doutputs = [] + output_tangents = forward_wrapper.output_tangents + output_indices = forward_wrapper.output_indices + if self._need_gradients_for_jvps: + # TODO(allenl): Consider using a throwaway graph to avoid extra gradient + # evaluations; gradients for jvps may have common subgraphs. + while num_processed_output_tangents != len(output_tangents): + for output in output_tangents[num_processed_output_tangents:]: + gradient_shape, gradient_dtype = default_gradient.shape_and_dtype( + output) + placeholder = graph_placeholder(gradient_dtype, gradient_shape) + gradients_wrt_output_tangents.append(placeholder) + tangent_doutputs.append(placeholder) + num_processed_output_tangents = len(output_tangents) + with ops.device(None): + gradients_wrt_inputs = gradients_util._GradientsHelper( # pylint: disable=protected-access + output_tangents, + forward_wrapper.graph.inputs, + grad_ys=gradients_wrt_output_tangents, + src_graph=forward_wrapper.graph) + dinputs = [ + backprop_util.AggregateIndexedSlicesGradients((existing, new)) + for existing, new in zip(dinputs, gradients_wrt_inputs) + if existing is not None or new is not None] + dinputs.extend(gradients_wrt_inputs[len(dinputs):]) + captures_from_forward = [ + c for c in wrapped_backwards_graph.external_captures + if (not isinstance(c, ops.EagerTensor) + and c.graph is forward_wrapper.graph)] + for capture in captures_from_forward: + if capture not in existing_outputs: + existing_outputs.add(capture) + forward_wrapper.outputs.append(capture) + output_indices, output_tangents = ( + forwardprop_util.pack_tangents(forward_wrapper.outputs)) + output_tangents = [forward_wrapper.graph.capture(t) + for t in output_tangents] + for t in output_tangents: + existing_outputs.add(t) + wrapped_backwards_graph.inputs = ( + forward_doutputs[:self._num_trainable_inference_outputs] + + tangent_doutputs + + forward_doutputs[self._num_trainable_inference_outputs:] + + wrapped_backwards_graph.internal_captures) + wrapped_backwards_graph.structured_outputs = dinputs + wrapped_backwards_graph.outputs = [t for t in dinputs if t is not None] + return (wrapped_backwards_graph, + forward_wrapper._replace(output_indices=output_indices, + output_tangents=output_tangents)) + + def _shuffle_forward_outputs(self, forward_wrapper): + """Reorders function outputs so captures are last.""" + def _index_map(original): + if original < self._num_inference_outputs: + return original + if original >= len(forward_wrapper.outputs): + return (original - len(forward_wrapper.outputs) + + self._num_inference_outputs) + return original + len(forward_wrapper.output_tangents) + output_indices = nest.map_structure( + _index_map, forward_wrapper.output_indices) + forward_wrapper.graph.outputs = ( + forward_wrapper.outputs[:self._num_inference_outputs] + + forward_wrapper.output_tangents + + forward_wrapper.outputs[self._num_inference_outputs:]) + return forward_wrapper._replace(output_indices=output_indices) + + def forward(self, inference_args, input_tangents): + """Construct or fetch a forward function with side-outputs. + + When graph building without a tape active, symbolic gradients rely on + regenerating the backward function for higher-order gradients (to account + for new side outputs of the rewritten forward function call). Thus there is + no fixed backward function for this case. However, when a tape is active + (eager or graph building), we generate fixed backward and forward functions + at forward function call time. + + This difference between the tape and non-tape cases is to avoid building + unneeded backward functions while graph building (where we may or may not + eventually need gradients). + + Args: + inference_args: A flat list of Tensors, arguments to the inference + function. + input_tangents: A flat list of Tensors, jvps associated with + `inference_args`. + + Returns: + A forward atomic_function.AtomicFunction. + """ + if self._forward is None: + ( + self._forward, + self._forward_graph, + self._backward, + self._forwardprop_output_indices, + self._num_forwardprop_outputs, + ) = self._forward_and_backward_functions(inference_args, input_tangents) + return self._forward + + def _wrap_backward_function( + self, forward_graph: func_graph_module.FuncGraph, backward, outputs + ): + """Create a backward function given `outputs` from the forward function.""" + capture_mapping = dict( + zip((ops.tensor_id(t) for t in forward_graph.outputs), outputs) + ) + captured_inputs = backward.captured_inputs + remapped_captures = [ + capture_mapping.get(ops.tensor_id(capture), capture) + for capture in captured_inputs + ] + if any( + t.graph is forward_graph + for t in remapped_captures + if not isinstance(t, ops.EagerTensor) + ): + incorrect_mapping = [ + t + for t in remapped_captures + if ( + not isinstance(t, ops.EagerTensor) + and t.graph is not forward_graph + ) + ] + raise errors.InternalError( + "Failed to map all backward graph captures to " + "the forward graph. Incorrectly mapped: " + f"{incorrect_mapping}." + ) + # We may need to use zeros_like to get a zero for variant Tensors with + # unconnected gradients. We do that in advance so we don't have to hold on + # to the outputs themselves, which may not be needed otherwise. + variant_zeros_like = {} + backward_function_inputs = len(backward.inputs) - len(captured_inputs) + recorded_outputs = [] + trainable_recorded_outputs = 0 + skip_positions = [] + if self._num_forwardprop_outputs and not self._need_gradients_for_jvps: + relevant_outputs = ( + outputs[: self._num_inference_outputs] + + outputs[ + self._num_inference_outputs + self._num_forwardprop_outputs : + ] + ) + else: + relevant_outputs = outputs + for output_index, output in enumerate(relevant_outputs): + if trainable_recorded_outputs < backward_function_inputs: + recorded_outputs.append(output) + if backprop_util.IsTrainable(output): + trainable_recorded_outputs += 1 + else: + skip_positions.append(output_index) + if output.dtype == dtypes.variant: + variant_zeros_like[output_index] = default_gradient.zeros_like(output) + + def _backward_function_wrapper(*args): + """Process output gradients and call the backward function.""" + if not backward.outputs: + return backward.structured_outputs + + processed_args = [] + input_index = 0 + for output_index, arg in enumerate(args): + # Convert IndexedSlices to dense tensors. The IndexedSlices optimization + # is only really effective when doing tf.gather(variable) as the + # adjoint functions for most operations are unlikely to preserve the + # sparsity in IndexedSlices. + if isinstance(arg, indexed_slices.IndexedSlices): + arg = ops.convert_to_tensor(arg) + if output_index in skip_positions: + continue + if arg is None: + # We're calling a (non-polymorphic) ConcreteFunction, so we need to + # have a Tensor value for each Tensor we thought would be trainable + # based on its dtype, even if it ended up being unconnected. + input_placeholder = backward.inputs[ + input_index] + if input_placeholder.dtype == dtypes.variant: + arg = variant_zeros_like[output_index] + else: + arg = array_ops.zeros( + *default_gradient.shape_and_dtype(input_placeholder)) + processed_args.append(arg) + input_index += 1 + if input_index >= backward_function_inputs: + break + return backward._call_flat( # pylint: disable=protected-access + processed_args, remapped_captures) + + return _backward_function_wrapper, recorded_outputs + + def record(self, flat_outputs, inference_args, input_tangents): + """Record the function call operation. + + For backprop, indicates the backward function to use and which new Tensors + must be watched. For forwardprop from eager, the function call itself will + have produced tangents which need to be recorded. + + Args: + flat_outputs: The result of running `forward`. + inference_args: A flat list of Tensors with inference inputs to the + operation. + input_tangents: A flat list of Tensors with input tangents consumed by the + operation. + """ + backward_function, to_record = self._wrap_backward_function( + self._forward_graph, self._backward, flat_outputs + ) + if self._forwardprop_output_indices: + record.record_operation_backprop_only( + self._forward.cached_definition.signature.name, + to_record, + inference_args, + backward_function, + ) + record.record_operation_forwardprop_only( + self._forward.cached_definition.signature.name, + flat_outputs, + inference_args + input_tangents, + backward_function, + self._forwardprop_output_indices, + ) + else: + record.record_operation( + self._forward.cached_definition.signature.name, + to_record, + inference_args + input_tangents, + backward_function, + ) + + +class _FirstOrderTapeGradientFunctions(_TapeGradientFunctions): + """Caches tape-friendly functions for first-order gradients.""" + + def __init__( + self, + func_graph: func_graph_module.FuncGraph, + attrs, + func_graph_deleter, + forwardprop_input_indices, + delayed_rewrite_functions, + need_gradients_for_jvps, + ): + super().__init__( + func_graph, + attrs, + func_graph_deleter, + forwardprop_input_indices, + delayed_rewrite_functions, + need_gradients_for_jvps, + ) + self._func_graph_deleter = func_graph_deleter + self._forwardprop_input_indices = forwardprop_input_indices + + def _forward_and_backward_functions(self, inference_args, input_tangents): + """Shortcut for when only first-order gradients are required. + + The returned backward function does not accept gradients with respect to + side output of forward_function. This is fine as long as the user can't + possibly request second order tape gradients, as when they've used a single + non-persistent GradientTape. Since we don't need the backward function to + take gradients with respect to side outputs, we can skip some potentially + slow graph building. + + Args: + inference_args: A flat list of Tensors, arguments to the inference + function. + input_tangents: A flat list of Tensors, jvps associated with + `inference_args`. + + Returns: + A tuple of (forward_function, backward_function): + forward_function: Takes the same inputs as the inference function, but + returns side outputs used by backward_function in addition to the + inference function's outputs. + backward_function: Takes side outputs from forward_function and + gradients with respect to the "real" outputs of forward_function and + returns gradients with respect to the inputs. + """ + outputs = self._func_graph.outputs[:self._num_inference_outputs] + return self._build_functions_for_outputs( + outputs, inference_args, input_tangents) + + +class _HigherOrderTapeGradientFunctions(_TapeGradientFunctions): + """Caches tape-friendly functions for higher-order gradients.""" + + # TODO(b/136189779): Cond/while under a tape may need similar logic. Consider + # generalizing if so. + def _forward_and_backward_functions(self, inference_args, input_tangents): + """Forward and backward functions suitable for higher-order gradients. + + Unlike in `_FirstOrderTapeGradientFunctions`, the backward function built by + this method accepts gradients for all of the outputs of the returned forward + function, including side outputs. + + Args: + inference_args: A flat list of Tensors, arguments to the inference + function. + input_tangents: A flat list of Tensors, jvps associated with + `inference_args`. + + Returns: + A tuple of (forward_function, backward_function): + forward_function: Takes the same inputs as the inference function, but + returns side outputs used by backward_function in addition to the + inference function's outputs. + backward_function: Takes side outputs from forward_function and + gradients with respect to all of its outputs, real and side. Returns + gradients with respect to the inputs. + """ + outputs = [] + iteration_count = 0 + # First we need to figure out how many side outputs from the forward pass + # will be required. We do this in a temporary graph to avoid actually + # running multiple copies of the backward pass (one per _GradientsHelper + # call). + # + # While computing gradients, the backward function captures Tensors from + # the forward function. We add these as side outputs of the original + # function. However, we then need to accept output gradients with respect + # to these side outputs for higher order gradients to work. Thus we loop + # until the number of outputs of the function stabilizes. Note that this + # is only required for tape gradients, where we need to declare in advance + # all of the forward op's outputs: symbolic gradients with tf.gradients + # instead rely on regenerating backward functions when higher-order + # gradients are requested. + while (len(outputs) < len(self._func_graph.outputs) + # It's possible for gradient generation to add new ops to the forward + # pass. If all of the new outputs are non-trainable, there's no + # reason to continue. + and any(backprop_util.IsTrainable(output) + for output in self._func_graph.outputs[len(outputs):])): + iteration_count += 1 + if iteration_count >= 20 and iteration_count % 5 == 0: + new_op_with_trainable_output = None + num_new_trainable_outputs = 0 + for output in self._func_graph.outputs[len(outputs):]: + if backprop_util.IsTrainable(output): + num_new_trainable_outputs += 1 + new_op_with_trainable_output = output.op + logging.warning( + ("Determining side outputs for the function '{}' is taking longer " + "than expected ({} iterations, typically this converges in 5 or " + "so). This could indicate that a gradient registration is adding " + "new ops to the forward pass every time gradients are generated. " + "{} new trainable output(s) were added this iteration, one from " + "the following op:\n {}\nThis may indicate a TensorFlow bug, or " + "an issue in a tf.custom_gradient.") + .format( + self._func_graph.name, iteration_count, + num_new_trainable_outputs, new_op_with_trainable_output)) + outputs = list(self._func_graph.outputs) + self._build_functions_for_outputs( + outputs, inference_args, input_tangents) + + (forward_function, forward_graph, + backward_function, output_indices, num_output_tangents) = ( + self._build_functions_for_outputs( + outputs, inference_args, input_tangents)) + if (len(self._func_graph.outputs) > len(outputs) + and any(backprop_util.IsTrainable(output) + for output in self._func_graph.outputs[len(outputs):])): + raise errors.InternalError( + "Unexpectedly added new outputs to the forward function when " + "building the backward function: " + f"{self._func_graph.outputs[len(outputs):]}.") + return (forward_function, forward_graph, backward_function, output_indices, + num_output_tangents) + + +class _ForwardBackwardCall(object): + """Holds the state of a function call between execution and recording.""" + + __slots__ = [ + "_functions", "_inference_args", "_input_tangents", "_tape_watching" + ] + + def __init__(self, functions, inference_args, input_tangents, tape_watching): + """Collects information about the function call. + + Args: + functions: An object which produces forward and backward functions, either + a _DelayedRewriteGradientFunctions or a _TapeGradientFunctions object. + inference_args: A flat list of Tensors, arguments to the inference + function. + input_tangents: A flat list of Tensors, jvps associated with + `inference_args`. + tape_watching: Boolean, with True indicating that recording is necessary. + """ + self._functions = functions + self._inference_args = inference_args + self._input_tangents = input_tangents + self._tape_watching = tape_watching + + def forward(self): + """Builds or retrieves a forward function for this call.""" + forward_function = self._functions.forward( + self._inference_args, self._input_tangents + ) + return forward_function, self._inference_args + self._input_tangents + + def record(self, flat_outputs): + """Given outputs from the execution of `forward`, records the operation.""" + if ( + self._tape_watching + and not isinstance(flat_outputs, ops.Operation) + and flat_outputs is not None + ): + # We only record function calls which have outputs, and then only when a + # tape is watching. + self._functions.record( + flat_outputs, self._inference_args, self._input_tangents + ) + + +class ConcreteFunction(core.ConcreteFunction, trackable.Trackable): + """A `tf.types.experimental.ConcreteFunction` created from `tf.function`.""" + + def __init__( + self, atomic_fn: atomic_function.AtomicFunction, shared_func_graph=True + ): + """Initialize a `ConcreteFunction`. + + Args: + atomic_fn: Inference atomic function to form basis of forward pass. + shared_func_graph: If False, the ConcreteFunction takes ownership of + `func_graph` and will break reference cycles when it is deleted. This + makes the FuncGraph inoperable. + + Raises: + ValueError: If number of input_placeholders is not equal to the number + of function inputs. + """ + # _arg_keywords and _num_positional_args define the flat signature. They + # are assigned after construction. + self._arg_keywords = None + self._num_positional_args = None + + self._func_graph = atomic_fn.graph + self._captured_inputs = ( + self._func_graph.external_captures + + self._func_graph.deferred_external_captures + ) + self._function_type = atomic_fn.function_type + + self._output_shapes = tuple( + output.shape for output in self._func_graph.outputs) + self._attrs = attributes_lib.parse_func_attrs( + atomic_fn.attributes or {} + ) + + if shared_func_graph: + self._garbage_collector = None + else: + self._garbage_collector = ConcreteFunctionGarbageCollector( + atomic_fn.graph + ) + + # Pairs of forward and backward functions used for computing gradients. + # + # These each get a reference to the FuncGraph deleter since they use the + # FuncGraph directly. + self._delayed_rewrite_functions = _DelayedRewriteGradientFunctions( + atomic_fn, self._garbage_collector) + self._first_order_tape_functions = {} + self._higher_order_tape_functions = {} + # Cache the inference function to avoid a (Python) function call when not + # building gradients. + self._inference_function = self._delayed_rewrite_functions.forward() + + @classmethod + def from_func_graph(cls, graph, function_type, attrs, shared_func_graph=True): + atomic_fn = atomic_function.from_func_graph( + _inference_name(graph.name), graph, attrs, function_type + ) + return ConcreteFunction(atomic_fn, shared_func_graph=shared_func_graph) + + @property + def function_type(self): + """Return the FunctionType associated with this ConcreteFunction.""" + return self._function_type + + @property + def inference_fn(self): + """Return the inference function associated with this ConcreteFunction.""" + return self._inference_function + + # TODO(fmuham): Remove this property. + @property + def _function_spec(self): + if self.function_type is None: + return None + + return function_type_utils.FunctionSpec( + self.function_type, + { + p.default + for p in self.function_type.parameters.values() + if p.optional + }, + False, + name=self.name, + ) + + @property + def variables(self): + """Sequence of variables for this function.""" + return tuple(self._func_graph.variables) + + def set_variables(self, variables): + self._func_graph.variables = variables + + @property + def trainable_variables(self): + """Sequence of trainable variables for this function.""" + return tuple(self._func_graph.trainable_variables) + + def __call__(self, *args, **kwargs): + """Executes the wrapped function. + + ConcreteFunctions have two signatures: + + * The signature of the original function wrapped by this ConcreteFunction. + * A flat signature, where each argument accepts a single Tensor. + + The original function signature is generally preferred, but the flat input + signature is supported for backward compatibility. + + ### Original Function Signature + + When calling a ConcreteFunction with the signature of the original function, + each argument must match the type or value that was used when the + ConcreteFunction's graph was traced. In particular: + + * Tensor arguments (including CompositeTensors, such as RaggedTensor) must + have matching `TypeSpec`s. + * Non-Tensor arguments (such as booleans or ints) must have equal values. + * Nested arguments (such as lists, tuples, or dictionaries) must have the + same nesting structure; and each nested value must have a matching type + or value. + + The default value for any arguments that were traced with non-Tensor values + is the value that was used in the trace. Arguments that were traced with + tensor arguments do not have a default value (even if the original function + had a default value for that argument). + + ### Flat Signature + + When calling a ConcreteFunction with the flat signature, the arguments + correspond to the flattened component tensors of the arguments that were + used to construct the ConcreteFunction. Parameter names are assigned based + on `TensorSpec.name` (when specified) or the original argument names (with + suffixes automatically added for nested arguments or composite tensors with + multiple components). + + Args: + *args: Positional arguments to the concrete function. + **kwargs: Keyword arguments to the concrete function. + + Returns: + The result of applying the TF function on the given Tensors. + + Raises: + AssertionError: If this `ConcreteFunction` was not created through + `get_concrete_function`. + TypeError: If the arguments do not match the function's signature. + """ + return self._call_impl(args, kwargs) + + def _call_impl(self, args, kwargs): + """See `__call__` for details.""" + with trace.Trace(self._func_graph.name, tf_function_call="concrete"): + # Construct the list of input tensors: check if the structured signature + # applies first; and if not, then use the flat signature. + if self.function_type is not None: + try: + return self._call_with_structured_signature(args, kwargs) + except TypeError as structured_err: + try: + return self._call_with_flat_signature(args, kwargs) + except (TypeError, ValueError) as flat_err: + raise TypeError( # pylint: disable=raise-missing-from + str(structured_err) + + "\nFallback to flat signature also failed due to: " + + str(flat_err) + ) + + return self._call_with_flat_signature(args, kwargs) + + def _call_with_flat_signature(self, args, kwargs): + """Executes the wrapped function with the flat signature. + + Args: + args: Positional arguments to the concrete function. + kwargs: Keyword arguments to the concrete function. + + Returns: + The result of applying the function on the Tensors/Variables contained in + `args` and `kwargs`. + Raises: + TypeError: if `args` and `kwargs` do not match the flat signature of this + `ConcreteFunction`. + """ + if len(args) > self._num_positional_args: + raise TypeError( + f"{self._flat_signature_summary()} takes {self._num_positional_args} " + f"positional arguments, got {len(args)}.") + args = list(args) + kwargs = dict(kwargs) + kwargs = { + function_type_lib.sanitize_arg_name(k): v for k, v in kwargs.items() + } + for keyword in self._arg_keywords[len(args):]: + try: + args.append( + kwargs.pop( + function_type_lib.sanitize_arg_name(compat.as_str(keyword)))) + except KeyError: + specified_keywords = ( + list(self._arg_keywords[:len(args)]) + list(kwargs.keys())) + missing_required_args = sorted( + set(self._arg_keywords) - set(specified_keywords)) + raise TypeError(f"{self._flat_signature_summary()} missing required " + f"arguments: {', '.join(missing_required_args)}.") + if kwargs: + positional_arg_keywords = set(self._arg_keywords[:len(args)]) + for unused_key in kwargs: + if unused_key in positional_arg_keywords: + raise TypeError(f"{self._flat_signature_summary()} got two values " + f"for '{unused_key}'.") + raise TypeError(f"{self._flat_signature_summary()} got unexpected " + f"keyword arguments: {', '.join(sorted(kwargs))}.") + + for i, arg in enumerate(args): + if not isinstance( + arg, (tensor_lib.Tensor, resource_variable_ops.BaseResourceVariable)): + raise TypeError(f"{self._flat_signature_summary()}: expected argument " + f"#{i}(zero-based) to be a Tensor; " + f"got {type(arg).__name__} ({arg}).") + return self._call_flat(args, self.captured_inputs) + + def _call_with_structured_signature(self, args, kwargs): + """Executes the wrapped function with the structured signature. + + Args: + args: Positional arguments to the concrete function. + kwargs: Keyword arguments to the concrete function. + + Returns: + The result of applying the function on the Tensors/Variables contained in + `args` and `kwargs`. + Raises: + TypeError: if `args` and `kwargs` do not match the structured signature + of this `ConcreteFunction`. + """ + bound_args = ( + function_type_utils.canonicalize_function_inputs( + args, kwargs, self.function_type) + ) + filtered_flat_args = self.function_type.unpack_inputs(bound_args) + return self._call_flat( + filtered_flat_args, + captured_inputs=self.captured_inputs) + + def _call_flat(self, tensor_inputs, captured_inputs): + """Executes the wrapped function. + + Args: + tensor_inputs: a list of only Tensors generated from args, kwargs. + captured_inputs: the captured inputs that are also part of the input args + to the actual execution. By default, it should be self._captured_inputs. + Returns: + The result of applying the TF function to `args`. + + Raises: + ValueError: If `args` contains anything other than Tensors or Variables. + """ + ctx = context.context() + executing_eagerly = ctx.executing_eagerly() + + # Copy saveable status of function's graph to current FuncGraph. + default_graph = ops.get_default_graph() + if default_graph.building_function and not self._func_graph.saveable: + default_graph.mark_as_unsaveable(self._func_graph.saving_errors) + + if (record.could_possibly_record() or + hasattr(default_graph, "watch_variable")): + for v in self._func_graph.variables: + resource_variable_ops.variable_accessed(v) + + # TODO(fmuham): check in eager mode too. + if not executing_eagerly: + for i, tensor_input in enumerate(tensor_inputs): + # Can not compare shapes in these cases + # TODO(b/216506654): Consider moving this check elsewhere and making it + # work for all types (e.g. by including shape for Variables). + if (tensor_input.dtype == dtypes.resource or + tensor_input.dtype == dtypes.variant): + continue + + # If we're graph building, shape inference is on. We check for input + # compatibility up front to avoid hard to debug incompatibilities + # later. + graph_input_shape = tensor_shape.TensorShape( + self._func_graph.inputs[i].shape) + if not graph_input_shape.is_compatible_with(tensor_input.shape): + raise ValueError( + f"Tensor {tensor_input} is not compatible with the shape this " + f"function was traced with. Expected shape " + f"{self._func_graph.inputs[i].shape}, but got shape " + f"{tensor_input.shape}.\n\nIf you called get_concrete_function, " + f"you may need to pass a tf.TensorSpec(..., shape=...) with a " + f"less specific shape, having None on axes which can vary.") + + args = tensor_inputs + captured_inputs + possible_gradient_type = gradients_util.PossibleTapeGradientTypes(args) + if (possible_gradient_type == gradients_util.POSSIBLE_GRADIENT_TYPES_NONE + and executing_eagerly): + # No tape is watching; skip to running the function. + return self._inference_function.call_preflattened(args) + forward_backward = self._select_forward_and_backward_functions( + args, + possible_gradient_type, + executing_eagerly) + forward_function, args_with_tangents = forward_backward.forward() + if executing_eagerly: + flat_outputs = forward_function.call_flat(*args_with_tangents) + else: + with default_graph._override_gradient_function( # pylint: disable=protected-access + {"PartitionedCall": self._get_gradient_function(), + "StatefulPartitionedCall": self._get_gradient_function()}): + flat_outputs = forward_function.call_flat(*args_with_tangents) + forward_backward.record(flat_outputs) + return self.function_type.pack_output(flat_outputs) + + @property + def name(self): + """`ConcreteFunction` name.""" + return self._delayed_rewrite_functions.forward().name + + @property + def graph(self): + """Returns the graph from which this function was constructed.""" + return self._func_graph + + @property + def inputs(self): + """Returns tensors in `self.graph` corresponding to arguments.""" + return self._func_graph.inputs + + @property + def structured_input_signature(self): + """Returns structured signature for this concrete function. + + Returns: + A tuple `(args, kwargs)`, where: + + * `args` is a tuple that specifies the expected type or value each for + positional argument. + * `kwargs` is a dictionary that specifies the expected type or value + for each keyword-only argument. + + The type or value for each argument is specified using one of the + following: + + * A `tf.TypeSpec`, indicating that a Tensor or other TensorFlow-native + value is expected. + * A Python value, such as an integer, indicating that an equal value + is expected. + * A nested structure of `tf.TypeSpec`s and Python values, indicating + that a corresponding nested structure is expected. + """ + return self._func_graph.structured_input_signature + + @property + def outputs(self): + """Returns tensors in `self.graph` corresponding to returned tensors.""" + return self._func_graph.outputs + + @property + def structured_outputs(self): + """Returns outputs in `self.graph` as returned by the original function.""" + return self._func_graph.structured_outputs + + def set_external_captures(self, captures): + """Updates the function capture values. + + The new values must have tensor types and shapes consistent with the + original captures of the concrete function, but it is allowed to change a + value captured with a deferred one and vice-versa. + + Args: + captures: A list of tensors or closures. Tensors are value captures, and + closures are call-time (deferred captures). + """ + # TODO(wxinyi): 1. verify that the new captures' type spec is compatible + # with the original's. However, doing so requires MirroredVariable captures + # initialized. 2. replace the original/new captures/deferred + # captures in the wrapped graph. Doing such for a capture-to-deferred + # capture replacement requires more arguments than the deferred capture + # itself, e.g. default value, spec. + self._captured_inputs = captures + + def replace_capture_with_deferred_capture(self, + tensor, + closure, + spec, + placeholder=None, + default_value=None): + """Replaces existing capture `tensor` with a deferred capture `closure`. + + This API replaces the capture `tensor` from the concrete function's captured + inputs list, and places the deferred capture `closure` in + its spot so the order of captured inputs is preserved. This is important + because the old `tensor` and the new `closure` will have the same internal + placeholder, which can be passed through the `placeholder` argument, or + skipped, in which case we find the placeholder from internal inputs by + indexing `tensor` in the external captured inputs list. Thus, it is + important that the new deferred capture has output spec (specified by the + `spec` argument) compatible with the internal placeholder (`placeholder`) + and the original capture (`tensor`). + + For example, + + ```python + bool_captured_tensor = tf.constant(True) + float_captured_tensor = tf.constant([3.], dtype=tf.float32) + value = tf.constant([2.], dtype=tf.float32) + + @tf.function + def fn(): + deferred_tensor = ops.get_default_graph().capture_call_time_value( + lambda: value, + tf.TensorSpec(shape=(1,), dtype=tf.float32)) + if bool_captured_tensor: + return deferred_tensor + else: + return deferred_tensor + float_captured_tensor + + concrete_fn = fn.get_concrete_function() + print(concrete_fn()) # tf.Tensor([2.], shape=(1,), dtype=float32) + + new_bool_captured_tensor = constant_op.constant(False) + def bool_closure(): + return new_bool_captured_tensor + + concrete_fn.replace_capture_with_deferred_capture( + bool_captured_tensor, + bool_closure, + spec=tensor_lib.TensorSpec(shape=(), dtype=dtypes.bool)) + + print(concrete_fn()) # tf.Tensor([5.], shape=(1,), dtype=float32) + ``` + + Args: + tensor: Tensor already captured. This `tensor` should be listed in + concrete_function.captured_inputs except when it's empty such as when + the concrete function is restored from SavedModel. + closure: function which takes no arguments, to be evaluated at function + call time, returning a nest of tensors compatible with `spec`. + spec: nest of TypeSpec for the value to capture. + placeholder: optional. The internal placeholder corresponding to the + captured `tensor` and the new `closure`. + default_value: optional value to use in environments that cannot safely + evaluate closure. + """ + capture_index = None + for i, capture in enumerate(self._captured_inputs): + if id(tensor) == id(capture): + capture_index = i + break + + if placeholder is None: + if capture_index is None: + raise ValueError( + f"Did not find `tensor` argument {tensor} in the ConcreteFunction's" + " captured inputs list, and did not receive a placeholder argument." + " Thus we're unable to infer the internal placeholder. ") + + placeholder = self.inputs[-len(self._captured_inputs) + capture_index] + + if not (spec.is_compatible_with(tensor) or + spec.is_compatible_with(placeholder)): + raise ValueError( + f"Attempting to substitute closure with spec {spec} that's " + f"incompatible with the original capture {tensor} or the internal " + f"placeholder {placeholder}.") + + self._func_graph.replace_capture_with_deferred_capture( + tensor=tensor, + closure=closure, + spec=spec, + placeholder=placeholder, + default_value=default_value) + + if capture_index is not None: + self._captured_inputs[capture_index] = closure + + @property + def captured_inputs(self): + """Returns external Tensors captured by this function. + + self.__call__(*args) passes `args + self.captured_inputs` to the function. + """ + return nest.flatten( + [x() if callable(x) else x for x in self._captured_inputs], + expand_composites=True) + + @property + def function_def(self): + """Returns a `FunctionDef` object representing this function.""" + return self._delayed_rewrite_functions.forward().cached_definition + + @property + def output_shapes(self): + """The function's output shapes.""" + return nest.map_structure( + lambda x: getattr(x, "shape", tensor_shape.TensorShape(None)), + composite_tensor.replace_composites_with_components( + self._func_graph.structured_outputs), + expand_composites=False) + + @property + def output_dtypes(self): + # TODO(akshayka): Consider removing this. + return nest.map_structure( + lambda x: x.dtype if x is not None else None, + composite_tensor.replace_composites_with_components( + self._func_graph.structured_outputs), + expand_composites=False) + + def add_to_graph(self, g=None, overwrite=False): + """Registers the function, adds it to the graph g or default graph. + + Args: + g: If specified, registers the function with this graph. Defaults to the + current context (either the default graph or the eager context). + overwrite: A bool. If True, its forward function will overwrite + any existing function of the same signature name in the graph `g`. + """ + # If we are not executing eagerly, adds the function to default graph if no + # graph is specified. + # In case of eager execution, function definition gets added to context + # during construction itself. + + if not context.executing_eagerly() and not g: + g = ops.get_default_graph() + + if g is not None: + g._add_function_recursive(self._delayed_rewrite_functions.forward()) # pylint: disable=protected-access + + def add_gradient_functions_to_graph(self, g=None): + """Add forward/backward functions to graph `g` or the current context.""" + if not context.executing_eagerly() and not g: + g = ops.get_default_graph() + g._add_function_recursive(self._delayed_rewrite_functions.forward()) # pylint: disable=protected-access + forward_function, backward_function = ( + self._delayed_rewrite_functions.forward_backward()) + g._add_function_recursive(forward_function) # pylint: disable=protected-access + backward_function.add_to_graph(g) + + def _get_gradient_function(self): + """Returns gradient function. It will be lazily created at first call.""" + return self._delayed_rewrite_functions._rewrite_forward_and_call_backward # pylint: disable=protected-access + + def _select_forward_and_backward_functions( + self, args, possible_gradient_type, executing_eagerly): + """Selects forward and backward functions based on the calling context. + + The forward function computes the "real" function outputs, `self._outputs`, + and any extra values needed by the corresponding backward function. + + Args: + args: A flat list of Tensors with all of the inputs to the forward + function (including user-specified and captured inputs). + possible_gradient_type: One of gradients_util.POSSIBLE_GRADIENT_TYPES_*. + executing_eagerly: Boolean, the value of context.executing_eagerly(). + + Returns: + An object with a `forward` method returning a tuple of (forward_function : + AtomicFunction, augmented_arguments : List), and a corresponding + `record` method which takes outputs from the forward function and records + the operation. forward_function should be called with augmented_arguments. + """ + if executing_eagerly: + input_tangents = forwardprop_util.pack_tangents(args) + else: + input_tangents = forwardprop_util.TangentInfo() + need_gradients_for_jvps = record.should_record_backprop( + input_tangents.tangents) + # Allows re-use of forward and backward function pairs depending on the + # tapes and forward accumulators watching its inputs. + cache_key = (need_gradients_for_jvps, input_tangents.indices) + if (possible_gradient_type + == gradients_util.POSSIBLE_GRADIENT_TYPES_FIRST_ORDER): + if input_tangents.indices or executing_eagerly: + # There is a single non-persistent tape active, so the user can only + # request first-order gradients from a tape. We can spend less time + # graph building since we know this. + # + # We may still end up computing higher-order gradients, but that'd be + # through `tf.gradients`, which can re-write the forward pass and so + # needs no preparation here. + functions = self._first_order_tape_functions.get(cache_key, None) + if functions is None: + functions = _FirstOrderTapeGradientFunctions( + self._func_graph, self._attrs, self._garbage_collector, + forwardprop_input_indices=input_tangents.indices, + delayed_rewrite_functions=self._delayed_rewrite_functions, + need_gradients_for_jvps=need_gradients_for_jvps) + self._first_order_tape_functions[cache_key] = functions + return _ForwardBackwardCall( + functions, args, input_tangents.tangents, tape_watching=True) + else: + # We can avoid computing second-order gradients in some cases by doing a + # delayed rewrite when graph building. Since we know we'll only compute + # first-order tape gradients, the delayed rewrite is safe: we won't need + # to tell the tape about side outputs. + # + # TODO(allenl): This case is really dirty. It would be better if we + # could temporarily pop all of the current tapes to avoid + # accidentally taking second-order gradients. + return _ForwardBackwardCall( + self._delayed_rewrite_functions, args, input_tangents.tangents, + tape_watching=True) + elif (possible_gradient_type + == gradients_util.POSSIBLE_GRADIENT_TYPES_HIGHER_ORDER): + # Either there's a persistent tape watching, or there are multiple nested + # tapes. Either way, the user may request higher-order gradients. We'll + # spend a bit more time and make sure higher-order gradients are correct. + functions = self._higher_order_tape_functions.get( + cache_key, None) + if functions is None: + functions = _HigherOrderTapeGradientFunctions( + self._func_graph, self._attrs, self._garbage_collector, + forwardprop_input_indices=input_tangents.indices, + delayed_rewrite_functions=self._delayed_rewrite_functions, + need_gradients_for_jvps=need_gradients_for_jvps) + self._higher_order_tape_functions[cache_key] = functions + return _ForwardBackwardCall(functions, args, input_tangents.tangents, + tape_watching=True) + # else possible_gradient_type == POSSIBLE_GRADIENT_TYPES_NONE, meaning no + # tape is recording. + return _ForwardBackwardCall( + self._delayed_rewrite_functions, args, input_tangents.tangents, + tape_watching=False) + + @property + def _as_name_attr_list(self): + """Returns a `NameAttrList` representing this function.""" + ret = attr_value_pb2.NameAttrList(name=self.name) + for name, value in self._attrs.items(): + ret.attr[name].CopyFrom(value) + return ret + + def _flat_signature_summary(self): + """Returns a string summarizing this function's flat signature.""" + assert self._arg_keywords is not None + assert self._num_positional_args is not None + arg_names = self._arg_keywords + if self._num_positional_args > len(arg_names): + arg_names.extend( + "".format(i + 1) + for i in range(len(arg_names), self._num_positional_args)) + return f"{self._func_graph.name}({', '.join(arg_names)})" + + def pretty_printed_signature(self, verbose=True): + """Returns a string summarizing the signature of this concrete function.""" + assert self.function_type is not None + if verbose: + return repr(self.function_type) + else: + return str(self.function_type) + + def __repr__(self): + if self.function_type is not None: + return "".format( + self.pretty_printed_signature(verbose=False), id(self) + ) + elif not (self._num_positional_args is None or self._arg_keywords is None): + return "".format( + self._flat_signature_summary(), id(self) + ) + else: + return object.__repr__(self) + + def __str__(self): + if self.function_type is not None: + return "ConcreteFunction {}".format( + self.pretty_printed_signature(verbose=True) + ) + else: + return self.__repr__() + + def _trackable_children(self, save_type="checkpoint", **kwargs): + """Implements `Trackable`.""" + if save_type == "checkpoint": + # Checkpoint dependencies do not include functions at all. Users + # expect the checkpointed variables to be saved using the model + # architecture, e.g. `model.layers[1].kernel` or `model.variables`. + return {} + + captured_trackables = {} + for n, (capture, _) in enumerate(self.graph.captures): + if (capture.dtype not in (dtypes.variant, dtypes.resource) and + not resource_variable_ops.is_resource_variable(capture)): + # Variant/resource type tensors are skipped since we have no way of + # getting the `Trackable` wrapper for these tensors. The wrappers are + # expected to be elsewhere in the saved object graph. + # TODO(b/223866972): Directly encode/decode tensor captures. + + # Resource variable captures are also skipped at this time, to maintain + # existing behavior. + # TODO(b/217979389): Return the non-constant captures as children. + + captured_trackables[f"capture_{n}"] = capture + + return captured_trackables + + def _deserialization_dependencies(self, children): + return children + + def _export_to_saved_model_graph(self, object_map, tensor_map, + **unused_kwargs): + if not self.graph.saveable: + raise ValueError( + (f"Unable to save function {self.name} for the following reason(s):\n" + + "\n".join(self.graph.saving_errors))) + self.add_to_graph() + object_map[self] = saved_model_exported_concrete.ExportedConcreteFunction( + self, tensor_map) + return [] + + +_pywrap_utils.RegisterType("Tensor", tensor_lib.Tensor) +_pywrap_utils.RegisterType("EagerTensor", ops.EagerTensor) +_pywrap_utils.RegisterType("IndexedSlices", indexed_slices.IndexedSlices) + + +class ConcreteFunctionGarbageCollector: + """Cleans up reference cycles when a `ConcreteFunction` goes out of scope.""" + + __slots__ = ["_func_graph"] + + def __init__(self, func_graph): + self._func_graph = func_graph + + def release(self): + """Call off the FuncGraph deletion.""" + self._func_graph = None + + def __del__(self): + if func_graph_module is None or self._func_graph is None: + return + try: + func_graph_module.dismantle_func_graph(self._func_graph) + except: # pylint: disable=bare-except + pass + + +class _Marker(object): + """Markers used to pretty-print nested args in function signatures.""" + + __slots__ = ["_s"] + + def __init__(self, s): + self._s = s + + def __repr__(self): + return str(self._s) + + +def _contains_type_spec(value): + return any(isinstance(x, type_spec.TypeSpec) for x in nest.flatten(value)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/eager_function_run.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/eager_function_run.py new file mode 100644 index 0000000000000000000000000000000000000000..19a4a5867d776e5f75807ee1b2d8e381b0be20fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/eager_function_run.py @@ -0,0 +1,111 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""Eager semantics for polymorphic function.""" + +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +RUN_FUNCTIONS_EAGERLY = False + + +@tf_export("config.functions_run_eagerly") +def functions_run_eagerly(): + """Returns the value of the `run_functions_eagerly` setting.""" + return RUN_FUNCTIONS_EAGERLY + + +@tf_export("config.run_functions_eagerly") +def run_functions_eagerly(run_eagerly): + """Enables / disables eager execution of `tf.function`s. + + Calling `tf.config.run_functions_eagerly(True)` will make all + invocations of `tf.function` run eagerly instead of running as a traced graph + function. This can be useful for debugging. As the code now runs line-by-line, + you can add arbitrary `print` messages or pdb breakpoints to monitor the + inputs/outputs of each Tensorflow operation. However, you should avoid using + this for actual production because it significantly slows down execution. + + >>> def my_func(a): + ... print(f'a: {a}') + ... return a + a + >>> a_fn = tf.function(my_func) + + >>> # A side effect the first time the function is traced + >>> # In tracing time, `a` is printed with shape and dtype only + >>> a_fn(tf.constant(1)) + a: Tensor("a:0", shape=(), dtype=int32) + + + >>> # `print` is a python side effect, it won't execute as the traced function + >>> # is called + >>> a_fn(tf.constant(2)) + + + >>> # Now, switch to eager running + >>> tf.config.run_functions_eagerly(True) + >>> # The code now runs eagerly and the actual value of `a` is printed + >>> a_fn(tf.constant(2)) + a: 2 + + + >>> # Turn this back off + >>> tf.config.run_functions_eagerly(False) + + Note: This flag has no effect on functions passed into tf.data transformations + as arguments. tf.data functions are never executed eagerly and are always + executed as a compiled Tensorflow Graph. + + Args: + run_eagerly: Boolean. Whether to run functions eagerly. + """ + global RUN_FUNCTIONS_EAGERLY + RUN_FUNCTIONS_EAGERLY = bool(run_eagerly) + + +@deprecation.deprecated( + None, "Use `tf.config.run_functions_eagerly` instead of the experimental " + "version.") +@tf_export("config.experimental_run_functions_eagerly") +def experimental_run_functions_eagerly(run_eagerly): + """Enables / disables eager execution of `tf.function`s. + + Calling `tf.config.experimental_run_functions_eagerly(True)` will make all + invocations of `tf.function` run eagerly instead of running as a traced graph + function. + + See `tf.config.run_functions_eagerly` for an example. + + Note: This flag has no effect on functions passed into tf.data transformations + as arguments. tf.data functions are never executed eagerly and are always + executed as a compiled Tensorflow Graph. + + Args: + run_eagerly: Boolean. Whether to run functions eagerly. + + Returns: + None + """ + return run_functions_eagerly(run_eagerly) + + +@deprecation.deprecated( + None, + "Use tf.config.functions_run_eagerly instead of the experimental version.") +@tf_export("config.experimental_functions_run_eagerly") +def experimental_functions_run_eagerly(): + """Returns the value of the `experimental_run_functions_eagerly` setting.""" + return functions_run_eagerly() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/function_context.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/function_context.py new file mode 100644 index 0000000000000000000000000000000000000000..76278dcc7bc5081ce7d429582a5c314981ccb3c1 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/function_context.py @@ -0,0 +1,127 @@ +# 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. +# ============================================================================== +"""Context information for a tf.function.""" + +from typing import NamedTuple, Any + +from tensorflow.core.function.polymorphism import function_cache +from tensorflow.python.eager import context +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.saved_model import save_context + + +# EagerContext is used by tf.function to identify cases where tracing +# needs to occur due to a change in conditions other than the arguments. +class EagerContext(NamedTuple): + parent_graph: Any + device_functions: Any + colocation_stack: Any + in_cross_replica_context: Any + variable_policy: Any + xla_context_id: Any + + +def make_function_context(scope_type=None) -> function_cache.FunctionContext: + """Generates a FunctionContext based on current contextual info.""" + ctx = context.context() + + # Don't need to open an init_scope if the tf.function call is in eager mode + # already. + executing_eagerly = ctx.executing_eagerly() + parent_graph = None + xla_context_id = 0 + if not executing_eagerly: + # We want to force function retracing for each different + # XLAControlFlowContext, so add `xla_context_id` to the context. + xla_context = _enclosing_xla_context() + if xla_context is not None and xla_context.RequiresUniqueFunctionRetracing( + ): + xla_context_id = id(xla_context) + + with ops.init_scope(): + # The graph, or whether we're executing eagerly, should be a part of the + # cache key so we don't improperly capture tensors such as variables. + executing_eagerly = ctx.executing_eagerly() + parent_graph = None if executing_eagerly else ops.get_default_graph() + + # pylint: disable=protected-access + default_graph = ops.get_default_graph() + # TODO(b/117617952): The current distribution strategy will affect graph + # building (e.g. accessing different variables from different devices) and + # so requires retracing for each device. + strategy_stack = default_graph._distribution_strategy_stack + uses_distribution_strategy = ( + strategy_stack and + strategy_stack[-1].strategy.extended._retrace_functions_for_each_device) + if executing_eagerly: + colocation_stack = () + if uses_distribution_strategy: + device_functions = (pydev.merge_device(ctx.device_name),) + else: + device_functions = () + else: + colocation_stack = tuple(default_graph._colocation_stack.peek_objs()) + if (uses_distribution_strategy or + func_graph_module.device_stack_has_callable( + default_graph._device_function_stack)): + # Putting the device in the cache key ensures that call-site device + # annotations are respected. + device_functions = tuple(default_graph._device_functions_outer_to_inner) + else: + device_functions = () + + in_cross_replica_context = False + try: + in_cross_replica_context = (strategy_stack[-1].replica_context is None) # pylint: disable=protected-access + except (AttributeError, IndexError): + pass + + if save_context.in_save_context(): + variable_policy = ( + save_context.get_save_options().experimental_variable_policy) + else: + variable_policy = None + + return function_cache.FunctionContext( + EagerContext( + parent_graph, + device_functions, + colocation_stack, + in_cross_replica_context, + variable_policy, + xla_context_id, + ), + scope_type, + ) + + +def _enclosing_xla_context(): + """Returns the XLAControlFlowContext, which exists inside a tpu.rewrite().""" + graph = ops.get_default_graph() + while graph is not None: + # pylint: disable=protected-access + context_ = graph._get_control_flow_context() + # pylint: enable=protected-access + while context_ is not None: + if isinstance(context_, control_flow_ops.XLAControlFlowContext): + return context_ + context_ = context_.outer_context + # This may be a FuncGraph due to defuns or v2 control flow. We need to + # find the original graph with the XLAControlFlowContext. + graph = getattr(graph, "outer_graph", None) + return None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/function_type_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/function_type_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..78528679a9be7111ada9ab6f119c53af0f938e7f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/function_type_utils.py @@ -0,0 +1,548 @@ +# 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. +# ============================================================================== +"""Utilities for using FunctionType with tf.function.""" + +import functools +import inspect +from typing import Any, Dict, Tuple + +import six + +from tensorflow.core.function import trace_type +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.util import nest + + +def to_fullargspec( + function_type: function_type_lib.FunctionType, + default_values: Dict[str, Any], +) -> inspect.FullArgSpec: + """Generates backwards compatible FullArgSpec from FunctionType.""" + args = [] + varargs = None + varkw = None + defaults = [] + kwonlyargs = [] + kwonlydefaults = {} + + for parameter in function_type.parameters.values(): + if parameter.kind in [ + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ]: + args.append(parameter.name) + if parameter.default is not inspect.Parameter.empty: + defaults.append(default_values[parameter.name]) + elif parameter.kind is inspect.Parameter.KEYWORD_ONLY: + kwonlyargs.append(parameter.name) + if parameter.default is not inspect.Parameter.empty: + kwonlydefaults[parameter.name] = default_values[parameter.name] + elif parameter.kind is inspect.Parameter.VAR_POSITIONAL: + varargs = parameter.name + elif parameter.kind is inspect.Parameter.VAR_KEYWORD: + varkw = parameter.name + + return inspect.FullArgSpec( + args, + varargs, + varkw, + tuple(defaults) if defaults else None, + kwonlyargs, + kwonlydefaults if kwonlydefaults else None, + annotations={}, + ) + + +def _to_default_values(fullargspec): + """Returns default values from the function's inspected fullargspec.""" + if fullargspec.defaults is not None: + defaults = { + name: value + for name, value in zip( + fullargspec.args[-len(fullargspec.defaults) :], fullargspec.defaults + ) + } + else: + defaults = {} + + if fullargspec.kwonlydefaults is not None: + defaults.update(fullargspec.kwonlydefaults) + + defaults = { + function_type_lib.sanitize_arg_name(name): value + for name, value in defaults.items() + } + + return defaults + + +def to_function_type(fullargspec): + """Generates FunctionType and default values from fullargspec.""" + default_values = _to_default_values(fullargspec) + parameters = [] + + for arg in fullargspec.args: + arg_name = function_type_lib.sanitize_arg_name(arg) + parameters.append( + function_type_lib.Parameter( + arg_name, + function_type_lib.Parameter.POSITIONAL_OR_KEYWORD, + arg_name in default_values, + None, + ) + ) + + if fullargspec.varargs is not None: + parameters.append( + function_type_lib.Parameter( + fullargspec.varargs, + function_type_lib.Parameter.VAR_POSITIONAL, + False, + None, + ) + ) + + for kwarg in fullargspec.kwonlyargs: + parameters.append( + function_type_lib.Parameter( + function_type_lib.sanitize_arg_name(kwarg), + function_type_lib.Parameter.KEYWORD_ONLY, + kwarg in default_values, + None, + ) + ) + + if fullargspec.varkw is not None: + parameters.append( + function_type_lib.Parameter( + fullargspec.varkw, + function_type_lib.Parameter.VAR_KEYWORD, + False, + None, + ) + ) + + return function_type_lib.FunctionType(parameters), default_values + + +def to_input_signature(function_type): + """Extracts an input_signature from function_type instance.""" + constrained_parameters = list(function_type.parameters.keys()) + + # self does not have a constraint in input_signature + if "self" in constrained_parameters: + constrained_parameters.pop(0) + + # There are no parameters to constrain. + if not constrained_parameters: + return tuple() + + constraints = [] + is_auto_constrained = False + + for parameter_name in constrained_parameters: + parameter = function_type.parameters[parameter_name] + constraint = None + if parameter.type_constraint: + # Generate legacy constraint representation. + constraint = parameter.type_constraint.placeholder_value( + trace_type.InternalPlaceholderContext(unnest_only=True) + ) + if any( + not isinstance(arg, tensor.TensorSpec) + for arg in nest.flatten([constraint], expand_composites=True) + ): + # input_signature only supports contiguous TensorSpec composites + is_auto_constrained = True + break + else: + constraints.append(constraint) + + # All constraints were generated by FunctionType + if is_auto_constrained and not constraints: + return tuple() + + # If the list is empty then there was no input_signature specified. + return tuple(constraints) if constraints else None + + +def to_arg_names(function_type): + """Generates a list of arg names from a FunctionType.""" + arg_names = [] + for p in function_type.parameters.values(): + if p.kind in { + function_type_lib.Parameter.POSITIONAL_ONLY, + function_type_lib.Parameter.POSITIONAL_OR_KEYWORD, + }: + arg_names.append(p.name) + return arg_names + + +# TODO(b/214462107): Minimize API surface for FunctionSpec. +class FunctionSpec(object): + """Specification of how to bind arguments to a function. + + Deprecated. Please use FunctionType instead. + """ + + @classmethod + def from_function_and_signature( + cls, python_function, input_signature, is_pure=False, jit_compile=None + ): + """Creates a FunctionSpec instance given a python function and signature. + + Args: + python_function: a function to inspect + input_signature: a signature of the function (None, if variable) + is_pure: if True all input arguments (including variables and constants) + will be converted to tensors and no variable changes allowed. + jit_compile: see `tf.function` + + Returns: + instance of FunctionSpec + """ + function_type, default_values = make_function_type( + python_function, input_signature) + # Get the function's name. Remove functools.partial wrappers if necessary. + while isinstance(python_function, functools.partial): + python_function = python_function.func + name = getattr(python_function, "__name__", "f") + + return FunctionSpec( + function_type, + default_values, + is_pure=is_pure, + jit_compile=jit_compile, + name=name, + ) + + @classmethod + def from_fullargspec_and_signature( + cls, + fullargspec, + input_signature, + is_pure=False, + name=None, + jit_compile=None, + ): + """Construct FunctionSpec from legacy FullArgSpec format.""" + function_type, default_values = to_function_type(fullargspec) + if input_signature: + input_signature = tuple(input_signature) + _validate_signature(input_signature) + function_type = function_type_lib.add_type_constraints( + function_type, input_signature, default_values + ) + + return FunctionSpec( + function_type, default_values, is_pure, name, jit_compile + ) + + def __init__( + self, + function_type, + default_values, + is_pure=False, + name=None, + jit_compile=None, + ): + """Constructs a FunctionSpec describing a python function. + + Args: + function_type: A FunctionType describing the python function signature. + default_values: Dictionary mapping parameter names to default values. + is_pure: if True all input arguments (including variables and constants) + will be converted to tensors and no variable changes allowed. + name: Name of the function + jit_compile: see `tf.function`. + """ + self._function_type = function_type + self._default_values = default_values + self._fullargspec = to_fullargspec(function_type, default_values) + self._is_pure = is_pure + self._jit_compile = jit_compile + + # TODO(edloper): Include name when serializing for SavedModel? + self._name = name or "f" + self._input_signature = to_input_signature(function_type) + + @property + def default_values(self): + """Returns dict mapping parameter names to default values.""" + return self._default_values + + @property + def function_type(self): + """Returns a FunctionType representing the Python function signature.""" + return self._function_type + + @property + def fullargspec(self): + return self._fullargspec + + # TODO(fmuham): Replace usages with FunctionType and remove. + @property + def input_signature(self): + return self._input_signature + + # TODO(fmuham): Replace usages with FunctionType and remove. + @property + def flat_input_signature(self): + return tuple(nest.flatten(self.input_signature, expand_composites=True)) + + @property + def is_pure(self): + return self._is_pure + + @property + def jit_compile(self): + return self._jit_compile + + # TODO(fmuham): Replace usages and remove. + @property + def arg_names(self): + return to_arg_names(self.function_type) + + def signature_summary(self, default_values=False): + """Returns a string summarizing this function's signature. + + Args: + default_values: If true, then include default values in the signature. + + Returns: + A `string`. + """ + summary = f"{self._function_type!r}" + if default_values: + summary += "\nDefaults:" + if self.default_values: + for name, value in self.default_values.items(): + summary += f"\n {name}: {value!r}" + else: + summary += "\n None" + return summary + + +def make_function_type(python_function, input_signature): + """Generates a FunctionType for python_function.""" + _validate_signature(input_signature) + + function_type = function_type_lib.FunctionType.from_callable( + python_function + ) + default_values = function_type_lib.FunctionType.get_default_values( + python_function + ) + + if input_signature is not None: + input_signature = tuple(input_signature) + function_type = function_type_lib.add_type_constraints( + function_type, input_signature, default_values + ) + + return function_type, default_values + + +def make_canonicalized_monomorphic_type( + args: Any, + kwargs: Any, + capture_types: Any, + polymorphic_type, +) -> Tuple[function_type_lib.FunctionType, trace_type.InternalTracingContext]: + """Generates function type given the function arguments.""" + kwargs = { + function_type_lib.sanitize_arg_name(name): value + for name, value in kwargs.items() + } + + function_type, type_context = ( + function_type_lib.canonicalize_to_monomorphic( + args, kwargs, {}, capture_types, polymorphic_type + ) + ) + + return function_type, type_context + + +def canonicalize_function_inputs( + args, kwargs, function_type, default_values=None, is_pure=False +): + """Canonicalizes `args` and `kwargs`. + + Canonicalize the inputs to the Python function using FunctionType. + In particular, we parse the varargs and kwargs that the + original function was called with into a tuple corresponding to the + Python function's positional (named) arguments and a dictionary + corresponding to its kwargs. Missing default arguments are added. + + If the FunctionType has an type constraints, then they are used to convert + arguments to tensors; otherwise, any inputs containing numpy arrays are + converted to tensors. + + + Args: + args: The varargs this object was called with. + kwargs: The keyword args this function was called with. + function_type: FunctionType to canonicalize against. + default_values: Default values to use. + is_pure: Force variable inputs to Tensors. + + Returns: + A canonicalized ordering of the inputs, as well as full and filtered + (Tensors and Variables only) versions of their concatenated flattened + representations, represented by a tuple in the form (args, kwargs, + flat_args, filtered_flat_args). Here: `args` is a full list of bound + arguments, and `kwargs` contains only true keyword arguments, as opposed + to named arguments called in a keyword-like fashion. + + Raises: + ValueError: If a keyword in `kwargs` cannot be matched with a positional + argument when an input signature is specified, or when the inputs + do not conform to the input signature. + """ + default_values = {} if not default_values else default_values + if is_pure: + args, kwargs = _convert_variables_to_tensors(args, kwargs) + bound_arguments = bind_function_inputs( + args, kwargs, function_type, default_values + ) + return bound_arguments + + +def bind_function_inputs(args, kwargs, function_type, default_values): + """Bind `args` and `kwargs` into a canonicalized signature args, kwargs.""" + sanitized_kwargs = { + function_type_lib.sanitize_arg_name(k): v for k, v in kwargs.items() + } + if len(kwargs) != len(sanitized_kwargs): + raise ValueError( + "Name collision after sanitization. Please rename " + "tf.function input parameters. Original: " + f"{sorted(kwargs.keys())}, Sanitized: " + f"{sorted(sanitized_kwargs.keys())}" + ) + + try: + bound_arguments = function_type.bind_with_defaults( + args, sanitized_kwargs, default_values + ) + except Exception as e: + raise TypeError( + f"Binding inputs to tf.function failed due to `{e}`. " + f"Received args: {args} and kwargs: {sanitized_kwargs} for signature:" + f" {function_type}." + ) from e + return bound_arguments + + +def _validate_signature(signature): + """Checks the input_signature to be valid.""" + if signature is None: + return + + if not isinstance(signature, (tuple, list)): + raise TypeError( + "input_signature must be either a tuple or a list, got " + f"{type(signature)}." + ) + + # TODO(xjun): Allow VariableSpec once we figure out API for de-aliasing. + variable_specs = _get_variable_specs(signature) + if variable_specs: + raise TypeError( + f"input_signature doesn't support VariableSpec, got {variable_specs}" + ) + + if any( + not isinstance(arg, tensor.TensorSpec) + for arg in nest.flatten(signature, expand_composites=True) + ): + bad_args = [ + arg + for arg in nest.flatten(signature, expand_composites=True) + if not isinstance(arg, tensor.TensorSpec) + ] + raise TypeError( + "input_signature must be a possibly nested sequence of " + f"TensorSpec objects, got invalid args {bad_args} with " + f"types {list(six.moves.map(type, bad_args))}." + ) + + +def _to_tensor_or_tensor_spec(x): + return ( + x + if isinstance(x, (tensor.Tensor, tensor.TensorSpec)) + else ops.convert_to_tensor(x) + ) + + +def _convert_variables_to_tensors(args, kwargs): + args = [_to_tensor_or_tensor_spec(x) for x in args] + kwargs = {kw: _to_tensor_or_tensor_spec(x) for kw, x in kwargs.items()} + return tuple(args), kwargs + + +def _get_variable_specs(args): + """Returns `VariableSpecs` from `args`.""" + variable_specs = [] + for arg in nest.flatten(args): + if not isinstance(arg, type_spec.TypeSpec): + continue + if isinstance(arg, resource_variable_ops.VariableSpec): + variable_specs.append(arg) + elif not isinstance(arg, tensor.TensorSpec): + # arg is a CompositeTensor spec. + variable_specs.extend(_get_variable_specs(arg._component_specs)) # pylint: disable=protected-access + return variable_specs + + +def derive_from_graph(func_graph): + """Derives a FunctionType from FuncGraph.""" + # TODO(fmuham): Include structure info from structured_inputs + input_signature = ( + tuple(trace_type.from_value(i) for i in func_graph.inputs), + {}, + ) + + # TODO(fmuham): Include output structure info from structured_outputs + output_signature = tuple(trace_type.from_value(o) for o in func_graph.outputs) + + return function_type_lib.from_structured_signature( + input_signature, + output_signature, + func_graph.function_captures.capture_types, + ) + + +# TODO(fmuham): Replace usages with TraceType and remove. +def is_same_structure(structure1, structure2, check_values=False): + """Check two structures for equality, optionally of types and of values.""" + try: + nest.assert_same_structure(structure1, structure2, expand_composites=True) + except (ValueError, TypeError): + return False + if check_values: + flattened1 = nest.flatten(structure1, expand_composites=True) + flattened2 = nest.flatten(structure2, expand_composites=True) + # First check the types to avoid AttributeErrors. + if any(type(f1) is not type(f2) for f1, f2 in zip(flattened1, flattened2)): + return False + return flattened1 == flattened2 + return True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/polymorphic_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/polymorphic_function.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3688722bd5780bb15e4e4569f045e8d28dff11 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/polymorphic_function.py @@ -0,0 +1,1716 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""API for defining graph functions with some additional eager semantics. + +tf.function utilizes varying configurations of tracing compilation to allow +initializing `tf.Variable`s with subgraphs of the function. For example: + +```python +class M(tf.Module): + def __init__(self): + self.v_opinit = None + self.v_arginit = None + + @tf.function + def __call__(self, x): + # Variables are only created on the first call to the function. This is a + # common pattern in layer libraries. + if self.v_opinit is None: + # self.v_opinit will outlive the function call, but `tf.ones` is traced as + # part of the function body before the `tf.Variable` object is + # created. This subgraph is easy to lift out of the function. + self.v_opinit = tf.Variable(tf.ones([])) + + # If arguments feed into variable initialization, it can be very tricky to + # disentangle from the rest of the function. We don't attempt it. + self.v_arginit = tf.Variable(tf.ones(tf.shape(x)) * tf.constant(2.)) + return self.v_opinit + self.v_arginit + x +``` + +These patterns using tracing compilation directly throw an error asking +the user to put the variable's initializer in a lambda. With tf.function they +work with eager semantics either by lifting the subgraph out of the function and +using it to initialize the variable, or by initializing variables on the first +call to the function (if they weren't already initialized by something else, +e.g. a checkpoint API). The latter requires tf.conds, and is not well supported +by TF-XLA, so we only do it when necessary. + +Since these patterns are relatively common in layer libraries, we expose the +wrapper in this file as `tf.function`. The defun concept in quarantine.py is a +legacy internal API. + +In order to support these variable initialization patterns, tf.function defines +a variable subtype (UnliftedInitializerVariable) which collects the input +subgraph. This type of variable replaces the regular variable type on the first +tf.function trace. To exclude initializers from the function body (the `tf.ones` +ops above and associated assignment operations), tf.function traces a second +time if it sees variables on the first call. +""" + +import dataclasses +import functools +import os +import threading +import types as types_lib +import weakref + +from google.protobuf import text_format as _text_format +from google.protobuf.message import DecodeError +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.function import trace_type +from tensorflow.core.function.capture import capture_container +from tensorflow.core.function.polymorphism import function_cache +from tensorflow.python.distribute.parallel_device import parallel_device +from tensorflow.python.eager import context +from tensorflow.python.eager import lift_to_graph +from tensorflow.python.eager import monitoring +from tensorflow.python.eager.polymorphic_function import attributes as attributes_lib +from tensorflow.python.eager.polymorphic_function import autograph_util +from tensorflow.python.eager.polymorphic_function import compiler_ir +from tensorflow.python.eager.polymorphic_function import eager_function_run +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.eager.polymorphic_function import tf_method_target +from tensorflow.python.eager.polymorphic_function import tracing_compilation +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import errors +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace +from tensorflow.python.trackable import base as trackable +from tensorflow.python.types import core +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import traceback_utils +from tensorflow.python.util.tf_export import tf_export + +FREQUENT_TRACING_WARNING_MAX_CALL_HISTORY = 10 +FREQUENT_TRACING_WARNING_THRESHOLD = 5 +FREQUENT_TRACING_WARNING_MAX_WARNING_PER_DETECTOR = 2 + +_tf_function_counter = monitoring.Counter( + "/tensorflow/core/tf_function_counter", + "Counter for the number of tf.functions created when Eager execution is " + "enabled.", + # jit_compile is "0" or "1". + "jit_compile") + + +class _FrequentTracingDetector(object): + """Class keeping track of how many recent calls triggered tracing.""" + + __slots__ = ["_calls_per_tracings", "_call_count", "_total_warning_count"] + + def __init__(self): + self._calls_per_tracings = [] + self._total_warning_count = 0 + self._call_count = 0 + + def called_with_tracing(self, function_name, omit_warning): + """Updates the list of most recent calls' tracing information. + + Warns the user when recent calls caused retracing too often. + + Args: + function_name: the python function being traced. + omit_warning: If 'True', this call will not warn the user even if + retracing happens too often. + """ + self._call_count += 1 + self._calls_per_tracings.append(1) + + while self._calls_per_tracings: + if (self._call_count - self._calls_per_tracings[0] > + FREQUENT_TRACING_WARNING_MAX_CALL_HISTORY): + self._call_count -= self._calls_per_tracings.pop(0) + else: + break + + if (omit_warning or self._total_warning_count >= + FREQUENT_TRACING_WARNING_MAX_WARNING_PER_DETECTOR): + return + if len(self._calls_per_tracings) >= FREQUENT_TRACING_WARNING_THRESHOLD: + self._total_warning_count += 1 + logging.warning( + "{} out of the last {} calls to {} triggered tf.function " + "retracing. Tracing is expensive and the excessive number of " + "tracings could be due to (1) creating @tf.function repeatedly in " + "a loop, (2) passing tensors with different shapes, (3) passing " + "Python objects instead of tensors. For (1), please define your " + "@tf.function outside of the loop. For (2), @tf.function has " + "reduce_retracing=True option that can avoid unnecessary " + "retracing. For (3), please refer to " + "https://www.tensorflow.org/guide/function#controlling_retracing" + " and https://www.tensorflow.org/api_docs/python/tf/function for " + " more details.".format( + len(self._calls_per_tracings), self._call_count, function_name)) + + def called_without_tracing(self): + # We don't count tracing when users load a concrete function directly or + # call get_concrete_function, so the first call can be not a tracing call. + if not self._calls_per_tracings: + self._calls_per_tracings = [0] + self._calls_per_tracings[-1] += 1 + self._call_count += 1 + + +class _FrequentTracingDetectorManager(object): + """Class for the management of all _FrequentTracingDetector objects.""" + + __slots__ = ["_detectors", "_lock"] + + def __init__(self): + self._detectors = weakref.WeakKeyDictionary() # GUARDED_BY(self._lock) + self._lock = threading.Lock() + + def _get_detector(self, key): + if key not in self._detectors: + self._detectors[key] = _FrequentTracingDetector() + return self._detectors[key] + + def called_without_tracing(self, key): + with self._lock: + detector = self._get_detector(key) + detector.called_without_tracing() + + def called_with_tracing(self, key, function_name, omit_warning): + with self._lock: + detector = self._get_detector(key) + detector.called_with_tracing(function_name, omit_warning) + + +_frequent_tracing_detector_manager = _FrequentTracingDetectorManager() + + +class UnliftedInitializerVariable(resource_variable_ops.UninitializedVariable): + """Variable which does not lift its initializer out of function context. + + Instances of this variable, when created, build a graph which runs their + initializer inside a tf.cond(is_initialized) block. + + This can only be created during tracing compilation called from + (eventually) eager mode. That is, non-function-building graphs are not + supported. + """ + + def __init__( + self, + initial_value=None, + trainable=None, + caching_device=None, + name=None, + dtype=None, + constraint=None, + add_initializers_to=None, + synchronization=None, + aggregation=None, + shape=None, + **unused_kwargs, + ): + """Creates a variable. + + Args: + initial_value: A `Tensor`, or Python object convertible to a `Tensor`, + which is the initial value for the Variable. The initial value must have + a shape specified unless `validate_shape` is set to False. Can also be a + callable with no argument that returns the initial value when called. + (Note that initializer functions from init_ops.py must first be bound to + a shape before being used here.) + trainable: If `True`, GradientTapes automatically watch uses of this + Variable. + caching_device: Optional device string or function describing where the + Variable should be cached for reading. Defaults to the Variable's + device. If not `None`, caches on another device. Typical use is to + cache on the device where the Ops using the Variable reside, to + deduplicate copying through `Switch` and other conditional statements. + name: Optional name for the variable. Defaults to `'Variable'` and gets + uniquified automatically. + dtype: If set, initial_value will be converted to the given type. If None, + either the datatype will be kept (if initial_value is a Tensor) or + float32 will be used (if it is a Python object convertible to a Tensor). + constraint: An optional projection function to be applied to the variable + after being updated by an `Optimizer` (e.g. used to implement norm + constraints or value constraints for layer weights). The function must + take as input the unprojected Tensor representing the value of the + variable and return the Tensor for the projected value (which must have + the same shape). Constraints are not safe to use when doing asynchronous + distributed training. + add_initializers_to: if not None and not in legacy graph mode, the + initializer tensor will be added to this map in addition to adding the + assignment to the function. + synchronization: Indicates when a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableSynchronization`. By default the synchronization is set to + `AUTO` and the current `DistributionStrategy` chooses when to + synchronize. + aggregation: Indicates how a distributed variable will be aggregated. + Accepted values are constants defined in the class + `tf.VariableAggregation`. + shape: (optional) The shape of this variable. If None, the shape of + `initial_value` will be used. When setting this argument to + `tf.TensorShape(None)` (representing an unspecified shape), the variable + can be assigned with values of different shapes. + + Raises: + ValueError: If the initial value is not specified, or does not have a + shape and `validate_shape` is `True`. + RuntimeError: If called outside of a function definition. + """ + with ops.init_scope(): + self._in_graph_mode = not context.executing_eagerly() + if not ops.inside_function(): + # If we've been init_scope()d out of the function definition nothing to do + # here; we can't really do the capturing or conditional logic. + resource_variable_ops.ResourceVariable.__init__( + self, initial_value=initial_value, trainable=trainable, + caching_device=caching_device, name=name, dtype=dtype, + constraint=constraint) + return + if initial_value is None: + raise ValueError("`initial_value` must be a Tensor or a Python " + "object convertible to a Tensor. Got None.") + init_from_fn = callable(initial_value) + + if constraint is not None and not callable(constraint): + raise ValueError(f"`constraint` with type {type(constraint)} must be a " + "callable.") + + with ops.name_scope(name, "Variable", [] + if init_from_fn else [initial_value]) as scope_name: + with ops.name_scope("Initializer"): + if init_from_fn: + initial_value = initial_value() + if isinstance(initial_value, trackable.CheckpointInitialValue): + self._maybe_initialize_trackable() + self._update_uid = initial_value.checkpoint_position.restore_uid + initial_value = initial_value.wrapped_value + + initial_value = ops.convert_to_tensor(initial_value, + name="initial_value", dtype=dtype) + assert initial_value is not None + + # Don't use `shape or initial_value.shape` since TensorShape has + # overridden `__bool__`. + if shape is None: + shape = initial_value.shape + + # Use the constructor for UninitializedVariable to start. Outside the name + # scope so we don't double up the prefix. + super().__init__( + trainable=trainable, + caching_device=caching_device, + name=name, + shape=shape, + dtype=initial_value.dtype, + constraint=constraint, + synchronization=synchronization, + aggregation=aggregation, + extra_handle_data=initial_value, + **unused_kwargs) + + with ops.name_scope(scope_name): + if self._in_graph_mode: + with ops.init_scope(): + outer_graph = ops.get_default_graph() + func_graph = ops.get_default_graph() + function_placeholders = ( + func_graph.inputs + func_graph.internal_captures) + placeholder_ops = set( + [tensor.op for tensor in function_placeholders]) + lifted_initializer = lift_to_graph.lift_to_graph( + [initial_value], outer_graph, + disallowed_placeholders=placeholder_ops)[initial_value] + with ops.init_scope(): + self._initial_value = lifted_initializer + with ops.name_scope("IsInitialized"): + self._is_initialized_op = ( + resource_variable_ops.var_is_initialized_op(self._handle)) + if initial_value is not None: + with ops.name_scope("Assign") as n, ops.colocate_with(self._handle): + self._initializer_op = resource_variable_ops.assign_variable_op( + self._handle, lifted_initializer, name=n) + elif context.executing_eagerly(): + # In this case, both current scope and init scope are eager. + # Assign_variable_op will be executed immediately. So we don't need to + # add it to "add_initializers_to" to lift it out. + with ops.name_scope("Assign") as n, ops.colocate_with(self._handle): + resource_variable_ops.assign_variable_op( + self._handle, initial_value, name=n) + else: + # Init scope is eager but current scope is graph. We will lift out this + # variable by addint it into "add_initializers_to". + if add_initializers_to is not None: + add_initializers_to.append((self, initial_value)) + + def assign_fn(): + with ops.name_scope("Assign") as n, ops.colocate_with(self._handle): + resource_variable_ops.assign_variable_op( + self._handle, + initial_value, + name=n) + # Returning values to keep tf.cond happy. + return ops.convert_to_tensor(1) + def not_assign_fn(): + return ops.convert_to_tensor(0) + # Note: this cond is always guaranteed to run because we're inside + # tracing compilation which will insert automatic control dependencies. + # It will only execute assign_fn if lifting failed. + graph = ops.get_default_graph() + + # Capture the handle ahead of time in order to avoid querying the shape + # of the handle which helps async execution performance + graph.capture(self._handle, shape=()) + cond.cond( + resource_variable_ops.var_is_initialized_op(self._handle), + not_assign_fn, assign_fn) + + +JIT_COMPILE_FUNCTIONS = ( + os.getenv("TF_FUNCTION_JIT_COMPILE_DEFAULT", "false").lower() + in ("true", "1")) + + +def _evaluate_var_is_initialized(variables): + """Compute booleans indicating whether each variable is initialized.""" + with ops.init_scope(): + var_is_initialized = [] + for v in variables: + var_is_initialized.append( + resource_variable_ops.var_is_initialized_op(v.handle)) + try: + # Stack all the var_is_initialized values into one tensor and interpret + # the numpy value. This will reduce the number of RPCs between client and + # worker in the remote case. + return array_ops_stack.stack(var_is_initialized).numpy() + except errors.UnimplementedError: + # Some devices do not support implicit copy-off to host. Fall back to + # variable-by-variable processing. + for index, v in enumerate(variables): + try: + numpy_value = var_is_initialized[index].numpy() + except errors.UnimplementedError: + # This is a variable on a parallel device; we'll extract its value on + # each replica and assert that they're identical. + components = parallel_device.unpack(var_is_initialized[index]) + with ops.device(None): + components = array_ops_stack.stack(components) + all_initialized = math_ops.reduce_all(components).numpy() + any_initialized = math_ops.reduce_any(components).numpy() + if all_initialized != any_initialized: + raise NotImplementedError( + f"Some but not all components of a parallel variable {v!r} " + "were initialized between their creation in a tf.function and " + "the function's trace having completed. This is not " + "supported; consider initializing either all or none of the " + "components, or moving initialization out of the function.") + numpy_value = all_initialized + var_is_initialized[index] = numpy_value + return var_is_initialized + + +class OptionalXlaContext: + """Wrapper for XLA context optionally applied under a context manager.""" + + def __init__(self, is_compiled): + wrap = is_compiled and not control_flow_util.GraphOrParentsInXlaContext( \ + ops.get_default_graph()) + self.xla_context = control_flow_ops.XLAControlFlowContext() \ + if wrap else None + + def __enter__(self): + if self.xla_context: + self.xla_context.Enter() + + def __exit__(self, t, value, traceback): + if self.xla_context: + self.xla_context.Exit() + + +@tf_export("__internal__.function.Function", v1=[]) +class Function(core.PolymorphicFunction, trackable.Trackable): + """A `tf.types.experimental.PolymorphicFunction` created by `tf.function`. + + Currently, individual methods/attributes under this class are not guaranteed + by the TF API contract, and are subject to future changes. + + (Previously also known as `tf.types.experimental.GenericFunction`) + """ + + def __init__(self, + python_function, + name, + input_signature=None, + autograph=True, + jit_compile=None, + reduce_retracing=False, + experimental_implements=None, + experimental_autograph_options=None, + experimental_attributes=None,): + """Initializes a `Function`. + + Args: + python_function: the function to be wrapped. + name: the name given to it. + input_signature: See the documentation for `tf.function`. + autograph: See the documentation for `tf.function`. + jit_compile: See the documentation for `tf.function`. + reduce_retracing: See the documentation for `tf.function`. + experimental_implements: See the documentation for `tf.function`. + experimental_autograph_options: See the documentation for `tf.function`. + experimental_attributes: See the documentation for `tf.function`. + + Raises: + ValueError: if `input_signature` is not None and the `python_function`'s + argspec has keyword arguments. + """ + self._lock = threading.RLock() + self._python_function = python_function + self._function_type, self._default_values = ( + function_type_utils.make_function_type(python_function, input_signature) + ) + self._function_cache = function_cache.FunctionCache() + self._function_captures = capture_container.FunctionCaptures() + + self._attributes = {} + if experimental_implements is not None: + self._attributes = self._create_implements_attribute( + experimental_implements + ) + + if experimental_attributes is not None: + self._attributes.update(experimental_attributes) + + for attribute in self._attributes: + if attribute not in attributes_lib.POLYMORPHIC_FUNCTION_ALLOWLIST: + raise ValueError( + f"`{attribute} is not supported by tf.function as an attribute." + ) + + self._is_pure = ( + self._attributes and attributes_lib.IMPLEMENTS in self._attributes + ) + # If `True`, the function uses the rendezvous of the parent. This is only + # needed to support code where raw send/recv operations are inserted and + # when functions are run in graph mode where they may not be inlined. + self._shared_rendezvous = None + self._autograph = autograph + self._experimental_autograph_options = experimental_autograph_options + self._reduce_retracing = reduce_retracing + self._jit_compile = jit_compile + self._created_variables = None # GUARDED_BY(self._lock) + self._variable_creation_config = None # GUARDED_BY(self._lock) + self._no_variable_creation_config = None # GUARDED_BY(self._lock) + self._descriptor_cache = weakref.WeakKeyDictionary() + self._name = name + self._key_for_call_stats = self._get_key_for_call_stats() + self._omit_frequent_tracing_warning = False + ops._tf_function_api_gauge.get_cell().set(True) # pylint: disable=protected-access + + @property + def name(self): + return self._name + + def __getstate__(self): + """Custom pickling, to omit unpickleable objects.""" + result = self.__dict__.copy() + del result["_lock"] + del result["_descriptor_cache"] + del result["_key_for_call_stats"] + return result + + def __setstate__(self, state): + """Restore from pickled state.""" + self.__dict__ = state + self._lock = threading.RLock() + self._descriptor_cache = weakref.WeakKeyDictionary() + self._key_for_call_stats = self._get_key_for_call_stats() + + def _get_key_for_call_stats(self): + """Returns key instance to track call stats and retracings. + + The key instance a best-effort to preserve global consistency. + """ + target_function = self._python_function + # `__wrapped__` is a conventional Python attribute that a higher-order + # function keeps its original function's instance. We also directly use + # this attribute for dealing with a class method. See + # `bound_method_wrapper` in `function.py`. If we don't use `__wrapped__`, + # all class methods will return the same `bound_method_wrapper` instance + # from this function. + while hasattr(target_function, "__wrapped__"): + target_function = target_function.__wrapped__ + + if hasattr(target_function, "__func__"): + target_function = target_function.__func__ + + if hasattr(target_function, "__code__"): + return target_function.__code__ + + return self._python_function + + def _generate_scoped_tracing_options(self, scope, scope_type): + """Creates TracingOptions for variable creator scopes.""" + + weak_wrapped_fn = None + compile_with_xla = self._jit_compile + + def wrapped_fn(*args, **kwds): + """Wraps `self._python_function` in a variable creator scope.""" + # We register a variable creator with reduced priority. If an outer + # variable creator is just modifying keyword arguments to the variable + # constructor, this will work harmoniously. Since the `scope` registered + # here actually creates the variable, it taking priority would otherwise + # ignore the outer creator. + # + # If an outer variable creator calls the variable constructor manually, + # for example creating a MirroredVariable, then they won't call our + # creator. This means we won't be able to trace the initialization graph, + # and so variable initializers can't depend on function arguments. This is + # better than the alternative, tracing the initialization graph but giving + # the user a variable type they didn't want. + default_graph = ops.get_default_graph() + with default_graph._variable_creator_scope(scope, priority=50): # pylint: disable=protected-access + # __wrapped__ allows AutoGraph to swap in a converted function. We give + # the function a weak reference to itself to avoid a reference cycle. + with OptionalXlaContext(compile_with_xla): + out = weak_wrapped_fn().__wrapped__(*args, **kwds) + return out + + weak_wrapped_fn = weakref.ref(wrapped_fn) + + return self._generate_tracing_options(tf_decorator.make_decorator( + self._python_function, + wrapped_fn), scope_type) + + def _create_implements_attribute(self, implements_arg): + """Creates the attribute value corresponding to attribute_lib.IMPLEMENTS.""" + attributes = {} + if isinstance(implements_arg, str): + # First check if the attribute_lib.IMPLEMENTS is specified as a + # NameAttrList. This is used when apart from the function name being + # implemented, a list of attributes is also being specified. + # The attributes are specified as key-value pairs in the NameAttrList + # of the corresponding AttrValue. The function name will be in the + # 'name' field of the NameAttrList. Else, it is just a string + # corresponding to the function name. + try: + attr_value = attr_value_pb2.AttrValue() + nameattrlist = attr_value_pb2.NameAttrList() + _text_format.Merge(implements_arg, nameattrlist) + attr_value.func.CopyFrom(nameattrlist) + attributes[attributes_lib.IMPLEMENTS] = attr_value + except (_text_format.ParseError, DecodeError): + attributes[attributes_lib.IMPLEMENTS] = implements_arg + return attributes + + def _generate_tracing_options(self, fn, scope_type): + """Return a TracingOptions catered to the input function.""" + attributes = self._attributes.copy() + + share = self._shared_rendezvous + if share is not None: + attributes[attributes_lib.SHARED_RENDEZVOUS] = share + + if self._jit_compile is not None: + attributes[attributes_lib.XLA_COMPILE] = bool(self._jit_compile) + if self._jit_compile: + attributes[attributes_lib.NO_INLINE] = True + + if self._autograph: + fn = autograph_util.py_func_from_autograph( + fn, self._experimental_autograph_options) + + return tracing_compilation.TracingOptions( + fn, + self._name, + polymorphic_type=self._function_type, + default_values=self._default_values, + scope_type=scope_type, + attributes=attributes, + autograph=self._autograph, + reduce_retracing=self._reduce_retracing, + autograph_options=self._experimental_autograph_options, + function_cache=self._function_cache, + function_captures=self._function_captures, + lock=self._lock, + ) + + def _initialize(self, args, kwds, add_initializers_to=None): + """Initializes, on the first call. + + Creates two `Function`s, one that will allow creation of variables + and one that won't. + + Additionally runs a trace for the `Function` that allows creation + of variables. + + Args: + args: Arguments to the underlying python callable. + kwds: Keyword arguments to the python callable. + add_initializers_to: Where to collect variable initializers, if not None. + """ + created_variables = [] + + def variable_capturing_scope(next_creator, **kwds): + """Creates UnliftedInitializerVariables and saves references to them.""" + enable_variable_lifting = kwds.get("experimental_enable_variable_lifting") + if enable_variable_lifting is None: + enable_variable_lifting = True + if not enable_variable_lifting: + return next_creator(**kwds) + v = UnliftedInitializerVariable( + add_initializers_to=add_initializers_to, **kwds + ) + created_variables.append(weakref.ref(v)) + return v + + self._created_variables = created_variables + self._variable_creation_config = self._generate_scoped_tracing_options( + variable_capturing_scope, + tracing_compilation.ScopeType.VARIABLE_CREATION, + ) + # Force the definition of the function for these arguments + self._concrete_variable_creation_fn = tracing_compilation.trace_function( + args, kwds, self._variable_creation_config + ) + + def invalid_creator_scope(*unused_args, **unused_kwds): + """Disables variable creation.""" + raise ValueError( + "tf.function only supports singleton tf.Variables created on the " + "first call. Make sure the tf.Variable is only created once or " + "created outside tf.function. See " + "https://www.tensorflow.org/guide/function#creating_tfvariables " + "for more information.") + + self._no_variable_creation_config = self._generate_scoped_tracing_options( + invalid_creator_scope, + tracing_compilation.ScopeType.NO_VARIABLE_CREATION, + ) + + def _clone(self, python_function): + """Clone the function with different python function.""" + f = Function( + python_function=(self._python_function + if python_function is None else python_function), + name=self._name, + input_signature=self.input_signature, + autograph=self._autograph, + jit_compile=self._jit_compile, + reduce_retracing=self._reduce_retracing, + experimental_attributes=self._attributes, + experimental_autograph_options=self._experimental_autograph_options) + + if self._shared_rendezvous: + f._shared_rendezvous = self._shared_rendezvous # pylint: disable=protected-access + + return f + + def _decorate(self, decorator): + """Allows the captured Python function to be decorated in place. + + This method is only safe to call when the Function has not been called by a + user. It makes sense to use this method to push a decorator into the + function rather than wrapping the function in the decorator. + + We use this in tf.Module to allow user annotated `tf.functions` to remain as + `Function` objects but still automatically enter the Module name_scope + when they are evaluated like all other methods. + + Args: + decorator: A callable accepting a single argument which is the function + to decorate and returning a callable result. + + Raises: + ValueError: If the function has been called a ValueError is raised. + """ + if ( + self._variable_creation_config is not None + or self._no_variable_creation_config is not None + ): + raise ValueError( + "Functions cannot be decorated after they have been traced." + ) + + self._python_function = decorator(self._python_function) + self._function_type, self._default_values = ( + function_type_utils.make_function_type( + self._python_function, self.input_signature + ) + ) + + # TODO: Remove this private method after updating all its uses + # A good moment to do this could be when the experimental label is removed + def _get_tracing_count(self): + return self.experimental_get_tracing_count() + + def experimental_get_tracing_count(self): + """Returns the number of times the function has been traced. + + For more information on when a function is traced and when it is + traced multiple times see https://www.tensorflow.org/guide/function. + Example: + + >>> @tf.function + ... def double(a): + ... return a + a + >>> double(tf.constant(1)) + >>> double(tf.constant(2)) + >>> double.experimental_get_tracing_count() + 1 + >>> double(tf.constant("a")) + >>> double.experimental_get_tracing_count() + 2 + + + The first time experimental_get_tracing_count is called + it returns 1, as the function is traced the first + time it is called, and the second time the same graph is used + since we're calling it with a parameter of the same type. + + The second time experimental_get_tracing_count is called + it returns 2, as we called double with a + different argument type, and so it was traced again. + + """ + return len(self._function_cache) + + @property + def _run_functions_eagerly(self): + return eager_function_run.RUN_FUNCTIONS_EAGERLY + + @traceback_utils.filter_traceback + def __call__(self, *args, **kwds): + # Implements PolymorphicFunction.__call__. + if self._run_functions_eagerly: + with trace.Trace(self._name, tf_function_call="eager"): + return self._python_function(*args, **kwds) + + # Only count the statistics the first time, before initialization took + # place. + if self._created_variables is None: + compiled = bool(self._jit_compile and + not control_flow_util.GraphOrParentsInXlaContext( + ops.get_default_graph())) + # For nested functions, increment the counter only when a function with + # jit_compile=True is called within a function with jit_compile=False. We + # count this special case to correctly record that both jit_compile=True + # and jit_compile=False is being used for parts of the outer function. + if ops.executing_eagerly_outside_functions() and ( + context.executing_eagerly() or compiled): + # Labels must be strings in Python, so we convert 'compiled' to a string + _tf_function_counter.get_cell(str(int(compiled))).increase_by(1) + + tracing_count = self.experimental_get_tracing_count() + with trace.Trace(self._name) as tm: + # TODO(cheshire): Do not duplicate the XLAControlFlowContext annotation. + compiler = "xla" if self._jit_compile else "nonXla" + + with OptionalXlaContext(self._jit_compile): + result = self._call(*args, **kwds) + + new_tracing_count = self.experimental_get_tracing_count() + without_tracing = (tracing_count == new_tracing_count) + execution_mode = "notTraced" if without_tracing else "traced" + tm.set_metadata(tf_function_call=execution_mode + "-" + compiler, + tracing_count=new_tracing_count) + + if context.executing_eagerly(): + if without_tracing: + _frequent_tracing_detector_manager.called_without_tracing( + self._key_for_call_stats) + else: + _frequent_tracing_detector_manager.called_with_tracing( + self._key_for_call_stats, self._python_function, + self._omit_frequent_tracing_warning) + + return result + + def _call(self, *args, **kwds): + """Calls the graph function.""" + self._lock.acquire() + bound_args = function_type_utils.canonicalize_function_inputs( + args, + kwds, + self._function_type, + self._default_values, + self._is_pure, + ) + args, kwds = bound_args.args, bound_args.kwargs + if self._created_variables: + # Release the lock early so that multiple threads can perform the call + # in parallel. + self._lock.release() + # In this case we have created variables on the first call, so we run the + # defunned version which is guaranteed to never create variables. + return tracing_compilation.call_function( + args, kwds, self._no_variable_creation_config + ) + elif self._variable_creation_config is not None: + # Release the lock early so that multiple threads can perform the call + # in parallel. + self._lock.release() + # In this case we have not created variables on the first call. So we can + # run the first trace but we should fail if variables are created. + results = tracing_compilation.call_function( + args, kwds, self._variable_creation_config + ) + if self._created_variables: + raise ValueError("Creating variables on a non-first call to a function" + " decorated with tf.function.") + return results + + try: + # This is the first call of __call__, so we have to initialize. + initializers = [] + self._initialize(args, kwds, add_initializers_to=initializers) + finally: + # At this point we know that the initialization is complete (or less + # interestingly an exception was raised) so we no longer need a lock. + self._lock.release() + + if self._created_variables: + try: + # Attempt to initialize variables eagerly and without conds by lifting + # out initialization graphs. This is the only initialization strategy + # compatible with XLA at the moment. + self._initialize_uninitialized_variables(initializers) + except lift_to_graph.UnliftableError: + pass # Fall through to cond-based initialization. + else: + # Lifting succeeded, so variables are initialized and we can run the + # no_variable_creation function. + return tracing_compilation.call_function( + args, kwds, self._no_variable_creation_config + ) + else: + bound_args = self._concrete_variable_creation_fn.function_type.bind( + *args, **kwds + ) + # If we did not create any variables the trace we have is good enough. + filtered_flat_args = ( + self._concrete_variable_creation_fn.function_type.unpack_inputs( + bound_args + ) + ) + return self._concrete_variable_creation_fn._call_flat( # pylint: disable=protected-access + filtered_flat_args, + self._concrete_variable_creation_fn.captured_inputs, + ) + + def fn_with_cond(inner_args, inner_kwds): + """Conditionally runs initialization if it's needed.""" + condition = True + for v, _ in initializers: + condition = math_ops.logical_and( + condition, resource_variable_ops.var_is_initialized_op( + v.handle)) + # We want to call no_variable_creation if possible because it avoids + # recomputing potentially expensive initializers. + return cond.cond( + condition, + lambda: tracing_compilation.call_function( # pylint: disable=g-long-lambda + inner_args, inner_kwds, self._no_variable_creation_config + ), + lambda: self._concrete_variable_creation_fn( # pylint: disable=g-long-lambda + *inner_args, **inner_kwds + ), + ) + + # We've created variables and are unable to lift the initialization graphs, + # so we fall back to initializing with conds while running the function. + # TODO(b/216870587) Note that this path is not currently supported for XLA. + if self._jit_compile: + raise errors.UnimplementedError( + None, None, + "We failed to lift variable creations out of this tf.function, " + "so this tf.function cannot be run on XLA. A possible workaround is " + "to move variable creation outside of the XLA compiled function.") + canon_args, canon_kwds = bound_args.args, bound_args.kwargs + options = tracing_compilation.TracingOptions(fn_with_cond, "fn_with_cond") + return tracing_compilation.call_function( + (canon_args, canon_kwds), {}, options + ) + + def experimental_get_compiler_ir(self, *args, **kwargs): + # Implements PolymorphicFunction.experimental_get_compiler_ir + context.ensure_initialized() + if not self._jit_compile: + raise ValueError("Compiler IR can only be returned for functions marked " + "with 'jit_compile=True'") + + is_tensor_spec = lambda x: isinstance(x, tensor_spec.TensorSpec) + + def _check_inputs(args, kwargs): + all_inputs = list(args) + list(kwargs.values()) + # Emtpy input is okay. + if not all_inputs: + return + if any(map(is_tensor_spec, all_inputs)) and any( + map(lambda x: not is_tensor_spec(x), all_inputs) + ): + raise ValueError( + "experimental_get_compiler_ir supports either " + "(1) all inputs are TensorSpec or " + "(2) all inputs are tf.Tensor/python variables" + ) + + _check_inputs(args, kwargs) + if ( + len(args) + len(kwargs.values()) > 0 + and all(map(is_tensor_spec, args)) + and all(map(is_tensor_spec, kwargs.values())) + ): + # For the case inputs are not empty and input types are all tf.TensorSpec + concrete_fn = self.get_concrete_function(*args, **kwargs) + return compiler_ir.from_concrete_function(concrete_fn) + + concrete_fn = self.get_concrete_function(*args, **kwargs) + fn_name = concrete_fn.name + + # pylint: disable=protected-access + bound_args = function_type_utils.canonicalize_function_inputs( + args, kwargs, concrete_fn.function_type + ) + filtered_flat_args = concrete_fn.function_type.unpack_inputs(bound_args) + + def compiler_ir_generator(stage="hlo", device_name=None): + device_name = compiler_ir.maybe_get_device_name(device_name) + res_bytes = context.context().get_compiler_ir( + device_name=device_name, + function_name=fn_name, + flat_args=list(filtered_flat_args), + captured_inputs=concrete_fn.captured_inputs, + stage=stage, + ) + if stage in ("hlo_serialized", "optimized_hlo_serialized", + "optimized_hlo_proto_serialized"): + return res_bytes + else: + return res_bytes.decode("utf-8") + + return compiler_ir_generator + + @property + def python_function(self): + """The python function wrapped in this tf.function.""" + return self._python_function + + @property + def input_signature(self): + return function_type_utils.to_input_signature(self._function_type) + + @property + def function_spec(self): + return function_type_utils.FunctionSpec( + self._function_type, + self._default_values, + False, + self._name, + self._jit_compile, + ) + + @property + def function_type(self): + return self._function_type + + def pretty_printed_concrete_signatures(self, verbose=True): + joiner = "\n\n" if verbose else "\n" + return joiner.join([ + c.pretty_printed_signature(verbose=verbose) + for c in self._list_all_concrete_functions() + ]) + + def _initialize_uninitialized_variables(self, initializers): + """Make and call a `ConcreteFunction` which initializes variables.""" + + if not initializers: + return + + var_is_initialized = _evaluate_var_is_initialized( + [v for v, _ in initializers]) + + def initialize_variables(): + op_map = object_identity.ObjectIdentityDictionary() + + inits = [] + for (v, init), is_initialized in zip(initializers, var_is_initialized): + with ops.init_scope(): + if is_initialized: + continue + inits.append(init) + + if inits: + op_map = lift_to_graph.lift_to_graph( + inits, ops.get_default_graph(), op_map=op_map) + for (v, init), is_initialized in zip(initializers, var_is_initialized): + with ops.init_scope(): + if is_initialized: + continue + v.assign(op_map[init], read_value=False) + + with ops.init_scope(): + # Note: using tracing compilation here avoids an infinite recursion. + # Most of the code in this function runs eagerly with init_scope, where + # autograph is not necessary. + options = tracing_compilation.TracingOptions( + initialize_variables, "initialize_variables", autograph=False + ) + return tracing_compilation.call_function(tracing_options=options) + + def get_initialization_function(self, *args, **kwargs): + """Returns a `ConcreteFunction` which initializes this function's variables. + + Requires that this function hasn't been accessed yet through either calling + it or calling get_concrete_function. Fails if we cannot build an initializer + function which does not depend on the concrete values of the inputs to this + function. + + Note that running this function will overwrite any values currently assigned + to variables, for example restores from a checkpoint. + + Args: + *args: arguments to the underlying python callable. + **kwargs: keyword arguments to the python callable. + + Returns: + A `ConcreteFunction` object which initializes the variables of this + function. + + Raises: + RuntimeError: if called after the variables have been initialized. + """ + with self._lock: + if self._variable_creation_config is not None: + raise RuntimeError( + "get_initialization_function cannot be called after the function " + "has been used") + # Here we trace the function, collect the initializers, and attempt to + # extract them and run them eagerly. Fail only if we cannot do so. + initializers = [] + self._initialize(args, kwargs, add_initializers_to=initializers) + + def initialize_variables(): + for v, init in initializers: + v.assign( + lift_to_graph.lift_to_graph([init], ops.get_default_graph())[init], + read_value=False) + + # Note: using tracing compilation here avoids an infinite recursion. + options = tracing_compilation.TracingOptions( + initialize_variables, "initialize_variables" + ) + return tracing_compilation.trace_function(tracing_options=options) + + def _list_all_concrete_functions(self): + """Returns all concrete functions.""" + if self.input_signature is not None: + self.get_concrete_function() + return self._function_cache.values() + + def _list_all_concrete_functions_for_serialization(self): + """Returns all concrete functions for serialization. + + Returns: + A list of instances of `ConcreteFunction`. + """ + seen_signatures = [] + if self.input_signature is not None: + seen_signatures.append((self.input_signature, {})) + else: + concrete_functions = self._list_all_concrete_functions() + for concrete_function in concrete_functions: + signature = concrete_function.structured_input_signature + flattened = nest.flatten(signature) + if any( + isinstance(arg, func_graph_module.UnknownArgument) + for arg in flattened): + logging.info("Unsupported signature for serialization: %s.", + signature) + continue + equal_to_signature = functools.partial( + function_type_utils.is_same_structure, signature, check_values=True) + if not any(equal_to_signature(s) for s in seen_signatures): + seen_signatures.append(signature) + + # Re-create concrete functions for these signatures. Re-creating ensures + # that if the cache key has changed, the function will be traced again. + concrete_functions = [] + for args, kwargs in seen_signatures: + concrete_functions.append(self.get_concrete_function(*args, **kwargs)) + return concrete_functions + + def _trackable_children(self, save_type="checkpoint", **kwargs): + """For implementing `Trackable`.""" + if save_type == "checkpoint": + return {} + return {f"trace_{n}": fn for n, fn in + enumerate(self._list_all_concrete_functions_for_serialization())} + + def _deserialization_dependencies(self, children): + """Returns concrete functions which must be loaded before this object.""" + return children + + def _get_concrete_function_garbage_collected(self, *args, **kwargs): + """Returns a `ConcreteFunction` specialized to inputs and execution context. + + Unlike `get_concrete_function(...)`, the graph will be deleted when the + returned function is deleted. It's useful to avoid creating a reference + cycle when you know for sure that the graph will be no longer used without + the returned function. + + Args: + *args: inputs to specialize on. + **kwargs: inputs to specialize on. + + Returns: + A TensorFlow function which takes exactly one `tf.Tensor` per argument. + + Raises: + ValueError: if this object has not yet been called on concrete values. + """ + with self._lock: + if self._variable_creation_config is None: + initializers = [] + self._initialize(args, kwargs, add_initializers_to=initializers) + self._initialize_uninitialized_variables(initializers) + + if self._created_variables: + # In this case we have created variables on the first call, so we run the + # version which is guaranteed to never create variables. + return tracing_compilation.trace_function( + args, + kwargs, + dataclasses.replace( + self._no_variable_creation_config, bind_graph_to_function=True + ), + ) + elif self._variable_creation_config is not None: + # In this case we have not created variables on the first call. So we can + # run the first trace but we should fail if variables are created. + concrete = tracing_compilation.trace_function( + args, + kwargs, + dataclasses.replace( + self._variable_creation_config, bind_graph_to_function=True + ), + ) + if self._created_variables: + raise ValueError("Creating variables on a non-first call to a function" + " decorated with tf.function.") + return concrete + + def get_concrete_function(self, *args, **kwargs): + # Implements PolymorphicFunction.get_concrete_function. + concrete = self._get_concrete_function_garbage_collected(*args, **kwargs) + concrete._garbage_collector.release() # pylint: disable=protected-access + return concrete + + def __tf_tracing_type__(self, _): + return trace_type.Weakref(weakref.ref(self)) + + def __get__(self, instance, owner): + """Makes it possible to decorate instance methods.""" + del owner + # `instance` here is the instance that this `Function` was accessed through + # e.g., for + # + # class Foo: + # + # @tf.function + # def bar(self): + # ... + # + # foo = Foo() + # foo.bar() # `foo.bar` is a `Function` instance + # + # then `instance` will be `foo` (and `owner` will be `Foo`). For composite + # tensors, we can just treat `instance` as a normal parameter. But for + # other types, we create a new instance of `Function` here to allow + # different instances each to create variables once, thereby allowing + # methods to be decorated with tf.function. Keeps a cache to avoid retracing + # the function every time the descriptor is accessed. + # TODO(mdan): Identify types which can just be parameters more generically. + # + # The check for instance._type_spec=None is used because certain classes + # (including subclasses of tf.linalg.LinearOperator) are subclasses of + # CompositeTensor but do not actually implement the required APIs. + # TODO(b/199278478): Fix those classes, then remove the check for + # `instance._type_spec is not None`. + if (isinstance(instance, composite_tensor.CompositeTensor) and + instance._type_spec is not None): # pylint: disable=protected-access + return types_lib.MethodType(self, instance) + if instance not in self._descriptor_cache: + if instance is None: + return self + # TODO(mdan): If the CompositeTensor path works, do the same here. + # It's unclear whether we need the tf-decorator, or could just call + # MethodType(self.clone(), instance) + self._descriptor_cache[instance] = ( + class_method_to_instance_method(self, instance)) + return self._descriptor_cache[instance] + + +@tf_export("function") +@deprecation.deprecated_args(None, + "experimental_compile is deprecated, use " + "jit_compile instead", "experimental_compile") +@deprecation.deprecated_args(None, + "experimental_relax_shapes is deprecated, use " + "reduce_retracing instead", + "experimental_relax_shapes") +@deprecation.deprecated_args(None, + "experimental_follow_type_hints is deprecated", + "experimental_follow_type_hints") +def function( + func=None, + input_signature=None, + autograph=True, + jit_compile=None, + reduce_retracing=False, + experimental_implements=None, + experimental_autograph_options=None, + experimental_attributes=None, + experimental_relax_shapes=None, + experimental_compile=None, + experimental_follow_type_hints=None # pylint: disable=unused-argument +) -> core.PolymorphicFunction: + """Compiles a function into a callable TensorFlow graph. + + `tf.function` constructs a `tf.types.experimental.PolymorphicFunction` that + executes a TensorFlow graph (`tf.Graph`) created by trace-compiling the + TensorFlow operations in `func`. More information on the topic can be found + in [Introduction to Graphs and tf.function] + (https://www.tensorflow.org/guide/intro_to_graphs). + + See [Better Performance with tf.function] + (https://www.tensorflow.org/guide/function) for tips on performance and + known limitations. + + Example usage: + + >>> @tf.function + ... def f(x, y): + ... return x ** 2 + y + >>> x = tf.constant([2, 3]) + >>> y = tf.constant([3, -2]) + >>> f(x, y) + + + The trace-compilation allows non-TensorFlow operations to execute, but under + special conditions. In general, only TensorFlow operations are guaranteed to + run and create fresh results whenever the `PolymorphicFunction` is called. + + ## Features + + `func` may use data-dependent Python control flow statements, including `if`, + `for`, `while` `break`, `continue` and `return`: + + >>> @tf.function + ... def f(x): + ... if tf.reduce_sum(x) > 0: + ... return x * x + ... else: + ... return -x // 2 + >>> f(tf.constant(-2)) + + + `func`'s closure may include `tf.Tensor` and `tf.Variable` objects: + + >>> @tf.function + ... def f(): + ... return x ** 2 + y + >>> x = tf.constant([-2, -3]) + >>> y = tf.Variable([3, -2]) + >>> f() + + + `func` may also use ops with side effects, such as `tf.print`, `tf.Variable` + and others: + + >>> v = tf.Variable(1) + >>> @tf.function + ... def f(x): + ... for i in tf.range(x): + ... v.assign_add(i) + >>> f(3) + >>> v + + + Important: Any Python side-effects (appending to a list, printing with + `print`, etc) will only happen once, when `func` is traced. To have + side-effects executed into your `tf.function` they need to be written + as TF ops: + + >>> l = [] + >>> @tf.function + ... def f(x): + ... for i in x: + ... l.append(i + 1) # Caution! Will only happen once when tracing + >>> f(tf.constant([1, 2, 3])) + >>> l + [] + + Instead, use TensorFlow collections like `tf.TensorArray`: + + >>> @tf.function + ... def f(x): + ... ta = tf.TensorArray(dtype=tf.int32, size=0, dynamic_size=True) + ... for i in range(len(x)): + ... ta = ta.write(i, x[i] + 1) + ... return ta.stack() + >>> f(tf.constant([1, 2, 3])) + + + ## `tf.function` creates polymorphic callables + + Internally, `tf.types.experimental.PolymorphicFunction` may contain multiple + `tf.types.experimental.ConcreteFunction`s, each specialized to arguments with + different data types or shapes, since TensorFlow can perform more + optimizations on graphs of specific shapes, dtypes and values of constant + arguments. `tf.function` treats any pure Python values as opaque objects (best + thought of as compile-time constants), and builds a separate `tf.Graph` for + each set of Python arguments that it encounters. + For more information, see the + [tf.function guide](https://www.tensorflow.org/guide/function#rules_of_tracing) + + Executing a `PolymorphicFunction` will select and execute the appropriate + `ConcreteFunction` based on the argument types and values. + + To obtain an individual `ConcreteFunction`, use the + `PolymorphicFunction.get_concrete_function` method. It can be called with the + same arguments as `func` and returns a + `tf.types.experimental.ConcreteFunction`. `ConcreteFunction`s are backed by a + single `tf.Graph`: + + >>> @tf.function + ... def f(x): + ... return x + 1 + >>> isinstance(f.get_concrete_function(1).graph, tf.Graph) + True + + `ConcreteFunction`s can be executed just like `PolymorphicFunction`s, but their + input is resticted to the types to which they're specialized. + + ## Retracing + + `ConcreteFunctions` are built (traced) on the fly, as the `PolymorphicFunction` is + called with new TensorFlow types or shapes, or with new Python values as + arguments. When `PolymorphicFunction` builds a new trace, it is said that `func` + is retraced. Retracing is a frequent performance concern for `tf.function` as + it can be considerably slower than executing a graph that's already been + traced. It is ideal to minimize the amount of retracing in your code. + + Caution: Passing python scalars or lists as arguments to `tf.function` will + usually retrace. To avoid this, pass numeric arguments as Tensors whenever + possible: + + >>> @tf.function + ... def f(x): + ... return tf.abs(x) + >>> f1 = f.get_concrete_function(1) + >>> f2 = f.get_concrete_function(2) # Slow - compiles new graph + >>> f1 is f2 + False + >>> f1 = f.get_concrete_function(tf.constant(1)) + >>> f2 = f.get_concrete_function(tf.constant(2)) # Fast - reuses f1 + >>> f1 is f2 + True + + Python numerical arguments should only be used when they take few distinct + values, such as hyperparameters like the number of layers in a neural network. + + ## Input signatures + + For Tensor arguments, `PolymorphicFunction`creates a new `ConcreteFunction` for + every unique set of input shapes and datatypes. The example below creates two + separate `ConcreteFunction`s, each specialized to a different shape: + + >>> @tf.function + ... def f(x): + ... return x + 1 + >>> vector = tf.constant([1.0, 1.0]) + >>> matrix = tf.constant([[3.0]]) + >>> f.get_concrete_function(vector) is f.get_concrete_function(matrix) + False + + An "input signature" can be optionally provided to `tf.function` to control + this process. The input signature specifies the shape and type of each + Tensor argument to the function using a `tf.TensorSpec` object. More general + shapes can be used. This ensures only one `ConcreteFunction` is created, and + restricts the `PolymorphicFunction` to the specified shapes and types. It is + an effective way to limit retracing when Tensors have dynamic shapes. + + >>> @tf.function( + ... input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)]) + ... def f(x): + ... return x + 1 + >>> vector = tf.constant([1.0, 1.0]) + >>> matrix = tf.constant([[3.0]]) + >>> f.get_concrete_function(vector) is f.get_concrete_function(matrix) + True + + ## Variables may only be created once + + `tf.function` only allows creating new `tf.Variable` objects when it is called + for the first time: + + >>> class MyModule(tf.Module): + ... def __init__(self): + ... self.v = None + ... + ... @tf.function + ... def __call__(self, x): + ... if self.v is None: + ... self.v = tf.Variable(tf.ones_like(x)) + ... return self.v * x + + In general, it is recommended to create `tf.Variable`s outside of + `tf.function`. + In simple cases, persisting state across `tf.function` boundaries may be + implemented using a pure functional style in which state is represented by + `tf.Tensor`s passed as arguments and returned as return values. + + Contrast the two styles below: + + >>> state = tf.Variable(1) + >>> @tf.function + ... def f(x): + ... state.assign_add(x) + >>> f(tf.constant(2)) # Non-pure functional style + >>> state + + + >>> state = tf.constant(1) + >>> @tf.function + ... def f(state, x): + ... state += x + ... return state + >>> state = f(state, tf.constant(2)) # Pure functional style + >>> state + + + ## Python operations execute only once per trace + + `func` may contain TensorFlow operations mixed with pure Python operations. + However, when the function is executed, only the TensorFlow operations will + run. The Python operations run only once, at trace time. If TensorFlow + operations depend on results from Python operations, those results will be + frozen into the graph. + + >>> @tf.function + ... def f(a, b): + ... print('this runs at trace time; a is', a, 'and b is', b) + ... return b + >>> f(1, tf.constant(1)) + this runs at trace time; a is 1 and b is Tensor("...", shape=(), dtype=int32) + + + >>> f(1, tf.constant(2)) + + + >>> f(2, tf.constant(1)) + this runs at trace time; a is 2 and b is Tensor("...", shape=(), dtype=int32) + + + >>> f(2, tf.constant(2)) + + + Args: + func: The function to be compiled. If `func` is None, `tf.function` returns + a decorator that can be invoked with a single argument - `func`. In other + words, `tf.function(input_signature=...)(func)` is equivalent to + `tf.function(func, input_signature=...)`. The former can be used as + decorator. + input_signature: A possibly nested sequence of `tf.TensorSpec` objects + specifying the shapes and dtypes of the Tensors that will be supplied to + this function. If `None`, a separate function is instantiated for each + inferred input signature. If input_signature is specified, every input to + `func` must be a `Tensor`, and `func` cannot accept `**kwargs`. + autograph: Whether autograph should be applied on `func` before tracing a + graph. Data-dependent Python control flow statements require + `autograph=True`. For more information, see the + [tf.function and AutoGraph guide]( + https://www.tensorflow.org/guide/function#autograph_transformations). + jit_compile: If `True`, compiles the function using + [XLA](https://tensorflow.org/xla). XLA performs compiler optimizations, + such as fusion, and attempts to emit more efficient code. This may + drastically improve the performance. If set to `True`, + the whole function needs to be compilable by XLA, or an + `errors.InvalidArgumentError` is thrown. + If `None` (default), compiles the function with XLA when running on TPU + and goes through the regular function execution path when running on + other devices. + If `False`, executes the function without XLA compilation. Set this value + to `False` when directly running a multi-device function on TPUs (e.g. two + TPU cores, one TPU core and its host CPU). + Not all functions are compilable, see a list of + [sharp corners](https://tensorflow.org/xla/known_issues). + reduce_retracing: When True, `tf.function` attempts to reduce the + amount of retracing, for example by using more generic shapes. This + can be controlled for user objects by customizing their associated + `tf.types.experimental.TraceType`. + experimental_implements: If provided, contains a name of a "known" function + this implements. For example "mycompany.my_recurrent_cell". + This is stored as an attribute in inference function, + which can then be detected when processing serialized function. + See [standardizing composite ops](https://github.com/tensorflow/community/blob/master/rfcs/20190610-standardizing-composite_ops.md) # pylint: disable=line-too-long + for details. For an example of utilizing this attribute see this + [example](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/mlir/lite/transforms/prepare_composite_functions_tf.cc) + The code above automatically detects and substitutes function that + implements "embedded_matmul" and allows TFLite to substitute its own + implementations. For instance, a tensorflow user can use this + attribute to mark that their function also implements + `embedded_matmul` (perhaps more efficiently!) + by specifying it using this parameter: + `@tf.function(experimental_implements="embedded_matmul")` + This can either be specified as just the string name of the function or + a NameAttrList corresponding to a list of key-value attributes associated + with the function name. The name of the function will be in the 'name' + field of the NameAttrList. To define a formal TF op for this function + implements, try the experimental [composite TF](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/mlir/tfr) + project. + experimental_autograph_options: Optional tuple of + `tf.autograph.experimental.Feature` values. + experimental_attributes: Optional dictionary of attributes to include in the + generated FunctionDefs. + experimental_relax_shapes: Deprecated. Use `reduce_retracing` + instead. + experimental_compile: Deprecated alias to 'jit_compile'. + experimental_follow_type_hints: Deprecated. Please use input_signature or + reduce_retracing instead. + + Returns: + If `func` is not None, returns a `tf.types.experimental.PolymorphicFunction`. + If `func` is None, returns a decorator that, when invoked with a single + `func` argument, returns a `tf.types.experimental.PolymorphicFunction`. + + Raises: + `ValueError` when attempting to use `jit_compile=True`, but XLA support is + not available. + """ + if jit_compile is None and JIT_COMPILE_FUNCTIONS: + jit_compile = True + + # TODO(b/224808187): Remove after renaming usages. + if experimental_relax_shapes: + reduce_retracing = True + + def decorated(inner_function): + try: + name = inner_function.__name__ + except AttributeError: + name = "function" + return tf_decorator.make_decorator( + inner_function, + decorator_name="tf.function", + decorator_func=Function( + inner_function, + name, + input_signature=input_signature, + autograph=autograph, + experimental_autograph_options=experimental_autograph_options, + reduce_retracing=reduce_retracing, + + # TODO(b/171825496): Update once `experimental_compile` is removed + # entirely in favor of 'jit_compile'. + jit_compile=deprecation.deprecated_argument_lookup( + "jit_compile", + jit_compile, + "experimental_compile", + experimental_compile), + experimental_implements=experimental_implements, + experimental_attributes=experimental_attributes)) + + # This code path is for the `foo = tf.function(foo, ...)` use case + if func is not None: + return decorated(func) + + # This code path is for the + # + # @tf.function(...) + # def foo(...): + # ... + # + # use case, which is equivalent to `foo = tf.function(...)(foo)` + return decorated + + +def class_method_to_instance_method(original_function, instance): + """Constructs a new `Function` with `self` bound.""" + weak_instance = weakref.ref(instance) + + # Note: while we could bind to a weakref proxy instead, that causes the + # bound method to be unhashable. + bound_method = types_lib.MethodType( + original_function.python_function, + tf_method_target.TfMethodTarget(weak_instance, + original_function.python_function)) + + # original_function is expected to be PolymorphicFunction + assert hasattr(original_function, "_name") + assert hasattr(original_function, "_autograph") + assert hasattr(original_function, "_function_type") + assert hasattr(original_function, "python_function") + + weak_bound_method_wrapper = None + + def bound_method_wrapper(*args, **kwargs): + """Wraps either a dummy MethodType or a converted AutoGraph function.""" + # __wrapped__ allows AutoGraph to swap in a converted function. + strong_bound_method_wrapper = weak_bound_method_wrapper() + wrapped_fn = strong_bound_method_wrapper.__wrapped__ + + if wrapped_fn is strong_bound_method_wrapper.__original_wrapped__: + # If __wrapped__ was not replaced, then call original_function. + # TODO(mdan): For better consistency, use the wrapper's call(). + wrapped_fn = original_function.python_function + return wrapped_fn(weak_instance(), *args, **kwargs) + + # If __wrapped__ was replaced, then it is always an unbound function. + # However, the replacer is still responsible for attaching self properly. + # TODO(mdan): Is it possible to do it here instead? + return wrapped_fn(*args, **kwargs) + + weak_bound_method_wrapper = weakref.ref(bound_method_wrapper) + + # pylint: disable=protected-access + # We make a dummy MethodType object to generate the correct bound method + # signature. The actual call is to a function with a weak reference to + # `instance`. + instance_func = type(original_function)( + tf_decorator.make_decorator(bound_method, bound_method_wrapper), + name=original_function._name, + autograph=original_function._autograph, + input_signature=original_function.input_signature, + reduce_retracing=original_function._reduce_retracing, + jit_compile=original_function._jit_compile, + experimental_attributes=original_function._attributes) + # pylint: enable=protected-access + + # We wrap the bound method with tf_decorator so inspection works correctly + wrapped_instance_func = tf_decorator.make_decorator(bound_method, + instance_func) + return wrapped_instance_func diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/saved_model_exported_concrete.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/saved_model_exported_concrete.py new file mode 100644 index 0000000000000000000000000000000000000000..84404fd1fcd607062180c55d06d368433833b387 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/saved_model_exported_concrete.py @@ -0,0 +1,121 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""ExportedConcreteFunction class and its associated functions. + +Part of saved model utils, a shim layer for working with +functions exported/restored from saved models. +This functionality should ultimately be moved into a first-class core API. +""" + +import gc +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.trackable import base as trackable + + +# TODO(kathywu): Delete this class when ConcreteFunctions can be copied with new +# captures. +class ExportedConcreteFunction(trackable.Trackable): + """A callable class that uses captures from the exported SavedModel graph.""" + __slots__ = ("function", "tensor_map") + + def __init__(self, function, tensor_map): + self.function = function + self.tensor_map = tensor_map + + def __call__(self, *args, **kwargs): + bound_arguments = function_type_utils.canonicalize_function_inputs( + args, kwargs, self.function._function_type + ) + filtered_flat_args = self.function._function_type.unpack_inputs( + bound_arguments + ) + export_captures = _map_captures_to_created_tensors( + self.function.graph.captures, self.tensor_map, self.function) + return self.function._call_flat(filtered_flat_args, export_captures) + + +def _map_captures_to_created_tensors(original_captures, tensor_map, function): + """Maps eager tensors captured by a function to Graph resources for export. + + Args: + original_captures: A dictionary mapping from tensors captured by the + function to interior placeholders for those tensors (inside the function + body). + tensor_map: A dictionary mapping from resource tensors owned by the eager + context to resource tensors in the exported graph. + function: Function with the original captures. Only used when raising the + AssertionError. + + Returns: + A list of stand-in tensors which belong to the exported graph, corresponding + to the function's captures. + + Raises: + AssertionError: If the function references a resource which is not part of + `tensor_map`. + """ + export_captures = [] + for exterior, interior in original_captures: + mapped_resource = tensor_map.get(exterior, None) + if mapped_resource is None: + _raise_untracked_capture_error(function.name, exterior, interior) + export_captures.append(mapped_resource) + return export_captures + + +def _raise_untracked_capture_error(function_name, capture, + internal_capture=None, + node_path=None): + """Raises AssertionError due to being unable to export a function.""" + msg = ("Tried to export a function which references an 'untracked' resource. " + "TensorFlow objects (e.g. tf.Variable) captured by functions must be " + "'tracked' by assigning them to an attribute of a tracked object or " + "assigned to an attribute of the main object directly. See the " + "information below:" + f"\n\tFunction name = {function_name}") + + if node_path is not None: + msg += f"\n\tPath to Function = {node_path}" + + msg += f"\n\tCaptured Tensor = {capture}" + msg += f"\n\t{_get_trackable_parent_error_string(capture)}" + + if internal_capture is not None: + msg += f"\n\tInternal Tensor = {internal_capture}" + raise AssertionError(msg) + + +def _get_trackable_parent_error_string(capture): + """Gets error string with the capture's parent object.""" + parent = getattr(capture, "_parent_trackable", None) + if parent is not None: + return f"Trackable referencing this tensor = {parent()}" + + # Try to figure out where the resource came from by iterating over objects + # which reference it. This is slow and doesn't help us figure out how to + # match it to other objects when loading the SavedModel as a checkpoint, + # so we can't continue saving. But we can at least tell the user what + # needs attaching. + trackable_referrers = [] + for primary_referrer in gc.get_referrers(capture): + if isinstance(primary_referrer, trackable.Trackable): + trackable_referrers.append(primary_referrer) + for secondary_referrer in gc.get_referrers(primary_referrer): + if isinstance(secondary_referrer, trackable.Trackable): + trackable_referrers.append(secondary_referrer) + return ("Trackable Python objects referring to this tensor " + "(from gc.get_referrers, limited to two hops) = [\n\t\t{}]" + .format("\n\t\t".join([repr(obj) for obj in trackable_referrers]))) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/saved_model_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/saved_model_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a42f572bd0c14cb898d3f603323fc044b5616418 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/saved_model_utils.py @@ -0,0 +1,82 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""A shim layer for working with functions exported/restored from saved models. + +This functionality should ultimately be moved into a first-class core API. +""" + +import numpy + +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.saved_model import registration +from tensorflow.python.trackable import base as trackable + + +@registration.register_tf_serializable() +class TrackableConstant(trackable.Trackable): + """Trackable class for captured constants.""" + __slots__ = ("capture", "function", "_exported_tensor") + + def __init__(self, capture, function): + self.capture = capture + self.function = function + self._exported_tensor = None + + def _export_to_saved_model_graph(self, tensor_map, **unused_kwargs): + capture_constant_value = tensor_util.constant_value(self.capture) + if capture_constant_value is None: + raise ValueError( + f"Unable to save function {self.function.name} because it " + f"captures graph tensor {self.capture} from a parent function which " + "cannot be converted to a constant with `tf.get_static_value`.") + + if numpy.prod(self.capture.shape.as_list()) > 1 and numpy.all( + capture_constant_value == capture_constant_value.flat[0]): + # For the common case of a constant array filled with the same + # value, rebuild the constant op specifically with the shape arg, + # since otherwise the whole array is written into the node def, + # causing performance and graph proto size issues (protos cannot be + # bigger than 2GB). + copied_tensor = constant_op.constant( + capture_constant_value.flat[0], + dtype=self.capture.dtype, + shape=self.capture.shape) + else: + copied_tensor = constant_op.constant(capture_constant_value) + + tensor_map[self.capture] = copied_tensor + self._exported_tensor = copied_tensor + return [self.capture] + + def _serialize_to_proto(self, object_proto=None, **kwargs): + object_proto.constant.operation = self._exported_tensor.op.name + + @classmethod + def _deserialize_from_proto(cls, object_proto, operation_attributes, + **kwargs): + tensor_proto = ( + operation_attributes[object_proto.constant.operation]["value"].tensor) + ndarray = tensor_util.MakeNdarray(tensor_proto) + if dtypes.as_dtype(tensor_proto.dtype) == dtypes.string: + with ops.device("CPU"): + # String operations should be done on the CPU. + imported_constant = constant_op.constant(ndarray) + else: + imported_constant = constant_op.constant(ndarray) + return imported_constant diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/tf_method_target.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/tf_method_target.py new file mode 100644 index 0000000000000000000000000000000000000000..23b9a127366689a64640d7d2f2315ecf23dbff2d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/tf_method_target.py @@ -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. +# ============================================================================== +"""Module for the TFMethodTarget Class.""" + +import weakref + +from tensorflow.python.util import tf_inspect + + +# When a method is bound to objects of this type, it allows AutoGraph to +# recover a weak reference the original method's self pointer, so that it can +# execute it consistent with class_method_to_instance_method's +# bound_method_wrapper. +# TODO(b/119246461): This is not pretty. Use a descriptor instead? +class TfMethodTarget: + """Binding target for methods replaced by function and defun.""" + + __slots__ = ("weakrefself_target__", "weakrefself_func__") + + def __init__(self, target, original_python_function): + self.weakrefself_target__ = target + self.weakrefself_func__ = weakref.ref(original_python_function) + + @property + def target(self): + return self.weakrefself_target__() + + @property + def target_class(self): + true_self = self.weakrefself_target__() + if tf_inspect.isclass(true_self): + # Class method + return true_self + else: + return true_self.__class__ + + def call(self, args, kwargs): + wrapped_fn = self.weakrefself_func__() + return wrapped_fn(self.weakrefself_target__(), *args, **kwargs) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/tracing_compilation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/tracing_compilation.py new file mode 100644 index 0000000000000000000000000000000000000000..7cf1642bfa7bb12dbbe12eaa1203cc437aa085cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/tracing_compilation.py @@ -0,0 +1,379 @@ +# 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. +# ============================================================================== +"""Compile Python functions to TF graphs using tracing.""" + +import contextlib +import dataclasses +import enum +import threading +from typing import Any, Callable, Dict, Optional, Tuple + +from tensorflow.core.function import trace_type +from tensorflow.core.function.capture import capture_container +from tensorflow.core.function.polymorphism import function_cache as function_cache_lib +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.eager import monitoring +from tensorflow.python.eager.polymorphic_function import attributes as attributes_lib +from tensorflow.python.eager.polymorphic_function import concrete_function as concrete_function_lib +from tensorflow.python.eager.polymorphic_function import function_context +from tensorflow.python.eager.polymorphic_function import function_type_utils +from tensorflow.python.eager.polymorphic_function import transform +from tensorflow.python.framework import func_graph as func_graph_module +from tensorflow.python.framework import ops +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace +from tensorflow.python.util import compat + +_graph_building_time_counter = monitoring.Counter( + "/tensorflow/core/tf_function/graph_building_time_usecs", + "Time for tf.function to build a graph (us).", +) + + +class ScopeType(enum.Enum): + """Enumerate scopes under which functions might be traced.""" + NO_SCOPE = 1 + VARIABLE_CREATION = 2 + NO_VARIABLE_CREATION = 3 + + +@dataclasses.dataclass +class TracingOptions: + """Configuration options for tracing.""" + # Python function to trace. + python_function: Callable[[Any], Any] = lambda *args, **kwargs: None + + # Name given to the traced function. + name: str = "function" + + # Known FunctionType of the python function. + polymorphic_type: Optional[function_type_lib.FunctionType] = None + + # Known default values for the python function parameters. + default_values: Optional[Dict[str, Any]] = None + + # Identifies effecting scope under which the function is traced. + scope_type: ScopeType = ScopeType.NO_SCOPE + + # FunctionDef attributes for traced function. + attributes: Optional[Dict[str, Any]] = None + + # See https://www.tensorflow.org/guide/autograph for more information. + # If autograph is enabled. + autograph: bool = True + # Optional tuple of `tf.autograph.experimental.Feature` values. + autograph_options: Optional[Tuple[Any, ...]] = None + + # Trace generalized functions where possible to avoid future retracing. + reduce_retracing: bool = False + + # If true, graph of generated Function will be destroyed with the function. + bind_graph_to_function: bool = False + + # A FunctionCache object that holds existing traced functions. + function_cache: Optional[function_cache_lib.FunctionCache] = None + + # A FunctionCaptures object that tracks by-ref captures. + function_captures: Optional[capture_container.FunctionCaptures] = None + + # If specified, guards tracing and function lookup + lock: Optional[threading.Lock] = None + + def __post_init__(self): + if self.attributes: + for attribute in self.attributes: + if attribute not in attributes_lib.TRACING_COMPILATION_ALLOWLIST: + raise ValueError( + f"Tracing compilation does not support `{attribute}` as an" + " attribute." + ) + + if not self.polymorphic_type or self.default_values is None: + self.polymorphic_type = function_type_lib.FunctionType.from_callable( + self.python_function + ) + self.default_values = function_type_lib.FunctionType.get_default_values( + self.python_function + ) + + self._input_signature = function_type_utils.to_input_signature( + self.polymorphic_type + ) + + @property + def is_pure(self): + return self.attributes and attributes_lib.IMPLEMENTS in self.attributes + + @property + def input_signature(self): + return self._input_signature + + +def call_function(args=None, kwargs=None, tracing_options=None): + """Traces a function for args and kwargs and calls it after.""" + if not tracing_options: + tracing_options = TracingOptions() + + args = args if args else () + kwargs = kwargs if kwargs else {} + function = trace_function( + args=args, kwargs=kwargs, tracing_options=tracing_options + ) + + # Bind it ourselves to skip unnecessary canonicalization of default call. + bound_args = function.function_type.bind(*args, **kwargs) + flat_inputs = function.function_type.unpack_inputs(bound_args) + return function._call_flat( # pylint: disable=protected-access + flat_inputs, captured_inputs=function.captured_inputs + ) + + +def trace_function(args=None, kwargs=None, tracing_options=None): + """Returns a `ConcreteFunction` specialized to inputs and execution context. + + Compiles a Graph corresponding to the Python function logic and uses that + to generate a differentiable ConcreteFunction. + + Args: + args: inputs to specialize on. Can be concrete values (e.g. 1) or + `tf.Tensor` or `tf.TensorSpec`. + kwargs: keyword inputs to specialize on. Concrete values (e.g. 1) or + `tf.Tensor` or `tf.TensorSpec`. + tracing_options: TracingOptions for the tracing process. + """ + if not tracing_options: + tracing_options = TracingOptions() + + args = args if args else () + kwargs = kwargs if kwargs else {} + + if tracing_options.input_signature and (args or kwargs): + # Check to see if a valid type can be generated from the args, kwargs + bound_args = function_type_utils.bind_function_inputs( + args, + kwargs, + tracing_options.polymorphic_type, + tracing_options.default_values, + ) + args, kwargs = bound_args.args, bound_args.kwargs + + with tracing_options.lock or contextlib.nullcontext(): + if tracing_options.input_signature and not args and not kwargs: + args = tracing_options.input_signature + kwargs = {} + + concrete_function = _maybe_define_function( + args, kwargs, tracing_options + ) + + if not tracing_options.bind_graph_to_function: + concrete_function._garbage_collector.release() # pylint: disable=protected-access + + return concrete_function + + +def _maybe_define_function(args, kwargs, tracing_options): + """Gets a function for these inputs, defining it if necessary. + + Args: + args: The varargs for the Python function. + kwargs: The keyword args for the Python function. + tracing_options: TracingOptions for the tracing process. + + Returns: + A ConcreteFunction generated based on args, kwargs and tracing_options. + + Raises: + ValueError: If inputs are incompatible with the input signature. + TypeError: If the function inputs include non-hashable objects + RuntimeError: If there's an internal bug (inconsistency) in handling + shape relaxation retracing. + """ + bound_args = function_type_utils.canonicalize_function_inputs( + args, + kwargs, + tracing_options.polymorphic_type, + tracing_options.default_values, + tracing_options.is_pure, + ) + args, kwargs = bound_args.args, bound_args.kwargs + + if tracing_options.input_signature is not None: + args = ( + *tracing_options.input_signature, + *args[len(tracing_options.input_signature) :], + ) + + current_func_context = function_context.make_function_context( + tracing_options.scope_type + ) + + capture_types = ( + tracing_options.function_captures.capture_types + if tracing_options.function_captures + else {} + ) + lookup_func_type, lookup_func_context = ( + function_type_utils.make_canonicalized_monomorphic_type( + args, + kwargs, + capture_types, + tracing_options.polymorphic_type, + ) + ) + + if tracing_options.function_cache is not None: + concrete_function = tracing_options.function_cache.lookup( + lookup_func_type, current_func_context + ) + else: + concrete_function = None + + if concrete_function is not None: + return concrete_function + + # Use a timer for graph building only if not already inside a function. This + # avoids double counting graph building time for nested functions. + with monitoring.MonitoredTimer( + _graph_building_time_counter.get_cell() + ) if not ops.inside_function() else contextlib.nullcontext(): + with trace.Trace("tf.function-graph_building"): + logging.vlog( + 1, + "Creating new FuncGraph for Python function %r (key: %r, %r)", + tracing_options.python_function, + current_func_context, + lookup_func_type, + ) + logging.vlog( + 2, "Python function signature [args: %s] [kwargs: %s]", args, kwargs + ) + ag_status = ( + ag_ctx.Status.ENABLED + if tracing_options.autograph + else ag_ctx.Status.DISABLED + ) + with ag_ctx.ControlStatusCtx( + status=ag_status, options=tracing_options.autograph_options + ): + func_graph = func_graph_module.FuncGraph(tracing_options.name) + if ( + tracing_options.input_signature is None + and tracing_options.reduce_retracing + and tracing_options.function_cache + ): + target_func_type = tracing_options.function_cache.generalize( + current_func_context, lookup_func_type + ) + else: + target_func_type = lookup_func_type + concrete_function = _create_concrete_function( + target_func_type, lookup_func_context, func_graph, tracing_options + ) + + if tracing_options.function_cache is not None: + tracing_options.function_cache.add( + concrete_function, current_func_context + ) + + return concrete_function + + +def _create_concrete_function( + function_type, type_context, func_graph, tracing_options +): + """Create a `ConcreteFunction` from `args`, `kwargs`, and `func_graph`.""" + placeholder_context = trace_type.InternalPlaceholderContext( + func_graph, type_context.get_placeholder_mapping() + ) + with func_graph.as_default(): + placeholder_bound_args = function_type.placeholder_arguments( + placeholder_context + ) + + disable_acd = tracing_options.attributes and tracing_options.attributes.get( + attributes_lib.DISABLE_ACD, False + ) + traced_func_graph = func_graph_module.func_graph_from_py_func( + tracing_options.name, + tracing_options.python_function, + placeholder_bound_args.args, + placeholder_bound_args.kwargs, + None, + func_graph=func_graph, + add_control_dependencies=not disable_acd, + arg_names=function_type_utils.to_arg_names(function_type), + create_placeholders=False, + ) + + transform.apply_func_graph_transforms(traced_func_graph) + + graph_capture_container = traced_func_graph.function_captures + + if tracing_options.function_captures: + # Maintain the list of all captures + tracing_options.function_captures.merge_by_ref_with(graph_capture_container) + + # Create a new FunctionType including captures and outputs. + output_type = trace_type.from_value( + traced_func_graph.structured_outputs, type_context + ) + traced_func_type = function_type_lib.FunctionType( + function_type.parameters.values(), + traced_func_graph.function_captures.capture_types, + return_annotation=output_type, + ) + + concrete_function = concrete_function_lib.ConcreteFunction.from_func_graph( + traced_func_graph, + traced_func_type, + tracing_options.attributes, + # Tell the ConcreteFunction to clean up its graph once it goes out of + # scope. This is not the default behavior since it gets used in some + # places (like Keras) where the FuncGraph lives longer than the + # ConcreteFunction. + shared_func_graph=False, + ) + _set_arg_keywords(concrete_function) + transform.call_concrete_function_callbacks(concrete_function) + + return concrete_function + + +def _set_arg_keywords(concrete_function): + """Sets arg keywords for ConcreteFunction.""" + seen_names = set() + concrete_function._arg_keywords = [] # pylint: disable=protected-access + prefix_counts = {} + graph = concrete_function.graph + num_captures = len(graph.internal_captures + graph.deferred_internal_captures) + num_positional = len(graph.inputs) - num_captures + for arg in concrete_function.graph.inputs[:num_positional]: + try: + user_arg_name = compat.as_str(arg.op.get_attr("_user_specified_name")) + except ValueError: + user_arg_name = "tensor_arg" + proposal = user_arg_name + while proposal in seen_names: + index = prefix_counts.get(user_arg_name, 1) + proposal = "{}_{}".format(user_arg_name, index) + prefix_counts[user_arg_name] = index + 1 + seen_names.add(proposal) + concrete_function._arg_keywords.append(proposal) # pylint: disable=protected-access + # Anything can be a positional argument, in the same order as .inputs + concrete_function._num_positional_args = ( # pylint: disable=protected-access + num_positional + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/transform.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d1a30a2220b9824b5f9a2c110b8fb70a1c4d21 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/polymorphic_function/transform.py @@ -0,0 +1,32 @@ +# 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. +# ============================================================================== +"""tf.function transformations implementation.""" + +# TODO(fmuham): Move this logic to core/function when layered. +# TODO(fmuham): Deprecate and migrate these as AtomicFunction transformations. +FUNC_GRAPH_TRANSFORMS = [] +CONCRETE_FUNCTION_CALLBACKS = [] + + +def apply_func_graph_transforms(func_graph): + """Applies registered transformations to FuncGraph.""" + for transform in FUNC_GRAPH_TRANSFORMS: + transform(func_graph) + + +def call_concrete_function_callbacks(concrete_fn): + """Calls registered callbacks against new ConcreteFunctions.""" + for callback in CONCRETE_FUNCTION_CALLBACKS: + callback(concrete_fn) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/profiler.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..4da9206ec78822fa59efd0bb8dcbfaff024a998c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/profiler.py @@ -0,0 +1,193 @@ +# 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. +# ============================================================================== +"""TensorFlow 2.0 Profiler for both Eager Mode and Graph Mode. + +The profiler has two mode: +- Programmatic Mode: start(), stop() and Profiler class. It will perform + when calling start() or create Profiler class and will stop + when calling stop() or destroying Profiler class. +- On-demand Mode: start_profiler_server(). It will perform profiling when + receive profiling request. + +NOTE: Only one active profiler session is allowed. Use of simultaneous +Programmatic Mode and On-demand Mode is undefined and will likely fail. + +NOTE: The Keras TensorBoard callback will automatically perform sampled +profiling. Before enabling customized profiling, set the callback flag +"profile_batches=[]" to disable automatic sampled profiling. +customized profiling. +""" + +import datetime +import os +import threading + +from tensorflow.python.client import _pywrap_events_writer +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler.internal import _pywrap_profiler +from tensorflow.python.util import compat +from tensorflow.python.util.deprecation import deprecated + +_profiler = None +_profiler_lock = threading.Lock() +_run_num = 0 +# This suffix should be kept in sync with kProfileEmptySuffix in +# tensorflow/core/profiler/rpc/client/capture_profile.cc. +_EVENT_FILE_SUFFIX = '.profile-empty' + + +class ProfilerAlreadyRunningError(Exception): + pass + + +class ProfilerNotRunningError(Exception): + pass + + +@deprecated('2020-07-01', 'use `tf.profiler.experimental.start` instead.') +def start(options=None): + """Start profiling. + + Args: + options: profiler options. + + Raises: + ProfilerAlreadyRunningError: If another profiling session is running. + """ + global _profiler + with _profiler_lock: + if _profiler is not None: + raise ProfilerAlreadyRunningError('Another profiler is running.') + if context.default_execution_mode == context.EAGER_MODE: + context.ensure_initialized() + _profiler = _pywrap_profiler.ProfilerSession() + try: + _profiler.start('', options if options is not None else {}) + except errors.AlreadyExistsError: + logging.warning('Another profiler session is running which is probably ' + 'created by profiler server. Please avoid using profiler ' + 'server and profiler APIs at the same time.') + raise ProfilerAlreadyRunningError('Another profiler is running.') + + +@deprecated('2020-07-01', 'use `tf.profiler.experimental.stop` instead.') +def stop(): + """Stop current profiling session and return its result. + + Returns: + A binary string of tensorflow.tpu.Trace. User can write the string + to file for offline analysis by tensorboard. + + Raises: + ProfilerNotRunningError: If there is no active profiling session. + """ + global _profiler + global _run_num + with _profiler_lock: + if _profiler is None: + raise ProfilerNotRunningError( + 'Cannot stop profiling. No profiler is running.') + if context.default_execution_mode == context.EAGER_MODE: + context.context().executor.wait() + result = _profiler.stop() + _profiler = None + _run_num += 1 + return result + + +@deprecated( + '2020-07-01', + '`tf.python.eager.profiler` has deprecated, use `tf.profiler` instead.' +) +def maybe_create_event_file(logdir): + """Create an empty event file if not already exists. + + This event file indicates that we have a plugins/profile/ directory in the + current logdir. + + Args: + logdir: log directory. + """ + for file_name in gfile.ListDirectory(logdir): + if file_name.endswith(_EVENT_FILE_SUFFIX): + return + # TODO(b/127330388): Use summary_ops_v2.create_file_writer instead. + event_writer = _pywrap_events_writer.EventsWriter( + compat.as_bytes(os.path.join(logdir, 'events'))) + event_writer.InitWithSuffix(compat.as_bytes(_EVENT_FILE_SUFFIX)) + + +@deprecated( + '2020-07-01', + '`tf.python.eager.profiler` has deprecated, use `tf.profiler` instead.' +) +def save(logdir, result): + """Save profile result to TensorBoard logdir. + + Args: + logdir: log directory read by TensorBoard. + result: profiling result returned by stop(). + """ + plugin_dir = os.path.join( + logdir, 'plugins', 'profile', + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')) + gfile.MakeDirs(plugin_dir) + maybe_create_event_file(logdir) + with gfile.Open(os.path.join(plugin_dir, 'local.trace'), 'wb') as f: + f.write(result) + + +@deprecated('2020-07-01', 'use `tf.profiler.experimental.server.start`.') +def start_profiler_server(port): + """Start a profiler grpc server that listens to given port. + + The profiler server will keep the program running even the training finishes. + Please shutdown the server with CTRL-C. It can be used in both eager mode and + graph mode. The service defined in + tensorflow/core/profiler/profiler_service.proto. Please use + tensorflow/contrib/tpu/profiler/capture_tpu_profile to capture tracable + file following https://cloud.google.com/tpu/docs/cloud-tpu-tools#capture_trace + + Args: + port: port profiler server listens to. + """ + if context.default_execution_mode == context.EAGER_MODE: + context.ensure_initialized() + _pywrap_profiler.start_server(port) + + +@deprecated('2020-07-01', 'use `tf.profiler.experimental.Profile` instead.') +class Profiler(object): + """Context-manager eager profiler api. + + Example usage: + ```python + with Profiler("/path/to/logdir"): + # do some work + ``` + """ + + def __init__(self, logdir): + self._logdir = logdir + + def __enter__(self): + start() + + def __exit__(self, typ, value, tb): + result = stop() + save(self._logdir, result) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/profiler_client.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/profiler_client.py new file mode 100644 index 0000000000000000000000000000000000000000..4f92604abfbc2745c7248ab0a38df5ee139f6e09 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/profiler_client.py @@ -0,0 +1,69 @@ +# 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. +# ============================================================================== +"""Profiler client APIs.""" + +from tensorflow.python.profiler.internal import _pywrap_profiler +from tensorflow.python.util.deprecation import deprecated + + +@deprecated('2020-07-01', 'use `tf.profiler.experimental.client.trace`.') +def start_tracing(service_addr, + logdir, + duration_ms, + worker_list='', + include_dataset_ops=True, + num_tracing_attempts=3): + """Sends grpc requests to profiler server to perform on-demand profiling. + + This method will block caller thread until receives tracing result. + + Args: + service_addr: Address of profiler service e.g. localhost:6009. + logdir: Path of TensorBoard log directory e.g. /tmp/tb_log. + duration_ms: Duration of tracing or monitoring in ms. + worker_list: The list of worker TPUs that we are about to profile in the + current session. (TPU only) + include_dataset_ops: Set to false to profile longer traces. + num_tracing_attempts: Automatically retry N times when no trace event is + collected. + + Raises: + UnavailableError: If no trace event is collected. + """ + _pywrap_profiler.trace(service_addr, logdir, worker_list, include_dataset_ops, + duration_ms, num_tracing_attempts, {}) + + +@deprecated('2020-07-01', 'use `tf.profiler.experimental.client.monitor`.') +def monitor(service_addr, + duration_ms, + monitoring_level=1, + display_timestamp=False): + """Sends grpc requests to profiler server to perform on-demand monitoring. + + This method will block caller thread until receives monitoring result. + + Args: + service_addr: Address of profiler service e.g. localhost:6009. + duration_ms: Duration of tracing or monitoring in ms. + monitoring_level: Choose a monitoring level between 1 and 2 to monitor your + job. Level 2 is more verbose than level 1 and shows more metrics. + display_timestamp: Set to true to display timestamp in monitoring result. + + Returns: + A string of monitoring output. + """ + return _pywrap_profiler.monitor(service_addr, duration_ms, monitoring_level, + display_timestamp) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/record.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/record.py new file mode 100644 index 0000000000000000000000000000000000000000..ea6c4ae4f8338e240a58ed545f346e4a025e630f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/record.py @@ -0,0 +1,121 @@ +# 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. +# ============================================================================== +"""Gradient record utilities.""" + +import contextlib + +from tensorflow.python import pywrap_tfe + + +class VariableWatcher(object): + """A scope that tracks all trainable variable accesses within it. + + This explicitly ignores variables that are not marked as trainable. + + Sample usage: + + var = tf.Variable(0.0) + with VariableWatcher() as variable_watcher: + var.assign_add(1.0) + + assert variable_watcher.watched_variables == [var] + """ + + __slots__ = ["_variable_watcher"] + + def __init__(self): + self._variable_watcher = None + + def __enter__(self): + self._variable_watcher = pywrap_tfe.TFE_Py_VariableWatcherNew() + return self + + def __exit__(self, typ, value, traceback): + pywrap_tfe.TFE_Py_VariableWatcherRemove(self._variable_watcher) + + def watched_variables(self): + """Returns a tuple of variables accessed under this scope.""" + return pywrap_tfe.TFE_Py_VariableWatcherWatchedVariables( + self._variable_watcher) + + +@contextlib.contextmanager +def stop_recording(): + """Stop all gradient recording (backprop and forwardprop).""" + is_stopped = pywrap_tfe.TFE_Py_TapeSetIsStopped() + try: + if not is_stopped: + pywrap_tfe.TFE_Py_TapeSetStopOnThread() + yield + finally: + if not is_stopped: + pywrap_tfe.TFE_Py_TapeSetRestartOnThread() + + +def should_record_backprop(tensors): + """Returns true if any tape in the stack watches any of these tensors. + + Only takes GradientTapes into account, not forward accumulators. + + Args: + tensors: Tensors to check, typically inputs to an operation. + + Returns: + Boolean, whether any tape watches any of `tensors`. + """ + return pywrap_tfe.TFE_Py_TapeSetShouldRecordBackprop(tensors) + + +def record_operation(op_type, output_tensors, input_tensors, backward_function, + forward_function=None): + """Records the operation on all tapes in the stack.""" + pywrap_tfe.TFE_Py_TapeSetRecordOperation(op_type, output_tensors, + input_tensors, backward_function, + forward_function) + + +def record_operation_backprop_only(op_type, output_tensors, input_tensors, + backward_function): + """Records the operation on all backward tapes in the stack.""" + pywrap_tfe.TFE_Py_TapeSetRecordOperationBackprop(op_type, output_tensors, + input_tensors, + backward_function) + + +def record_operation_forwardprop_only(op_type, output_tensors, input_tensors, + backward_function, + forwardprop_output_indices): + """Records the operation on all forward accumulators in the stack. + + Args: + op_type: a string for the operation type, used in the backprop code + output_tensors: a list of Python Tensor objects output by the operation + input_tensors: a list of input Tensors to the recorded operation + backward_function: the function to be called to, given the gradients of the + output tensors, produce the gradients of the input tensors. This function + is automatically transposed to produce output gradients given input + gradients. + forwardprop_output_indices: indicates any output_tensors which contain JVPs. + Typically these will have come from TFE_Py_PackForwardGradients. May be + None or an empty sequence if there are no JVP outputs from the operation. + """ + pywrap_tfe.TFE_Py_TapeSetRecordOperationForwardprop( + op_type, output_tensors, input_tensors, backward_function, + forwardprop_output_indices) + + +def could_possibly_record(): + """Returns True if any tape is active.""" + return not pywrap_tfe.TFE_Py_TapeSetIsEmpty() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/remote.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/remote.py new file mode 100644 index 0000000000000000000000000000000000000000..2808f5a056f00a9933129c9fc4e567a55371ead5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/remote.py @@ -0,0 +1,279 @@ +# 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. +# ============================================================================== +"""Helpers to connect to remote servers.""" + +import copy + +from absl import logging + +from tensorflow.core.protobuf.tensorflow_server_pb2 import ServerDef +from tensorflow.python import pywrap_tfe +from tensorflow.python.distribute import device_util +from tensorflow.python.distribute.cluster_resolver import cluster_resolver +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.platform import remote_utils +from tensorflow.python.training import server_lib +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +_GRPC_PREFIX = "grpc://" +_LOCAL_MASTERS = ("", "local") + + +@tf_export("config.experimental_connect_to_host") +def connect_to_remote_host(remote_host=None, job_name="worker"): + """Connects to a single machine to enable remote execution on it. + + Will make devices on the remote host available to use. Note that calling this + more than once will work, but will invalidate any tensor handles on the old + remote devices. + + Using the default job_name of worker, you can schedule ops to run remotely as + follows: + ```python + # When eager execution is enabled, connect to the remote host. + tf.config.experimental_connect_to_host("exampleaddr.com:9876") + + with ops.device("job:worker/replica:0/task:1/device:CPU:0"): + # The following tensors should be resident on the remote device, and the op + # will also execute remotely. + x1 = array_ops.ones([2, 2]) + x2 = array_ops.ones([2, 2]) + y = math_ops.matmul(x1, x2) + ``` + + Args: + remote_host: a single or a list the remote server addr in host-port format. + job_name: The job name under which the new server will be accessible. + + Raises: + ValueError: if remote_host is None. + """ + if not remote_host: + raise ValueError("Must provide at least one remote_host") + + remote_hosts = nest.flatten(remote_host) + cluster_spec = server_lib.ClusterSpec( + {job_name: [_strip_prefix(host, _GRPC_PREFIX) for host in remote_hosts]}) + + connect_to_cluster(cluster_spec) + + +@tf_export("config.experimental_connect_to_cluster") +def connect_to_cluster(cluster_spec_or_resolver, + job_name="localhost", + task_index=0, + protocol=None, + make_master_device_default=True, + cluster_device_filters=None): + """Connects to the given cluster. + + Will make devices on the cluster available to use. Note that calling this more + than once will work, but will invalidate any tensor handles on the old remote + devices. + + If the given local job name is not present in the cluster specification, it + will be automatically added, using an unused port on the localhost. + + Device filters can be specified to isolate groups of remote tasks to avoid + undesired accesses between workers. Workers accessing resources or launching + ops / functions on filtered remote devices will result in errors (unknown + devices). For any remote task, if no device filter is present, all cluster + devices will be visible; if any device filter is specified, it can only + see devices matching at least one filter. Devices on the task itself are + always visible. Device filters can be particially specified. + + For example, for a cluster set up for parameter server training, the following + device filters might be specified: + + ```python + cdf = tf.config.experimental.ClusterDeviceFilters() + # For any worker, only the devices on PS nodes and itself are visible + for i in range(num_workers): + cdf.set_device_filters('worker', i, ['/job:ps']) + # Similarly for any ps, only the devices on workers and itself are visible + for i in range(num_ps): + cdf.set_device_filters('ps', i, ['/job:worker']) + + tf.config.experimental_connect_to_cluster(cluster_def, + cluster_device_filters=cdf) + ``` + + Args: + cluster_spec_or_resolver: A `ClusterSpec` or `ClusterResolver` describing + the cluster. + job_name: The name of the local job. + task_index: The local task index. + protocol: The communication protocol, such as `"grpc"`. If unspecified, will + use the default from `python/platform/remote_utils.py`. + make_master_device_default: If True and a cluster resolver is passed, will + automatically enter the master task device scope, which indicates the + master becomes the default device to run ops. It won't do anything if + a cluster spec is passed. Will throw an error if the caller is currently + already in some device scope. + cluster_device_filters: an instance of + `tf.train.experimental/ClusterDeviceFilters` that specify device filters + to the remote tasks in cluster. + """ + if not context.executing_eagerly(): + raise ValueError( + "`tf.config.experimental_connect_to_cluster` can only be called in " + "eager mode." + ) + protocol = protocol or remote_utils.get_default_communication_protocol() + if isinstance(cluster_spec_or_resolver, server_lib.ClusterSpec): + cluster_spec = cluster_spec_or_resolver + elif isinstance(cluster_spec_or_resolver, cluster_resolver.ClusterResolver): + if cluster_spec_or_resolver.master() in _LOCAL_MASTERS: + # Do nothing if the master is local. + return + cluster_spec = cluster_spec_or_resolver.cluster_spec() + else: + raise ValueError( + "`cluster_spec_or_resolver` must be a `ClusterSpec` or a " + "`ClusterResolver`.") + + cluster_def = copy.deepcopy(cluster_spec.as_cluster_def()) + if cluster_device_filters: + if isinstance(cluster_device_filters, server_lib.ClusterDeviceFilters): + cluster_device_filters = copy.deepcopy( + cluster_device_filters._as_cluster_device_filters()) # pylint: disable=protected-access + else: + raise ValueError("`cluster_device_filters` must be an instance of " + "`tf.train.experimental.ClusterDeviceFilters`.") + + # Check whether the server def has changed. We need to do the check before the + # local job is added to the cluster. + is_server_def_changed = False + current_server_def = context.get_server_def() + if current_server_def and job_name not in cluster_spec.jobs: + for i, job in enumerate(current_server_def.cluster.job): + if job.name == job_name: + del current_server_def.cluster.job[i] + if (current_server_def is None or current_server_def.cluster != cluster_def or + current_server_def.job_name != job_name or + current_server_def.task_index != task_index): + is_server_def_changed = True + + # Automatically add local job, if not part of the cluster spec. + if job_name not in cluster_spec.jobs: + local_port = pywrap_tfe.TF_PickUnusedPortOrDie() + job_def = cluster_def.job.add() + job_def.name = job_name + # TODO(fishx): Update this to make sure remote worker has valid ip address + # to connect with local. + job_def.tasks[0] = "localhost:{}".format(local_port) + + if context.context().coordination_service is None: + service_type = remote_utils.coordination_service_type(protocol) + service_leader = "" + # Maybe enable coordination service for the communication protocol + # TODO(b/243839559): Fix UPTC + Coordination service crashing + # Check if cluster_spec_or_resolver is an instance of + # tpu_cluster_resolver.TPUClusterResolver + if (isinstance(cluster_spec_or_resolver, cluster_resolver.ClusterResolver) + and hasattr(cluster_spec_or_resolver, "tpu_hardware_feature")): + service_leader = cluster_spec_or_resolver.get_coordination_service_leader( + ) + # Maybe enable coordination service internally. + if cluster_spec_or_resolver.environment == "google": + is_uptc_sess = ".uptc-worker." in cluster_spec_or_resolver.master() + service_type = remote_utils.coordination_service_type( + protocol, is_uptc_sess) + # Enable coordination service for Cloud TPU. + else: + service_type = "standalone" + + if service_type: + # If `enable_health_check` is true, coordination service agent would + # do connecting (and tasks would send heartbeat if connection is set up) + # while creating eager contexts. Enabling health check does not mutate + # coordination service. + context.context().configure_coordination_service( + service_type=service_type, + service_leader=service_leader, + enable_health_check=False) + + default_session_config = copy.deepcopy(context.context().config) + + for name in cluster_spec.jobs: + # assuming any of the non-local job is the worker jobs. + # should we use cluster_spec_or_resolver.get_job_name() instead when + # it is available? + # maybe consolicate this with the 'master' logic below + if name == job_name: + continue + + default_session_config.experimental.collective_group_leader = ( + f"/job:{name}/replica:0/task:0" + ) + + logging.info("default session config: %s", default_session_config) + + server_def = ServerDef( + cluster=cluster_def, + job_name=job_name, + task_index=task_index, + protocol=protocol, + default_session_config=default_session_config, + cluster_device_filters=cluster_device_filters, + ) + + if is_server_def_changed: + context.set_server_def(server_def) + else: + context.update_server_def(server_def) + + if make_master_device_default and isinstance( + cluster_spec_or_resolver, + cluster_resolver.ClusterResolver) and cluster_spec_or_resolver.master(): + master = cluster_spec_or_resolver.master() + master_job_name = None + master_task_id = None + for job_name in cluster_spec.jobs: + for task_id in cluster_spec.task_indices(job_name): + task_address = cluster_spec.task_address(job_name, task_id) + if master in task_address or task_address in master: + master_job_name = job_name + master_task_id = task_id + break + + if not master_job_name: + raise ValueError( + "`make_master_device_default` is set to True but cannot find " + "master %s in the cluster" % master) + + master_device = "/job:{}/replica:0/task:{}".format(master_job_name, + master_task_id) + master_device = device_util.canonicalize(master_device) + current_device = device_util.current() + if current_device: + current_device = device_util.canonicalize(current_device) + if current_device and current_device != master_device: + raise ValueError("`connect_to_cluster` is called inside existing device " + "scope %s, which is different from the master device " + "scope %s to enter. This is not allowed." % + (current_device, master_device)) + # TODO(b/138389076): Think of the entering device scope behavior in the + # failure recovery case when dealing with preemptions. + if not current_device: + logging.info("Entering into master device scope: %s", master_device) + ops.device(master_device).__enter__() + + +def _strip_prefix(s, prefix): + return s[len(prefix):] if s.startswith(prefix) else s diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/tape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/tape.py new file mode 100644 index 0000000000000000000000000000000000000000..194ccd5a9116eb48a86bb04a2f835415535173cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/tape.py @@ -0,0 +1,109 @@ +# 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. +# ============================================================================== +"""Gradient tape utilities.""" + +from tensorflow.python import pywrap_tfe + + +class Tape(object): + """Represents a gradient propagation trace.""" + + __slots__ = ["_tape"] + + def __init__(self, tape): + self._tape = tape + + def watched_variables(self): + return pywrap_tfe.TFE_Py_TapeWatchedVariables(self._tape) + + +def push_new_tape(persistent=False, watch_accessed_variables=True): + """Pushes a new tape onto the tape stack.""" + tape = pywrap_tfe.TFE_Py_TapeSetNew(persistent, watch_accessed_variables) + return Tape(tape) + + +def push_tape(tape): + """Pushes an existing tape onto the tape stack.""" + pywrap_tfe.TFE_Py_TapeSetAdd(tape._tape) # pylint: disable=protected-access + + +def watch(tape, tensor): + """Marks this tensor to be watched by the given tape.""" + pywrap_tfe.TFE_Py_TapeWatch(tape._tape, tensor) # pylint: disable=protected-access + + +def default_get_variables(variable): + return [variable] + +# Gets a list of changed variables. Can be overriden using +# register_variables_override. An example of overriding is for getting the +# varibles within a distributed context. +_variables_override = default_get_variables + + +def register_watched_variable_resolver(resolver): + """Registers the resolver to be used to get the list of variables to watch. + + Args: + resolver: callable, takes a Variable and returns a list of Variables that + shall be watched. + """ + global _variables_override + assert _variables_override is default_get_variables + _variables_override = resolver + + +def watch_variable(tape, variable): + """Marks this variable to be watched by the given tape.""" + variables = _variables_override(variable) + for var in variables: + pywrap_tfe.TFE_Py_TapeWatchVariable(tape._tape, var) # pylint: disable=protected-access + pywrap_tfe.TFE_Py_VariableWatcherVariableAccessed(var) + + +def variable_accessed(variable): + """Notifies all tapes in the stack that a variable has been accessed. + + Args: + variable: variable to be watched. + """ + variables = _variables_override(variable) + for var in variables: + pywrap_tfe.TFE_Py_TapeVariableAccessed(var) + pywrap_tfe.TFE_Py_VariableWatcherVariableAccessed(var) + + +def variables_accessed(variables): + """Notifies all tapes in the stack that variables have been accessed. + + Only trainable variables are marked as accessed. + + Args: + variables: iterable of variables to mark as accessed. + """ + accessed = [] + for variable in variables: + if variable.trainable: + accessed.extend(_variables_override(variable)) + + for var in accessed: + pywrap_tfe.TFE_Py_TapeVariableAccessed(var) + pywrap_tfe.TFE_Py_VariableWatcherVariableAccessed(var) + + +def pop_tape(tape): + """Pops the given tape in the stack.""" + pywrap_tfe.TFE_Py_TapeSetRemove(tape._tape) # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/test.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/test.py new file mode 100644 index 0000000000000000000000000000000000000000..be1ccc532911f543233cecc74af11cf2ea0f1fdf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/test.py @@ -0,0 +1,25 @@ +# 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 testing tfe code.""" + +from tensorflow.python.framework import ops as _ops +from tensorflow.python.platform import test as _test +from tensorflow.python.platform.test import * # pylint: disable=wildcard-import + + +# TODO(akshayka): Do away with this file. +def main(argv=None): # pylint: disable=function-redefined + _ops.enable_eager_execution() + _test.main(argv) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/wrap_function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/wrap_function.py new file mode 100644 index 0000000000000000000000000000000000000000..65228aeb2bbe19645b359619d1dca668af675de8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/eager/wrap_function.py @@ -0,0 +1,678 @@ +# 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. +# ============================================================================== +# pylint: disable=unidiomatic-typecheck +"""Prototype decorator for defining legacy-graph-mode functions.""" + +import weakref + +from tensorflow.core.function.polymorphism import function_type as function_type_lib +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.eager import context +from tensorflow.python.eager import function +from tensorflow.python.eager import lift_to_graph +from tensorflow.python.eager.polymorphic_function import atomic_function +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import importer +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.trackable import data_structures +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +class VariableHolder(object): + """Holds variables for a python function.""" + + def __init__(self, fn=None, share_variables=False): + self._fn = fn + + self._share_variables = share_variables + self._variables_by_name = data_structures.Mapping() + + @property + def variables(self): + return self._variables_by_name + + def variable_creator_scope(self, next_creator, **kwargs): + """Creates variables & adds them to collections to match legacy code.""" + collections = kwargs.pop("collections", None) + v = None + + # Get expected variable name. + with ops.name_scope( + kwargs.get("name", None), "Variable", skip_on_eager=False) as name: + variable_name = ops.name_from_scope_name(name) + kwargs["name"] = name + + if self._share_variables: + v = self._variables_by_name.get(variable_name, None) + + if v is None: + v = next_creator(**kwargs) + self._variables_by_name[variable_name] = v + + if collections is None: + collections = [ops.GraphKeys.GLOBAL_VARIABLES] + if v.trainable and ops.GraphKeys.TRAINABLE_VARIABLES not in collections: + collections = list(collections) + [ops.GraphKeys.TRAINABLE_VARIABLES] + + ops.add_to_collections(collections, v) + + return v + + def __call__(self, *args, **kwargs): + return self.call_with_variable_creator_scope(self._fn)(*args, **kwargs) + + def call_with_variable_creator_scope(self, fn): + + def wrapped(*args, **kwargs): + with variable_scope.variable_creator_scope(self.variable_creator_scope): + return fn(*args, **kwargs) + + return wrapped + + +def _get_element_from_tensor_info(tensor_info, graph): + """Simplified copy of the deprecated `get_tensor_from_tensor_info`.""" + encoding = tensor_info.WhichOneof("encoding") + if encoding == "name": + # We may get operations here in some cases. TensorInfo is a bit of a + # misnomer if so. + return graph.as_graph_element(tensor_info.name) + elif encoding == "coo_sparse": + return sparse_tensor.SparseTensor( + graph.get_tensor_by_name(tensor_info.coo_sparse.indices_tensor_name), + graph.get_tensor_by_name(tensor_info.coo_sparse.values_tensor_name), + graph.get_tensor_by_name( + tensor_info.coo_sparse.dense_shape_tensor_name)) + elif encoding == "composite_tensor": + spec_proto = struct_pb2.StructuredValue( + type_spec_value=tensor_info.composite_tensor.type_spec) + spec = nested_structure_coder.decode_proto(spec_proto) + components = [graph.get_tensor_by_name(component.name) for component in + tensor_info.composite_tensor.components] + return spec._from_components(components) # pylint: disable=protected-access + else: + raise ValueError(f"Invalid TensorInfo.encoding: {encoding}. Valid " + "encodings are 'name', 'coo_sparse', and " + "'composite_tensor'.") + + +def _lift_single_variable(old_variable, graph, variable_holder): + """Lifts `old_variable` out of the `FuncGraph` `graph`.""" + new_variable = resource_variable_ops.UninitializedVariable( + shape=old_variable.shape, + dtype=old_variable.dtype, + name=old_variable.op.name, + trainable=old_variable.trainable, + extra_handle_data=old_variable.handle) + new_variable._initializer_op = old_variable._initializer_op # pylint: disable=protected-access + graph.add_capture(new_variable.handle, old_variable.handle) + # Now that we've added the new variable to graph.captures, + # graph.capture will use that cached value and do some post-processing + # on the capture like recording it on the tape. + graph.capture(new_variable.handle) + # pylint: disable=protected-access + variable_name = new_variable.name.split(":")[0] + variable_holder._variables_by_name[variable_name] = new_variable + graph._weak_variables.append(weakref.ref(new_variable)) + # pylint: enable=protected-access + graph.watch_variable(new_variable) + return new_variable + + +def _lift_unlifted_variables(graph, variable_holder): + """Finds resource variables and lifts them into the outer context. + + When we import a GraphDef inside a wrap_function, no Python graph building + code runs. This means we get VarHandleOps which create variable resources, + but no corresponding Python objects. Leaving them like this works but gives + the user no way to interact with or modify the variables outside the graph. + + This method searches for variables and lifts them out as regular variable + objects when possible, indicating to the FuncGraph that they are captures. + + Args: + graph: The FuncGraph to lift variables from. + variable_holder: A VariableHolder to record the lifted variables in. + """ + with graph.as_default(): + global_collection_variables = ops.get_collection( + ops.GraphKeys.GLOBAL_VARIABLES) + local_collection_variables = ops.get_collection( + ops.GraphKeys.LOCAL_VARIABLES) + existing_captures = {id(c) for c in graph.internal_captures} + lifted_variables = {} + + def _should_lift_variable(v): + return ((v._in_graph_mode # pylint: disable=protected-access + and v.graph.building_function) + and isinstance(v, resource_variable_ops.BaseResourceVariable) + and id(v.handle) not in existing_captures) + + for old_variable in global_collection_variables: + if _should_lift_variable(old_variable): + new_variable = _lift_single_variable( + old_variable, graph, variable_holder) + lifted_variables[id(old_variable)] = new_variable + existing_captures.add(id(old_variable.handle)) + + for old_variable in local_collection_variables: + if _should_lift_variable(old_variable): + new_variable = _lift_single_variable( + old_variable, graph, variable_holder) + lifted_variables[id(old_variable)] = new_variable + existing_captures.add(id(old_variable.handle)) + if new_variable._in_graph_mode: # pylint: disable=protected-access + outer_graph = new_variable.graph + # Variables are added to the global collection by default. In this + # case we only want the variable in the local collection, so we'll pop + # it out. + global_collection = outer_graph.get_collection_ref( + ops.GraphKeys.GLOBAL_VARIABLES) + global_collection.remove(new_variable) + outer_graph.add_to_collection( + ops.GraphKeys.LOCAL_VARIABLES, new_variable) + + # Update the FuncGraph's collections, partly for the user and partly so this + # function is idempotent when it runs again in prune() calls. + for collection_name in [ + ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.LOCAL_VARIABLES + ]: + mutable_collection = ops.get_collection_ref(collection_name) + for index, current in enumerate(mutable_collection): + mutable_collection[index] = lifted_variables.get(id(current), current) + if not resource_variable_ops.is_resource_variable( + mutable_collection[index]): + logging.log_first_n( + logging.WARN, + "Unable to create a python object for variable {} because it is " + "a reference variable. It may not be visible to training APIs. " + "If this is a problem, consider rebuilding the SavedModel after " + "running tf.compat.v1.enable_resource_variables().".format( + mutable_collection[index]), + 5) + + +# TODO(allenl): make this trackable +class WrappedFunction(function.ConcreteFunction): + """Wraps a tf V1 piece of code in a function.""" + + def __init__(self, fn_graph, variable_holder, attrs=None, signature=None): + self._variable_holder = variable_holder + _lift_unlifted_variables(fn_graph, variable_holder) + # We call __init__ after lifting variables so that the function's signature + # properly reflects the new captured inputs. + for f in fn_graph.as_graph_def().library.function: + context.context().add_function_def(f) + self._signature = signature + function_type = function_type_lib.from_structured_signature( + fn_graph.structured_input_signature, + fn_graph.structured_outputs, + fn_graph.function_captures.capture_types, + ) + atomic_fn = atomic_function.from_func_graph( + function._inference_name(fn_graph.name), fn_graph, attrs, function_type + ) + super().__init__(atomic_fn) + + def _call_impl(self, args, kwargs): + if self._arg_keywords is None: + if kwargs: + raise NotImplementedError( + "Keyword arguments are not supported when calling a " + f"wrap_function-decorated function. Got {kwargs}.") + if self._signature is not None: + args = list(args) + for i, arg in enumerate(args): + if isinstance(self._signature[i], tensor_lib.DenseSpec): + args[i] = ops.convert_to_tensor(arg, self._signature[i].dtype) + return self._call_flat(args, self.captured_inputs) + else: + return super()._call_impl(args, kwargs) + + def prune(self, feeds, fetches, name=None, input_signature=None): + """Extract a subgraph of this function's underlying graph. + + Wraps the subgraph in a new `WrappedFunction` object. + + Args: + feeds: Input tensors to the subgraph to extract, as `Tensor` objects. + fetches: Possibly-nested Python data structure containing information + about outputs of the target subgraph. Each entry can either be a + `Tensor` object (for data outputs), an `Operation` object (for control + outputs), or a `TensorInfo` proto. Any additional shape/dtype + information provided in a `TensorInfo` and not present in the original + graph will be added to the returned subgraph. + name: (optional) Name to give to the underlying `FuncGraph` of the + returned object. If no name is provided, the graph's name will be + `"pruned"`. + input_signature: (optional) possibly-nested Python data structure + containing `TensorSpec` objects, with which to populate the returned + functions's `FuncGraph`'s `structured_input_signature` field. + + Returns: + A new `WrappedFunction` object containing a copy of the portion of this + object's graph that goes from `feeds` to `fetches`. + """ + # TODO(b/129646028): Add support for CompositeTensors. + name = name or "pruned" + flat_feeds = nest.flatten(feeds, expand_composites=True) + flat_feeds = [self.graph.as_graph_element(t) for t in flat_feeds] + for f in flat_feeds: + if not isinstance(f, tensor_lib.Tensor): + raise ValueError( + "All members of argument `feeds` must be tensors. " + f"Got {f} with type {type(f)}." + ) + + # Ignoring all feeds that are captures allows prune to be called + # using wrapped_func.inputs even when it uses variables + internal_captures = {id(c) for c in self.graph.internal_captures} + flat_feeds = [f for f in flat_feeds if id(f) not in internal_captures] + + operation_fetches = [] + tensor_fetches = [] + tensor_infos = [] + + def _fetch_preprocessing_callback(fetch): + """Extract out lists of ops, tensors, and tensor type info. + + Turns TensorInfos into Tensors in the original `fetches` structure. + Also extracts ops from `fetches`. + + Args: + fetch: The fetch to preprocess: Tensor, TensorInfo, or Operation, or + string identifying a Tensor or Operation. + + Returns: + `fetch` converted to a Tensor. + """ + if isinstance(fetch, ops.Operation): + operation_fetches.append(fetch) + return fetch + elif isinstance(fetch, meta_graph_pb2.TensorInfo): + tensor_infos.append(fetch) + decoded = _get_element_from_tensor_info(fetch, self._func_graph) + if (tensor_util.is_tf_type(decoded) or + isinstance(decoded, composite_tensor.CompositeTensor)): + tensor_fetches.append(decoded) + else: + operation_fetches.append(decoded) + return decoded + elif isinstance( + fetch, (tensor_lib.Tensor, composite_tensor.CompositeTensor)): + tensor_fetches.append(fetch) + return fetch + else: + graph_element = self.graph.as_graph_element(fetch) + return _fetch_preprocessing_callback(graph_element) + + fetches = nest.map_structure(_fetch_preprocessing_callback, fetches) + + # Expand composite tensors into their component dense Tensors. + tensor_fetches = nest.flatten(tensor_fetches, expand_composites=True) + + for f in flat_feeds + tensor_fetches + operation_fetches: + if f.graph is not self._func_graph: + raise ValueError("Can only prune function whose feeds and fetches " + f"from graph {self._func_graph}. Input " + f"{f} is from a different graph {f.graph}.") + with self._func_graph.as_default(): + pruned_graph = func_graph.FuncGraph(name) + lift_map = lift_to_graph.lift_to_graph( + operation_fetches + tensor_fetches, + pruned_graph, + sources=flat_feeds + self.graph.internal_captures, + base_graph=self._func_graph) + + # Note that we add the component tensors of any composite tensors to the + # returned function's outputs list; the list must contain these component + # tensors, or the function's sparse outputs won't work properly. + pruned_graph.outputs.extend(lift_map[x] for x in tensor_fetches) + pruned_graph.control_outputs.extend( + [lift_map[operation] for operation in operation_fetches]) + pruned_graph.inputs.extend(lift_map[x] for x in flat_feeds) + for external_capture, internal_capture in self.graph.captures: + pruned_graph.add_capture(external_capture, lift_map[internal_capture]) + for ti in tensor_infos: + if ti.WhichOneof("encoding") == "name": # Dense tensors only + t = pruned_graph.as_graph_element(ti.name) + if tensor_util.is_tf_type(t): + t.set_shape(tensor_shape.TensorShape(ti.tensor_shape)) + # pylint: disable=protected-access + for f in self.graph._functions.values(): + pruned_graph._add_function(f) + # pylint: enable=protected-access + + pruned_graph.variables = self.graph.variables + + def _structured_output_mapping(fetched): + """callback for `nest.map_structure()`""" + lifted = lift_map[fetched] + if isinstance(lifted, ops.Operation): + return None + return lifted + + # expand_composites=True here causes composite tensors to be expanded + # into their component dense Tensors, mapped to the new graph, and then + # reconstituted into their original composite form. + pruned_graph.structured_outputs = nest.map_structure( + _structured_output_mapping, fetches, expand_composites=True) + + if input_signature: + # canonicalize the signature before setting + args, kwargs = input_signature + args = () if args is None else args + input_signature = (args, kwargs) + + pruned_graph.structured_input_signature = input_signature + pruned_fn = WrappedFunction( + pruned_graph, variable_holder=self._variable_holder) + pruned_fn._num_positional_args = len(flat_feeds) # pylint: disable=protected-access + # TODO(kathywu): Enable keyword arguments if an input signature is specified + pruned_fn._arg_keywords = [tensor.op.name for tensor in flat_feeds] # pylint: disable=protected-access + return pruned_fn + + +def _filter_returned_ops(fn): + """Filtering out any ops returned by function. + + Args: + fn: a function + + Returns: + A tuple of ( + Wrapped function that returns `None` in place of any ops, + dict that maps the index in the flat output structure to the returned op + ) + """ + returned_ops = {} + + def wrap_and_filter_returned_ops(*args, **kwargs): + outputs = fn(*args, **kwargs) + flat_outputs = nest.flatten(outputs) + for n in range(len(flat_outputs)): + output = flat_outputs[n] + if isinstance(output, ops.Operation): + returned_ops[n] = output + flat_outputs[n] = None + return nest.pack_sequence_as(outputs, flat_outputs) + + return wrap_and_filter_returned_ops, returned_ops + + +class WrappedGraph(object): + """Class for wrapping multiple TF 1.X functions in a single graph. + + Maintains a dictionary mapping names to wrapped functions. See + `tf.compat.v1.wrap_function` to learn more about wrapping V1 functions. + + Functions wrapped using this class have access to variables and collections + created in other wrapped functions, using the standard TF 1.X API ( + `tf.compat.v1.get_variable` or + `tf.compat.v1.get_default_graph().get_collection(...)`) + + Outside a function, variables and collections may be accessed using the + `variables` and `graph` properties. + + Example: + + ``` + def add_v1(x): + with tf.compat.v1.variable_scope('vars', reuse=tf.compat.v1.AUTO_REUSE): + v = tf.compat.v1.get_variable('v', shape=[], dtype=tf.int32) + return v + x + + def increment_var_v1(x): + with tf.compat.v1.variable_scope('vars', reuse=tf.compat.v1.AUTO_REUSE): + v = tf.compat.v1.get_variable('v', shape=[], dtype=tf.int32) + return v.assign_add(x) + + g = WrappedGraph() + add = g.wrap_function(add_v1, [tf.TensorSpec([], tf.int32)]) + increment_var = g.wrap_function(increment_var_v1, + [tf.TensorSpec([], tf.int32)]) + + assert len(g.variables) == 1 + assert g.variables[0].numpy() == 0 + increment_var(tf.constant(5)) + assert g.variables[0].numpy() == 5 + + ``` + """ + + def __init__(self, variable_holder=None, **kwargs): + self._variable_holder = ( + variable_holder or VariableHolder(share_variables=True)) + + name = kwargs.pop("name", "wrapped_function_graph") + # Always start with empty collections, unless otherwise specified. Setting + # `collections=None` will copy the collections from the outer graph. + collections = kwargs.pop("collections", {}) + self.graph = func_graph.FuncGraph(name, collections=collections, **kwargs) + + self._wrapped_function = WrappedFunction(self.graph, self._variable_holder) + self._functions = {} + + @property + def functions(self): + return self._functions + + @property + def variables(self): + return self._variable_holder.variables + + def wrap_function(self, fn, signature, name=None): + """Wraps a TF 1.X function and returns an eager-compatible function. + + All functions wrapped in the same `WrappedGraph` will have access to the + same graph (`tf.compat.v1.get_default_graph` to get the graph object + within a function, or `WrappedGraph.graph` to get the graph outside a + function). Variables created within the function will be added to the + `variables` list. + + Function inputs: All inputs to the function must be tensors (nested ok), + with their shapes and dtypes defined in the `signature` argument. + + Function outputs: + + * The 1.X function may return tensors, variables, and ops. The wrapped + eager-compatible function will always return tensors in the same nested + structure. + * Variables are replaced with a tensor containing the latest read values. + * Returned ops are executed, and replaced with None. + * The order of op execution and variable reads in the return is + nondeterministic. For example: + + ``` + def update_var(x): + v = tf.Variable(0) + op = tf.compat.v1.assign(v, x).op + return v, op + + g = WrappedGraph() + fn = g.wrap_function(update_var) + read_value, _ = fn(tf.constant(3)) + print(read_value.numpy()) # could be 0 or 3 + print(g.variables[0].numpy()) # always 3 + ``` + + To ensure that ops in the function are executed (e.g. ops added to the + `tf.GraphKeys.UPDATE_OPS` collection), include them in the function returns. + + Args: + fn: a 1.X tensorflow function. + signature: a possibly nested sequence of `TensorSpecs` specifying the + shapes and dtypes of the arguments. + name: an optional string name for the function. The function will be saved + with key `name` in the `functions` dictionary. + + Returns: + An eager-compatible function. + """ + return self._wrap_function(fn, signature=signature, name=name) + + def _wrap_function(self, + fn, + args=None, + kwargs=None, + signature=None, + name=None): + """Internal wrap function method with extended func_graph arguments.""" + fn_with_filter_and_scope, returned_ops = _filter_returned_ops( + self._variable_holder.call_with_variable_creator_scope(fn)) + + func_graph.func_graph_from_py_func( + None, # Name is unused. + fn_with_filter_and_scope, + args=args, + kwargs=kwargs, + signature=signature, + add_control_dependencies=False, + func_graph=self.graph) + + # This code relies on questional behavior from `func_graph_from_py_func`. + # If an existing FuncGraph is passed into the `func_graph` arg, the inputs + # and structured outputs are overwritten. Pretty sure this is a bug, + # because structured outputs doesn't match up with the outputs... + fn_inputs = self.graph.inputs[:-len(self.graph.captures)] + + # Return filtered ops to the flattened outputs. + flat_fn_outputs = nest.flatten(self.graph.structured_outputs) + for index, op in returned_ops.items(): + flat_fn_outputs[index] = op + fn_outputs = nest.pack_sequence_as(self.graph.structured_outputs, + flat_fn_outputs) + + name = name or fn.__name__ + wrapped_function = self._wrapped_function.prune( + fn_inputs, fn_outputs, name, self.graph.structured_input_signature) + self._functions[name] = wrapped_function + return wrapped_function + + +@tf_export(v1=["wrap_function"]) +def wrap_function(fn, signature, name=None): + """Wraps the TF 1.x function fn into a graph function. + + The python function `fn` will be called once with symbolic arguments specified + in the `signature`, traced, and turned into a graph function. Any variables + created by `fn` will be owned by the object returned by `wrap_function`. The + resulting graph function can be called with tensors which match the + signature. + + ```python + def f(x, do_add): + v = tf.Variable(5.0) + if do_add: + op = v.assign_add(x) + else: + op = v.assign_sub(x) + with tf.control_dependencies([op]): + return v.read_value() + + f_add = tf.compat.v1.wrap_function(f, [tf.TensorSpec((), tf.float32), True]) + + assert float(f_add(1.0)) == 6.0 + assert float(f_add(1.0)) == 7.0 + + # Can call tf.compat.v1.wrap_function again to get a new trace, a new set + # of variables, and possibly different non-template arguments. + f_sub= tf.compat.v1.wrap_function(f, [tf.TensorSpec((), tf.float32), False]) + + assert float(f_sub(1.0)) == 4.0 + assert float(f_sub(1.0)) == 3.0 + ``` + + Both `tf.compat.v1.wrap_function` and `tf.function` create a callable + TensorFlow graph. But while `tf.function` runs all stateful operations + (e.g. `tf.print`) and sequences operations to provide the same semantics as + eager execution, `wrap_function` is closer to the behavior of `session.run` in + TensorFlow 1.x. It will not run any operations unless they are required to + compute the function's outputs, either through a data dependency or a control + dependency. Nor will it sequence operations. + + Unlike `tf.function`, `wrap_function` will only trace the Python function + once. As with placeholders in TF 1.x, shapes and dtypes must be provided to + `wrap_function`'s `signature` argument. + + Since it is only traced once, variables and state may be created inside the + function and owned by the function wrapper object. + + Args: + fn: python function to be wrapped + signature: the placeholder and python arguments to be passed to the wrapped + function + name: Optional. The name of the function. + + Returns: + the wrapped graph function. + """ + holder = VariableHolder(fn) + func_graph_name = "wrapped_function" + if name is not None: + func_graph_name = "wrapped_function_" + name + return WrappedFunction( + func_graph.func_graph_from_py_func( + func_graph_name, + holder, + args=None, + kwargs=None, + signature=signature, + add_control_dependencies=False, + collections={}), + variable_holder=holder, + signature=signature) + + +def function_from_graph_def(graph_def, inputs, outputs, captures=None): + """Creates a ConcreteFunction from a GraphDef. + + Args: + graph_def: A GraphDef to make a function out of. + inputs: A Tensor name or nested structure of names in `graph_def` which + should be inputs to the function. + outputs: A Tensor name or nested structure of names in `graph_def` which + should be outputs of the function. + captures: (Optional) A dictionary mapping node names in `graph_def` that + should be captured as inputs to tensors containing the value of the + captured inputs. + + Returns: + A ConcreteFunction. + """ + + def _imports_graph_def(): + importer.import_graph_def(graph_def, name="") + graph = ops.get_default_graph() + if captures is not None: + for c in captures: + graph.add_capture(captures[c], graph.get_tensor_by_name(str(c) + ":0")) + + wrapped_import = wrap_function(_imports_graph_def, []) + import_graph = wrapped_import.graph + return wrapped_import.prune( + nest.map_structure(import_graph.as_graph_element, inputs), + nest.map_structure(import_graph.as_graph_element, outputs)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/baseline.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..65fb13a8918a842ddaaea811a55158cb554a93c2 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/baseline.py @@ -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. +# ============================================================================== +"""baseline python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import baseline + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +baseline.__all__ = [s for s in dir(baseline) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.canned.baseline import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/dnn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/dnn.py new file mode 100644 index 0000000000000000000000000000000000000000..d45b045b91f39049b1b0f782465fe286dac8db4c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/dnn.py @@ -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. +# ============================================================================== +"""dnn python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import dnn + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +dnn.__all__ = [s for s in dir(dnn) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.canned.dnn import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/dnn_linear_combined.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/dnn_linear_combined.py new file mode 100644 index 0000000000000000000000000000000000000000..ec0b27170c3074ca5c43716ebf7b97a3fd79b999 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/dnn_linear_combined.py @@ -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. +# ============================================================================== +"""dnn_linear_combined python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import dnn_linear_combined + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +dnn_linear_combined.__all__ = [ + s for s in dir(dnn_linear_combined) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.canned.dnn_linear_combined import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/head.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/head.py new file mode 100644 index 0000000000000000000000000000000000000000..d1af4d78ed79e6966652b239cd19f47899627ca0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/head.py @@ -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. +# ============================================================================== +"""head python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import head + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +head.__all__ = [s for s in dir(head) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.canned.head import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/linear.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..50588079c02dd5852db5eef61545c3b5ca911d39 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/linear.py @@ -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. +# ============================================================================== +"""linear python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import linear + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +linear.__all__ = [s for s in dir(linear) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.canned.linear import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/metric_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/metric_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0df59c0eb83cec942273adadbda9f1010119a3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/metric_keys.py @@ -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. +# ============================================================================== +"""metric_keys python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import metric_keys + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +metric_keys.__all__ = [s for s in dir(metric_keys) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.canned.metric_keys import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/optimizers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/optimizers.py new file mode 100644 index 0000000000000000000000000000000000000000..66cc56673a9d736646ffabf9610455f2356136b6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/optimizers.py @@ -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. +# ============================================================================== +"""optimizers python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import optimizers + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +optimizers.__all__ = [s for s in dir(optimizers) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.canned.optimizers import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/parsing_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/parsing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f66b70a2d70161d0179d118833b50dc1a89382 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/parsing_utils.py @@ -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. +# ============================================================================== +"""parsing_utils python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import parsing_utils + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +parsing_utils.__all__ = [ + s for s in dir(parsing_utils) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.canned.parsing_utils import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/prediction_keys.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/prediction_keys.py new file mode 100644 index 0000000000000000000000000000000000000000..e7278795b2eaa1262aefab64bdd4135b4ca16ddd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/canned/prediction_keys.py @@ -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. +# ============================================================================== +"""prediction_keys python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.canned import prediction_keys + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +prediction_keys.__all__ = [ + s for s in dir(prediction_keys) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.canned.prediction_keys import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/estimator.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..a55f3bc1e36ca722b552f539577c90c2f4ce8118 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/estimator.py @@ -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. +# ============================================================================== +"""estimator python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import estimator + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +estimator.__all__ = [s for s in dir(estimator) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.estimator import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/estimator_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/estimator_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4b9046c6052bdaa2f686a673eff14aa38de639 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/estimator_lib.py @@ -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. +# ============================================================================== +"""estimator_lib python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import estimator_lib + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +estimator_lib.__all__ = [ + s for s in dir(estimator_lib) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.estimator_lib import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export.py new file mode 100644 index 0000000000000000000000000000000000000000..627c25aa4bbf35ca97297fdc48a7d8159d86f59e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export.py @@ -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. +# ============================================================================== +"""export python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.export import export + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +export.__all__ = [s for s in dir(export) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.export.export import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..c3f2758952b0548feb8711e23196f8623b9f6494 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export_lib.py @@ -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. +# ============================================================================== +"""export_lib python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.export import export_lib + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +export_lib.__all__ = [s for s in dir(export_lib) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.export.export_lib import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export_output.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export_output.py new file mode 100644 index 0000000000000000000000000000000000000000..54e1587254d0791eb48c2c7b9bb12906615e85c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/export/export_output.py @@ -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. +# ============================================================================== +"""export_output python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.export import export_output + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +export_output.__all__ = [ + s for s in dir(export_output) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.export.export_output import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/exporter.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..2096794a2649cafe75e8696c951dfe94849d481a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/exporter.py @@ -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. +# ============================================================================== +"""exporter python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import exporter + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +exporter.__all__ = [s for s in dir(exporter) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.exporter import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/gc.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/gc.py new file mode 100644 index 0000000000000000000000000000000000000000..8a28a59b1c2c3e8d29a8a071641e7a4102ba4746 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/gc.py @@ -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. +# ============================================================================== +"""gc python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import gc + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +gc.__all__ = [s for s in dir(gc) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.gc import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/inputs.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb9bb6ac1a0d066ca67f492d7cd666a52c5e658 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/inputs.py @@ -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. +# ============================================================================== +"""inputs python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.inputs import inputs + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +inputs.__all__ = [s for s in dir(inputs) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.inputs.inputs import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/numpy_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/numpy_io.py new file mode 100644 index 0000000000000000000000000000000000000000..881866d39e7e71b6c51db73b9d6e0fcde08ac005 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/numpy_io.py @@ -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. +# ============================================================================== +"""numpy_io python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.inputs import numpy_io + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +numpy_io.__all__ = [s for s in dir(numpy_io) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.inputs.numpy_io import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/pandas_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/pandas_io.py new file mode 100644 index 0000000000000000000000000000000000000000..8a1959ab2e92dabe8a99c64d11f377b0b9f85fcb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/pandas_io.py @@ -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. +# ============================================================================== +"""pandas_io python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.inputs import pandas_io + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +pandas_io.__all__ = [s for s in dir(pandas_io) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.inputs.pandas_io import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/feeding_functions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/feeding_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..58cd3c5b3aa543478cc95fd5a68422e9ed72850e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/feeding_functions.py @@ -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. +# ============================================================================== +"""feeding_functions python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.inputs.queues import feeding_functions + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +feeding_functions.__all__ = [ + s for s in dir(feeding_functions) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.inputs.queues.feeding_functions import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..ccae0c98defbfbbcf222dbee1376490f985ef167 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py @@ -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. +# ============================================================================== +"""feeding_queue_runner python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator.inputs.queues import feeding_queue_runner + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +feeding_queue_runner.__all__ = [ + s for s in dir(feeding_queue_runner) if not s.startswith('__') +] + +from tensorflow_estimator.python.estimator.inputs.queues.feeding_queue_runner import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/keras.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/keras.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ab5df9eab02b8dfcef5338c64a3db50e36b0b9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/keras.py @@ -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. +# ============================================================================== +"""keras python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import keras_lib + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +keras_lib.__all__ = [s for s in dir(keras_lib) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.keras_lib import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/model_fn.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/model_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..96c09d5d43ca182882ad5bfe4d80ea319f04c552 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/model_fn.py @@ -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. +# ============================================================================== +"""model_fn python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import model_fn + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +model_fn.__all__ = [s for s in dir(model_fn) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.model_fn import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/run_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/run_config.py new file mode 100644 index 0000000000000000000000000000000000000000..65dbd2a26d81bcbb58dc00c93ab26f63399aff47 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/run_config.py @@ -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. +# ============================================================================== +"""run_config python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import run_config + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +run_config.__all__ = [s for s in dir(run_config) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.run_config import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/training.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/training.py new file mode 100644 index 0000000000000000000000000000000000000000..768c35dd49ef2627862b86bf64f4341e4782bcae --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/training.py @@ -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. +# ============================================================================== +"""training python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import training + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +training.__all__ = [s for s in dir(training) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.training import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/util.py new file mode 100644 index 0000000000000000000000000000000000000000..112e3a825a31834bad828060726ff9ca165244e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/estimator/util.py @@ -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. +# ============================================================================== +"""util python module. + +Importing from tensorflow.python.estimator is unsupported +and will soon break! +""" +# pylint: disable=unused-import,g-bad-import-order,g-import-not-at-top,wildcard-import + +from tensorflow_estimator.python.estimator import util + +# Include attrs that start with single underscore. +_HAS_DYNAMIC_ATTRIBUTES = True +util.__all__ = [s for s in dir(util) if not s.startswith('__')] + +from tensorflow_estimator.python.estimator.util import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column.py new file mode 100644 index 0000000000000000000000000000000000000000..0f82f1fbad287a894ed3a40d70baf2fdbffd00a7 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column.py @@ -0,0 +1,3324 @@ +# 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 API defines FeatureColumn abstraction. + +FeatureColumns provide a high level abstraction for ingesting and representing +features. FeatureColumns are also the primary way of encoding features for +canned `tf.estimator.Estimator`s. + +When using FeatureColumns with `Estimators`, the type of feature column you +should choose depends on (1) the feature type and (2) the model type. + +1. Feature type: + + * Continuous features can be represented by `numeric_column`. + * Categorical features can be represented by any `categorical_column_with_*` + column: + - `categorical_column_with_vocabulary_list` + - `categorical_column_with_vocabulary_file` + - `categorical_column_with_hash_bucket` + - `categorical_column_with_identity` + - `weighted_categorical_column` + +2. Model type: + + * Deep neural network models (`DNNClassifier`, `DNNRegressor`). + + Continuous features can be directly fed into deep neural network models. + + age_column = numeric_column("age") + + To feed sparse features into DNN models, wrap the column with + `embedding_column` or `indicator_column`. `indicator_column` is recommended + for features with only a few possible values. For features with many + possible values, to reduce the size of your model, `embedding_column` is + recommended. + + embedded_dept_column = embedding_column( + categorical_column_with_vocabulary_list( + "department", ["math", "philosophy", ...]), dimension=10) + + * Wide (aka linear) models (`LinearClassifier`, `LinearRegressor`). + + Sparse features can be fed directly into linear models. They behave like an + indicator column but with an efficient implementation. + + dept_column = categorical_column_with_vocabulary_list("department", + ["math", "philosophy", "english"]) + + It is recommended that continuous features be bucketized before being + fed into linear models. + + bucketized_age_column = bucketized_column( + source_column=age_column, + boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) + + Sparse features can be crossed (also known as conjuncted or combined) in + order to form non-linearities, and then fed into linear models. + + cross_dept_age_column = crossed_column( + columns=["department", bucketized_age_column], + hash_bucket_size=1000) + +Example of building canned `Estimator`s using FeatureColumns: + + ```python + # Define features and transformations + deep_feature_columns = [age_column, embedded_dept_column] + wide_feature_columns = [dept_column, bucketized_age_column, + cross_dept_age_column] + + # Build deep model + estimator = DNNClassifier( + feature_columns=deep_feature_columns, + hidden_units=[500, 250, 50]) + estimator.train(...) + + # Or build a wide model + estimator = LinearClassifier( + feature_columns=wide_feature_columns) + estimator.train(...) + + # Or build a wide and deep model! + estimator = DNNLinearCombinedClassifier( + linear_feature_columns=wide_feature_columns, + dnn_feature_columns=deep_feature_columns, + dnn_hidden_units=[500, 250, 50]) + estimator.train(...) + ``` + + +FeatureColumns can also be transformed into a generic input layer for +custom models using `input_layer`. + +Example of building model using FeatureColumns, this can be used in a +`model_fn` which is given to the {tf.estimator.Estimator}: + + ```python + # Building model via layers + + deep_feature_columns = [age_column, embedded_dept_column] + columns_to_tensor = parse_feature_columns_from_examples( + serialized=my_data, + feature_columns=deep_feature_columns) + first_layer = input_layer( + features=columns_to_tensor, + feature_columns=deep_feature_columns) + second_layer = fully_connected(first_layer, ...) + ``` + +NOTE: Functions prefixed with "_" indicate experimental or private parts of +the API subject to change, and should not be relied upon! + +NOTE: The new feature columns are being developed in feature_column_v2.py and +are a somewhat duplicate of the code here. Please make sure to update logic +in both places. +""" + +import abc +import collections +import math + +import numpy as np +import six + +from tensorflow.python.eager import context +from tensorflow.python.feature_column import utils as fc_utils +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.layers import base +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops import template +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import checkpoint_utils +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +_FEATURE_COLUMN_DEPRECATION_WARNING = """\ + Warning: tf.feature_column is not recommended for new code. Instead, + feature preprocessing can be done directly using either [Keras preprocessing + layers](https://www.tensorflow.org/guide/migrate/migrating_feature_columns) + or through the one-stop utility [`tf.keras.utils.FeatureSpace`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/FeatureSpace) + built on top of them. See the [migration guide](https://tensorflow.org/guide/migrate) + for details. + """ + +_FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING = ( + 'Use Keras preprocessing layers instead, either directly or via the ' + '`tf.keras.utils.FeatureSpace` utility. Each of `tf.feature_column.*` has ' + 'a functional equivalent in `tf.keras.layers` for feature preprocessing ' + 'when training a Keras model.') + + +def _internal_input_layer(features, + feature_columns, + weight_collections=None, + trainable=True, + cols_to_vars=None, + scope=None, + cols_to_output_tensors=None, + from_template=False): + """See input_layer. `scope` is a name or variable scope to use.""" + + feature_columns = _normalize_feature_columns(feature_columns) + for column in feature_columns: + if not isinstance(column, _DenseColumn): + raise ValueError( + 'Items of feature_columns must be a _DenseColumn. ' + 'You can wrap a categorical column with an ' + 'embedding_column or indicator_column. Given: {}'.format(column)) + weight_collections = list(weight_collections or []) + if ops.GraphKeys.GLOBAL_VARIABLES not in weight_collections: + weight_collections.append(ops.GraphKeys.GLOBAL_VARIABLES) + if ops.GraphKeys.MODEL_VARIABLES not in weight_collections: + weight_collections.append(ops.GraphKeys.MODEL_VARIABLES) + + def _get_logits(): # pylint: disable=missing-docstring + builder = _LazyBuilder(features) + output_tensors = [] + ordered_columns = [] + for column in sorted(feature_columns, key=lambda x: x.name): + ordered_columns.append(column) + with variable_scope.variable_scope( + None, default_name=column._var_scope_name): # pylint: disable=protected-access + tensor = column._get_dense_tensor( # pylint: disable=protected-access + builder, + weight_collections=weight_collections, + trainable=trainable) + num_elements = column._variable_shape.num_elements() # pylint: disable=protected-access + batch_size = array_ops.shape(tensor)[0] + output_tensor = array_ops.reshape( + tensor, shape=(batch_size, num_elements)) + output_tensors.append(output_tensor) + if cols_to_vars is not None: + # Retrieve any variables created (some _DenseColumn's don't create + # variables, in which case an empty list is returned). + cols_to_vars[column] = ops.get_collection( + ops.GraphKeys.GLOBAL_VARIABLES, + scope=variable_scope.get_variable_scope().name) + if cols_to_output_tensors is not None: + cols_to_output_tensors[column] = output_tensor + _verify_static_batch_size_equality(output_tensors, ordered_columns) + return array_ops.concat(output_tensors, 1) + + # If we're constructing from the `make_template`, that by default adds a + # variable scope with the name of the layer. In that case, we dont want to + # add another `variable_scope` as that would break checkpoints. + if from_template: + return _get_logits() + else: + with variable_scope.variable_scope( + scope, default_name='input_layer', values=features.values()): + return _get_logits() + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export(v1=['feature_column.input_layer']) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def input_layer(features, + feature_columns, + weight_collections=None, + trainable=True, + cols_to_vars=None, + cols_to_output_tensors=None): + """Returns a dense `Tensor` as input layer based on given `feature_columns`. + + Generally a single example in training data is described with FeatureColumns. + At the first layer of the model, this column oriented data should be converted + to a single `Tensor`. + + Example: + + ```python + price = numeric_column('price') + keywords_embedded = embedding_column( + categorical_column_with_hash_bucket("keywords", 10K), dimensions=16) + columns = [price, keywords_embedded, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + for units in [128, 64, 32]: + dense_tensor = tf.compat.v1.layers.dense(dense_tensor, units, tf.nn.relu) + prediction = tf.compat.v1.layers.dense(dense_tensor, 1) + ``` + + Args: + features: A mapping from key to tensors. `_FeatureColumn`s look up via these + keys. For example `numeric_column('price')` will look at 'price' key in + this dict. Values can be a `SparseTensor` or a `Tensor` depends on + corresponding `_FeatureColumn`. + feature_columns: An iterable containing the FeatureColumns to use as inputs + to your model. All items should be instances of classes derived from + `_DenseColumn` such as `numeric_column`, `embedding_column`, + `bucketized_column`, `indicator_column`. If you have categorical features, + you can wrap them with an `embedding_column` or `indicator_column`. + weight_collections: A list of collection names to which the Variable will be + added. Note that variables will also be added to collections + `tf.GraphKeys.GLOBAL_VARIABLES` and `ops.GraphKeys.MODEL_VARIABLES`. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + cols_to_vars: If not `None`, must be a dictionary that will be filled with a + mapping from `_FeatureColumn` to list of `Variable`s. For example, after + the call, we might have cols_to_vars = {_EmbeddingColumn( + categorical_column=_HashedCategoricalColumn( key='sparse_feature', + hash_bucket_size=5, dtype=tf.string), dimension=10): [], 'bias': [], _NumericColumn( + key='numeric_feature2', shape=(2,)): []} If a column creates no + variables, its value will be an empty list. Note that cols_to_vars will + also contain a string key 'bias' that maps to a list of Variables. + + Returns: + A `Tensor` which represents predictions/logits of a linear model. Its shape + is (batch_size, units) and its dtype is `float32`. + + Raises: + ValueError: if an item in `feature_columns` is neither a `_DenseColumn` + nor `_CategoricalColumn`. + """ + with variable_scope.variable_scope(None, 'linear_model') as vs: + model_name = _strip_leading_slashes(vs.name) + linear_model_layer = _LinearModel( + feature_columns=feature_columns, + units=units, + sparse_combiner=sparse_combiner, + weight_collections=weight_collections, + trainable=trainable, + name=model_name) + retval = linear_model_layer(features) # pylint: disable=not-callable + if cols_to_vars is not None: + cols_to_vars.update(linear_model_layer.cols_to_vars()) + return retval + + +def _add_to_collections(var, weight_collections): + """Adds a var to the list of weight_collections provided. + + Handles the case for partitioned and non-partitioned variables. + + Args: + var: A variable or Partitioned Variable. + weight_collections: List of collections to add variable to. + """ + for weight_collection in weight_collections: + # The layer self.add_variable call already adds it to GLOBAL_VARIABLES. + if weight_collection == ops.GraphKeys.GLOBAL_VARIABLES: + continue + # TODO(rohanj): Explore adding a _get_variable_list method on `Variable` + # so that we don't have to do this check. + if isinstance(var, variables.PartitionedVariable): + for constituent_var in list(var): + ops.add_to_collection(weight_collection, constituent_var) + else: + ops.add_to_collection(weight_collection, var) + + +class _FCLinearWrapper(base.Layer): + """Wraps a _FeatureColumn in a layer for use in a linear model. + + See `linear_model` above. + """ + + def __init__(self, + feature_column, + units=1, + sparse_combiner='sum', + weight_collections=None, + trainable=True, + name=None, + **kwargs): + super(_FCLinearWrapper, self).__init__( + trainable=trainable, name=name, **kwargs) + self._feature_column = feature_column + self._units = units + self._sparse_combiner = sparse_combiner + self._weight_collections = weight_collections + + def build(self, _): + if isinstance(self._feature_column, _CategoricalColumn): + weight = self.add_variable( + name='weights', + shape=(self._feature_column._num_buckets, self._units), # pylint: disable=protected-access + initializer=init_ops.zeros_initializer(), + trainable=self.trainable) + else: + num_elements = self._feature_column._variable_shape.num_elements() # pylint: disable=protected-access + weight = self.add_variable( + name='weights', + shape=[num_elements, self._units], + initializer=init_ops.zeros_initializer(), + trainable=self.trainable) + _add_to_collections(weight, self._weight_collections) + self._weight_var = weight + self.built = True + + def call(self, builder): + weighted_sum = _create_weighted_sum( + column=self._feature_column, + builder=builder, + units=self._units, + sparse_combiner=self._sparse_combiner, + weight_collections=self._weight_collections, + trainable=self.trainable, + weight_var=self._weight_var) + return weighted_sum + + +class _BiasLayer(base.Layer): + """A layer for the bias term.""" + + def __init__(self, + units=1, + trainable=True, + weight_collections=None, + name=None, + **kwargs): + super(_BiasLayer, self).__init__(trainable=trainable, name=name, **kwargs) + self._units = units + self._weight_collections = weight_collections + + def build(self, _): + self._bias_variable = self.add_variable( + 'bias_weights', + shape=[self._units], + initializer=init_ops.zeros_initializer(), + trainable=self.trainable) + _add_to_collections(self._bias_variable, self._weight_collections) + self.built = True + + def call(self, _): + return self._bias_variable + + +def _get_expanded_variable_list(variable): + if (isinstance(variable, variables.Variable) or + resource_variable_ops.is_resource_variable(variable)): + return [variable] # Single variable case. + else: # Must be a PartitionedVariable, so convert into a list. + return list(variable) + + +def _strip_leading_slashes(name): + return name.rsplit('/', 1)[-1] + + +class _LinearModel(base.Layer): + """Creates a linear model using feature columns. + + See `linear_model` for details. + """ + + def __init__(self, + feature_columns, + units=1, + sparse_combiner='sum', + weight_collections=None, + trainable=True, + name=None, + **kwargs): + super(_LinearModel, self).__init__(name=name, **kwargs) + # We force the keras_style to be True here, as a workaround to not being + # able to inherit keras.layers.Layer as base class. Setting this will let + # us skip all the legacy behavior for base.Layer. + # Also note that we use Layer as base class, instead of Model, since there + # isn't any Model specific behavior gets used, eg compile/fit. + self._keras_style = True + self._feature_columns = _normalize_feature_columns(feature_columns) + self._weight_collections = list(weight_collections or []) + if ops.GraphKeys.GLOBAL_VARIABLES not in self._weight_collections: + self._weight_collections.append(ops.GraphKeys.GLOBAL_VARIABLES) + if ops.GraphKeys.MODEL_VARIABLES not in self._weight_collections: + self._weight_collections.append(ops.GraphKeys.MODEL_VARIABLES) + + column_layers = {} + for column in sorted(self._feature_columns, key=lambda x: x.name): + with variable_scope.variable_scope( + None, default_name=column._var_scope_name) as vs: # pylint: disable=protected-access + # Having the fully expressed variable scope name ends up doubly + # expressing the outer scope (scope with which this method was called) + # in the name of the variable that would get created. + column_name = _strip_leading_slashes(vs.name) + column_layer = _FCLinearWrapper(column, units, sparse_combiner, + self._weight_collections, trainable, + column_name, **kwargs) + column_layers[column_name] = column_layer + self._column_layers = self._add_layers(column_layers) + self._bias_layer = _BiasLayer( + units=units, + trainable=trainable, + weight_collections=self._weight_collections, + name='bias_layer', + **kwargs) + self._cols_to_vars = {} + + def cols_to_vars(self): + """Returns a dict mapping _FeatureColumns to variables. + + See `linear_model` for more information. + This is not populated till `call` is called i.e. layer is built. + """ + return self._cols_to_vars + + def call(self, features): + with variable_scope.variable_scope(self.name): + for column in self._feature_columns: + if not isinstance(column, (_DenseColumn, _CategoricalColumn)): + raise ValueError( + 'Items of feature_columns must be either a ' + '_DenseColumn or _CategoricalColumn. Given: {}'.format(column)) + weighted_sums = [] + ordered_columns = [] + builder = _LazyBuilder(features) + for layer in sorted(self._column_layers.values(), key=lambda x: x.name): + column = layer._feature_column # pylint: disable=protected-access + ordered_columns.append(column) + weighted_sum = layer(builder) + weighted_sums.append(weighted_sum) + self._cols_to_vars[column] = ops.get_collection( + ops.GraphKeys.GLOBAL_VARIABLES, scope=layer.scope_name) + + _verify_static_batch_size_equality(weighted_sums, ordered_columns) + predictions_no_bias = math_ops.add_n( + weighted_sums, name='weighted_sum_no_bias') + predictions = nn_ops.bias_add( + predictions_no_bias, + self._bias_layer( # pylint: disable=not-callable + builder, + scope=variable_scope.get_variable_scope()), # pylint: disable=not-callable + name='weighted_sum') + bias = self._bias_layer.variables[0] + self._cols_to_vars['bias'] = _get_expanded_variable_list(bias) + return predictions + + def _add_layers(self, layers): + # "Magic" required for keras.Model classes to track all the variables in + # a list of layers.Layer objects. + # TODO(ashankar): Figure out API so user code doesn't have to do this. + for name, layer in layers.items(): + setattr(self, 'layer-%s' % name, layer) + return layers + + +def _transform_features(features, feature_columns): + """Returns transformed features based on features columns passed in. + + Please note that most probably you would not need to use this function. Please + check `input_layer` and `linear_model` to see whether they will + satisfy your use case or not. + + Example: + + ```python + # Define features and transformations + crosses_a_x_b = crossed_column( + columns=["sparse_feature_a", "sparse_feature_b"], hash_bucket_size=10000) + price_buckets = bucketized_column( + source_column=numeric_column("price"), boundaries=[...]) + + columns = [crosses_a_x_b, price_buckets] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + transformed = transform_features(features=features, feature_columns=columns) + + assertCountEqual(columns, transformed.keys()) + ``` + + Args: + features: A mapping from key to tensors. `_FeatureColumn`s look up via these + keys. For example `numeric_column('price')` will look at 'price' key in + this dict. Values can be a `SparseTensor` or a `Tensor` depends on + corresponding `_FeatureColumn`. + feature_columns: An iterable containing all the `_FeatureColumn`s. + + Returns: + A `dict` mapping `_FeatureColumn` to `Tensor` and `SparseTensor` values. + """ + feature_columns = _normalize_feature_columns(feature_columns) + outputs = {} + with ops.name_scope( + None, default_name='transform_features', values=features.values()): + builder = _LazyBuilder(features) + for column in sorted(feature_columns, key=lambda x: x.name): + with ops.name_scope(None, default_name=column.name): + outputs[column] = builder.get(column) + return outputs + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export(v1=['feature_column.make_parse_example_spec']) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def make_parse_example_spec(feature_columns): + """Creates parsing spec dictionary from input feature_columns. + + The returned dictionary can be used as arg 'features' in + `tf.io.parse_example`. + + Typical usage example: + + ```python + # Define features and transformations + feature_a = categorical_column_with_vocabulary_file(...) + feature_b = numeric_column(...) + feature_c_bucketized = bucketized_column(numeric_column("feature_c"), ...) + feature_a_x_feature_c = crossed_column( + columns=["feature_a", feature_c_bucketized], ...) + + feature_columns = set( + [feature_b, feature_c_bucketized, feature_a_x_feature_c]) + features = tf.io.parse_example( + serialized=serialized_examples, + features=make_parse_example_spec(feature_columns)) + ``` + + For the above example, make_parse_example_spec would return the dict: + + ```python + { + "feature_a": parsing_ops.VarLenFeature(tf.string), + "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32), + "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32) + } + ``` + + Args: + feature_columns: An iterable containing all feature columns. All items + should be instances of classes derived from `_FeatureColumn`. + + Returns: + A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` + value. + + Raises: + ValueError: If any of the given `feature_columns` is not a `_FeatureColumn` + instance. + """ + result = {} + for column in feature_columns: + if not isinstance(column, _FeatureColumn): + raise ValueError('All feature_columns must be _FeatureColumn instances. ' + 'Given: {}'.format(column)) + config = column._parse_example_spec # pylint: disable=protected-access + for key, value in six.iteritems(config): + if key in result and value != result[key]: + raise ValueError('feature_columns contain different parse_spec for key ' + '{}. Given {} and {}'.format(key, value, result[key])) + result.update(config) + return result + + +def _embedding_column(categorical_column, + dimension, + combiner='mean', + initializer=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + use_safe_embedding_lookup=True): + """`_DenseColumn` that converts from sparse, categorical input. + + Use this when your inputs are sparse, but you want to convert them to a dense + representation (e.g., to feed to a DNN). + + Inputs must be a `_CategoricalColumn` created by any of the + `categorical_column_*` function. Here is an example of using + `embedding_column` with `DNNClassifier`: + + ```python + video_id = categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [embedding_column(video_id, 9),...] + + estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...) + + label_column = ... + def input_fn(): + features = tf.io.parse_example( + ..., features=make_parse_example_spec(columns + [label_column])) + labels = features.pop(label_column.name) + return features, labels + + estimator.train(input_fn=input_fn, steps=100) + ``` + + Here is an example using `embedding_column` with model_fn: + + ```python + def model_fn(features, ...): + video_id = categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [embedding_column(video_id, 9),...] + dense_tensor = input_layer(features, columns) + # Form DNN layers, calculate loss, and return EstimatorSpec. + ... + ``` + + Args: + categorical_column: A `_CategoricalColumn` created by a + `categorical_column_with_*` function. This column produces the sparse IDs + that are inputs to the embedding lookup. + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries in + a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with + 'mean' the default. 'sqrtn' often achieves good accuracy, in particular + with bag-of-words columns. Each of this can be thought as example level + normalizations on the column. For more information, see + `tf.embedding_lookup_sparse`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `tf.compat.v1.truncated_normal_initializer` with mean `0.0` and standard + deviation `1/sqrt(dimension)`. + ckpt_to_load_from: String representing checkpoint name/pattern from which to + restore column weights. Required if `tensor_name_in_ckpt` is not `None`. + tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which + to restore the column weights. Required if `ckpt_to_load_from` is not + `None`. + max_norm: If not `None`, embedding values are l2-normalized to this value. + trainable: Whether or not the embedding is trainable. Default is True. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + `_DenseColumn` that converts from sparse input. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt` + is specified. + ValueError: if `initializer` is specified and is not callable. + RuntimeError: If eager execution is enabled. + """ + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + if (ckpt_to_load_from is None) != (tensor_name_in_ckpt is None): + raise ValueError('Must specify both `ckpt_to_load_from` and ' + '`tensor_name_in_ckpt` or none of them.') + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified. ' + 'Embedding of column_name: {}'.format( + categorical_column.name)) + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + embedding_shape = categorical_column._num_buckets, dimension # pylint: disable=protected-access + + def _creator(weight_collections, scope): + embedding_column_layer = _EmbeddingColumnLayer( + embedding_shape=embedding_shape, + initializer=initializer, + weight_collections=weight_collections, + trainable=trainable, + name='embedding_column_layer') + return embedding_column_layer(None, scope=scope) # pylint: disable=not-callable + + return _EmbeddingColumn( + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + layer_creator=_creator, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + +def _numeric_column(key, + shape=(1,), + default_value=None, + dtype=dtypes.float32, + normalizer_fn=None): + """Represents real valued or numerical features. + + Example: + + ```python + price = numeric_column('price') + columns = [price, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + + # or + bucketized_price = bucketized_column(price, boundaries=[...]) + columns = [bucketized_price, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + shape: An iterable of integers specifies the shape of the `Tensor`. An + integer can be given which means a single dimension `Tensor` with given + width. The `Tensor` representing the column will have the shape of + [batch_size] + `shape`. + default_value: A single value compatible with `dtype` or an iterable of + values compatible with `dtype` which the column takes on during + `tf.Example` parsing if data is missing. A default value of `None` will + cause `tf.io.parse_example` to fail if an example does not contain this + column. If a single value is provided, the same value will be applied as + the default value for every item. If an iterable of values is provided, + the shape of the `default_value` should be equal to the given `shape`. + dtype: defines the type of values. Default value is `tf.float32`. Must be a + non-quantized, real integer or floating point type. + normalizer_fn: If not `None`, a function that can be used to normalize the + value of the tensor after `default_value` is applied for parsing. + Normalizer function takes the input `Tensor` as its argument, and returns + the output `Tensor`. (e.g. lambda x: (x - 3.0) / 4.2). Please note that + even though the most common use case of this function is normalization, it + can be used for any kind of Tensorflow transformations. + + Returns: + A `_NumericColumn`. + + Raises: + TypeError: if any dimension in shape is not an int + ValueError: if any dimension in shape is not a positive integer + TypeError: if `default_value` is an iterable but not compatible with `shape` + TypeError: if `default_value` is not compatible with `dtype`. + ValueError: if `dtype` is not convertible to `tf.float32`. + """ + shape = _check_shape(shape, key) + if not (dtype.is_integer or dtype.is_floating): + raise ValueError('dtype must be convertible to float. ' + 'dtype: {}, key: {}'.format(dtype, key)) + default_value = fc_utils.check_default_value(shape, default_value, dtype, key) + + if normalizer_fn is not None and not callable(normalizer_fn): + raise TypeError( + 'normalizer_fn must be a callable. Given: {}'.format(normalizer_fn)) + + fc_utils.assert_key_is_string(key) + return _NumericColumn( + key, + shape=shape, + default_value=default_value, + dtype=dtype, + normalizer_fn=normalizer_fn) + + +def _bucketized_column(source_column, boundaries): + """Represents discretized dense input. + + Buckets include the left boundary, and exclude the right boundary. Namely, + `boundaries=[0., 1., 2.]` generates buckets `(-inf, 0.)`, `[0., 1.)`, + `[1., 2.)`, and `[2., +inf)`. + + For example, if the inputs are + + ```python + boundaries = [0, 10, 100] + input tensor = [[-5, 10000] + [150, 10] + [5, 100]] + ``` + + then the output will be + + ```python + output = [[0, 3] + [3, 2] + [1, 3]] + ``` + + Example: + + ```python + price = numeric_column('price') + bucketized_price = bucketized_column(price, boundaries=[...]) + columns = [bucketized_price, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + + # or + columns = [bucketized_price, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + A `bucketized_column` can also be crossed with another categorical column + using `crossed_column`: + + ```python + price = numeric_column('price') + # bucketized_column converts numerical feature to a categorical one. + bucketized_price = bucketized_column(price, boundaries=[...]) + # 'keywords' is a string feature. + price_x_keywords = crossed_column([bucketized_price, 'keywords'], 50K) + columns = [price_x_keywords, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + Args: + source_column: A one-dimensional dense column which is generated with + `numeric_column`. + boundaries: A sorted list or tuple of floats specifying the boundaries. + + Returns: + A `_BucketizedColumn`. + + Raises: + ValueError: If `source_column` is not a numeric column, or if it is not + one-dimensional. + ValueError: If `boundaries` is not a sorted list or tuple. + """ + if not isinstance(source_column, _NumericColumn): + raise ValueError( + 'source_column must be a column generated with numeric_column(). ' + 'Given: {}'.format(source_column)) + if len(source_column.shape) > 1: + raise ValueError('source_column must be one-dimensional column. ' + 'Given: {}'.format(source_column)) + if (not boundaries or + not (isinstance(boundaries, list) or isinstance(boundaries, tuple))): + raise ValueError('boundaries must be a sorted list.') + for i in range(len(boundaries) - 1): + if boundaries[i] >= boundaries[i + 1]: + raise ValueError('boundaries must be a sorted list.') + return _BucketizedColumn(source_column, tuple(boundaries)) + + +def _categorical_column_with_hash_bucket(key, + hash_bucket_size, + dtype=dtypes.string): + """Represents sparse feature where ids are set by hashing. + + Use this when your sparse features are in string or integer format, and you + want to distribute your inputs into a finite number of buckets by hashing. + output_id = Hash(input_feature_string) % bucket_size for string type input. + For int type input, the value is converted to its string representation first + and then hashed by the same formula. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example: + + ```python + keywords = categorical_column_with_hash_bucket("keywords", 10K) + columns = [keywords, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + + # or + keywords_embedded = embedding_column(keywords, 16) + columns = [keywords_embedded, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + hash_bucket_size: An int > 1. The number of buckets. + dtype: The type of features. Only string and integer types are supported. + + Returns: + A `_HashedCategoricalColumn`. + + Raises: + ValueError: `hash_bucket_size` is not greater than 1. + ValueError: `dtype` is neither string nor integer. + """ + if hash_bucket_size is None: + raise ValueError('hash_bucket_size must be set. ' 'key: {}'.format(key)) + + if hash_bucket_size < 1: + raise ValueError('hash_bucket_size must be at least 1. ' + 'hash_bucket_size: {}, key: {}'.format( + hash_bucket_size, key)) + + fc_utils.assert_key_is_string(key) + fc_utils.assert_string_or_int(dtype, prefix='column_name: {}'.format(key)) + + return _HashedCategoricalColumn(key, hash_bucket_size, dtype) + + +def _categorical_column_with_vocabulary_file(key, + vocabulary_file, + vocabulary_size=None, + num_oov_buckets=0, + default_value=None, + dtype=dtypes.string): + """A `_CategoricalColumn` with a vocabulary file. + + Use this when your inputs are in string or integer format, and you have a + vocabulary file that maps each value to an integer ID. By default, + out-of-vocabulary values are ignored. Use either (but not both) of + `num_oov_buckets` and `default_value` to specify how to include + out-of-vocabulary values. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example with `num_oov_buckets`: + File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state + abbreviation. All inputs with values in that file are assigned an ID 0-49, + corresponding to its line number. All other values are hashed and assigned an + ID 50-54. + + ```python + states = categorical_column_with_vocabulary_file( + key='states', vocabulary_file='/us/states.txt', vocabulary_size=50, + num_oov_buckets=5) + columns = [states, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + Example with `default_value`: + File '/us/states.txt' contains 51 lines - the first line is 'XX', and the + other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' + in input, and other values missing from the file, will be assigned ID 0. All + others are assigned the corresponding line number 1-50. + + ```python + states = categorical_column_with_vocabulary_file( + key='states', vocabulary_file='/us/states.txt', vocabulary_size=51, + default_value=0) + columns = [states, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + And to make an embedding with either: + + ```python + columns = [embedding_column(states, 3),...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + vocabulary_file: The vocabulary file name. + vocabulary_size: Number of the elements in the vocabulary. This must be no + greater than length of `vocabulary_file`, if less than length, later + values are ignored. If None, it is set to the length of `vocabulary_file`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of + the input value. A positive `num_oov_buckets` can not be specified with + `default_value`. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + dtype: The type of features. Only string and integer types are supported. + + Returns: + A `_CategoricalColumn` with a vocabulary file. + + Raises: + ValueError: `vocabulary_file` is missing or cannot be opened. + ValueError: `vocabulary_size` is missing or < 1. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: `dtype` is neither string nor integer. + """ + if not vocabulary_file: + raise ValueError('Missing vocabulary_file in {}.'.format(key)) + + if vocabulary_size is None: + if not gfile.Exists(vocabulary_file): + raise ValueError('vocabulary_file in {} does not exist.'.format(key)) + + with gfile.GFile(vocabulary_file) as f: + vocabulary_size = sum(1 for _ in f) + logging.info( + 'vocabulary_size = %d in %s is inferred from the number of elements ' + 'in the vocabulary_file %s.', vocabulary_size, key, vocabulary_file) + + # `vocabulary_size` isn't required for lookup, but it is for `_num_buckets`. + if vocabulary_size < 1: + raise ValueError('Invalid vocabulary_size in {}.'.format(key)) + if num_oov_buckets: + if default_value is not None: + raise ValueError( + 'Can\'t specify both num_oov_buckets and default_value in {}.'.format( + key)) + if num_oov_buckets < 0: + raise ValueError('Invalid num_oov_buckets {} in {}.'.format( + num_oov_buckets, key)) + fc_utils.assert_string_or_int(dtype, prefix='column_name: {}'.format(key)) + fc_utils.assert_key_is_string(key) + return _VocabularyFileCategoricalColumn( + key=key, + vocabulary_file=vocabulary_file, + vocabulary_size=vocabulary_size, + num_oov_buckets=0 if num_oov_buckets is None else num_oov_buckets, + default_value=-1 if default_value is None else default_value, + dtype=dtype) + + +def _categorical_column_with_vocabulary_list(key, + vocabulary_list, + dtype=None, + default_value=-1, + num_oov_buckets=0): + """A `_CategoricalColumn` with in-memory vocabulary. + + Use this when your inputs are in string or integer format, and you have an + in-memory vocabulary mapping each value to an integer ID. By default, + out-of-vocabulary values are ignored. Use either (but not both) of + `num_oov_buckets` and `default_value` to specify how to include + out-of-vocabulary values. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example with `num_oov_buckets`: + In the following example, each input in `vocabulary_list` is assigned an ID + 0-3 corresponding to its index (e.g., input 'B' produces output 2). All other + inputs are hashed and assigned an ID 4-5. + + ```python + colors = categorical_column_with_vocabulary_list( + key='colors', vocabulary_list=('R', 'G', 'B', 'Y'), + num_oov_buckets=2) + columns = [colors, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + Example with `default_value`: + In the following example, each input in `vocabulary_list` is assigned an ID + 0-4 corresponding to its index (e.g., input 'B' produces output 3). All other + inputs are assigned `default_value` 0. + + + ```python + colors = categorical_column_with_vocabulary_list( + key='colors', vocabulary_list=('X', 'R', 'G', 'B', 'Y'), default_value=0) + columns = [colors, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + And to make an embedding with either: + + ```python + columns = [embedding_column(colors, 3),...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + vocabulary_list: An ordered iterable defining the vocabulary. Each feature + is mapped to the index of its value (if present) in `vocabulary_list`. + Must be castable to `dtype`. + dtype: The type of features. Only string and integer types are supported. If + `None`, it will be inferred from `vocabulary_list`. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[len(vocabulary_list), len(vocabulary_list)+num_oov_buckets)` based on a + hash of the input value. A positive `num_oov_buckets` can not be specified + with `default_value`. + + Returns: + A `_CategoricalColumn` with in-memory vocabulary. + + Raises: + ValueError: if `vocabulary_list` is empty, or contains duplicate keys. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: if `dtype` is not integer or string. + """ + if (vocabulary_list is None) or (len(vocabulary_list) < 1): + raise ValueError( + 'vocabulary_list {} must be non-empty, column_name: {}'.format( + vocabulary_list, key)) + if len(set(vocabulary_list)) != len(vocabulary_list): + raise ValueError( + 'Duplicate keys in vocabulary_list {}, column_name: {}'.format( + vocabulary_list, key)) + vocabulary_dtype = dtypes.as_dtype(np.array(vocabulary_list).dtype) + if num_oov_buckets: + if default_value != -1: + raise ValueError( + 'Can\'t specify both num_oov_buckets and default_value in {}.'.format( + key)) + if num_oov_buckets < 0: + raise ValueError('Invalid num_oov_buckets {} in {}.'.format( + num_oov_buckets, key)) + fc_utils.assert_string_or_int( + vocabulary_dtype, prefix='column_name: {} vocabulary'.format(key)) + if dtype is None: + dtype = vocabulary_dtype + elif dtype.is_integer != vocabulary_dtype.is_integer: + raise ValueError( + 'dtype {} and vocabulary dtype {} do not match, column_name: {}'.format( + dtype, vocabulary_dtype, key)) + fc_utils.assert_string_or_int(dtype, prefix='column_name: {}'.format(key)) + fc_utils.assert_key_is_string(key) + + return _VocabularyListCategoricalColumn( + key=key, + vocabulary_list=tuple(vocabulary_list), + dtype=dtype, + default_value=default_value, + num_oov_buckets=num_oov_buckets) + + +def _categorical_column_with_identity(key, num_buckets, default_value=None): + """A `_CategoricalColumn` that returns identity values. + + Use this when your inputs are integers in the range `[0, num_buckets)`, and + you want to use the input value itself as the categorical ID. Values outside + this range will result in `default_value` if specified, otherwise it will + fail. + + Typically, this is used for contiguous ranges of integer indexes, but + it doesn't have to be. This might be inefficient, however, if many of IDs + are unused. Consider `categorical_column_with_hash_bucket` in that case. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + In the following examples, each input in the range `[0, 1000000)` is assigned + the same value. All other inputs are assigned `default_value` 0. Note that a + literal 0 in inputs will result in the same default ID. + + Linear model: + + ```python + video_id = categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [video_id, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + Embedding for a DNN model: + + ```python + columns = [embedding_column(video_id, 9),...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + num_buckets: Range of inputs and outputs is `[0, num_buckets)`. + default_value: If set, values outside of range `[0, num_buckets)` will be + replaced with this value. If not set, values >= num_buckets will cause a + failure while values < 0 will be dropped. + + Returns: + A `_CategoricalColumn` that returns identity values. + + Raises: + ValueError: if `num_buckets` is less than one. + ValueError: if `default_value` is not in range `[0, num_buckets)`. + """ + if num_buckets < 1: + raise ValueError('num_buckets {} < 1, column_name {}'.format( + num_buckets, key)) + if (default_value is not None) and ((default_value < 0) or + (default_value >= num_buckets)): + raise ValueError( + 'default_value {} not in range [0, {}), column_name {}'.format( + default_value, num_buckets, key)) + fc_utils.assert_key_is_string(key) + return _IdentityCategoricalColumn( + key=key, num_buckets=num_buckets, default_value=default_value) + + +def _indicator_column(categorical_column): + """Represents multi-hot representation of given categorical column. + + - For DNN model, `indicator_column` can be used to wrap any + `categorical_column_*` (e.g., to feed to DNN). Consider to Use + `embedding_column` if the number of buckets/unique(values) are large. + + - For Wide (aka linear) model, `indicator_column` is the internal + representation for categorical column when passing categorical column + directly (as any element in feature_columns) to `linear_model`. See + `linear_model` for details. + + ```python + name = indicator_column(categorical_column_with_vocabulary_list( + 'name', ['bob', 'george', 'wanda']) + columns = [name, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + + dense_tensor == [[1, 0, 0]] # If "name" bytes_list is ["bob"] + dense_tensor == [[1, 0, 1]] # If "name" bytes_list is ["bob", "wanda"] + dense_tensor == [[2, 0, 0]] # If "name" bytes_list is ["bob", "bob"] + ``` + + Args: + categorical_column: A `_CategoricalColumn` which is created by + `categorical_column_with_*` or `crossed_column` functions. + + Returns: + An `_IndicatorColumn`. + """ + return _IndicatorColumn(categorical_column) + + +def _weighted_categorical_column(categorical_column, + weight_feature_key, + dtype=dtypes.float32): + """Applies weight values to a `_CategoricalColumn`. + + Use this when each of your sparse inputs has both an ID and a value. For + example, if you're representing text documents as a collection of word + frequencies, you can provide 2 parallel sparse input features ('terms' and + 'frequencies' below). + + Example: + + Input `tf.Example` objects: + + ```proto + [ + features { + feature { + key: "terms" + value {bytes_list {value: "very" value: "model"}} + } + feature { + key: "frequencies" + value {float_list {value: 0.3 value: 0.1}} + } + }, + features { + feature { + key: "terms" + value {bytes_list {value: "when" value: "course" value: "human"}} + } + feature { + key: "frequencies" + value {float_list {value: 0.4 value: 0.1 value: 0.2}} + } + } + ] + ``` + + ```python + categorical_column = categorical_column_with_hash_bucket( + column_name='terms', hash_bucket_size=1000) + weighted_column = weighted_categorical_column( + categorical_column=categorical_column, weight_feature_key='frequencies') + columns = [weighted_column, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + This assumes the input dictionary contains a `SparseTensor` for key + 'terms', and a `SparseTensor` for key 'frequencies'. These 2 tensors must have + the same indices and dense shape. + + Args: + categorical_column: A `_CategoricalColumn` created by + `categorical_column_with_*` functions. + weight_feature_key: String key for weight values. + dtype: Type of weights, such as `tf.float32`. Only float and integer weights + are supported. + + Returns: + A `_CategoricalColumn` composed of two sparse features: one represents id, + the other represents weight (value) of the id feature in that example. + + Raises: + ValueError: if `dtype` is not convertible to float. + """ + if (dtype is None) or not (dtype.is_integer or dtype.is_floating): + raise ValueError('dtype {} is not convertible to float.'.format(dtype)) + return _WeightedCategoricalColumn( + categorical_column=categorical_column, + weight_feature_key=weight_feature_key, + dtype=dtype) + + +def _crossed_column(keys, hash_bucket_size, hash_key=None): + """Returns a column for performing crosses of categorical features. + + Crossed features are hashed according to `hash_bucket_size`. Conceptually, + the transformation can be thought of as: + Hash(cartesian product of features) % `hash_bucket_size` + + For example, if the input features are: + + * SparseTensor referred by first key: + + ```python + shape = [2, 2] + { + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + } + ``` + + * SparseTensor referred by second key: + + ```python + shape = [2, 1] + { + [0, 0]: "d" + [1, 0]: "e" + } + ``` + + then crossed feature will look like: + + ```python + shape = [2, 2] + { + [0, 0]: Hash64("d", Hash64("a")) % hash_bucket_size + [1, 0]: Hash64("e", Hash64("b")) % hash_bucket_size + [1, 1]: Hash64("e", Hash64("c")) % hash_bucket_size + } + ``` + + Here is an example to create a linear model with crosses of string features: + + ```python + keywords_x_doc_terms = crossed_column(['keywords', 'doc_terms'], 50K) + columns = [keywords_x_doc_terms, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + You could also use vocabulary lookup before crossing: + + ```python + keywords = categorical_column_with_vocabulary_file( + 'keywords', '/path/to/vocabulary/file', vocabulary_size=1K) + keywords_x_doc_terms = crossed_column([keywords, 'doc_terms'], 50K) + columns = [keywords_x_doc_terms, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + If an input feature is of numeric type, you can use + `categorical_column_with_identity`, or `bucketized_column`, as in the example: + + ```python + # vertical_id is an integer categorical feature. + vertical_id = categorical_column_with_identity('vertical_id', 10K) + price = numeric_column('price') + # bucketized_column converts numerical feature to a categorical one. + bucketized_price = bucketized_column(price, boundaries=[...]) + vertical_id_x_price = crossed_column([vertical_id, bucketized_price], 50K) + columns = [vertical_id_x_price, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + To use crossed column in DNN model, you need to add it in an embedding column + as in this example: + + ```python + vertical_id_x_price = crossed_column([vertical_id, bucketized_price], 50K) + vertical_id_x_price_embedded = embedding_column(vertical_id_x_price, 10) + dense_tensor = input_layer(features, [vertical_id_x_price_embedded, ...]) + ``` + + Args: + keys: An iterable identifying the features to be crossed. Each element can + be either: + * string: Uses the corresponding feature which must be of string type. + * `_CategoricalColumn`: Uses the transformed tensor produced by this + column. Does not support hashed categorical column. + hash_bucket_size: An int > 1. The number of buckets. + hash_key: Specify the hash_key that will be used by the `FingerprintCat64` + function to combine the crosses fingerprints on SparseCrossOp (optional). + + Returns: + A `_CrossedColumn`. + + Raises: + ValueError: If `len(keys) < 2`. + ValueError: If any of the keys is neither a string nor `_CategoricalColumn`. + ValueError: If any of the keys is `_HashedCategoricalColumn`. + ValueError: If `hash_bucket_size < 1`. + """ + if not hash_bucket_size or hash_bucket_size < 1: + raise ValueError('hash_bucket_size must be > 1. ' + 'hash_bucket_size: {}'.format(hash_bucket_size)) + if not keys or len(keys) < 2: + raise ValueError( + 'keys must be a list with length > 1. Given: {}'.format(keys)) + for key in keys: + if (not isinstance(key, six.string_types) and + not isinstance(key, _CategoricalColumn)): + raise ValueError( + 'Unsupported key type. All keys must be either string, or ' + 'categorical column except _HashedCategoricalColumn. ' + 'Given: {}'.format(key)) + if isinstance(key, _HashedCategoricalColumn): + raise ValueError( + 'categorical_column_with_hash_bucket is not supported for crossing. ' + 'Hashing before crossing will increase probability of collision. ' + 'Instead, use the feature name as a string. Given: {}'.format(key)) + return _CrossedColumn( + keys=tuple(keys), hash_bucket_size=hash_bucket_size, hash_key=hash_key) + + +# TODO(rohanj): Clearly define semantics of this layer. +class _EmbeddingColumnLayer(base.Layer): + """A layer that stores all the state required for a embedding column.""" + + def __init__(self, + embedding_shape, + initializer, + weight_collections=None, + trainable=True, + name=None, + **kwargs): + """Constructor. + + Args: + embedding_shape: Shape of the embedding variable used for lookup. + initializer: A variable initializer function to be used in embedding + variable initialization. + weight_collections: A list of collection names to which the Variable will + be added. Note that, variables will also be added to collections + `tf.GraphKeys.GLOBAL_VARIABLES` and `ops.GraphKeys.MODEL_VARIABLES`. + trainable: If `True` also add the variable to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + name: Name of the layer + **kwargs: keyword named properties. + """ + super(_EmbeddingColumnLayer, self).__init__( + trainable=trainable, name=name, **kwargs) + self._embedding_shape = embedding_shape + self._initializer = initializer + self._weight_collections = weight_collections + + def set_weight_collections(self, weight_collections): + """Sets the weight collections for the layer. + + Args: + weight_collections: A list of collection names to which the Variable will + be added. + """ + self._weight_collections = weight_collections + + def build(self, _): + self._embedding_weight_var = self.add_variable( + name='embedding_weights', + shape=self._embedding_shape, + dtype=dtypes.float32, + initializer=self._initializer, + trainable=self.trainable) + if self._weight_collections and not context.executing_eagerly(): + _add_to_collections(self._embedding_weight_var, self._weight_collections) + self.built = True + + def call(self, _): + return self._embedding_weight_var + + +@six.add_metaclass(abc.ABCMeta) +class _FeatureColumn(object): + """Represents a feature column abstraction. + + WARNING: Do not subclass this layer unless you know what you are doing: + the API is subject to future changes. + + To distinguish the concept of a feature family and a specific binary feature + within a family, we refer to a feature family like "country" as a feature + column. Following is an example feature in a `tf.Example` format: + {key: "country", value: [ "US" ]} + In this example the value of feature is "US" and "country" refers to the + column of the feature. + + This class is an abstract class. User should not create instances of this. + """ + + @abc.abstractproperty + def name(self): + """Returns string. Used for naming and for name_scope.""" + pass + + def __lt__(self, other): + """Allows feature columns to be sorted in Python 3 as they are in Python 2. + + Feature columns need to occasionally be sortable, for example when used as + keys in a features dictionary passed to a layer. + + In CPython, `__lt__` must be defined for all objects in the + sequence being sorted. If any objects do not have an `__lt__` compatible + with feature column objects (such as strings), then CPython will fall back + to using the `__gt__` method below. + https://docs.python.org/3/library/stdtypes.html#list.sort + + Args: + other: The other object to compare to. + + Returns: + True if the string representation of this object is lexicographically less + than the string representation of `other`. For FeatureColumn objects, + this looks like "<__main__.FeatureColumn object at 0xa>". + """ + return str(self) < str(other) + + def __gt__(self, other): + """Allows feature columns to be sorted in Python 3 as they are in Python 2. + + Feature columns need to occasionally be sortable, for example when used as + keys in a features dictionary passed to a layer. + + `__gt__` is called when the "other" object being compared during the sort + does not have `__lt__` defined. + Example: + ``` + # __lt__ only class + class A(): + def __lt__(self, other): return str(self) < str(other) + + a = A() + a < "b" # True + "0" < a # Error + + # __lt__ and __gt__ class + class B(): + def __lt__(self, other): return str(self) < str(other) + def __gt__(self, other): return str(self) > str(other) + + b = B() + b < "c" # True + "0" < b # True + ``` + + + Args: + other: The other object to compare to. + + Returns: + True if the string representation of this object is lexicographically + greater than the string representation of `other`. For FeatureColumn + objects, this looks like "<__main__.FeatureColumn object at 0xa>". + """ + return str(self) > str(other) + + @property + def _var_scope_name(self): + """Returns string. Used for variable_scope. Defaults to self.name.""" + return self.name + + @abc.abstractmethod + def _transform_feature(self, inputs): + """Returns intermediate representation (usually a `Tensor`). + + Uses `inputs` to create an intermediate representation (usually a `Tensor`) + that other feature columns can use. + + Example usage of `inputs`: + Let's say a Feature column depends on raw feature ('raw') and another + `_FeatureColumn` (input_fc). To access corresponding `Tensor`s, inputs will + be used as follows: + + ```python + raw_tensor = inputs.get('raw') + fc_tensor = inputs.get(input_fc) + ``` + + Args: + inputs: A `_LazyBuilder` object to access inputs. + + Returns: + Transformed feature `Tensor`. + """ + pass + + @abc.abstractproperty + def _parse_example_spec(self): + """Returns a `tf.Example` parsing spec as dict. + + It is used for get_parsing_spec for `tf.io.parse_example`. Returned spec is + a dict from keys ('string') to `VarLenFeature`, `FixedLenFeature`, and other + supported objects. Please check documentation of `tf.io.parse_example` for + all supported spec objects. + + Let's say a Feature column depends on raw feature ('raw') and another + `_FeatureColumn` (input_fc). One possible implementation of + _parse_example_spec is as follows: + + ```python + spec = {'raw': tf.io.FixedLenFeature(...)} + spec.update(input_fc._parse_example_spec) + return spec + ``` + """ + pass + + def _reset_config(self): + """Resets the configuration in the column. + + Some feature columns e.g. embedding or shared embedding columns might + have some state that is needed to be reset sometimes. Use this method + in that scenario. + """ + + +class _DenseColumn(_FeatureColumn): + """Represents a column which can be represented as `Tensor`. + + WARNING: Do not subclass this layer unless you know what you are doing: + the API is subject to future changes. + + Some examples of this type are: numeric_column, embedding_column, + indicator_column. + """ + + @abc.abstractproperty + def _variable_shape(self): + """`TensorShape` of `_get_dense_tensor`, without batch dimension.""" + pass + + @abc.abstractmethod + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + """Returns a `Tensor`. + + The output of this function will be used by model-builder-functions. For + example the pseudo code of `input_layer` will be like: + + ```python + def input_layer(features, feature_columns, ...): + outputs = [fc._get_dense_tensor(...) for fc in feature_columns] + return tf.concat(outputs) + ``` + + Args: + inputs: A `_LazyBuilder` object to access inputs. + weight_collections: List of graph collections to which Variables (if any + will be created) are added. + trainable: If `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). + + Returns: + `Tensor` of shape [batch_size] + `_variable_shape`. + """ + pass + + +def _create_weighted_sum(column, + builder, + units, + sparse_combiner, + weight_collections, + trainable, + weight_var=None): + """Creates a weighted sum for a dense/categorical column for linear_model.""" + if isinstance(column, _CategoricalColumn): + return _create_categorical_column_weighted_sum( + column=column, + builder=builder, + units=units, + sparse_combiner=sparse_combiner, + weight_collections=weight_collections, + trainable=trainable, + weight_var=weight_var) + else: + return _create_dense_column_weighted_sum( + column=column, + builder=builder, + units=units, + weight_collections=weight_collections, + trainable=trainable, + weight_var=weight_var) + + +def _create_dense_column_weighted_sum(column, + builder, + units, + weight_collections, + trainable, + weight_var=None): + """Create a weighted sum of a dense column for linear_model.""" + tensor = column._get_dense_tensor( # pylint: disable=protected-access + builder, + weight_collections=weight_collections, + trainable=trainable) + num_elements = column._variable_shape.num_elements() # pylint: disable=protected-access + batch_size = array_ops.shape(tensor)[0] + tensor = array_ops.reshape(tensor, shape=(batch_size, num_elements)) + if weight_var is not None: + weight = weight_var + else: + weight = variable_scope.get_variable( + name='weights', + shape=[num_elements, units], + initializer=init_ops.zeros_initializer(), + trainable=trainable, + collections=weight_collections) + return math_ops.matmul(tensor, weight, name='weighted_sum') + + +class _CategoricalColumn(_FeatureColumn): + """Represents a categorical feature. + + WARNING: Do not subclass this layer unless you know what you are doing: + the API is subject to future changes. + + A categorical feature typically handled with a `tf.sparse.SparseTensor` of + IDs. + """ + + IdWeightPair = collections.namedtuple( # pylint: disable=invalid-name + 'IdWeightPair', ['id_tensor', 'weight_tensor']) + + @abc.abstractproperty + def _num_buckets(self): + """Returns number of buckets in this sparse feature.""" + pass + + @abc.abstractmethod + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + """Returns an IdWeightPair. + + `IdWeightPair` is a pair of `SparseTensor`s which represents ids and + weights. + + `IdWeightPair.id_tensor` is typically a `batch_size` x `num_buckets` + `SparseTensor` of `int64`. `IdWeightPair.weight_tensor` is either a + `SparseTensor` of `float` or `None` to indicate all weights should be + taken to be 1. If specified, `weight_tensor` must have exactly the same + shape and indices as `sp_ids`. Expected `SparseTensor` is same as parsing + output of a `VarLenFeature` which is a ragged matrix. + + Args: + inputs: A `LazyBuilder` as a cache to get input tensors required to create + `IdWeightPair`. + weight_collections: List of graph collections to which variables (if any + will be created) are added. + trainable: If `True` also add variables to the graph collection + `GraphKeys.TRAINABLE_VARIABLES` (see `tf.compat.v1.get_variable`). + """ + pass + + +def _create_categorical_column_weighted_sum(column, + builder, + units, + sparse_combiner, + weight_collections, + trainable, + weight_var=None): + # pylint: disable=g-doc-return-or-yield,g-doc-args + """Create a weighted sum of a categorical column for linear_model. + + Note to maintainer: As implementation details, the weighted sum is + implemented via embedding_lookup_sparse toward efficiency. Mathematically, + they are the same. + + To be specific, conceptually, categorical column can be treated as multi-hot + vector. Say: + + ```python + x = [0 0 1] # categorical column input + w = [a b c] # weights + ``` + The weighted sum is `c` in this case, which is same as `w[2]`. + + Another example is + + ```python + x = [0 1 1] # categorical column input + w = [a b c] # weights + ``` + The weighted sum is `b + c` in this case, which is same as `w[2] + w[3]`. + + For both cases, we can implement weighted sum via embedding_lookup with + sparse_combiner = "sum". + """ + + sparse_tensors = column._get_sparse_tensors( # pylint: disable=protected-access + builder, + weight_collections=weight_collections, + trainable=trainable) + id_tensor = sparse_ops.sparse_reshape( + sparse_tensors.id_tensor, + [array_ops.shape(sparse_tensors.id_tensor)[0], -1]) + weight_tensor = sparse_tensors.weight_tensor + if weight_tensor is not None: + weight_tensor = sparse_ops.sparse_reshape( + weight_tensor, [array_ops.shape(weight_tensor)[0], -1]) + + if weight_var is not None: + weight = weight_var + else: + weight = variable_scope.get_variable( + name='weights', + shape=(column._num_buckets, units), # pylint: disable=protected-access + initializer=init_ops.zeros_initializer(), + trainable=trainable, + collections=weight_collections) + return embedding_ops.safe_embedding_lookup_sparse( + weight, + id_tensor, + sparse_weights=weight_tensor, + combiner=sparse_combiner, + name='weighted_sum') + + +class _SequenceDenseColumn(_FeatureColumn): + """Represents dense sequence data.""" + + TensorSequenceLengthPair = collections.namedtuple( # pylint: disable=invalid-name + 'TensorSequenceLengthPair', ['dense_tensor', 'sequence_length']) + + @abc.abstractmethod + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + """Returns a `TensorSequenceLengthPair`.""" + pass + + +class _LazyBuilder(object): + """Handles caching of transformations while building the model. + + `_FeatureColumn` specifies how to digest an input column to the network. Some + feature columns require data transformations. This class caches those + transformations. + + Some features may be used in more than one place. For example, one can use a + bucketized feature by itself and a cross with it. In that case we + should create only one bucketization op instead of creating ops for each + feature column separately. To handle re-use of transformed columns, + `_LazyBuilder` caches all previously transformed columns. + + Example: + We're trying to use the following `_FeatureColumn`s: + + ```python + bucketized_age = fc.bucketized_column(fc.numeric_column("age"), ...) + keywords = fc.categorical_column_with_hash_buckets("keywords", ...) + age_X_keywords = fc.crossed_column([bucketized_age, "keywords"]) + ... = linear_model(features, + [bucketized_age, keywords, age_X_keywords] + ``` + + If we transform each column independently, then we'll get duplication of + bucketization (one for cross, one for bucketization itself). + The `_LazyBuilder` eliminates this duplication. + """ + + def __init__(self, features): + """Creates a `_LazyBuilder`. + + Args: + features: A mapping from feature column to objects that are `Tensor` or + `SparseTensor`, or can be converted to same via + `sparse_tensor.convert_to_tensor_or_sparse_tensor`. A `string` key + signifies a base feature (not-transformed). A `_FeatureColumn` key means + that this `Tensor` is the output of an existing `_FeatureColumn` which + can be reused. + """ + self._features = features.copy() + self._feature_tensors = {} + + def get(self, key): + """Returns a `Tensor` for the given key. + + A `str` key is used to access a base feature (not-transformed). When a + `_FeatureColumn` is passed, the transformed feature is returned if it + already exists, otherwise the given `_FeatureColumn` is asked to provide its + transformed output, which is then cached. + + Args: + key: a `str` or a `_FeatureColumn`. + + Returns: + The transformed `Tensor` corresponding to the `key`. + + Raises: + ValueError: if key is not found or a transformed `Tensor` cannot be + computed. + """ + if key in self._feature_tensors: + # FeatureColumn is already transformed or converted. + return self._feature_tensors[key] + + if key in self._features: + feature_tensor = self._get_raw_feature_as_tensor(key) + self._feature_tensors[key] = feature_tensor + return feature_tensor + + if isinstance(key, six.string_types): + raise ValueError('Feature {} is not in features dictionary.'.format(key)) + + if not isinstance(key, _FeatureColumn): + raise TypeError('"key" must be either a "str" or "_FeatureColumn". ' + 'Provided: {}'.format(key)) + + column = key + logging.debug('Transforming feature_column %s.', column) + transformed = column._transform_feature(self) # pylint: disable=protected-access + if transformed is None: + raise ValueError('Column {} is not supported.'.format(column.name)) + self._feature_tensors[column] = transformed + return transformed + + def _get_raw_feature_as_tensor(self, key): + """Gets the raw_feature (keyed by `key`) as `tensor`. + + The raw feature is converted to (sparse) tensor and maybe expand dim. + + For both `Tensor` and `SparseTensor`, the rank will be expanded (to 2) if + the rank is 1. This supports dynamic rank also. For rank 0 raw feature, will + error out as it is not supported. + + Args: + key: A `str` key to access the raw feature. + + Returns: + A `Tensor` or `SparseTensor`. + + Raises: + ValueError: if the raw feature has rank 0. + """ + raw_feature = self._features[key] + feature_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor( + raw_feature) + + def expand_dims(input_tensor): + # Input_tensor must have rank 1. + if isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + return sparse_ops.sparse_reshape(input_tensor, + [array_ops.shape(input_tensor)[0], 1]) + else: + return array_ops.expand_dims(input_tensor, -1) + + rank = feature_tensor.get_shape().ndims + if rank is not None: + if rank == 0: + raise ValueError( + 'Feature (key: {}) cannot have rank 0. Given: {}'.format( + key, feature_tensor)) + return feature_tensor if rank != 1 else expand_dims(feature_tensor) + + # Handle dynamic rank. + with ops.control_dependencies([ + check_ops.assert_positive( + array_ops.rank(feature_tensor), + message='Feature (key: {}) cannot have rank 0. Given: {}'.format( + key, feature_tensor)) + ]): + return cond.cond( + math_ops.equal(1, array_ops.rank(feature_tensor)), + lambda: expand_dims(feature_tensor), lambda: feature_tensor) + + +# TODO(ptucker): Move to third_party/tensorflow/python/ops/sparse_ops.py +def _shape_offsets(shape): + """Returns moving offset for each dimension given shape.""" + offsets = [] + for dim in reversed(shape): + if offsets: + offsets.append(dim * offsets[-1]) + else: + offsets.append(dim) + offsets.reverse() + return offsets + + +# TODO(ptucker): Move to third_party/tensorflow/python/ops/sparse_ops.py +def _to_sparse_input_and_drop_ignore_values(input_tensor, ignore_value=None): + """Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells. + + If `input_tensor` is already a `SparseTensor`, just return it. + + Args: + input_tensor: A string or integer `Tensor`. + ignore_value: Entries in `dense_tensor` equal to this value will be absent + from the resulting `SparseTensor`. If `None`, default value of + `dense_tensor`'s dtype will be used ('' for `str`, -1 for `int`). + + Returns: + A `SparseTensor` with the same shape as `input_tensor`. + + Raises: + ValueError: when `input_tensor`'s rank is `None`. + """ + input_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor( + input_tensor) + if isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + return input_tensor + with ops.name_scope(None, 'to_sparse_input', ( + input_tensor, + ignore_value, + )): + if ignore_value is None: + if input_tensor.dtype == dtypes.string: + # Exception due to TF strings are converted to numpy objects by default. + ignore_value = '' + elif input_tensor.dtype.is_integer: + ignore_value = -1 # -1 has a special meaning of missing feature + else: + # NOTE: `as_numpy_dtype` is a property, so with the parentheses this is + # constructing a new numpy object of the given type, which yields the + # default value for that type. + ignore_value = input_tensor.dtype.as_numpy_dtype() + ignore_value = math_ops.cast( + ignore_value, input_tensor.dtype, name='ignore_value') + indices = array_ops.where( + math_ops.not_equal(input_tensor, ignore_value), name='indices') + return sparse_tensor_lib.SparseTensor( + indices=indices, + values=array_ops.gather_nd(input_tensor, indices, name='values'), + dense_shape=array_ops.shape( + input_tensor, out_type=dtypes.int64, name='dense_shape')) + + +def _normalize_feature_columns(feature_columns): + """Normalizes the `feature_columns` input. + + This method converts the `feature_columns` to list type as best as it can. In + addition, verifies the type and other parts of feature_columns, required by + downstream library. + + Args: + feature_columns: The raw feature columns, usually passed by users. + + Returns: + The normalized feature column list. + + Raises: + ValueError: for any invalid inputs, such as empty, duplicated names, etc. + """ + if isinstance(feature_columns, _FeatureColumn): + feature_columns = [feature_columns] + + if isinstance(feature_columns, collections_abc.Iterator): + feature_columns = list(feature_columns) + + if isinstance(feature_columns, dict): + raise ValueError('Expected feature_columns to be iterable, found dict.') + + for column in feature_columns: + if not isinstance(column, _FeatureColumn): + raise ValueError('Items of feature_columns must be a _FeatureColumn. ' + 'Given (type {}): {}.'.format(type(column), column)) + if not feature_columns: + raise ValueError('feature_columns must not be empty.') + name_to_column = {} + for column in feature_columns: + if column.name in name_to_column: + raise ValueError('Duplicate feature column name found for columns: {} ' + 'and {}. This usually means that these columns refer to ' + 'same base feature. Either one must be discarded or a ' + 'duplicated but renamed item must be inserted in ' + 'features dict.'.format(column, + name_to_column[column.name])) + name_to_column[column.name] = column + + return feature_columns + + +class _NumericColumn( + _DenseColumn, + collections.namedtuple( + '_NumericColumn', + ['key', 'shape', 'default_value', 'dtype', 'normalizer_fn'])): + """see `numeric_column`.""" + + @property + def name(self): + return self.key + + @property + def _parse_example_spec(self): + return { + self.key: + parsing_ops.FixedLenFeature(self.shape, self.dtype, + self.default_value) + } + + def _transform_feature(self, inputs): + input_tensor = inputs.get(self.key) + if isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + raise ValueError( + 'The corresponding Tensor of numerical column must be a Tensor. ' + 'SparseTensor is not supported. key: {}'.format(self.key)) + if self.normalizer_fn is not None: + input_tensor = self.normalizer_fn(input_tensor) + return math_ops.cast(input_tensor, dtypes.float32) + + @property + def _variable_shape(self): + return tensor_shape.TensorShape(self.shape) + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + """Returns dense `Tensor` representing numeric feature. + + Args: + inputs: A `_LazyBuilder` object to access inputs. + weight_collections: Unused `weight_collections` since no variables are + created in this function. + trainable: Unused `trainable` bool since no variables are created in this + function. + + Returns: + Dense `Tensor` created within `_transform_feature`. + """ + # Do nothing with weight_collections and trainable since no variables are + # created in this function. + del weight_collections + del trainable + # Feature has been already transformed. Return the intermediate + # representation created by _transform_feature. + return inputs.get(self) + + +class _BucketizedColumn(_DenseColumn, _CategoricalColumn, + collections.namedtuple('_BucketizedColumn', + ['source_column', 'boundaries']) + ): + """See `bucketized_column`.""" + + @property + def name(self): + return '{}_bucketized'.format(self.source_column.name) + + @property + def _parse_example_spec(self): + return self.source_column._parse_example_spec # pylint: disable=protected-access + + def _transform_feature(self, inputs): + source_tensor = inputs.get(self.source_column) + return math_ops._bucketize( # pylint: disable=protected-access + source_tensor, + boundaries=self.boundaries) + + @property + def _variable_shape(self): + return tensor_shape.TensorShape( + tuple(self.source_column.shape) + (len(self.boundaries) + 1,)) + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + del weight_collections + del trainable + input_tensor = inputs.get(self) + return array_ops.one_hot( + indices=math_ops.cast(input_tensor, dtypes.int64), + depth=len(self.boundaries) + 1, + on_value=1., + off_value=0.) + + @property + def _num_buckets(self): + # By construction, source_column is always one-dimensional. + return (len(self.boundaries) + 1) * self.source_column.shape[0] + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + """Converts dense inputs to SparseTensor so downstream code can use it.""" + input_tensor = inputs.get(self) + batch_size = array_ops.shape(input_tensor)[0] + # By construction, source_column is always one-dimensional. + source_dimension = self.source_column.shape[0] + + i1 = array_ops.reshape( + array_ops.tile( + array_ops.expand_dims(math_ops.range(0, batch_size), 1), + [1, source_dimension]), (-1,)) + i2 = array_ops.tile(math_ops.range(0, source_dimension), [batch_size]) + # Flatten the bucket indices and unique them across dimensions + # E.g. 2nd dimension indices will range from k to 2*k-1 with k buckets + bucket_indices = ( + array_ops.reshape(input_tensor, + (-1,)) + (len(self.boundaries) + 1) * i2) + + indices = math_ops.cast( + array_ops.transpose(array_ops_stack.stack((i1, i2))), dtypes.int64) + dense_shape = math_ops.cast( + array_ops_stack.stack([batch_size, source_dimension]), dtypes.int64) + sparse_tensor = sparse_tensor_lib.SparseTensor( + indices=indices, values=bucket_indices, dense_shape=dense_shape) + return _CategoricalColumn.IdWeightPair(sparse_tensor, None) + + +class _EmbeddingColumn( + _DenseColumn, _SequenceDenseColumn, + collections.namedtuple( + '_EmbeddingColumn', + ('categorical_column', 'dimension', 'combiner', 'layer_creator', + 'ckpt_to_load_from', 'tensor_name_in_ckpt', 'max_norm', 'trainable', + 'use_safe_embedding_lookup'))): + """See `embedding_column`.""" + + def __new__(cls, + categorical_column, + dimension, + combiner, + layer_creator, + ckpt_to_load_from, + tensor_name_in_ckpt, + max_norm, + trainable, + use_safe_embedding_lookup=True): + return super(_EmbeddingColumn, cls).__new__( + cls, + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + layer_creator=layer_creator, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + @property + def name(self): + if not hasattr(self, '_name'): + self._name = '{}_embedding'.format(self.categorical_column.name) + return self._name + + @property + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + def _transform_feature(self, inputs): + return inputs.get(self.categorical_column) + + @property + def _variable_shape(self): + if not hasattr(self, '_shape'): + self._shape = tensor_shape.TensorShape([self.dimension]) + return self._shape + + def _get_dense_tensor_internal(self, + inputs, + weight_collections=None, + trainable=None): + """Private method that follows the signature of _get_dense_tensor.""" + # Get sparse IDs and weights. + sparse_tensors = self.categorical_column._get_sparse_tensors( # pylint: disable=protected-access + inputs, + weight_collections=weight_collections, + trainable=trainable) + sparse_ids = sparse_tensors.id_tensor + sparse_weights = sparse_tensors.weight_tensor + + embedding_weights = self.layer_creator( + weight_collections=weight_collections, + scope=variable_scope.get_variable_scope()) + + if self.ckpt_to_load_from is not None: + to_restore = embedding_weights + if isinstance(to_restore, variables.PartitionedVariable): + to_restore = to_restore._get_variable_list() # pylint: disable=protected-access + checkpoint_utils.init_from_checkpoint( + self.ckpt_to_load_from, {self.tensor_name_in_ckpt: to_restore}) + + sparse_id_rank = tensor_shape.dimension_value( + sparse_ids.dense_shape.get_shape()[0]) + embedding_lookup_sparse = embedding_ops.safe_embedding_lookup_sparse + if (not self.use_safe_embedding_lookup and sparse_id_rank is not None and + sparse_id_rank <= 2): + embedding_lookup_sparse = embedding_ops.embedding_lookup_sparse_v2 + # Return embedding lookup result. + return embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights, + combiner=self.combiner, + name='%s_weights' % self.name, + max_norm=self.max_norm) + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + if isinstance(self.categorical_column, _SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must not be of type _SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use input_layer, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'sequence_input_layer instead of input_layer. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + return self._get_dense_tensor_internal( + inputs=inputs, + weight_collections=weight_collections, + trainable=trainable) + + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + if not isinstance(self.categorical_column, _SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must be of type _SequenceCategoricalColumn ' + 'to use sequence_input_layer. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + dense_tensor = self._get_dense_tensor_internal( # pylint: disable=protected-access + inputs=inputs, + weight_collections=weight_collections, + trainable=trainable) + + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return _SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + +def _get_graph_for_variable(var): + if isinstance(var, variables.PartitionedVariable): + return list(var)[0].graph + else: + return var.graph + + +class _SharedEmbeddingColumn( + _DenseColumn, _SequenceDenseColumn, + collections.namedtuple( + '_SharedEmbeddingColumn', + ('categorical_column', 'dimension', 'combiner', 'initializer', + 'shared_embedding_collection_name', 'ckpt_to_load_from', + 'tensor_name_in_ckpt', 'max_norm', 'trainable', + 'use_safe_embedding_lookup'))): + """See `embedding_column`.""" + + @property + def name(self): + if not hasattr(self, '_name'): + self._name = '{}_shared_embedding'.format(self.categorical_column.name) + return self._name + + @property + def _var_scope_name(self): + return self.shared_embedding_collection_name + + @property + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + def _transform_feature(self, inputs): + return inputs.get(self.categorical_column) + + @property + def _variable_shape(self): + if not hasattr(self, '_shape'): + self._shape = tensor_shape.TensorShape([self.dimension]) + return self._shape + + def _get_dense_tensor_internal(self, + inputs, + weight_collections=None, + trainable=None): + """Private method that follows the signature of _get_dense_tensor.""" + # This method is called from a variable_scope with name _var_scope_name, + # which is shared among all shared embeddings. Open a name_scope here, so + # that the ops for different columns have distinct names. + with ops.name_scope(None, default_name=self.name): + # Get sparse IDs and weights. + sparse_tensors = self.categorical_column._get_sparse_tensors( # pylint: disable=protected-access + inputs, + weight_collections=weight_collections, + trainable=trainable) + sparse_ids = sparse_tensors.id_tensor + sparse_weights = sparse_tensors.weight_tensor + + embedding_shape = (self.categorical_column._num_buckets, self.dimension) # pylint: disable=protected-access + shared_embedding_collection = ops.get_collection( + self.shared_embedding_collection_name) + if shared_embedding_collection: + if len(shared_embedding_collection) > 1: + raise ValueError( + 'Collection {} can only contain one variable. ' + 'Suggested fix A: Choose a unique name for this collection. ' + 'Suggested fix B: Do not add any variables to this collection. ' + 'The feature_column library already adds a variable under the ' + 'hood.'.format(shared_embedding_collection)) + embedding_weights = shared_embedding_collection[0] + if embedding_weights.get_shape() != embedding_shape: + raise ValueError( + 'Shared embedding collection {} contains variable {} of ' + 'unexpected shape {}. Expected shape is {}. ' + 'Suggested fix A: Choose a unique name for this collection. ' + 'Suggested fix B: Do not add any variables to this collection. ' + 'The feature_column library already adds a variable under the ' + 'hood.'.format(self.shared_embedding_collection_name, + embedding_weights.name, + embedding_weights.get_shape(), embedding_shape)) + else: + embedding_weights = variable_scope.get_variable( + name='embedding_weights', + shape=embedding_shape, + dtype=dtypes.float32, + initializer=self.initializer, + trainable=self.trainable and trainable, + collections=weight_collections) + ops.add_to_collection(self.shared_embedding_collection_name, + embedding_weights) + if self.ckpt_to_load_from is not None: + to_restore = embedding_weights + if isinstance(to_restore, variables.PartitionedVariable): + to_restore = to_restore._get_variable_list() # pylint: disable=protected-access + checkpoint_utils.init_from_checkpoint( + self.ckpt_to_load_from, {self.tensor_name_in_ckpt: to_restore}) + + sparse_id_rank = tensor_shape.dimension_value( + sparse_ids.dense_shape.get_shape()[0]) + embedding_lookup_sparse = embedding_ops.safe_embedding_lookup_sparse + if (not self.use_safe_embedding_lookup and sparse_id_rank is not None and + sparse_id_rank <= 2): + embedding_lookup_sparse = embedding_ops.embedding_lookup_sparse_v2 + # Return embedding lookup result. + return embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights, + combiner=self.combiner, + name='%s_weights' % self.name, + max_norm=self.max_norm) + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + if isinstance(self.categorical_column, _SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must not be of type _SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use input_layer, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'sequence_input_layer instead of input_layer. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + return self._get_dense_tensor_internal( + inputs=inputs, + weight_collections=weight_collections, + trainable=trainable) + + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + if not isinstance(self.categorical_column, _SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must be of type _SequenceCategoricalColumn ' + 'to use sequence_input_layer. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + dense_tensor = self._get_dense_tensor_internal( # pylint: disable=protected-access + inputs=inputs, + weight_collections=weight_collections, + trainable=trainable) + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return _SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + +def _check_shape(shape, key): + """Returns shape if it's valid, raises error otherwise.""" + assert shape is not None + if not nest.is_nested(shape): + shape = [shape] + shape = tuple(shape) + for dimension in shape: + if not isinstance(dimension, six.integer_types): + raise TypeError('shape dimensions must be integer. ' + 'shape: {}, key: {}'.format(shape, key)) + if dimension < 1: + raise ValueError('shape dimensions must be greater than 0. ' + 'shape: {}, key: {}'.format(shape, key)) + return shape + + +class _HashedCategoricalColumn(_CategoricalColumn, + collections.namedtuple( + '_HashedCategoricalColumn', + ['key', 'hash_bucket_size', 'dtype'])): + """see `categorical_column_with_hash_bucket`.""" + + @property + def name(self): + return self.key + + @property + def _parse_example_spec(self): + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + if not isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + raise ValueError('SparseColumn input must be a SparseTensor.') + + fc_utils.assert_string_or_int( + input_tensor.dtype, + prefix='column_name: {} input_tensor'.format(self.key)) + + if self.dtype.is_integer != input_tensor.dtype.is_integer: + raise ValueError( + 'Column dtype and SparseTensors dtype must be compatible. ' + 'key: {}, column dtype: {}, tensor dtype: {}'.format( + self.key, self.dtype, input_tensor.dtype)) + + if self.dtype == dtypes.string: + sparse_values = input_tensor.values + else: + sparse_values = string_ops.as_string(input_tensor.values) + + sparse_id_values = string_ops.string_to_hash_bucket_fast( + sparse_values, self.hash_bucket_size, name='lookup') + return sparse_tensor_lib.SparseTensor(input_tensor.indices, + sparse_id_values, + input_tensor.dense_shape) + + @property + def _num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.hash_bucket_size + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + return _CategoricalColumn.IdWeightPair(inputs.get(self), None) + + +class _VocabularyFileCategoricalColumn( + _CategoricalColumn, + collections.namedtuple('_VocabularyFileCategoricalColumn', + ('key', 'vocabulary_file', 'vocabulary_size', + 'num_oov_buckets', 'dtype', 'default_value'))): + """See `categorical_column_with_vocabulary_file`.""" + + @property + def name(self): + return self.key + + @property + def _parse_example_spec(self): + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + + if self.dtype.is_integer != input_tensor.dtype.is_integer: + raise ValueError( + 'Column dtype and SparseTensors dtype must be compatible. ' + 'key: {}, column dtype: {}, tensor dtype: {}'.format( + self.key, self.dtype, input_tensor.dtype)) + + fc_utils.assert_string_or_int( + input_tensor.dtype, + prefix='column_name: {} input_tensor'.format(self.key)) + + key_dtype = self.dtype + if input_tensor.dtype.is_integer: + # `index_table_from_file` requires 64-bit integer keys. + key_dtype = dtypes.int64 + input_tensor = math_ops.cast(input_tensor, dtypes.int64) + + return lookup_ops.index_table_from_file( + vocabulary_file=self.vocabulary_file, + num_oov_buckets=self.num_oov_buckets, + vocab_size=self.vocabulary_size, + default_value=self.default_value, + key_dtype=key_dtype, + name='{}_lookup'.format(self.key)).lookup(input_tensor) + + @property + def _num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.vocabulary_size + self.num_oov_buckets + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + return _CategoricalColumn.IdWeightPair(inputs.get(self), None) + + +class _VocabularyListCategoricalColumn( + _CategoricalColumn, + collections.namedtuple( + '_VocabularyListCategoricalColumn', + ('key', 'vocabulary_list', 'dtype', 'default_value', 'num_oov_buckets')) +): + """See `categorical_column_with_vocabulary_list`.""" + + @property + def name(self): + return self.key + + @property + def _parse_example_spec(self): + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + + if self.dtype.is_integer != input_tensor.dtype.is_integer: + raise ValueError( + 'Column dtype and SparseTensors dtype must be compatible. ' + 'key: {}, column dtype: {}, tensor dtype: {}'.format( + self.key, self.dtype, input_tensor.dtype)) + + fc_utils.assert_string_or_int( + input_tensor.dtype, + prefix='column_name: {} input_tensor'.format(self.key)) + + key_dtype = self.dtype + if input_tensor.dtype.is_integer: + # `index_table_from_tensor` requires 64-bit integer keys. + key_dtype = dtypes.int64 + input_tensor = math_ops.cast(input_tensor, dtypes.int64) + + return lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self.vocabulary_list), + default_value=self.default_value, + num_oov_buckets=self.num_oov_buckets, + dtype=key_dtype, + name='{}_lookup'.format(self.key)).lookup(input_tensor) + + @property + def _num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return len(self.vocabulary_list) + self.num_oov_buckets + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + return _CategoricalColumn.IdWeightPair(inputs.get(self), None) + + +class _IdentityCategoricalColumn(_CategoricalColumn, + collections.namedtuple( + '_IdentityCategoricalColumn', + ('key', 'num_buckets', 'default_value'))): + """See `categorical_column_with_identity`.""" + + @property + def name(self): + return self.key + + @property + def _parse_example_spec(self): + return {self.key: parsing_ops.VarLenFeature(dtypes.int64)} + + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + + if not input_tensor.dtype.is_integer: + raise ValueError('Invalid input, not integer. key: {} dtype: {}'.format( + self.key, input_tensor.dtype)) + values = input_tensor.values + if input_tensor.values.dtype != dtypes.int64: + values = math_ops.cast(values, dtypes.int64, name='values') + if self.default_value is not None: + num_buckets = math_ops.cast( + self.num_buckets, dtypes.int64, name='num_buckets') + zero = math_ops.cast(0, dtypes.int64, name='zero') + # Assign default for out-of-range values. + values = array_ops.where( + math_ops.logical_or( + values < zero, values >= num_buckets, name='out_of_range'), + array_ops.fill( + dims=array_ops.shape(values), + value=math_ops.cast(self.default_value, dtypes.int64), + name='default_values'), values) + return sparse_tensor_lib.SparseTensor( + indices=input_tensor.indices, + values=values, + dense_shape=input_tensor.dense_shape) + + @property + def _num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.num_buckets + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + return _CategoricalColumn.IdWeightPair(inputs.get(self), None) + + +class _WeightedCategoricalColumn( + _CategoricalColumn, + collections.namedtuple( + '_WeightedCategoricalColumn', + ('categorical_column', 'weight_feature_key', 'dtype'))): + """See `weighted_categorical_column`.""" + + @property + def name(self): + return '{}_weighted_by_{}'.format(self.categorical_column.name, + self.weight_feature_key) + + @property + def _parse_example_spec(self): + config = self.categorical_column._parse_example_spec # pylint: disable=protected-access + if self.weight_feature_key in config: + raise ValueError('Parse config {} already exists for {}.'.format( + config[self.weight_feature_key], self.weight_feature_key)) + config[self.weight_feature_key] = parsing_ops.VarLenFeature(self.dtype) + return config + + @property + def _num_buckets(self): + return self.categorical_column._num_buckets # pylint: disable=protected-access + + def _transform_feature(self, inputs): + weight_tensor = inputs.get(self.weight_feature_key) + if weight_tensor is None: + raise ValueError('Missing weights {}.'.format(self.weight_feature_key)) + weight_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor( + weight_tensor) + if self.dtype != weight_tensor.dtype.base_dtype: + raise ValueError('Bad dtype, expected {}, but got {}.'.format( + self.dtype, weight_tensor.dtype)) + if not isinstance(weight_tensor, sparse_tensor_lib.SparseTensor): + # The weight tensor can be a regular Tensor. In this case, sparsify it. + weight_tensor = _to_sparse_input_and_drop_ignore_values( + weight_tensor, ignore_value=0.0) + if not weight_tensor.dtype.is_floating: + weight_tensor = math_ops.cast(weight_tensor, dtypes.float32) + return (inputs.get(self.categorical_column), weight_tensor) + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + del weight_collections + del trainable + tensors = inputs.get(self) + return _CategoricalColumn.IdWeightPair(tensors[0], tensors[1]) + + +class _CrossedColumn( + _CategoricalColumn, + collections.namedtuple('_CrossedColumn', + ['keys', 'hash_bucket_size', 'hash_key'])): + """See `crossed_column`.""" + + @property + def name(self): + feature_names = [] + for key in _collect_leaf_level_keys(self): + if isinstance(key, _FeatureColumn): + feature_names.append(key.name) + else: # key must be a string + feature_names.append(key) + return '_X_'.join(sorted(feature_names)) + + @property + def _parse_example_spec(self): + config = {} + for key in self.keys: + if isinstance(key, _FeatureColumn): + config.update(key._parse_example_spec) # pylint: disable=protected-access + else: # key must be a string + config.update({key: parsing_ops.VarLenFeature(dtypes.string)}) + return config + + def _transform_feature(self, inputs): + feature_tensors = [] + for key in _collect_leaf_level_keys(self): + if isinstance(key, six.string_types): + feature_tensors.append(inputs.get(key)) + elif isinstance(key, _CategoricalColumn): + ids_and_weights = key._get_sparse_tensors(inputs) # pylint: disable=protected-access + if ids_and_weights.weight_tensor is not None: + raise ValueError( + 'crossed_column does not support weight_tensor, but the given ' + 'column populates weight_tensor. ' + 'Given column: {}'.format(key.name)) + feature_tensors.append(ids_and_weights.id_tensor) + else: + raise ValueError('Unsupported column type. Given: {}'.format(key)) + return sparse_ops.sparse_cross_hashed( + inputs=feature_tensors, + num_buckets=self.hash_bucket_size, + hash_key=self.hash_key) + + @property + def _num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.hash_bucket_size + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + return _CategoricalColumn.IdWeightPair(inputs.get(self), None) + + +def _collect_leaf_level_keys(cross): + """Collects base keys by expanding all nested crosses. + + Args: + cross: A `_CrossedColumn`. + + Returns: + A list of strings or `_CategoricalColumn` instances. + """ + leaf_level_keys = [] + for k in cross.keys: + if isinstance(k, _CrossedColumn): + leaf_level_keys.extend(_collect_leaf_level_keys(k)) + else: + leaf_level_keys.append(k) + return leaf_level_keys + + +class _IndicatorColumn(_DenseColumn, _SequenceDenseColumn, + collections.namedtuple('_IndicatorColumn', + ['categorical_column'])): + """Represents a one-hot column for use in deep networks. + + Args: + categorical_column: A `_CategoricalColumn` which is created by + `categorical_column_with_*` function. + """ + + @property + def name(self): + return '{}_indicator'.format(self.categorical_column.name) + + def _transform_feature(self, inputs): + """Returns dense `Tensor` representing feature. + + Args: + inputs: A `_LazyBuilder` object to access inputs. + + Returns: + Transformed feature `Tensor`. + + Raises: + ValueError: if input rank is not known at graph building time. + """ + id_weight_pair = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + id_tensor = id_weight_pair.id_tensor + weight_tensor = id_weight_pair.weight_tensor + + # If the underlying column is weighted, return the input as a dense tensor. + if weight_tensor is not None: + weighted_column = sparse_ops.sparse_merge( + sp_ids=id_tensor, + sp_values=weight_tensor, + vocab_size=int(self._variable_shape[-1])) + # Remove (?, -1) index. + weighted_column = sparse_ops.sparse_slice(weighted_column, [0, 0], + weighted_column.dense_shape) + # Use scatter_nd to merge duplicated indices if existed, + # instead of sparse_tensor_to_dense. + return array_ops.scatter_nd(weighted_column.indices, + weighted_column.values, + weighted_column.dense_shape) + + dense_id_tensor = sparse_ops.sparse_tensor_to_dense( + id_tensor, default_value=-1) + + # One hot must be float for tf.concat reasons since all other inputs to + # input_layer are float32. + one_hot_id_tensor = array_ops.one_hot( + dense_id_tensor, + depth=self._variable_shape[-1], + on_value=1.0, + off_value=0.0) + + # Reduce to get a multi-hot per example. + return math_ops.reduce_sum(one_hot_id_tensor, axis=[-2]) + + @property + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + @property + def _variable_shape(self): + """Returns a `TensorShape` representing the shape of the dense `Tensor`.""" + return tensor_shape.TensorShape([1, self.categorical_column._num_buckets]) # pylint: disable=protected-access + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + """Returns dense `Tensor` representing feature. + + Args: + inputs: A `_LazyBuilder` object to access inputs. + weight_collections: Unused `weight_collections` since no variables are + created in this function. + trainable: Unused `trainable` bool since no variables are created in this + function. + + Returns: + Dense `Tensor` created within `_transform_feature`. + + Raises: + ValueError: If `categorical_column` is a `_SequenceCategoricalColumn`. + """ + # Do nothing with weight_collections and trainable since no variables are + # created in this function. + del weight_collections + del trainable + if isinstance(self.categorical_column, _SequenceCategoricalColumn): + raise ValueError( + 'In indicator_column: {}. ' + 'categorical_column must not be of type _SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use input_layer, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'sequence_input_layer instead of input_layer. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Feature has been already transformed. Return the intermediate + # representation created by _transform_feature. + return inputs.get(self) + + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + # Do nothing with weight_collections and trainable since no variables are + # created in this function. + del weight_collections + del trainable + if not isinstance(self.categorical_column, _SequenceCategoricalColumn): + raise ValueError( + 'In indicator_column: {}. ' + 'categorical_column must be of type _SequenceCategoricalColumn ' + 'to use sequence_input_layer. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Feature has been already transformed. Return the intermediate + # representation created by _transform_feature. + dense_tensor = inputs.get(self) + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return _SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + +def _verify_static_batch_size_equality(tensors, columns): + """Validates that the first dim (batch size) of all tensors are equal or None. + + Args: + tensors: list of tensors to check. + columns: list of feature columns matching tensors. Will be used for error + messaging. + + Raises: + ValueError: if one of the tensors has a variant batch size + """ + # bath_size is a tf.compat.v1.Dimension object. + expected_batch_size = None + for i in range(0, len(tensors)): + if tensors[i].shape.dims[0].value is not None: + if expected_batch_size is None: + bath_size_column_index = i + expected_batch_size = tensors[i].shape.dims[0] + elif not expected_batch_size.is_compatible_with(tensors[i].shape.dims[0]): + raise ValueError( + 'Batch size (first dimension) of each feature must be same. ' + 'Batch size of columns ({}, {}): ({}, {})'.format( + columns[bath_size_column_index].name, columns[i].name, + expected_batch_size, tensors[i].shape.dims[0])) + + +class _SequenceCategoricalColumn(_CategoricalColumn, + collections.namedtuple( + '_SequenceCategoricalColumn', + ['categorical_column'])): + """Represents sequences of categorical data.""" + + @property + def name(self): + return self.categorical_column.name + + @property + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + def _transform_feature(self, inputs): + return self.categorical_column._transform_feature(inputs) # pylint: disable=protected-access + + @property + def _num_buckets(self): + return self.categorical_column._num_buckets # pylint: disable=protected-access + + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + id_tensor = sparse_tensors.id_tensor + weight_tensor = sparse_tensors.weight_tensor + + # Expands third dimension, if necessary so that embeddings are not + # combined during embedding lookup. If the tensor is already 3D, leave + # as-is. + shape = array_ops.shape(id_tensor) + # Compute the third dimension explicitly instead of setting it to -1, as + # that doesn't work for dynamically shaped tensors with 0-length at runtime. + # This happens for empty sequences. + target_shape = [shape[0], shape[1], math_ops.reduce_prod(shape[2:])] + id_tensor = sparse_ops.sparse_reshape(id_tensor, target_shape) + if weight_tensor is not None: + weight_tensor = sparse_ops.sparse_reshape(weight_tensor, target_shape) + + return _CategoricalColumn.IdWeightPair(id_tensor, weight_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..811d1e13e3eba10a97d323e4f633455f52bfaa7c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_lib.py @@ -0,0 +1,22 @@ +# 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. +# ============================================================================== +"""FeatureColumns: tools for ingesting and representing features.""" + +# pylint: disable=unused-import,line-too-long,wildcard-import,g-bad-import-order +from tensorflow.python.feature_column.feature_column import * +from tensorflow.python.feature_column.feature_column_v2 import * +from tensorflow.python.feature_column.sequence_feature_column import * +from tensorflow.python.feature_column.serialization import * +# pylint: enable=unused-import,line-too-long diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_v2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e5e22867cf8273da74c0c604b9581d0667f5fe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_v2.py @@ -0,0 +1,4414 @@ +# 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 API defines FeatureColumn abstraction. + +FeatureColumns provide a high level abstraction for ingesting and representing +features. FeatureColumns are also the primary way of encoding features for +canned `tf.estimator.Estimator`s. + +When using FeatureColumns with `Estimators`, the type of feature column you +should choose depends on (1) the feature type and (2) the model type. + +1. Feature type: + + * Continuous features can be represented by `numeric_column`. + * Categorical features can be represented by any `categorical_column_with_*` + column: + - `categorical_column_with_vocabulary_list` + - `categorical_column_with_vocabulary_file` + - `categorical_column_with_hash_bucket` + - `categorical_column_with_identity` + - `weighted_categorical_column` + +2. Model type: + + * Deep neural network models (`DNNClassifier`, `DNNRegressor`). + + Continuous features can be directly fed into deep neural network models. + + age_column = numeric_column("age") + + To feed sparse features into DNN models, wrap the column with + `embedding_column` or `indicator_column`. `indicator_column` is recommended + for features with only a few possible values. For features with many + possible values, to reduce the size of your model, `embedding_column` is + recommended. + + embedded_dept_column = embedding_column( + categorical_column_with_vocabulary_list( + "department", ["math", "philosophy", ...]), dimension=10) + + * Wide (aka linear) models (`LinearClassifier`, `LinearRegressor`). + + Sparse features can be fed directly into linear models. They behave like an + indicator column but with an efficient implementation. + + dept_column = categorical_column_with_vocabulary_list("department", + ["math", "philosophy", "english"]) + + It is recommended that continuous features be bucketized before being + fed into linear models. + + bucketized_age_column = bucketized_column( + source_column=age_column, + boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) + + Sparse features can be crossed (also known as conjuncted or combined) in + order to form non-linearities, and then fed into linear models. + + cross_dept_age_column = crossed_column( + columns=["department", bucketized_age_column], + hash_bucket_size=1000) + +Example of building canned `Estimator`s using FeatureColumns: + + ```python + # Define features and transformations + deep_feature_columns = [age_column, embedded_dept_column] + wide_feature_columns = [dept_column, bucketized_age_column, + cross_dept_age_column] + + # Build deep model + estimator = DNNClassifier( + feature_columns=deep_feature_columns, + hidden_units=[500, 250, 50]) + estimator.train(...) + + # Or build a wide model + estimator = LinearClassifier( + feature_columns=wide_feature_columns) + estimator.train(...) + + # Or build a wide and deep model! + estimator = DNNLinearCombinedClassifier( + linear_feature_columns=wide_feature_columns, + dnn_feature_columns=deep_feature_columns, + dnn_hidden_units=[500, 250, 50]) + estimator.train(...) + ``` + + +FeatureColumns can also be transformed into a generic input layer for +custom models using `input_layer`. + +Example of building model using FeatureColumns, this can be used in a +`model_fn` which is given to the {tf.estimator.Estimator}: + + ```python + # Building model via layers + + deep_feature_columns = [age_column, embedded_dept_column] + columns_to_tensor = parse_feature_columns_from_examples( + serialized=my_data, + feature_columns=deep_feature_columns) + first_layer = input_layer( + features=columns_to_tensor, + feature_columns=deep_feature_columns) + second_layer = fully_connected(first_layer, ...) + ``` + +NOTE: Functions prefixed with "_" indicate experimental or private parts of +the API subject to change, and should not be relied upon! +""" + +import abc +import collections +import math +import re + +import numpy as np +import six + +from tensorflow.python.data.experimental.ops import lookup_ops as data_lookup_ops +from tensorflow.python.data.ops import readers +from tensorflow.python.eager import context +from tensorflow.python.feature_column import feature_column as fc_old +from tensorflow.python.feature_column import feature_column_v2_types as fc_types +from tensorflow.python.feature_column import serialization +from tensorflow.python.feature_column import utils as fc_utils +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import lookup_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import string_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.ops import variables +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.trackable import autotrackable +from tensorflow.python.trackable import base as trackable +from tensorflow.python.trackable import data_structures +from tensorflow.python.training import checkpoint_utils +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +_FEATURE_COLUMN_DEPRECATION_DATE = None +_FEATURE_COLUMN_DEPRECATION = ('The old _FeatureColumn APIs are being ' + 'deprecated. Please use the new FeatureColumn ' + 'APIs instead.') +_FEATURE_COLUMN_DEPRECATION_WARNING = """\ + Warning: tf.feature_column is not recommended for new code. Instead, + feature preprocessing can be done directly using either [Keras preprocessing + layers](https://www.tensorflow.org/guide/migrate/migrating_feature_columns) + or through the one-stop utility [`tf.keras.utils.FeatureSpace`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/FeatureSpace) + built on top of them. See the [migration guide](https://tensorflow.org/guide/migrate) + for details. + """ +_FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING = ( + 'Use Keras preprocessing layers instead, either directly or via the ' + '`tf.keras.utils.FeatureSpace` utility. Each of `tf.feature_column.*` has ' + 'a functional equivalent in `tf.keras.layers` for feature preprocessing ' + 'when training a Keras model.') + + +class StateManager(object): + """Manages the state associated with FeatureColumns. + + Some `FeatureColumn`s create variables or resources to assist their + computation. The `StateManager` is responsible for creating and storing these + objects since `FeatureColumn`s are supposed to be stateless configuration + only. + """ + + def create_variable(self, + feature_column, + name, + shape, + dtype=None, + trainable=True, + use_resource=True, + initializer=None): + """Creates a new variable. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + name: variable name. + shape: variable shape. + dtype: The type of the variable. Defaults to `self.dtype` or `float32`. + trainable: Whether this variable is trainable or not. + use_resource: If true, we use resource variables. Otherwise we use + RefVariable. + initializer: initializer instance (callable). + + Returns: + The created variable. + """ + del feature_column, name, shape, dtype, trainable, use_resource, initializer + raise NotImplementedError('StateManager.create_variable') + + def add_variable(self, feature_column, var): + """Adds an existing variable to the state. + + Args: + feature_column: A `FeatureColumn` object to associate this variable with. + var: The variable. + """ + del feature_column, var + raise NotImplementedError('StateManager.add_variable') + + def get_variable(self, feature_column, name): + """Returns an existing variable. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + name: variable name. + """ + del feature_column, name + raise NotImplementedError('StateManager.get_var') + + def add_resource(self, feature_column, name, resource): + """Creates a new resource. + + Resources can be things such as tables, variables, trackables, etc. + + Args: + feature_column: A `FeatureColumn` object this resource corresponds to. + name: Name of the resource. + resource: The resource. + + Returns: + The created resource. + """ + del feature_column, name, resource + raise NotImplementedError('StateManager.add_resource') + + def has_resource(self, feature_column, name): + """Returns true iff a resource with same name exists. + + Resources can be things such as tables, variables, trackables, etc. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + name: Name of the resource. + """ + del feature_column, name + raise NotImplementedError('StateManager.has_resource') + + def get_resource(self, feature_column, name): + """Returns an already created resource. + + Resources can be things such as tables, variables, trackables, etc. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + name: Name of the resource. + """ + del feature_column, name + raise NotImplementedError('StateManager.get_resource') + + +@tf_export('__internal__.feature_column.StateManager', v1=[]) +class _StateManagerImpl(StateManager): + """Manages the state of DenseFeatures and LinearLayer. + + Some `FeatureColumn`s create variables or resources to assist their + computation. The `StateManager` is responsible for creating and storing these + objects since `FeatureColumn`s are supposed to be stateless configuration + only. + """ + + def __init__(self, layer, trainable): + """Creates an _StateManagerImpl object. + + Args: + layer: The input layer this state manager is associated with. + trainable: Whether by default, variables created are trainable or not. + """ + self._trainable = trainable + self._layer = layer + if self._layer is not None and not hasattr(self._layer, '_resources'): + self._layer._resources = data_structures.Mapping() # pylint: disable=protected-access + self._cols_to_vars_map = collections.defaultdict(lambda: {}) + self._cols_to_resources_map = collections.defaultdict(lambda: {}) + + def create_variable(self, + feature_column, + name, + shape, + dtype=None, + trainable=True, + use_resource=True, + initializer=None): + """Creates a new variable. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + name: variable name. + shape: variable shape. + dtype: The type of the variable. Defaults to `self.dtype` or `float32`. + trainable: Whether this variable is trainable or not. + use_resource: If true, we use resource variables. Otherwise we use + RefVariable. + initializer: initializer instance (callable). + + Returns: + The created variable. + """ + if name in self._cols_to_vars_map[feature_column]: + raise ValueError('Variable already exists.') + + # We explicitly track these variables since `name` is not guaranteed to be + # unique and disable manual tracking that the add_weight call does. + with trackable.no_manual_dependency_tracking_scope(self._layer): + var = self._layer.add_weight( + name=name, + shape=shape, + dtype=dtype, + initializer=initializer, + trainable=self._trainable and trainable, + use_resource=use_resource, + # TODO(rohanj): Get rid of this hack once we have a mechanism for + # specifying a default partitioner for an entire layer. In that case, + # the default getter for Layers should work. + getter=variable_scope.get_variable) + if isinstance(var, variables.PartitionedVariable): + for v in var: + part_name = name + '/' + str(v._get_save_slice_info().var_offset[0]) # pylint: disable=protected-access + self._layer._track_trackable(v, feature_column.name + '/' + part_name) # pylint: disable=protected-access + else: + if isinstance(var, trackable.Trackable): + self._layer._track_trackable(var, feature_column.name + '/' + name) # pylint: disable=protected-access + + self._cols_to_vars_map[feature_column][name] = var + return var + + def get_variable(self, feature_column, name): + """Returns an existing variable. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + name: variable name. + """ + if name in self._cols_to_vars_map[feature_column]: + return self._cols_to_vars_map[feature_column][name] + raise ValueError('Variable does not exist.') + + def add_resource(self, feature_column, resource_name, resource): + """Creates a new resource. + + Resources can be things such as tables, variables, trackables, etc. + + Args: + feature_column: A `FeatureColumn` object this resource corresponds to. + resource_name: Name of the resource. + resource: The resource. + + Returns: + The created resource. + """ + self._cols_to_resources_map[feature_column][resource_name] = resource + # pylint: disable=protected-access + if self._layer is not None and isinstance(resource, trackable.Trackable): + # Add trackable resources to the layer for serialization. + if feature_column.name not in self._layer._resources: + self._layer._resources[feature_column.name] = data_structures.Mapping() + if resource_name not in self._layer._resources[feature_column.name]: + self._layer._resources[feature_column.name][resource_name] = resource + # pylint: enable=protected-access + + def has_resource(self, feature_column, resource_name): + """Returns true iff a resource with same name exists. + + Resources can be things such as tables, variables, trackables, etc. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + resource_name: Name of the resource. + """ + return resource_name in self._cols_to_resources_map[feature_column] + + def get_resource(self, feature_column, resource_name): + """Returns an already created resource. + + Resources can be things such as tables, variables, trackables, etc. + + Args: + feature_column: A `FeatureColumn` object this variable corresponds to. + resource_name: Name of the resource. + """ + if (feature_column not in self._cols_to_resources_map or + resource_name not in self._cols_to_resources_map[feature_column]): + raise ValueError('Resource does not exist.') + return self._cols_to_resources_map[feature_column][resource_name] + + +def _transform_features_v2(features, feature_columns, state_manager): + """Returns transformed features based on features columns passed in. + + Please note that most probably you would not need to use this function. Please + check `input_layer` and `linear_model` to see whether they will + satisfy your use case or not. + + Example: + + ```python + # Define features and transformations + crosses_a_x_b = crossed_column( + columns=["sparse_feature_a", "sparse_feature_b"], hash_bucket_size=10000) + price_buckets = bucketized_column( + source_column=numeric_column("price"), boundaries=[...]) + + columns = [crosses_a_x_b, price_buckets] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + transformed = transform_features(features=features, feature_columns=columns) + + assertCountEqual(columns, transformed.keys()) + ``` + + Args: + features: A mapping from key to tensors. `FeatureColumn`s look up via these + keys. For example `numeric_column('price')` will look at 'price' key in + this dict. Values can be a `SparseTensor` or a `Tensor` depends on + corresponding `FeatureColumn`. + feature_columns: An iterable containing all the `FeatureColumn`s. + state_manager: A StateManager object that holds the FeatureColumn state. + + Returns: + A `dict` mapping `FeatureColumn` to `Tensor` and `SparseTensor` values. + """ + feature_columns = _normalize_feature_columns(feature_columns) + outputs = {} + with ops.name_scope( + None, default_name='transform_features', values=features.values()): + transformation_cache = FeatureTransformationCache(features) + for column in feature_columns: + with ops.name_scope( + None, + default_name=_sanitize_column_name_for_variable_scope(column.name)): + outputs[column] = transformation_cache.get(column, state_manager) + return outputs + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export( + 'feature_column.make_parse_example_spec', + v1=[]) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def make_parse_example_spec_v2(feature_columns): + """Creates parsing spec dictionary from input feature_columns. + + The returned dictionary can be used as arg 'features' in + `tf.io.parse_example`. + + Typical usage example: + + ```python + # Define features and transformations + feature_a = tf.feature_column.categorical_column_with_vocabulary_file(...) + feature_b = tf.feature_column.numeric_column(...) + feature_c_bucketized = tf.feature_column.bucketized_column( + tf.feature_column.numeric_column("feature_c"), ...) + feature_a_x_feature_c = tf.feature_column.crossed_column( + columns=["feature_a", feature_c_bucketized], ...) + + feature_columns = set( + [feature_b, feature_c_bucketized, feature_a_x_feature_c]) + features = tf.io.parse_example( + serialized=serialized_examples, + features=tf.feature_column.make_parse_example_spec(feature_columns)) + ``` + + For the above example, make_parse_example_spec would return the dict: + + ```python + { + "feature_a": parsing_ops.VarLenFeature(tf.string), + "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32), + "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32) + } + ``` + + Args: + feature_columns: An iterable containing all feature columns. All items + should be instances of classes derived from `FeatureColumn`. + + Returns: + A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` + value. + + Raises: + ValueError: If any of the given `feature_columns` is not a `FeatureColumn` + instance. + """ + result = {} + for column in feature_columns: + if not isinstance(column, fc_types.FeatureColumn): + raise ValueError('All feature_columns must be FeatureColumn instances. ' + 'Given: {}'.format(column)) + config = column.parse_example_spec + for key, value in six.iteritems(config): + if key in result and value != result[key]: + raise ValueError('feature_columns contain different parse_spec for key ' + '{}. Given {} and {}'.format(key, value, result[key])) + result.update(config) + return result + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.embedding_column') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def embedding_column(categorical_column, + dimension, + combiner='mean', + initializer=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + use_safe_embedding_lookup=True): + """`DenseColumn` that converts from sparse, categorical input. + + Use this when your inputs are sparse, but you want to convert them to a dense + representation (e.g., to feed to a DNN). + + Inputs must be a `CategoricalColumn` created by any of the + `categorical_column_*` function. Here is an example of using + `embedding_column` with `DNNClassifier`: + + ```python + video_id = categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [embedding_column(video_id, 9),...] + + estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...) + + label_column = ... + def input_fn(): + features = tf.io.parse_example( + ..., features=make_parse_example_spec(columns + [label_column])) + labels = features.pop(label_column.name) + return features, labels + + estimator.train(input_fn=input_fn, steps=100) + ``` + + Here is an example using `embedding_column` with model_fn: + + ```python + def model_fn(features, ...): + video_id = categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [embedding_column(video_id, 9),...] + dense_tensor = input_layer(features, columns) + # Form DNN layers, calculate loss, and return EstimatorSpec. + ... + ``` + + Args: + categorical_column: A `CategoricalColumn` created by a + `categorical_column_with_*` function. This column produces the sparse IDs + that are inputs to the embedding lookup. + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries in + a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with + 'mean' the default. 'sqrtn' often achieves good accuracy, in particular + with bag-of-words columns. Each of this can be thought as example level + normalizations on the column. For more information, see + `tf.embedding_lookup_sparse`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `truncated_normal_initializer` with mean `0.0` and standard deviation + `1/sqrt(dimension)`. + ckpt_to_load_from: String representing checkpoint name/pattern from which to + restore column weights. Required if `tensor_name_in_ckpt` is not `None`. + tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which + to restore the column weights. Required if `ckpt_to_load_from` is not + `None`. + max_norm: If not `None`, embedding values are l2-normalized to this value. + trainable: Whether or not the embedding is trainable. Default is True. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + `DenseColumn` that converts from sparse input. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt` + is specified. + ValueError: if `initializer` is specified and is not callable. + RuntimeError: If eager execution is enabled. + """ + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + if (ckpt_to_load_from is None) != (tensor_name_in_ckpt is None): + raise ValueError('Must specify both `ckpt_to_load_from` and ' + '`tensor_name_in_ckpt` or none of them.') + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified. ' + 'Embedding of column_name: {}'.format( + categorical_column.name)) + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1 / math.sqrt(dimension)) + + return EmbeddingColumn( + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + initializer=initializer, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export(v1=['feature_column.shared_embedding_columns']) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def shared_embedding_columns(categorical_columns, + dimension, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + use_safe_embedding_lookup=True): + """List of dense columns that convert from sparse, categorical input. + + This is similar to `embedding_column`, except that it produces a list of + embedding columns that share the same embedding weights. + + Use this when your inputs are sparse and of the same type (e.g. watched and + impression video IDs that share the same vocabulary), and you want to convert + them to a dense representation (e.g., to feed to a DNN). + + Inputs must be a list of categorical columns created by any of the + `categorical_column_*` function. They must all be of the same type and have + the same arguments except `key`. E.g. they can be + categorical_column_with_vocabulary_file with the same vocabulary_file. Some or + all columns could also be weighted_categorical_column. + + Here is an example embedding of two features for a DNNClassifier model: + + ```python + watched_video_id = categorical_column_with_vocabulary_file( + 'watched_video_id', video_vocabulary_file, video_vocabulary_size) + impression_video_id = categorical_column_with_vocabulary_file( + 'impression_video_id', video_vocabulary_file, video_vocabulary_size) + columns = shared_embedding_columns( + [watched_video_id, impression_video_id], dimension=10) + + estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...) + + label_column = ... + def input_fn(): + features = tf.io.parse_example( + ..., features=make_parse_example_spec(columns + [label_column])) + labels = features.pop(label_column.name) + return features, labels + + estimator.train(input_fn=input_fn, steps=100) + ``` + + Here is an example using `shared_embedding_columns` with model_fn: + + ```python + def model_fn(features, ...): + watched_video_id = categorical_column_with_vocabulary_file( + 'watched_video_id', video_vocabulary_file, video_vocabulary_size) + impression_video_id = categorical_column_with_vocabulary_file( + 'impression_video_id', video_vocabulary_file, video_vocabulary_size) + columns = shared_embedding_columns( + [watched_video_id, impression_video_id], dimension=10) + dense_tensor = input_layer(features, columns) + # Form DNN layers, calculate loss, and return EstimatorSpec. + ... + ``` + + Args: + categorical_columns: List of categorical columns created by a + `categorical_column_with_*` function. These columns produce the sparse IDs + that are inputs to the embedding lookup. All columns must be of the same + type and have the same arguments except `key`. E.g. they can be + categorical_column_with_vocabulary_file with the same vocabulary_file. + Some or all columns could also be weighted_categorical_column. + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries in + a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with + 'mean' the default. 'sqrtn' often achieves good accuracy, in particular + with bag-of-words columns. Each of this can be thought as example level + normalizations on the column. For more information, see + `tf.embedding_lookup_sparse`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `truncated_normal_initializer` with mean `0.0` and standard deviation + `1/sqrt(dimension)`. + shared_embedding_collection_name: Optional name of the collection where + shared embedding weights are added. If not given, a reasonable name will + be chosen based on the names of `categorical_columns`. This is also used + in `variable_scope` when creating shared embedding weights. + ckpt_to_load_from: String representing checkpoint name/pattern from which to + restore column weights. Required if `tensor_name_in_ckpt` is not `None`. + tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which + to restore the column weights. Required if `ckpt_to_load_from` is not + `None`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value, before combining. + trainable: Whether or not the embedding is trainable. Default is True. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + A list of dense columns that converts from sparse input. The order of + results follows the ordering of `categorical_columns`. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if any of the given `categorical_columns` is of different type + or has different arguments than the others. + ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt` + is specified. + ValueError: if `initializer` is specified and is not callable. + RuntimeError: if eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('shared_embedding_columns are not supported when eager ' + 'execution is enabled.') + + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + if (ckpt_to_load_from is None) != (tensor_name_in_ckpt is None): + raise ValueError('Must specify both `ckpt_to_load_from` and ' + '`tensor_name_in_ckpt` or none of them.') + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified.') + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1. / math.sqrt(dimension)) + + # Sort the columns so the default collection name is deterministic even if the + # user passes columns from an unsorted collection, such as dict.values(). + sorted_columns = sorted(categorical_columns, key=lambda x: x.name) + + c0 = sorted_columns[0] + num_buckets = c0._num_buckets # pylint: disable=protected-access + if not isinstance(c0, fc_old._CategoricalColumn): # pylint: disable=protected-access + raise ValueError( + 'All categorical_columns must be subclasses of _CategoricalColumn. ' + 'Given: {}, of type: {}'.format(c0, type(c0))) + while isinstance( + c0, + ( + fc_old._WeightedCategoricalColumn, # pylint: disable=protected-access + WeightedCategoricalColumn, + fc_old._SequenceCategoricalColumn, # pylint: disable=protected-access + SequenceCategoricalColumn)): + c0 = c0.categorical_column + for c in sorted_columns[1:]: + while isinstance( + c, + ( + fc_old._WeightedCategoricalColumn, # pylint: disable=protected-access + WeightedCategoricalColumn, + fc_old._SequenceCategoricalColumn, # pylint: disable=protected-access + SequenceCategoricalColumn)): + c = c.categorical_column + if not isinstance(c, type(c0)): + raise ValueError( + 'To use shared_embedding_column, all categorical_columns must have ' + 'the same type, or be weighted_categorical_column or sequence column ' + 'of the same type. Given column: {} of type: {} does not match given ' + 'column: {} of type: {}'.format(c0, type(c0), c, type(c))) + if num_buckets != c._num_buckets: # pylint: disable=protected-access + raise ValueError( + 'To use shared_embedding_column, all categorical_columns must have ' + 'the same number of buckets. ven column: {} with buckets: {} does ' + 'not match column: {} with buckets: {}'.format( + c0, num_buckets, c, c._num_buckets)) # pylint: disable=protected-access + + if not shared_embedding_collection_name: + shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns) + shared_embedding_collection_name += '_shared_embedding' + + result = [] + for column in categorical_columns: + result.append( + fc_old._SharedEmbeddingColumn( # pylint: disable=protected-access + categorical_column=column, + initializer=initializer, + dimension=dimension, + combiner=combiner, + shared_embedding_collection_name=shared_embedding_collection_name, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup)) + + return result + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export( + 'feature_column.shared_embeddings', + v1=[]) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def shared_embedding_columns_v2(categorical_columns, + dimension, + combiner='mean', + initializer=None, + shared_embedding_collection_name=None, + ckpt_to_load_from=None, + tensor_name_in_ckpt=None, + max_norm=None, + trainable=True, + use_safe_embedding_lookup=True): + """List of dense columns that convert from sparse, categorical input. + + This is similar to `embedding_column`, except that it produces a list of + embedding columns that share the same embedding weights. + + Use this when your inputs are sparse and of the same type (e.g. watched and + impression video IDs that share the same vocabulary), and you want to convert + them to a dense representation (e.g., to feed to a DNN). + + Inputs must be a list of categorical columns created by any of the + `categorical_column_*` function. They must all be of the same type and have + the same arguments except `key`. E.g. they can be + categorical_column_with_vocabulary_file with the same vocabulary_file. Some or + all columns could also be weighted_categorical_column. + + Here is an example embedding of two features for a DNNClassifier model: + + ```python + watched_video_id = categorical_column_with_vocabulary_file( + 'watched_video_id', video_vocabulary_file, video_vocabulary_size) + impression_video_id = categorical_column_with_vocabulary_file( + 'impression_video_id', video_vocabulary_file, video_vocabulary_size) + columns = shared_embedding_columns( + [watched_video_id, impression_video_id], dimension=10) + + estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...) + + label_column = ... + def input_fn(): + features = tf.io.parse_example( + ..., features=make_parse_example_spec(columns + [label_column])) + labels = features.pop(label_column.name) + return features, labels + + estimator.train(input_fn=input_fn, steps=100) + ``` + + Here is an example using `shared_embedding_columns` with model_fn: + + ```python + def model_fn(features, ...): + watched_video_id = categorical_column_with_vocabulary_file( + 'watched_video_id', video_vocabulary_file, video_vocabulary_size) + impression_video_id = categorical_column_with_vocabulary_file( + 'impression_video_id', video_vocabulary_file, video_vocabulary_size) + columns = shared_embedding_columns( + [watched_video_id, impression_video_id], dimension=10) + dense_tensor = input_layer(features, columns) + # Form DNN layers, calculate loss, and return EstimatorSpec. + ... + ``` + + Args: + categorical_columns: List of categorical columns created by a + `categorical_column_with_*` function. These columns produce the sparse IDs + that are inputs to the embedding lookup. All columns must be of the same + type and have the same arguments except `key`. E.g. they can be + categorical_column_with_vocabulary_file with the same vocabulary_file. + Some or all columns could also be weighted_categorical_column. + dimension: An integer specifying dimension of the embedding, must be > 0. + combiner: A string specifying how to reduce if there are multiple entries in + a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with + 'mean' the default. 'sqrtn' often achieves good accuracy, in particular + with bag-of-words columns. Each of this can be thought as example level + normalizations on the column. For more information, see + `tf.embedding_lookup_sparse`. + initializer: A variable initializer function to be used in embedding + variable initialization. If not specified, defaults to + `truncated_normal_initializer` with mean `0.0` and standard deviation + `1/sqrt(dimension)`. + shared_embedding_collection_name: Optional collective name of these columns. + If not given, a reasonable name will be chosen based on the names of + `categorical_columns`. + ckpt_to_load_from: String representing checkpoint name/pattern from which to + restore column weights. Required if `tensor_name_in_ckpt` is not `None`. + tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which + to restore the column weights. Required if `ckpt_to_load_from` is not + `None`. + max_norm: If not `None`, each embedding is clipped if its l2-norm is larger + than this value, before combining. + trainable: Whether or not the embedding is trainable. Default is True. + use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse + instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures + there are no empty rows and all weights and ids are positive at the + expense of extra compute cost. This only applies to rank 2 (NxM) shaped + input tensors. Defaults to true, consider turning off if the above checks + are not needed. Note that having empty rows will not trigger any error + though the output result might be 0 or omitted. + + Returns: + A list of dense columns that converts from sparse input. The order of + results follows the ordering of `categorical_columns`. + + Raises: + ValueError: if `dimension` not > 0. + ValueError: if any of the given `categorical_columns` is of different type + or has different arguments than the others. + ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt` + is specified. + ValueError: if `initializer` is specified and is not callable. + RuntimeError: if eager execution is enabled. + """ + if context.executing_eagerly(): + raise RuntimeError('shared_embedding_columns are not supported when eager ' + 'execution is enabled.') + + if (dimension is None) or (dimension < 1): + raise ValueError('Invalid dimension {}.'.format(dimension)) + if (ckpt_to_load_from is None) != (tensor_name_in_ckpt is None): + raise ValueError('Must specify both `ckpt_to_load_from` and ' + '`tensor_name_in_ckpt` or none of them.') + + if (initializer is not None) and (not callable(initializer)): + raise ValueError('initializer must be callable if specified.') + if initializer is None: + initializer = init_ops.truncated_normal_initializer( + mean=0.0, stddev=1. / math.sqrt(dimension)) + + # Sort the columns so the default collection name is deterministic even if the + # user passes columns from an unsorted collection, such as dict.values(). + sorted_columns = sorted(categorical_columns, key=lambda x: x.name) + + c0 = sorted_columns[0] + num_buckets = c0.num_buckets + if not isinstance(c0, CategoricalColumn): + raise ValueError( + 'All categorical_columns must be subclasses of CategoricalColumn. ' + 'Given: {}, of type: {}'.format(c0, type(c0))) + while isinstance(c0, (WeightedCategoricalColumn, SequenceCategoricalColumn)): + c0 = c0.categorical_column + for c in sorted_columns[1:]: + while isinstance(c, (WeightedCategoricalColumn, SequenceCategoricalColumn)): + c = c.categorical_column + if not isinstance(c, type(c0)): + raise ValueError( + 'To use shared_embedding_column, all categorical_columns must have ' + 'the same type, or be weighted_categorical_column or sequence column ' + 'of the same type. Given column: {} of type: {} does not match given ' + 'column: {} of type: {}'.format(c0, type(c0), c, type(c))) + if num_buckets != c.num_buckets: + raise ValueError( + 'To use shared_embedding_column, all categorical_columns must have ' + 'the same number of buckets. Given column: {} with buckets: {} does ' + 'not match column: {} with buckets: {}'.format( + c0, num_buckets, c, c.num_buckets)) + + if not shared_embedding_collection_name: + shared_embedding_collection_name = '_'.join(c.name for c in sorted_columns) + shared_embedding_collection_name += '_shared_embedding' + + column_creator = SharedEmbeddingColumnCreator( + dimension, initializer, ckpt_to_load_from, tensor_name_in_ckpt, + num_buckets, trainable, shared_embedding_collection_name, + use_safe_embedding_lookup) + + result = [] + for column in categorical_columns: + result.append( + column_creator( + categorical_column=column, combiner=combiner, max_norm=max_norm)) + + return result + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.numeric_column') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def numeric_column(key, + shape=(1,), + default_value=None, + dtype=dtypes.float32, + normalizer_fn=None): + """Represents real valued or numerical features. + + Example: + + Assume we have data with two features `a` and `b`. + + >>> data = {'a': [15, 9, 17, 19, 21, 18, 25, 30], + ... 'b': [5.0, 6.4, 10.5, 13.6, 15.7, 19.9, 20.3 , 0.0]} + + Let us represent the features `a` and `b` as numerical features. + + >>> a = tf.feature_column.numeric_column('a') + >>> b = tf.feature_column.numeric_column('b') + + Feature column describe a set of transformations to the inputs. + + For example, to "bucketize" feature `a`, wrap the `a` column in a + `feature_column.bucketized_column`. + Providing `5` bucket boundaries, the bucketized_column api + will bucket this feature in total of `6` buckets. + + >>> a_buckets = tf.feature_column.bucketized_column(a, + ... boundaries=[10, 15, 20, 25, 30]) + + Create a `DenseFeatures` layer which will apply the transformations + described by the set of `tf.feature_column` objects: + + >>> feature_layer = tf.keras.layers.DenseFeatures([a_buckets, b]) + >>> print(feature_layer(data)) + tf.Tensor( + [[ 0. 0. 1. 0. 0. 0. 5. ] + [ 1. 0. 0. 0. 0. 0. 6.4] + [ 0. 0. 1. 0. 0. 0. 10.5] + [ 0. 0. 1. 0. 0. 0. 13.6] + [ 0. 0. 0. 1. 0. 0. 15.7] + [ 0. 0. 1. 0. 0. 0. 19.9] + [ 0. 0. 0. 0. 1. 0. 20.3] + [ 0. 0. 0. 0. 0. 1. 0. ]], shape=(8, 7), dtype=float32) + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + shape: An iterable of integers specifies the shape of the `Tensor`. An + integer can be given which means a single dimension `Tensor` with given + width. The `Tensor` representing the column will have the shape of + [batch_size] + `shape`. + default_value: A single value compatible with `dtype` or an iterable of + values compatible with `dtype` which the column takes on during + `tf.Example` parsing if data is missing. A default value of `None` will + cause `tf.io.parse_example` to fail if an example does not contain this + column. If a single value is provided, the same value will be applied as + the default value for every item. If an iterable of values is provided, + the shape of the `default_value` should be equal to the given `shape`. + dtype: defines the type of values. Default value is `tf.float32`. Must be a + non-quantized, real integer or floating point type. + normalizer_fn: If not `None`, a function that can be used to normalize the + value of the tensor after `default_value` is applied for parsing. + Normalizer function takes the input `Tensor` as its argument, and returns + the output `Tensor`. (e.g. lambda x: (x - 3.0) / 4.2). Please note that + even though the most common use case of this function is normalization, it + can be used for any kind of Tensorflow transformations. + + Returns: + A `NumericColumn`. + + Raises: + TypeError: if any dimension in shape is not an int + ValueError: if any dimension in shape is not a positive integer + TypeError: if `default_value` is an iterable but not compatible with `shape` + TypeError: if `default_value` is not compatible with `dtype`. + ValueError: if `dtype` is not convertible to `tf.float32`. + """ + shape = _check_shape(shape, key) + if not (dtype.is_integer or dtype.is_floating): + raise ValueError('dtype must be convertible to float. ' + 'dtype: {}, key: {}'.format(dtype, key)) + default_value = fc_utils.check_default_value(shape, default_value, dtype, key) + + if normalizer_fn is not None and not callable(normalizer_fn): + raise TypeError( + 'normalizer_fn must be a callable. Given: {}'.format(normalizer_fn)) + + fc_utils.assert_key_is_string(key) + return NumericColumn( + key, + shape=shape, + default_value=default_value, + dtype=dtype, + normalizer_fn=normalizer_fn) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.bucketized_column') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def bucketized_column(source_column, boundaries): + """Represents discretized dense input bucketed by `boundaries`. + + Buckets include the left boundary, and exclude the right boundary. Namely, + `boundaries=[0., 1., 2.]` generates buckets `(-inf, 0.)`, `[0., 1.)`, + `[1., 2.)`, and `[2., +inf)`. + + For example, if the inputs are + + ```python + boundaries = [0, 10, 100] + input tensor = [[-5, 10000] + [150, 10] + [5, 100]] + ``` + + then the output will be + + ```python + output = [[0, 3] + [3, 2] + [1, 3]] + ``` + + Example: + + ```python + price = tf.feature_column.numeric_column('price') + bucketized_price = tf.feature_column.bucketized_column( + price, boundaries=[...]) + columns = [bucketized_price, ...] + features = tf.io.parse_example( + ..., features=tf.feature_column.make_parse_example_spec(columns)) + dense_tensor = tf.keras.layers.DenseFeatures(columns)(features) + ``` + + A `bucketized_column` can also be crossed with another categorical column + using `crossed_column`: + + ```python + price = tf.feature_column.numeric_column('price') + # bucketized_column converts numerical feature to a categorical one. + bucketized_price = tf.feature_column.bucketized_column( + price, boundaries=[...]) + # 'keywords' is a string feature. + price_x_keywords = tf.feature_column.crossed_column( + [bucketized_price, 'keywords'], 50K) + columns = [price_x_keywords, ...] + features = tf.io.parse_example( + ..., features=tf.feature_column.make_parse_example_spec(columns)) + dense_tensor = tf.keras.layers.DenseFeatures(columns)(features) + linear_model = tf.keras.experimental.LinearModel(units=...)(dense_tensor) + ``` + + Args: + source_column: A one-dimensional dense column which is generated with + `numeric_column`. + boundaries: A sorted list or tuple of floats specifying the boundaries. + + Returns: + A `BucketizedColumn`. + + Raises: + ValueError: If `source_column` is not a numeric column, or if it is not + one-dimensional. + ValueError: If `boundaries` is not a sorted list or tuple. + """ + if not isinstance(source_column, (NumericColumn, fc_old._NumericColumn)): # pylint: disable=protected-access + raise ValueError( + 'source_column must be a column generated with numeric_column(). ' + 'Given: {}'.format(source_column)) + if len(source_column.shape) > 1: + raise ValueError('source_column must be one-dimensional column. ' + 'Given: {}'.format(source_column)) + if not boundaries: + raise ValueError('boundaries must not be empty.') + if not (isinstance(boundaries, list) or isinstance(boundaries, tuple)): + raise ValueError('boundaries must be a sorted list.') + for i in range(len(boundaries) - 1): + if boundaries[i] >= boundaries[i + 1]: + raise ValueError('boundaries must be a sorted list.') + return BucketizedColumn(source_column, tuple(boundaries)) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.categorical_column_with_hash_bucket') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def categorical_column_with_hash_bucket(key, + hash_bucket_size, + dtype=dtypes.string): + """Represents sparse feature where ids are set by hashing. + + Use this when your sparse features are in string or integer format, and you + want to distribute your inputs into a finite number of buckets by hashing. + output_id = Hash(input_feature_string) % bucket_size for string type input. + For int type input, the value is converted to its string representation first + and then hashed by the same formula. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example: + + ```python + import tensorflow as tf + keywords = tf.feature_column.categorical_column_with_hash_bucket("keywords", + 10000) + columns = [keywords] + features = {'keywords': tf.constant([['Tensorflow', 'Keras', 'RNN', 'LSTM', + 'CNN'], ['LSTM', 'CNN', 'Tensorflow', 'Keras', 'RNN'], ['CNN', 'Tensorflow', + 'LSTM', 'Keras', 'RNN']])} + linear_prediction, _, _ = tf.compat.v1.feature_column.linear_model(features, + columns) + + # or + import tensorflow as tf + keywords = tf.feature_column.categorical_column_with_hash_bucket("keywords", + 10000) + keywords_embedded = tf.feature_column.embedding_column(keywords, 16) + columns = [keywords_embedded] + features = {'keywords': tf.constant([['Tensorflow', 'Keras', 'RNN', 'LSTM', + 'CNN'], ['LSTM', 'CNN', 'Tensorflow', 'Keras', 'RNN'], ['CNN', 'Tensorflow', + 'LSTM', 'Keras', 'RNN']])} + input_layer = tf.keras.layers.DenseFeatures(columns) + dense_tensor = input_layer(features) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + hash_bucket_size: An int > 1. The number of buckets. + dtype: The type of features. Only string and integer types are supported. + + Returns: + A `HashedCategoricalColumn`. + + Raises: + ValueError: `hash_bucket_size` is not greater than 1. + ValueError: `dtype` is neither string nor integer. + """ + if hash_bucket_size is None: + raise ValueError('hash_bucket_size must be set. ' 'key: {}'.format(key)) + + if hash_bucket_size < 1: + raise ValueError('hash_bucket_size must be at least 1. ' + 'hash_bucket_size: {}, key: {}'.format( + hash_bucket_size, key)) + + fc_utils.assert_key_is_string(key) + fc_utils.assert_string_or_int(dtype, prefix='column_name: {}'.format(key)) + + return HashedCategoricalColumn(key, hash_bucket_size, dtype) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export(v1=['feature_column.categorical_column_with_vocabulary_file']) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def categorical_column_with_vocabulary_file(key, + vocabulary_file, + vocabulary_size=None, + num_oov_buckets=0, + default_value=None, + dtype=dtypes.string): + """A `CategoricalColumn` with a vocabulary file. + + Use this when your inputs are in string or integer format, and you have a + vocabulary file that maps each value to an integer ID. By default, + out-of-vocabulary values are ignored. Use either (but not both) of + `num_oov_buckets` and `default_value` to specify how to include + out-of-vocabulary values. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example with `num_oov_buckets`: + File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state + abbreviation. All inputs with values in that file are assigned an ID 0-49, + corresponding to its line number. All other values are hashed and assigned an + ID 50-54. + + ```python + import tensorflow as tf + states = tf.feature_column.categorical_column_with_vocabulary_file( + key='states', vocabulary_file='states.txt', vocabulary_size=5, + num_oov_buckets=1) + columns = [states] + features = {'states':tf.constant([['california', 'georgia', 'michigan', + 'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan', + 'texas']])} + linear_prediction = tf.compat.v1.feature_column.linear_model(features, + columns) + ``` + + Example with `default_value`: + File '/us/states.txt' contains 51 lines - the first line is 'XX', and the + other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' + in input, and other values missing from the file, will be assigned ID 0. All + others are assigned the corresponding line number 1-50. + + ```python + import tensorflow as tf + states = tf.feature_column.categorical_column_with_vocabulary_file( + key='states', vocabulary_file='states.txt', vocabulary_size=6, + default_value=0) + columns = [states] + features = {'states':tf.constant([['california', 'georgia', 'michigan', + 'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan', + 'texas']])} + linear_prediction = tf.compat.v1.feature_column.linear_model(features, + columns) + ``` + + And to make an embedding with either: + + ```python + import tensorflow as tf + states = tf.feature_column.categorical_column_with_vocabulary_file( + key='states', vocabulary_file='states.txt', vocabulary_size=5, + num_oov_buckets=1) + columns = [tf.feature_column.embedding_column(states, 3)] + features = {'states':tf.constant([['california', 'georgia', 'michigan', + 'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan', + 'texas']])} + input_layer = tf.keras.layers.DenseFeatures(columns) + dense_tensor = input_layer(features) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + vocabulary_file: The vocabulary file name. + vocabulary_size: Number of the elements in the vocabulary. This must be no + greater than length of `vocabulary_file`, if less than length, later + values are ignored. If None, it is set to the length of `vocabulary_file`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of + the input value. A positive `num_oov_buckets` can not be specified with + `default_value`. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + dtype: The type of features. Only string and integer types are supported. + + Returns: + A `CategoricalColumn` with a vocabulary file. + + Raises: + ValueError: `vocabulary_file` is missing or cannot be opened. + ValueError: `vocabulary_size` is missing or < 1. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: `dtype` is neither string nor integer. + """ + return categorical_column_with_vocabulary_file_v2(key, vocabulary_file, + vocabulary_size, dtype, + default_value, + num_oov_buckets) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export( + 'feature_column.categorical_column_with_vocabulary_file', + v1=[]) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def categorical_column_with_vocabulary_file_v2(key, + vocabulary_file, + vocabulary_size=None, + dtype=dtypes.string, + default_value=None, + num_oov_buckets=0, + file_format=None): + """A `CategoricalColumn` with a vocabulary file. + + Use this when your inputs are in string or integer format, and you have a + vocabulary file that maps each value to an integer ID. By default, + out-of-vocabulary values are ignored. Use either (but not both) of + `num_oov_buckets` and `default_value` to specify how to include + out-of-vocabulary values. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example with `num_oov_buckets`: + File `'/us/states.txt'` contains 50 lines, each with a 2-character U.S. state + abbreviation. All inputs with values in that file are assigned an ID 0-49, + corresponding to its line number. All other values are hashed and assigned an + ID 50-54. + + ```python + states = categorical_column_with_vocabulary_file( + key='states', vocabulary_file='/us/states.txt', vocabulary_size=50, + num_oov_buckets=5) + columns = [states, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + Example with `default_value`: + File `'/us/states.txt'` contains 51 lines - the first line is `'XX'`, and the + other 50 each have a 2-character U.S. state abbreviation. Both a literal + `'XX'` in input, and other values missing from the file, will be assigned + ID 0. All others are assigned the corresponding line number 1-50. + + ```python + states = categorical_column_with_vocabulary_file( + key='states', vocabulary_file='/us/states.txt', vocabulary_size=51, + default_value=0) + columns = [states, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + And to make an embedding with either: + + ```python + columns = [embedding_column(states, 3),...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + vocabulary_file: The vocabulary file name. + vocabulary_size: Number of the elements in the vocabulary. This must be no + greater than length of `vocabulary_file`, if less than length, later + values are ignored. If None, it is set to the length of `vocabulary_file`. + dtype: The type of features. Only string and integer types are supported. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of + the input value. A positive `num_oov_buckets` can not be specified with + `default_value`. + file_format: The format of the vocabulary file. The format is 'text' by + default unless `vocabulary_file` is a string which ends in 'tfrecord.gz'. + Accepted alternative value for `file_format` is 'tfrecord_gzip'. + + Returns: + A `CategoricalColumn` with a vocabulary file. + + Raises: + ValueError: `vocabulary_file` is missing or cannot be opened. + ValueError: `vocabulary_size` is missing or < 1. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: `dtype` is neither string nor integer. + """ + if not vocabulary_file: + raise ValueError('Missing vocabulary_file in {}.'.format(key)) + + if file_format is None and vocabulary_file.endswith('tfrecord.gz'): + file_format = 'tfrecord_gzip' + + if vocabulary_size is None: + if not gfile.Exists(vocabulary_file): + raise ValueError('vocabulary_file in {} does not exist.'.format(key)) + + if file_format == 'tfrecord_gzip': + ds = readers.TFRecordDataset(vocabulary_file, 'GZIP') + vocabulary_size = ds.reduce(0, lambda x, _: x + 1) + if context.executing_eagerly(): + vocabulary_size = vocabulary_size.numpy() + else: + with gfile.GFile(vocabulary_file, mode='rb') as f: + vocabulary_size = sum(1 for _ in f) + logging.info( + 'vocabulary_size = %d in %s is inferred from the number of elements ' + 'in the vocabulary_file %s.', vocabulary_size, key, vocabulary_file) + + # `vocabulary_size` isn't required for lookup, but it is for `_num_buckets`. + if not isinstance(vocabulary_size, tensor_lib.Tensor) and vocabulary_size < 1: + raise ValueError('Invalid vocabulary_size in {}.'.format(key)) + if num_oov_buckets: + if default_value is not None: + raise ValueError( + 'Can\'t specify both num_oov_buckets and default_value in {}.'.format( + key)) + if num_oov_buckets < 0: + raise ValueError('Invalid num_oov_buckets {} in {}.'.format( + num_oov_buckets, key)) + fc_utils.assert_string_or_int(dtype, prefix='column_name: {}'.format(key)) + fc_utils.assert_key_is_string(key) + return VocabularyFileCategoricalColumn( + key=key, + vocabulary_file=vocabulary_file, + vocabulary_size=vocabulary_size, + num_oov_buckets=0 if num_oov_buckets is None else num_oov_buckets, + default_value=-1 if default_value is None else default_value, + dtype=dtype, + file_format=file_format) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.categorical_column_with_vocabulary_list') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def categorical_column_with_vocabulary_list(key, + vocabulary_list, + dtype=None, + default_value=-1, + num_oov_buckets=0): + """A `CategoricalColumn` with in-memory vocabulary. + + Use this when your inputs are in string or integer format, and you have an + in-memory vocabulary mapping each value to an integer ID. By default, + out-of-vocabulary values are ignored. Use either (but not both) of + `num_oov_buckets` and `default_value` to specify how to include + out-of-vocabulary values. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + Example with `num_oov_buckets`: + In the following example, each input in `vocabulary_list` is assigned an ID + 0-3 corresponding to its index (e.g., input 'B' produces output 2). All other + inputs are hashed and assigned an ID 4-5. + + ```python + colors = categorical_column_with_vocabulary_list( + key='colors', vocabulary_list=('R', 'G', 'B', 'Y'), + num_oov_buckets=2) + columns = [colors, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + Example with `default_value`: + In the following example, each input in `vocabulary_list` is assigned an ID + 0-4 corresponding to its index (e.g., input 'B' produces output 3). All other + inputs are assigned `default_value` 0. + + + ```python + colors = categorical_column_with_vocabulary_list( + key='colors', vocabulary_list=('X', 'R', 'G', 'B', 'Y'), default_value=0) + columns = [colors, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + And to make an embedding with either: + + ```python + columns = [embedding_column(colors, 3),...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + vocabulary_list: An ordered iterable defining the vocabulary. Each feature + is mapped to the index of its value (if present) in `vocabulary_list`. + Must be castable to `dtype`. + dtype: The type of features. Only string and integer types are supported. If + `None`, it will be inferred from `vocabulary_list`. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[len(vocabulary_list), len(vocabulary_list)+num_oov_buckets)` based on a + hash of the input value. A positive `num_oov_buckets` can not be specified + with `default_value`. + + Returns: + A `CategoricalColumn` with in-memory vocabulary. + + Raises: + ValueError: if `vocabulary_list` is empty, or contains duplicate keys. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: if `dtype` is not integer or string. + """ + if (vocabulary_list is None) or (len(vocabulary_list) < 1): + raise ValueError( + 'vocabulary_list {} must be non-empty, column_name: {}'.format( + vocabulary_list, key)) + if len(set(vocabulary_list)) != len(vocabulary_list): + raise ValueError( + 'Duplicate keys in vocabulary_list {}, column_name: {}'.format( + vocabulary_list, key)) + vocabulary_dtype = dtypes.as_dtype(np.array(vocabulary_list).dtype) + if num_oov_buckets: + if default_value != -1: + raise ValueError( + 'Can\'t specify both num_oov_buckets and default_value in {}.'.format( + key)) + if num_oov_buckets < 0: + raise ValueError('Invalid num_oov_buckets {} in {}.'.format( + num_oov_buckets, key)) + fc_utils.assert_string_or_int( + vocabulary_dtype, prefix='column_name: {} vocabulary'.format(key)) + if dtype is None: + dtype = vocabulary_dtype + elif dtype.is_integer != vocabulary_dtype.is_integer: + raise ValueError( + 'dtype {} and vocabulary dtype {} do not match, column_name: {}'.format( + dtype, vocabulary_dtype, key)) + fc_utils.assert_string_or_int(dtype, prefix='column_name: {}'.format(key)) + fc_utils.assert_key_is_string(key) + + return VocabularyListCategoricalColumn( + key=key, + vocabulary_list=tuple(vocabulary_list), + dtype=dtype, + default_value=default_value, + num_oov_buckets=num_oov_buckets) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.categorical_column_with_identity') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def categorical_column_with_identity(key, num_buckets, default_value=None): + """A `CategoricalColumn` that returns identity values. + + Use this when your inputs are integers in the range `[0, num_buckets)`, and + you want to use the input value itself as the categorical ID. Values outside + this range will result in `default_value` if specified, otherwise it will + fail. + + Typically, this is used for contiguous ranges of integer indexes, but + it doesn't have to be. This might be inefficient, however, if many of IDs + are unused. Consider `categorical_column_with_hash_bucket` in that case. + + For input dictionary `features`, `features[key]` is either `Tensor` or + `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int + and `''` for string, which will be dropped by this feature column. + + In the following examples, each input in the range `[0, 1000000)` is assigned + the same value. All other inputs are assigned `default_value` 0. Note that a + literal 0 in inputs will result in the same default ID. + + Linear model: + + ```python + import tensorflow as tf + video_id = tf.feature_column.categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [video_id] + features = {'video_id': tf.sparse.from_dense([[2, 85, 0, 0, 0], + [33,78, 2, 73, 1]])} + linear_prediction = tf.compat.v1.feature_column.linear_model(features, + columns) + ``` + + Embedding for a DNN model: + + ```python + import tensorflow as tf + video_id = tf.feature_column.categorical_column_with_identity( + key='video_id', num_buckets=1000000, default_value=0) + columns = [tf.feature_column.embedding_column(video_id, 9)] + features = {'video_id': tf.sparse.from_dense([[2, 85, 0, 0, 0], + [33,78, 2, 73, 1]])} + input_layer = tf.keras.layers.DenseFeatures(columns) + dense_tensor = input_layer(features) + ``` + + Args: + key: A unique string identifying the input feature. It is used as the column + name and the dictionary key for feature parsing configs, feature `Tensor` + objects, and feature columns. + num_buckets: Range of inputs and outputs is `[0, num_buckets)`. + default_value: If set, values outside of range `[0, num_buckets)` will be + replaced with this value. If not set, values >= num_buckets will cause a + failure while values < 0 will be dropped. + + Returns: + A `CategoricalColumn` that returns identity values. + + Raises: + ValueError: if `num_buckets` is less than one. + ValueError: if `default_value` is not in range `[0, num_buckets)`. + """ + if num_buckets < 1: + raise ValueError('num_buckets {} < 1, column_name {}'.format( + num_buckets, key)) + if (default_value is not None) and ((default_value < 0) or + (default_value >= num_buckets)): + raise ValueError( + 'default_value {} not in range [0, {}), column_name {}'.format( + default_value, num_buckets, key)) + fc_utils.assert_key_is_string(key) + return IdentityCategoricalColumn( + key=key, number_buckets=num_buckets, default_value=default_value) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.indicator_column') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def indicator_column(categorical_column): + """Represents multi-hot representation of given categorical column. + + - For DNN model, `indicator_column` can be used to wrap any + `categorical_column_*` (e.g., to feed to DNN). Consider to Use + `embedding_column` if the number of buckets/unique(values) are large. + + - For Wide (aka linear) model, `indicator_column` is the internal + representation for categorical column when passing categorical column + directly (as any element in feature_columns) to `linear_model`. See + `linear_model` for details. + + ```python + name = indicator_column(categorical_column_with_vocabulary_list( + 'name', ['bob', 'george', 'wanda'])) + columns = [name, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + dense_tensor = input_layer(features, columns) + + dense_tensor == [[1, 0, 0]] # If "name" bytes_list is ["bob"] + dense_tensor == [[1, 0, 1]] # If "name" bytes_list is ["bob", "wanda"] + dense_tensor == [[2, 0, 0]] # If "name" bytes_list is ["bob", "bob"] + ``` + + Args: + categorical_column: A `CategoricalColumn` which is created by + `categorical_column_with_*` or `crossed_column` functions. + + Returns: + An `IndicatorColumn`. + + Raises: + ValueError: If `categorical_column` is not CategoricalColumn type. + """ + if not isinstance(categorical_column, + (CategoricalColumn, fc_old._CategoricalColumn)): # pylint: disable=protected-access + raise ValueError( + 'Unsupported input type. Input must be a CategoricalColumn. ' + 'Given: {}'.format(categorical_column)) + return IndicatorColumn(categorical_column) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.weighted_categorical_column') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def weighted_categorical_column(categorical_column, + weight_feature_key, + dtype=dtypes.float32): + """Applies weight values to a `CategoricalColumn`. + + Use this when each of your sparse inputs has both an ID and a value. For + example, if you're representing text documents as a collection of word + frequencies, you can provide 2 parallel sparse input features ('terms' and + 'frequencies' below). + + Example: + + Input `tf.Example` objects: + + ```proto + [ + features { + feature { + key: "terms" + value {bytes_list {value: "very" value: "model"}} + } + feature { + key: "frequencies" + value {float_list {value: 0.3 value: 0.1}} + } + }, + features { + feature { + key: "terms" + value {bytes_list {value: "when" value: "course" value: "human"}} + } + feature { + key: "frequencies" + value {float_list {value: 0.4 value: 0.1 value: 0.2}} + } + } + ] + ``` + + ```python + categorical_column = categorical_column_with_hash_bucket( + column_name='terms', hash_bucket_size=1000) + weighted_column = weighted_categorical_column( + categorical_column=categorical_column, weight_feature_key='frequencies') + columns = [weighted_column, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction, _, _ = linear_model(features, columns) + ``` + + This assumes the input dictionary contains a `SparseTensor` for key + 'terms', and a `SparseTensor` for key 'frequencies'. These 2 tensors must have + the same indices and dense shape. + + Args: + categorical_column: A `CategoricalColumn` created by + `categorical_column_with_*` functions. + weight_feature_key: String key for weight values. + dtype: Type of weights, such as `tf.float32`. Only float and integer weights + are supported. + + Returns: + A `CategoricalColumn` composed of two sparse features: one represents id, + the other represents weight (value) of the id feature in that example. + + Raises: + ValueError: if `dtype` is not convertible to float. + """ + if (dtype is None) or not (dtype.is_integer or dtype.is_floating): + raise ValueError('dtype {} is not convertible to float.'.format(dtype)) + return WeightedCategoricalColumn( + categorical_column=categorical_column, + weight_feature_key=weight_feature_key, + dtype=dtype) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.crossed_column') +@deprecation.deprecated( + None, + 'Use `tf.keras.layers.experimental.preprocessing.HashedCrossing` ' + 'instead for feature crossing when preprocessing data to train a ' + 'Keras model.') +def crossed_column(keys, hash_bucket_size, hash_key=None): + """Returns a column for performing crosses of categorical features. + + Crossed features will be hashed according to `hash_bucket_size`. Conceptually, + the transformation can be thought of as: + Hash(cartesian product of features) % `hash_bucket_size` + + For example, if the input features are: + + * SparseTensor referred by first key: + + ```python + shape = [2, 2] + { + [0, 0]: "a" + [1, 0]: "b" + [1, 1]: "c" + } + ``` + + * SparseTensor referred by second key: + + ```python + shape = [2, 1] + { + [0, 0]: "d" + [1, 0]: "e" + } + ``` + + then crossed feature will look like: + + ```python + shape = [2, 2] + { + [0, 0]: Hash64("d", Hash64("a")) % hash_bucket_size + [1, 0]: Hash64("e", Hash64("b")) % hash_bucket_size + [1, 1]: Hash64("e", Hash64("c")) % hash_bucket_size + } + ``` + + Here is an example to create a linear model with crosses of string features: + + ```python + keywords_x_doc_terms = crossed_column(['keywords', 'doc_terms'], 50K) + columns = [keywords_x_doc_terms, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + You could also use vocabulary lookup before crossing: + + ```python + keywords = categorical_column_with_vocabulary_file( + 'keywords', '/path/to/vocabulary/file', vocabulary_size=1K) + keywords_x_doc_terms = crossed_column([keywords, 'doc_terms'], 50K) + columns = [keywords_x_doc_terms, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + If an input feature is of numeric type, you can use + `categorical_column_with_identity`, or `bucketized_column`, as in the example: + + ```python + # vertical_id is an integer categorical feature. + vertical_id = categorical_column_with_identity('vertical_id', 10K) + price = numeric_column('price') + # bucketized_column converts numerical feature to a categorical one. + bucketized_price = bucketized_column(price, boundaries=[...]) + vertical_id_x_price = crossed_column([vertical_id, bucketized_price], 50K) + columns = [vertical_id_x_price, ...] + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + linear_prediction = linear_model(features, columns) + ``` + + To use crossed column in DNN model, you need to add it in an embedding column + as in this example: + + ```python + vertical_id_x_price = crossed_column([vertical_id, bucketized_price], 50K) + vertical_id_x_price_embedded = embedding_column(vertical_id_x_price, 10) + dense_tensor = input_layer(features, [vertical_id_x_price_embedded, ...]) + ``` + + Args: + keys: An iterable identifying the features to be crossed. Each element can + be either: + * string: Will use the corresponding feature which must be of string type. + * `CategoricalColumn`: Will use the transformed tensor produced by this + column. Does not support hashed categorical column. + hash_bucket_size: An int > 1. The number of buckets. + hash_key: Specify the hash_key that will be used by the `FingerprintCat64` + function to combine the crosses fingerprints on SparseCrossOp (optional). + + Returns: + A `CrossedColumn`. + + Raises: + ValueError: If `len(keys) < 2`. + ValueError: If any of the keys is neither a string nor `CategoricalColumn`. + ValueError: If any of the keys is `HashedCategoricalColumn`. + ValueError: If `hash_bucket_size < 1`. + """ + if not hash_bucket_size or hash_bucket_size < 1: + raise ValueError('hash_bucket_size must be > 1. ' + 'hash_bucket_size: {}'.format(hash_bucket_size)) + if not keys or len(keys) < 2: + raise ValueError( + 'keys must be a list with length > 1. Given: {}'.format(keys)) + for key in keys: + if (not isinstance(key, six.string_types) and + not isinstance(key, (CategoricalColumn, fc_old._CategoricalColumn))): # pylint: disable=protected-access + raise ValueError( + 'Unsupported key type. All keys must be either string, or ' + 'categorical column except HashedCategoricalColumn. ' + 'Given: {}'.format(key)) + if isinstance(key, + (HashedCategoricalColumn, fc_old._HashedCategoricalColumn)): # pylint: disable=protected-access + raise ValueError( + 'categorical_column_with_hash_bucket is not supported for crossing. ' + 'Hashing before crossing will increase probability of collision. ' + 'Instead, use the feature name as a string. Given: {}'.format(key)) + return CrossedColumn( + keys=tuple(keys), hash_bucket_size=hash_bucket_size, hash_key=hash_key) + + +# TODO(b/181853833): Add a tf.type for instance type checking. +@tf_export('__internal__.feature_column.DenseColumn', v1=[]) +class DenseColumn(fc_types.FeatureColumn): + """Represents a column which can be represented as `Tensor`. + + Some examples of this type are: numeric_column, embedding_column, + indicator_column. + """ + + @abc.abstractproperty + def variable_shape(self): + """`TensorShape` of `get_dense_tensor`, without batch dimension.""" + pass + + @abc.abstractmethod + def get_dense_tensor(self, transformation_cache, state_manager): + """Returns a `Tensor`. + + The output of this function will be used by model-builder-functions. For + example the pseudo code of `input_layer` will be like: + + ```python + def input_layer(features, feature_columns, ...): + outputs = [fc.get_dense_tensor(...) for fc in feature_columns] + return tf.concat(outputs) + ``` + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + `Tensor` of shape [batch_size] + `variable_shape`. + """ + pass + + +def is_feature_column_v2(feature_columns): + """Returns True if all feature columns are V2.""" + for feature_column in feature_columns: + if not isinstance(feature_column, fc_types.FeatureColumn): + return False + if not feature_column._is_v2_column: # pylint: disable=protected-access + return False + return True + + +def _create_weighted_sum(column, transformation_cache, state_manager, + sparse_combiner, weight_var): + """Creates a weighted sum for a dense/categorical column for linear_model.""" + if isinstance(column, CategoricalColumn): + return _create_categorical_column_weighted_sum( + column=column, + transformation_cache=transformation_cache, + state_manager=state_manager, + sparse_combiner=sparse_combiner, + weight_var=weight_var) + else: + return _create_dense_column_weighted_sum( + column=column, + transformation_cache=transformation_cache, + state_manager=state_manager, + weight_var=weight_var) + + +def _create_dense_column_weighted_sum(column, transformation_cache, + state_manager, weight_var): + """Create a weighted sum of a dense column for linear_model.""" + tensor = column.get_dense_tensor(transformation_cache, state_manager) + num_elements = column.variable_shape.num_elements() + batch_size = array_ops.shape(tensor)[0] + tensor = array_ops.reshape(tensor, shape=(batch_size, num_elements)) + return math_ops.matmul(tensor, weight_var, name='weighted_sum') + + +class CategoricalColumn(fc_types.FeatureColumn): + """Represents a categorical feature. + + A categorical feature typically handled with a `tf.sparse.SparseTensor` of + IDs. + """ + + IdWeightPair = collections.namedtuple( # pylint: disable=invalid-name + 'IdWeightPair', ('id_tensor', 'weight_tensor')) + + @abc.abstractproperty + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + pass + + @abc.abstractmethod + def get_sparse_tensors(self, transformation_cache, state_manager): + """Returns an IdWeightPair. + + `IdWeightPair` is a pair of `SparseTensor`s which represents ids and + weights. + + `IdWeightPair.id_tensor` is typically a `batch_size` x `num_buckets` + `SparseTensor` of `int64`. `IdWeightPair.weight_tensor` is either a + `SparseTensor` of `float` or `None` to indicate all weights should be + taken to be 1. If specified, `weight_tensor` must have exactly the same + shape and indices as `sp_ids`. Expected `SparseTensor` is same as parsing + output of a `VarLenFeature` which is a ragged matrix. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + """ + pass + + +def _create_categorical_column_weighted_sum(column, transformation_cache, + state_manager, sparse_combiner, + weight_var): + # pylint: disable=g-doc-return-or-yield,g-doc-args + """Create a weighted sum of a categorical column for linear_model. + + Note to maintainer: As implementation details, the weighted sum is + implemented via embedding_lookup_sparse toward efficiency. Mathematically, + they are the same. + + To be specific, conceptually, categorical column can be treated as multi-hot + vector. Say: + + ```python + x = [0 0 1] # categorical column input + w = [a b c] # weights + ``` + The weighted sum is `c` in this case, which is same as `w[2]`. + + Another example is + + ```python + x = [0 1 1] # categorical column input + w = [a b c] # weights + ``` + The weighted sum is `b + c` in this case, which is same as `w[2] + w[3]`. + + For both cases, we can implement weighted sum via embedding_lookup with + sparse_combiner = "sum". + """ + + sparse_tensors = column.get_sparse_tensors(transformation_cache, + state_manager) + id_tensor = sparse_ops.sparse_reshape( + sparse_tensors.id_tensor, + [array_ops.shape(sparse_tensors.id_tensor)[0], -1]) + weight_tensor = sparse_tensors.weight_tensor + if weight_tensor is not None: + weight_tensor = sparse_ops.sparse_reshape( + weight_tensor, [array_ops.shape(weight_tensor)[0], -1]) + + return embedding_ops.safe_embedding_lookup_sparse( + weight_var, + id_tensor, + sparse_weights=weight_tensor, + combiner=sparse_combiner, + name='weighted_sum') + + +# TODO(b/181853833): Add a tf.type for instance type checking. +@tf_export('__internal__.feature_column.SequenceDenseColumn', v1=[]) +@serialization.register_feature_column +class SequenceDenseColumn(fc_types.FeatureColumn): + """Represents dense sequence data.""" + + TensorSequenceLengthPair = collections.namedtuple( # pylint: disable=invalid-name + 'TensorSequenceLengthPair', ('dense_tensor', 'sequence_length')) + + @abc.abstractmethod + def get_sequence_dense_tensor(self, transformation_cache, state_manager): + """Returns a `TensorSequenceLengthPair`. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + """ + pass + + +@tf_export('__internal__.feature_column.FeatureTransformationCache', v1=[]) +class FeatureTransformationCache(object): + """Handles caching of transformations while building the model. + + `FeatureColumn` specifies how to digest an input column to the network. Some + feature columns require data transformations. This class caches those + transformations. + + Some features may be used in more than one place. For example, one can use a + bucketized feature by itself and a cross with it. In that case we + should create only one bucketization op instead of creating ops for each + feature column separately. To handle re-use of transformed columns, + `FeatureTransformationCache` caches all previously transformed columns. + + Example: + We're trying to use the following `FeatureColumn`s: + + ```python + bucketized_age = fc.bucketized_column(fc.numeric_column("age"), ...) + keywords = fc.categorical_column_with_hash_buckets("keywords", ...) + age_X_keywords = fc.crossed_column([bucketized_age, "keywords"]) + ... = linear_model(features, + [bucketized_age, keywords, age_X_keywords] + ``` + + If we transform each column independently, then we'll get duplication of + bucketization (one for cross, one for bucketization itself). + The `FeatureTransformationCache` eliminates this duplication. + """ + + def __init__(self, features): + """Creates a `FeatureTransformationCache`. + + Args: + features: A mapping from feature column to objects that are `Tensor` or + `SparseTensor`, or can be converted to same via + `sparse_tensor.convert_to_tensor_or_sparse_tensor`. A `string` key + signifies a base feature (not-transformed). A `FeatureColumn` key means + that this `Tensor` is the output of an existing `FeatureColumn` which + can be reused. + """ + self._features = features.copy() + self._feature_tensors = {} + + def get(self, key, state_manager, training=None): + """Returns a `Tensor` for the given key. + + A `str` key is used to access a base feature (not-transformed). When a + `FeatureColumn` is passed, the transformed feature is returned if it + already exists, otherwise the given `FeatureColumn` is asked to provide its + transformed output, which is then cached. + + Args: + key: a `str` or a `FeatureColumn`. + state_manager: A StateManager object that holds the FeatureColumn state. + training: Boolean indicating whether to the column is being used in + training mode. This argument is passed to the transform_feature method + of any `FeatureColumn` that takes a `training` argument. For example, if + a `FeatureColumn` performed dropout, it could expose a `training` + argument to control whether the dropout should be applied. + + Returns: + The transformed `Tensor` corresponding to the `key`. + + Raises: + ValueError: if key is not found or a transformed `Tensor` cannot be + computed. + """ + if key in self._feature_tensors: + # FeatureColumn is already transformed or converted. + return self._feature_tensors[key] + + if key in self._features: + feature_tensor = self._get_raw_feature_as_tensor(key) + self._feature_tensors[key] = feature_tensor + return feature_tensor + + if isinstance(key, six.string_types): + raise ValueError('Feature {} is not in features dictionary.'.format(key)) + + if not isinstance(key, fc_types.FeatureColumn): + raise TypeError('"key" must be either a "str" or "FeatureColumn". ' + 'Provided: {}'.format(key)) + + column = key + logging.debug('Transforming feature_column %s.', column) + + # Some columns may need information about whether the transformation is + # happening in training or prediction mode, but not all columns expose this + # argument. + try: + transformed = column.transform_feature( + self, state_manager, training=training) + except TypeError: + transformed = column.transform_feature(self, state_manager) + if transformed is None: + raise ValueError('Column {} is not supported.'.format(column.name)) + self._feature_tensors[column] = transformed + return transformed + + def _get_raw_feature_as_tensor(self, key): + """Gets the raw_feature (keyed by `key`) as `tensor`. + + The raw feature is converted to (sparse) tensor and maybe expand dim. + + For both `Tensor` and `SparseTensor`, the rank will be expanded (to 2) if + the rank is 1. This supports dynamic rank also. For rank 0 raw feature, will + error out as it is not supported. + + Args: + key: A `str` key to access the raw feature. + + Returns: + A `Tensor` or `SparseTensor`. + + Raises: + ValueError: if the raw feature has rank 0. + """ + raw_feature = self._features[key] + feature_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor( + raw_feature) + + def expand_dims(input_tensor): + # Input_tensor must have rank 1. + if isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + return sparse_ops.sparse_reshape(input_tensor, + [array_ops.shape(input_tensor)[0], 1]) + else: + return array_ops.expand_dims(input_tensor, -1) + + rank = feature_tensor.get_shape().ndims + if rank is not None: + if rank == 0: + raise ValueError( + 'Feature (key: {}) cannot have rank 0. Given: {}'.format( + key, feature_tensor)) + return feature_tensor if rank != 1 else expand_dims(feature_tensor) + + # Handle dynamic rank. + with ops.control_dependencies([ + check_ops.assert_positive( + array_ops.rank(feature_tensor), + message='Feature (key: {}) cannot have rank 0. Given: {}'.format( + key, feature_tensor)) + ]): + return cond.cond( + math_ops.equal(1, array_ops.rank(feature_tensor)), + lambda: expand_dims(feature_tensor), lambda: feature_tensor) + + +# TODO(ptucker): Move to third_party/tensorflow/python/ops/sparse_ops.py +def _to_sparse_input_and_drop_ignore_values(input_tensor, ignore_value=None): + """Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells. + + If `input_tensor` is already a `SparseTensor`, just return it. + + Args: + input_tensor: A string or integer `Tensor`. + ignore_value: Entries in `dense_tensor` equal to this value will be absent + from the resulting `SparseTensor`. If `None`, default value of + `dense_tensor`'s dtype will be used ('' for `str`, -1 for `int`). + + Returns: + A `SparseTensor` with the same shape as `input_tensor`. + + Raises: + ValueError: when `input_tensor`'s rank is `None`. + """ + input_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor( + input_tensor) + if isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + return input_tensor + with ops.name_scope(None, 'to_sparse_input', ( + input_tensor, + ignore_value, + )): + if ignore_value is None: + if input_tensor.dtype == dtypes.string: + # Exception due to TF strings are converted to numpy objects by default. + ignore_value = '' + elif input_tensor.dtype.is_integer: + ignore_value = -1 # -1 has a special meaning of missing feature + else: + # NOTE: `as_numpy_dtype` is a property, so with the parentheses this is + # constructing a new numpy object of the given type, which yields the + # default value for that type. + ignore_value = input_tensor.dtype.as_numpy_dtype() + ignore_value = math_ops.cast( + ignore_value, input_tensor.dtype, name='ignore_value') + indices = array_ops.where_v2( + math_ops.not_equal(input_tensor, ignore_value), name='indices') + return sparse_tensor_lib.SparseTensor( + indices=indices, + values=array_ops.gather_nd(input_tensor, indices, name='values'), + dense_shape=array_ops.shape( + input_tensor, out_type=dtypes.int64, name='dense_shape')) + + +def _normalize_feature_columns(feature_columns): + """Normalizes the `feature_columns` input. + + This method converts the `feature_columns` to list type as best as it can. In + addition, verifies the type and other parts of feature_columns, required by + downstream library. + + Args: + feature_columns: The raw feature columns, usually passed by users. + + Returns: + The normalized feature column list. + + Raises: + ValueError: for any invalid inputs, such as empty, duplicated names, etc. + """ + if isinstance(feature_columns, fc_types.FeatureColumn): + feature_columns = [feature_columns] + + if isinstance(feature_columns, collections_abc.Iterator): + feature_columns = list(feature_columns) + + if isinstance(feature_columns, dict): + raise ValueError('Expected feature_columns to be iterable, found dict.') + + for column in feature_columns: + if not isinstance(column, fc_types.FeatureColumn): + raise ValueError('Items of feature_columns must be a FeatureColumn. ' + 'Given (type {}): {}.'.format(type(column), column)) + if not feature_columns: + raise ValueError('feature_columns must not be empty.') + name_to_column = {} + for column in feature_columns: + if column.name in name_to_column: + raise ValueError('Duplicate feature column name found for columns: {} ' + 'and {}. This usually means that these columns refer to ' + 'same base feature. Either one must be discarded or a ' + 'duplicated but renamed item must be inserted in ' + 'features dict.'.format(column, + name_to_column[column.name])) + name_to_column[column.name] = column + + return sorted(feature_columns, key=lambda x: x.name) + + +@serialization.register_feature_column +class NumericColumn( + DenseColumn, + fc_old._DenseColumn, # pylint: disable=protected-access + collections.namedtuple( + 'NumericColumn', + ('key', 'shape', 'default_value', 'dtype', 'normalizer_fn'))): + """see `numeric_column`.""" + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.key + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return { + self.key: + parsing_ops.FixedLenFeature(self.shape, self.dtype, + self.default_value) + } + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.parse_example_spec + + def _transform_input_tensor(self, input_tensor): + if isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + raise ValueError( + 'The corresponding Tensor of numerical column must be a Tensor. ' + 'SparseTensor is not supported. key: {}'.format(self.key)) + if self.normalizer_fn is not None: + input_tensor = self.normalizer_fn(input_tensor) + return math_ops.cast(input_tensor, dtypes.float32) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + input_tensor = inputs.get(self.key) + return self._transform_input_tensor(input_tensor) + + def transform_feature(self, transformation_cache, state_manager): + """See `FeatureColumn` base class. + + In this case, we apply the `normalizer_fn` to the input tensor. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Normalized input tensor. + Raises: + ValueError: If a SparseTensor is passed in. + """ + input_tensor = transformation_cache.get(self.key, state_manager) + return self._transform_input_tensor(input_tensor) + + @property + def variable_shape(self): + """See `DenseColumn` base class.""" + return tensor_shape.TensorShape(self.shape) + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _variable_shape(self): + return self.variable_shape + + def get_dense_tensor(self, transformation_cache, state_manager): + """Returns dense `Tensor` representing numeric feature. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Dense `Tensor` created within `transform_feature`. + """ + # Feature has been already transformed. Return the intermediate + # representation created by _transform_feature. + return transformation_cache.get(self, state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + del weight_collections + del trainable + return inputs.get(self) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + config = dict(zip(self._fields, self)) + config['normalizer_fn'] = serialization._serialize_keras_object( # pylint: disable=protected-access + self.normalizer_fn) + config['dtype'] = self.dtype.name + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['normalizer_fn'] = serialization._deserialize_keras_object( # pylint: disable=protected-access + config['normalizer_fn'], + custom_objects=custom_objects) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + + return cls(**kwargs) + + +@serialization.register_feature_column +class BucketizedColumn( + DenseColumn, + CategoricalColumn, + fc_old._DenseColumn, # pylint: disable=protected-access + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple('BucketizedColumn', + ('source_column', 'boundaries'))): + """See `bucketized_column`.""" + + @property + def _is_v2_column(self): + return ( + isinstance(self.source_column, fc_types.FeatureColumn) + and self.source_column._is_v2_column + ) # pylint: disable=protected-access + + @property + def name(self): + """See `FeatureColumn` base class.""" + return '{}_bucketized'.format(self.source_column.name) + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return self.source_column.parse_example_spec + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.source_column._parse_example_spec # pylint: disable=protected-access + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + """Returns bucketized categorical `source_column` tensor.""" + source_tensor = inputs.get(self.source_column) + return math_ops._bucketize( # pylint: disable=protected-access + source_tensor, + boundaries=self.boundaries) + + def transform_feature(self, transformation_cache, state_manager): + """Returns bucketized categorical `source_column` tensor.""" + source_tensor = transformation_cache.get(self.source_column, state_manager) + return math_ops._bucketize( # pylint: disable=protected-access + source_tensor, + boundaries=self.boundaries) + + @property + def variable_shape(self): + """See `DenseColumn` base class.""" + return tensor_shape.TensorShape( + tuple(self.source_column.shape) + (len(self.boundaries) + 1,)) + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _variable_shape(self): + return self.variable_shape + + def _get_dense_tensor_for_input_tensor(self, input_tensor): + return array_ops.one_hot( + indices=math_ops.cast(input_tensor, dtypes.int64), + depth=len(self.boundaries) + 1, + on_value=1., + off_value=0.) + + def get_dense_tensor(self, transformation_cache, state_manager): + """Returns one hot encoded dense `Tensor`.""" + input_tensor = transformation_cache.get(self, state_manager) + return self._get_dense_tensor_for_input_tensor(input_tensor) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + del weight_collections + del trainable + input_tensor = inputs.get(self) + return self._get_dense_tensor_for_input_tensor(input_tensor) + + @property + def num_buckets(self): + """See `CategoricalColumn` base class.""" + # By construction, source_column is always one-dimensional. + return (len(self.boundaries) + 1) * self.source_column.shape[0] + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.num_buckets + + def _get_sparse_tensors_for_input_tensor(self, input_tensor): + batch_size = array_ops.shape(input_tensor)[0] + # By construction, source_column is always one-dimensional. + source_dimension = self.source_column.shape[0] + + i1 = array_ops.reshape( + array_ops.tile( + array_ops.expand_dims(math_ops.range(0, batch_size), 1), + [1, source_dimension]), (-1,)) + i2 = array_ops.tile(math_ops.range(0, source_dimension), [batch_size]) + # Flatten the bucket indices and unique them across dimensions + # E.g. 2nd dimension indices will range from k to 2*k-1 with k buckets + bucket_indices = ( + array_ops.reshape(input_tensor, + (-1,)) + (len(self.boundaries) + 1) * i2) + + indices = math_ops.cast( + array_ops.transpose(array_ops_stack.stack((i1, i2))), dtypes.int64) + dense_shape = math_ops.cast( + array_ops_stack.stack([batch_size, source_dimension]), dtypes.int64) + sparse_tensor = sparse_tensor_lib.SparseTensor( + indices=indices, values=bucket_indices, dense_shape=dense_shape) + return CategoricalColumn.IdWeightPair(sparse_tensor, None) + + def get_sparse_tensors(self, transformation_cache, state_manager): + """Converts dense inputs to SparseTensor so downstream code can use it.""" + input_tensor = transformation_cache.get(self, state_manager) + return self._get_sparse_tensors_for_input_tensor(input_tensor) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + """Converts dense inputs to SparseTensor so downstream code can use it.""" + del weight_collections + del trainable + input_tensor = inputs.get(self) + return self._get_sparse_tensors_for_input_tensor(input_tensor) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.source_column] + + def get_config(self): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top + config = dict(zip(self._fields, self)) + config['source_column'] = serialize_feature_column(self.source_column) + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import deserialize_feature_column # pylint: disable=g-import-not-at-top + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['source_column'] = deserialize_feature_column( + config['source_column'], custom_objects, columns_by_name) + return cls(**kwargs) + + +@serialization.register_feature_column +class EmbeddingColumn( + DenseColumn, + SequenceDenseColumn, + fc_old._DenseColumn, # pylint: disable=protected-access + fc_old._SequenceDenseColumn, # pylint: disable=protected-access + collections.namedtuple( + 'EmbeddingColumn', + ('categorical_column', 'dimension', 'combiner', 'initializer', + 'ckpt_to_load_from', 'tensor_name_in_ckpt', 'max_norm', 'trainable', + 'use_safe_embedding_lookup'))): + """See `embedding_column`.""" + + def __new__(cls, + categorical_column, + dimension, + combiner, + initializer, + ckpt_to_load_from, + tensor_name_in_ckpt, + max_norm, + trainable, + use_safe_embedding_lookup=True): + return super(EmbeddingColumn, cls).__new__( + cls, + categorical_column=categorical_column, + dimension=dimension, + combiner=combiner, + initializer=initializer, + ckpt_to_load_from=ckpt_to_load_from, + tensor_name_in_ckpt=tensor_name_in_ckpt, + max_norm=max_norm, + trainable=trainable, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + @property + def _is_v2_column(self): + return ( + isinstance(self.categorical_column, fc_types.FeatureColumn) + and self.categorical_column._is_v2_column + ) # pylint: disable=protected-access + + @property + def name(self): + """See `FeatureColumn` base class.""" + return '{}_embedding'.format(self.categorical_column.name) + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return self.categorical_column.parse_example_spec + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + def transform_feature(self, transformation_cache, state_manager): + """Transforms underlying `categorical_column`.""" + return transformation_cache.get(self.categorical_column, state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + return inputs.get(self.categorical_column) + + @property + def variable_shape(self): + """See `DenseColumn` base class.""" + return tensor_shape.TensorShape([self.dimension]) + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _variable_shape(self): + return self.variable_shape + + def create_state(self, state_manager): + """Creates the embedding lookup variable.""" + default_num_buckets = ( + self.categorical_column.num_buckets + if self._is_v2_column else self.categorical_column._num_buckets) # pylint: disable=protected-access + num_buckets = getattr(self.categorical_column, 'num_buckets', + default_num_buckets) + embedding_shape = (num_buckets, self.dimension) + state_manager.create_variable( + self, + name='embedding_weights', + shape=embedding_shape, + dtype=dtypes.float32, + trainable=self.trainable, + use_resource=True, + initializer=self.initializer) + + def _get_dense_tensor_internal_helper(self, sparse_tensors, + embedding_weights): + sparse_ids = sparse_tensors.id_tensor + sparse_weights = sparse_tensors.weight_tensor + + if self.ckpt_to_load_from is not None: + to_restore = embedding_weights + if isinstance(to_restore, variables.PartitionedVariable): + to_restore = to_restore._get_variable_list() # pylint: disable=protected-access + checkpoint_utils.init_from_checkpoint( + self.ckpt_to_load_from, {self.tensor_name_in_ckpt: to_restore}) + + sparse_id_rank = tensor_shape.dimension_value( + sparse_ids.dense_shape.get_shape()[0]) + embedding_lookup_sparse = embedding_ops.safe_embedding_lookup_sparse + if (not self.use_safe_embedding_lookup and sparse_id_rank is not None and + sparse_id_rank <= 2): + embedding_lookup_sparse = embedding_ops.embedding_lookup_sparse_v2 + # Return embedding lookup result. + return embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights, + combiner=self.combiner, + name='%s_weights' % self.name, + max_norm=self.max_norm) + + def _get_dense_tensor_internal(self, sparse_tensors, state_manager): + """Private method that follows the signature of get_dense_tensor.""" + embedding_weights = state_manager.get_variable( + self, name='embedding_weights') + return self._get_dense_tensor_internal_helper(sparse_tensors, + embedding_weights) + + def _old_get_dense_tensor_internal(self, sparse_tensors, weight_collections, + trainable): + """Private method that follows the signature of _get_dense_tensor.""" + embedding_shape = (self.categorical_column._num_buckets, self.dimension) # pylint: disable=protected-access + if (weight_collections and + ops.GraphKeys.GLOBAL_VARIABLES not in weight_collections): + weight_collections.append(ops.GraphKeys.GLOBAL_VARIABLES) + embedding_weights = variable_scope.get_variable( + name='embedding_weights', + shape=embedding_shape, + dtype=dtypes.float32, + initializer=self.initializer, + trainable=self.trainable and trainable, + collections=weight_collections) + return self._get_dense_tensor_internal_helper(sparse_tensors, + embedding_weights) + + def get_dense_tensor(self, transformation_cache, state_manager): + """Returns tensor after doing the embedding lookup. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Embedding lookup tensor. + + Raises: + ValueError: `categorical_column` is SequenceCategoricalColumn. + """ + if isinstance(self.categorical_column, SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must not be of type SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use DenseFeatures, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'SequenceFeatures instead of DenseFeatures. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Get sparse IDs and weights. + sparse_tensors = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + return self._get_dense_tensor_internal(sparse_tensors, state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + if isinstance( + self.categorical_column, + (SequenceCategoricalColumn, fc_old._SequenceCategoricalColumn)): # pylint: disable=protected-access + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must not be of type _SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use DenseFeatures, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'SequenceFeatures instead of DenseFeatures. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + sparse_tensors = self.categorical_column._get_sparse_tensors( # pylint: disable=protected-access + inputs, weight_collections, trainable) + return self._old_get_dense_tensor_internal(sparse_tensors, + weight_collections, trainable) + + def get_sequence_dense_tensor(self, transformation_cache, state_manager): + """See `SequenceDenseColumn` base class.""" + if not isinstance(self.categorical_column, SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must be of type SequenceCategoricalColumn ' + 'to use SequenceFeatures. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + sparse_tensors = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + dense_tensor = self._get_dense_tensor_internal(sparse_tensors, + state_manager) + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + if not isinstance( + self.categorical_column, + (SequenceCategoricalColumn, fc_old._SequenceCategoricalColumn)): # pylint: disable=protected-access + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must be of type SequenceCategoricalColumn ' + 'to use SequenceFeatures. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + dense_tensor = self._old_get_dense_tensor_internal( + sparse_tensors, + weight_collections=weight_collections, + trainable=trainable) + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.categorical_column] + + def get_config(self): + """See 'FeatureColumn` base class.""" + config = dict(zip(self._fields, self)) + config['categorical_column'] = serialization.serialize_feature_column( + self.categorical_column) + config['initializer'] = serialization._serialize_keras_object( # pylint: disable=protected-access + self.initializer) + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + if 'use_safe_embedding_lookup' not in config: + config['use_safe_embedding_lookup'] = True + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['categorical_column'] = serialization.deserialize_feature_column( + config['categorical_column'], custom_objects, columns_by_name) + all_initializers = dict(tf_inspect.getmembers(init_ops, tf_inspect.isclass)) + kwargs['initializer'] = serialization._deserialize_keras_object( # pylint: disable=protected-access + config['initializer'], + module_objects=all_initializers, + custom_objects=custom_objects) + return cls(**kwargs) + + +def _raise_shared_embedding_column_error(): + raise ValueError('SharedEmbeddingColumns are not supported in ' + '`linear_model` or `input_layer`. Please use ' + '`DenseFeatures` or `LinearModel` instead.') + + +class SharedEmbeddingColumnCreator(autotrackable.AutoTrackable): + """Class that creates a `SharedEmbeddingColumn`.""" + + def __init__(self, + dimension, + initializer, + ckpt_to_load_from, + tensor_name_in_ckpt, + num_buckets, + trainable, + name='shared_embedding_column_creator', + use_safe_embedding_lookup=True): + self._dimension = dimension + self._initializer = initializer + self._ckpt_to_load_from = ckpt_to_load_from + self._tensor_name_in_ckpt = tensor_name_in_ckpt + self._num_buckets = num_buckets + self._trainable = trainable + self._name = name + self._use_safe_embedding_lookup = use_safe_embedding_lookup + # Map from graph keys to embedding_weight variables. + self._embedding_weights = {} + + def __call__(self, categorical_column, combiner, max_norm): + return SharedEmbeddingColumn(categorical_column, self, combiner, max_norm, + self._use_safe_embedding_lookup) + + @property + def embedding_weights(self): + key = ops.get_default_graph()._graph_key # pylint: disable=protected-access + if key not in self._embedding_weights: + embedding_shape = (self._num_buckets, self._dimension) + var = variable_scope.get_variable( + name=self._name, + shape=embedding_shape, + dtype=dtypes.float32, + initializer=self._initializer, + trainable=self._trainable) + + if self._ckpt_to_load_from is not None: + to_restore = var + if isinstance(to_restore, variables.PartitionedVariable): + to_restore = to_restore._get_variable_list() # pylint: disable=protected-access + checkpoint_utils.init_from_checkpoint( + self._ckpt_to_load_from, {self._tensor_name_in_ckpt: to_restore}) + self._embedding_weights[key] = var + return self._embedding_weights[key] + + @property + def dimension(self): + return self._dimension + + +@serialization.register_feature_column +class SharedEmbeddingColumn( + DenseColumn, + SequenceDenseColumn, + fc_old._DenseColumn, # pylint: disable=protected-access + fc_old._SequenceDenseColumn, # pylint: disable=protected-access + collections.namedtuple( + 'SharedEmbeddingColumn', + ('categorical_column', 'shared_embedding_column_creator', 'combiner', + 'max_norm', 'use_safe_embedding_lookup'))): + """See `embedding_column`.""" + + def __new__(cls, + categorical_column, + shared_embedding_column_creator, + combiner, + max_norm, + use_safe_embedding_lookup=True): + return super(SharedEmbeddingColumn, cls).__new__( + cls, + categorical_column=categorical_column, + shared_embedding_column_creator=shared_embedding_column_creator, + combiner=combiner, + max_norm=max_norm, + use_safe_embedding_lookup=use_safe_embedding_lookup) + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return '{}_shared_embedding'.format(self.categorical_column.name) + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return self.categorical_column.parse_example_spec + + @property + def _parse_example_spec(self): + return _raise_shared_embedding_column_error() + + def transform_feature(self, transformation_cache, state_manager): + """See `FeatureColumn` base class.""" + return transformation_cache.get(self.categorical_column, state_manager) + + def _transform_feature(self, inputs): + return _raise_shared_embedding_column_error() + + @property + def variable_shape(self): + """See `DenseColumn` base class.""" + return tensor_shape.TensorShape( + [self.shared_embedding_column_creator.dimension]) + + @property + def _variable_shape(self): + return _raise_shared_embedding_column_error() + + def _get_dense_tensor_internal(self, transformation_cache, state_manager): + """Private method that follows the signature of _get_dense_tensor.""" + # This method is called from a variable_scope with name _var_scope_name, + # which is shared among all shared embeddings. Open a name_scope here, so + # that the ops for different columns have distinct names. + with ops.name_scope(None, default_name=self.name): + # Get sparse IDs and weights. + sparse_tensors = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + sparse_ids = sparse_tensors.id_tensor + sparse_weights = sparse_tensors.weight_tensor + + embedding_weights = self.shared_embedding_column_creator.embedding_weights + + sparse_id_rank = tensor_shape.dimension_value( + sparse_ids.dense_shape.get_shape()[0]) + embedding_lookup_sparse = embedding_ops.safe_embedding_lookup_sparse + if (not self.use_safe_embedding_lookup and sparse_id_rank is not None and + sparse_id_rank <= 2): + embedding_lookup_sparse = embedding_ops.embedding_lookup_sparse_v2 + # Return embedding lookup result. + return embedding_lookup_sparse( + embedding_weights, + sparse_ids, + sparse_weights, + combiner=self.combiner, + name='%s_weights' % self.name, + max_norm=self.max_norm) + + def get_dense_tensor(self, transformation_cache, state_manager): + """Returns the embedding lookup result.""" + if isinstance(self.categorical_column, SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must not be of type SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use DenseFeatures, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'SequenceFeatures instead of DenseFeatures. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + return self._get_dense_tensor_internal(transformation_cache, state_manager) + + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + return _raise_shared_embedding_column_error() + + def get_sequence_dense_tensor(self, transformation_cache, state_manager): + """See `SequenceDenseColumn` base class.""" + if not isinstance(self.categorical_column, SequenceCategoricalColumn): + raise ValueError( + 'In embedding_column: {}. ' + 'categorical_column must be of type SequenceCategoricalColumn ' + 'to use SequenceFeatures. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + dense_tensor = self._get_dense_tensor_internal(transformation_cache, + state_manager) + sparse_tensors = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + return _raise_shared_embedding_column_error() + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.categorical_column] + + +def _check_shape(shape, key): + """Returns shape if it's valid, raises error otherwise.""" + assert shape is not None + if not nest.is_nested(shape): + shape = [shape] + shape = tuple(shape) + for dimension in shape: + if not isinstance(dimension, int): + raise TypeError('shape dimensions must be integer. ' + 'shape: {}, key: {}'.format(shape, key)) + if dimension < 1: + raise ValueError('shape dimensions must be greater than 0. ' + 'shape: {}, key: {}'.format(shape, key)) + return shape + + +@serialization.register_feature_column +class HashedCategoricalColumn( + CategoricalColumn, + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple('HashedCategoricalColumn', + ('key', 'hash_bucket_size', 'dtype'))): + """see `categorical_column_with_hash_bucket`.""" + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.key + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.parse_example_spec + + def _transform_input_tensor(self, input_tensor): + """Hashes the values in the feature_column.""" + if not isinstance(input_tensor, sparse_tensor_lib.SparseTensor): + raise ValueError('SparseColumn input must be a SparseTensor.') + + fc_utils.assert_string_or_int( + input_tensor.dtype, + prefix='column_name: {} input_tensor'.format(self.key)) + + if self.dtype.is_integer != input_tensor.dtype.is_integer: + raise ValueError( + 'Column dtype and SparseTensors dtype must be compatible. ' + 'key: {}, column dtype: {}, tensor dtype: {}'.format( + self.key, self.dtype, input_tensor.dtype)) + + if self.dtype == dtypes.string: + sparse_values = input_tensor.values + else: + sparse_values = string_ops.as_string(input_tensor.values) + + sparse_id_values = string_ops.string_to_hash_bucket_fast( + sparse_values, self.hash_bucket_size, name='lookup') + return sparse_tensor_lib.SparseTensor(input_tensor.indices, + sparse_id_values, + input_tensor.dense_shape) + + def transform_feature(self, transformation_cache, state_manager): + """Hashes the values in the feature_column.""" + input_tensor = _to_sparse_input_and_drop_ignore_values( + transformation_cache.get(self.key, state_manager)) + return self._transform_input_tensor(input_tensor) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + return self._transform_input_tensor(input_tensor) + + @property + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.hash_bucket_size + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.num_buckets + + def get_sparse_tensors(self, transformation_cache, state_manager): + """See `CategoricalColumn` base class.""" + return CategoricalColumn.IdWeightPair( + transformation_cache.get(self, state_manager), None) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + del weight_collections + del trainable + return CategoricalColumn.IdWeightPair(inputs.get(self), None) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + config = dict(zip(self._fields, self)) + config['dtype'] = self.dtype.name + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + return cls(**kwargs) + + +@serialization.register_feature_column +class VocabularyFileCategoricalColumn( + CategoricalColumn, + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple( + 'VocabularyFileCategoricalColumn', + ('key', 'vocabulary_file', 'vocabulary_size', 'num_oov_buckets', + 'dtype', 'default_value', 'file_format'))): + """See `categorical_column_with_vocabulary_file`.""" + + def __new__(cls, + key, + vocabulary_file, + vocabulary_size, + num_oov_buckets, + dtype, + default_value, + file_format=None): + return super(VocabularyFileCategoricalColumn, cls).__new__( + cls, + key=key, + vocabulary_file=vocabulary_file, + vocabulary_size=vocabulary_size, + num_oov_buckets=num_oov_buckets, + dtype=dtype, + default_value=default_value, + file_format=file_format) + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.key + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.parse_example_spec + + def _make_table_from_tfrecord_gzip_file(self, key_dtype, name): + dataset = readers.TFRecordDataset( + self.vocabulary_file, compression_type='GZIP') + + def key_dtype_fn(key): + return key if key_dtype is dtypes.string else string_ops.string_to_number( + key, out_type=key_dtype) + + return data_lookup_ops.index_table_from_dataset( + dataset.map(key_dtype_fn), + num_oov_buckets=self.num_oov_buckets, + vocab_size=self.vocabulary_size, + default_value=self.default_value, + key_dtype=key_dtype, + name=name) + + def _make_table(self, key_dtype, state_manager): + name = '{}_lookup'.format(self.key) + if state_manager is None or not state_manager.has_resource(self, name): + with ops.init_scope(): + if self.file_format == 'tfrecord_gzip': + table = self._make_table_from_tfrecord_gzip_file(key_dtype, name) + else: + table = lookup_ops.index_table_from_file( + vocabulary_file=self.vocabulary_file, + num_oov_buckets=self.num_oov_buckets, + vocab_size=self.vocabulary_size, + default_value=self.default_value, + key_dtype=key_dtype, + name=name) + if state_manager is not None: + state_manager.add_resource(self, name, table) + else: + # Reuse the table from the previous run. + table = state_manager.get_resource(self, name) + return table + + def _transform_input_tensor(self, input_tensor, state_manager=None): + """Creates a lookup table for the vocabulary.""" + if self.dtype.is_integer != input_tensor.dtype.is_integer: + raise ValueError( + 'Column dtype and SparseTensors dtype must be compatible. ' + 'key: {}, column dtype: {}, tensor dtype: {}'.format( + self.key, self.dtype, input_tensor.dtype)) + + fc_utils.assert_string_or_int( + input_tensor.dtype, + prefix='column_name: {} input_tensor'.format(self.key)) + + key_dtype = self.dtype + if input_tensor.dtype.is_integer: + # `index_table_from_file` requires 64-bit integer keys. + key_dtype = dtypes.int64 + input_tensor = math_ops.cast(input_tensor, dtypes.int64) + return self._make_table(key_dtype, state_manager).lookup(input_tensor) + + def transform_feature(self, transformation_cache, state_manager): + """Creates a lookup table for the vocabulary.""" + input_tensor = _to_sparse_input_and_drop_ignore_values( + transformation_cache.get(self.key, state_manager)) + return self._transform_input_tensor(input_tensor, state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + return self._transform_input_tensor(input_tensor) + + @property + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.vocabulary_size + self.num_oov_buckets + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.num_buckets + + def get_sparse_tensors(self, transformation_cache, state_manager): + """See `CategoricalColumn` base class.""" + return CategoricalColumn.IdWeightPair( + transformation_cache.get(self, state_manager), None) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + del weight_collections + del trainable + return CategoricalColumn.IdWeightPair(inputs.get(self), None) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + config = dict(zip(self._fields, self)) + config['dtype'] = self.dtype.name + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + return cls(**kwargs) + + +@serialization.register_feature_column +class VocabularyListCategoricalColumn( + CategoricalColumn, + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple( + 'VocabularyListCategoricalColumn', + ('key', 'vocabulary_list', 'dtype', 'default_value', 'num_oov_buckets')) +): + """See `categorical_column_with_vocabulary_list`.""" + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.key + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.parse_example_spec + + def _transform_input_tensor(self, input_tensor, state_manager=None): + """Creates a lookup table for the vocabulary list.""" + if self.dtype.is_integer != input_tensor.dtype.is_integer: + raise ValueError( + 'Column dtype and SparseTensors dtype must be compatible. ' + 'key: {}, column dtype: {}, tensor dtype: {}'.format( + self.key, self.dtype, input_tensor.dtype)) + + fc_utils.assert_string_or_int( + input_tensor.dtype, + prefix='column_name: {} input_tensor'.format(self.key)) + + key_dtype = self.dtype + if input_tensor.dtype.is_integer: + # `index_table_from_tensor` requires 64-bit integer keys. + key_dtype = dtypes.int64 + input_tensor = math_ops.cast(input_tensor, dtypes.int64) + + name = '{}_lookup'.format(self.key) + if state_manager is None or not state_manager.has_resource(self, name): + with ops.init_scope(): + table = lookup_ops.index_table_from_tensor( + vocabulary_list=tuple(self.vocabulary_list), + default_value=self.default_value, + num_oov_buckets=self.num_oov_buckets, + dtype=key_dtype, + name=name) + if state_manager is not None: + state_manager.add_resource(self, name, table) + else: + # Reuse the table from the previous run. + table = state_manager.get_resource(self, name) + return table.lookup(input_tensor) + + def transform_feature(self, transformation_cache, state_manager): + """Creates a lookup table for the vocabulary list.""" + input_tensor = _to_sparse_input_and_drop_ignore_values( + transformation_cache.get(self.key, state_manager)) + return self._transform_input_tensor(input_tensor, state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + return self._transform_input_tensor(input_tensor) + + @property + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return len(self.vocabulary_list) + self.num_oov_buckets + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.num_buckets + + def get_sparse_tensors(self, transformation_cache, state_manager): + """See `CategoricalColumn` base class.""" + return CategoricalColumn.IdWeightPair( + transformation_cache.get(self, state_manager), None) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + del weight_collections + del trainable + return CategoricalColumn.IdWeightPair(inputs.get(self), None) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + config = dict(zip(self._fields, self)) + config['dtype'] = self.dtype.name + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + return cls(**kwargs) + + +@serialization.register_feature_column +class IdentityCategoricalColumn( + CategoricalColumn, + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple('IdentityCategoricalColumn', + ('key', 'number_buckets', 'default_value'))): + """See `categorical_column_with_identity`.""" + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.key + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return {self.key: parsing_ops.VarLenFeature(dtypes.int64)} + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.parse_example_spec + + def _transform_input_tensor(self, input_tensor): + """Returns a SparseTensor with identity values.""" + if not input_tensor.dtype.is_integer: + raise ValueError('Invalid input, not integer. key: {} dtype: {}'.format( + self.key, input_tensor.dtype)) + values = input_tensor.values + if input_tensor.values.dtype != dtypes.int64: + values = math_ops.cast(values, dtypes.int64, name='values') + if self.default_value is not None: + values = math_ops.cast(input_tensor.values, dtypes.int64, name='values') + num_buckets = math_ops.cast( + self.num_buckets, dtypes.int64, name='num_buckets') + zero = math_ops.cast(0, dtypes.int64, name='zero') + # Assign default for out-of-range values. + values = array_ops.where_v2( + math_ops.logical_or( + values < zero, values >= num_buckets, name='out_of_range'), + array_ops.fill( + dims=array_ops.shape(values), + value=math_ops.cast(self.default_value, dtypes.int64), + name='default_values'), values) + + return sparse_tensor_lib.SparseTensor( + indices=input_tensor.indices, + values=values, + dense_shape=input_tensor.dense_shape) + + def transform_feature(self, transformation_cache, state_manager): + """Returns a SparseTensor with identity values.""" + input_tensor = _to_sparse_input_and_drop_ignore_values( + transformation_cache.get(self.key, state_manager)) + return self._transform_input_tensor(input_tensor) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + input_tensor = _to_sparse_input_and_drop_ignore_values(inputs.get(self.key)) + return self._transform_input_tensor(input_tensor) + + @property + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.number_buckets + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.num_buckets + + def get_sparse_tensors(self, transformation_cache, state_manager): + """See `CategoricalColumn` base class.""" + return CategoricalColumn.IdWeightPair( + transformation_cache.get(self, state_manager), None) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + del weight_collections + del trainable + return CategoricalColumn.IdWeightPair(inputs.get(self), None) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + return dict(zip(self._fields, self)) + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + return cls(**kwargs) + + +@serialization.register_feature_column +class WeightedCategoricalColumn( + CategoricalColumn, + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple( + 'WeightedCategoricalColumn', + ('categorical_column', 'weight_feature_key', 'dtype'))): + """See `weighted_categorical_column`.""" + + @property + def _is_v2_column(self): + return ( + isinstance(self.categorical_column, fc_types.FeatureColumn) + and self.categorical_column._is_v2_column + ) # pylint: disable=protected-access + + @property + def name(self): + """See `FeatureColumn` base class.""" + return '{}_weighted_by_{}'.format(self.categorical_column.name, + self.weight_feature_key) + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + config = self.categorical_column.parse_example_spec + if self.weight_feature_key in config: + raise ValueError('Parse config {} already exists for {}.'.format( + config[self.weight_feature_key], self.weight_feature_key)) + config[self.weight_feature_key] = parsing_ops.VarLenFeature(self.dtype) + return config + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + config = self.categorical_column._parse_example_spec # pylint: disable=protected-access + if self.weight_feature_key in config: + raise ValueError('Parse config {} already exists for {}.'.format( + config[self.weight_feature_key], self.weight_feature_key)) + config[self.weight_feature_key] = parsing_ops.VarLenFeature(self.dtype) + return config + + @property + def num_buckets(self): + """See `DenseColumn` base class.""" + return self.categorical_column.num_buckets + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.categorical_column._num_buckets # pylint: disable=protected-access + + def _transform_weight_tensor(self, weight_tensor): + if weight_tensor is None: + raise ValueError('Missing weights {}.'.format(self.weight_feature_key)) + weight_tensor = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor( + weight_tensor) + if self.dtype != weight_tensor.dtype.base_dtype: + raise ValueError('Bad dtype, expected {}, but got {}.'.format( + self.dtype, weight_tensor.dtype)) + if not isinstance(weight_tensor, sparse_tensor_lib.SparseTensor): + # The weight tensor can be a regular Tensor. In this case, sparsify it. + weight_tensor = _to_sparse_input_and_drop_ignore_values( + weight_tensor, ignore_value=0.0) + if not weight_tensor.dtype.is_floating: + weight_tensor = math_ops.cast(weight_tensor, dtypes.float32) + return weight_tensor + + def transform_feature(self, transformation_cache, state_manager): + """Applies weights to tensor generated from `categorical_column`'.""" + weight_tensor = transformation_cache.get(self.weight_feature_key, + state_manager) + sparse_weight_tensor = self._transform_weight_tensor(weight_tensor) + sparse_categorical_tensor = _to_sparse_input_and_drop_ignore_values( + transformation_cache.get(self.categorical_column, state_manager)) + return (sparse_categorical_tensor, sparse_weight_tensor) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + """Applies weights to tensor generated from `categorical_column`'.""" + weight_tensor = inputs.get(self.weight_feature_key) + weight_tensor = self._transform_weight_tensor(weight_tensor) + return (inputs.get(self.categorical_column), weight_tensor) + + def get_sparse_tensors(self, transformation_cache, state_manager): + """See `CategoricalColumn` base class.""" + tensors = transformation_cache.get(self, state_manager) + return CategoricalColumn.IdWeightPair(tensors[0], tensors[1]) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + del weight_collections + del trainable + tensors = inputs.get(self) + return CategoricalColumn.IdWeightPair(tensors[0], tensors[1]) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.categorical_column, self.weight_feature_key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top + config = dict(zip(self._fields, self)) + config['categorical_column'] = serialize_feature_column( + self.categorical_column) + config['dtype'] = self.dtype.name + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import deserialize_feature_column # pylint: disable=g-import-not-at-top + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['categorical_column'] = deserialize_feature_column( + config['categorical_column'], custom_objects, columns_by_name) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + return cls(**kwargs) + + +@serialization.register_feature_column +class CrossedColumn( + CategoricalColumn, + fc_old._CategoricalColumn, # pylint: disable=protected-access + collections.namedtuple('CrossedColumn', + ('keys', 'hash_bucket_size', 'hash_key'))): + """See `crossed_column`.""" + + @property + def _is_v2_column(self): + for key in _collect_leaf_level_keys(self): + if isinstance(key, six.string_types): + continue + if not isinstance(key, fc_types.FeatureColumn): + return False + if not key._is_v2_column: # pylint: disable=protected-access + return False + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + feature_names = [] + for key in _collect_leaf_level_keys(self): + if isinstance(key, (fc_types.FeatureColumn, fc_old._FeatureColumn)): # pylint: disable=protected-access + feature_names.append(key.name) + else: # key must be a string + feature_names.append(key) + return '_X_'.join(sorted(feature_names)) + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + config = {} + for key in self.keys: + if isinstance(key, fc_types.FeatureColumn): + config.update(key.parse_example_spec) + elif isinstance(key, fc_old._FeatureColumn): # pylint: disable=protected-access + config.update(key._parse_example_spec) # pylint: disable=protected-access + else: # key must be a string + config.update({key: parsing_ops.VarLenFeature(dtypes.string)}) + return config + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.parse_example_spec + + def transform_feature(self, transformation_cache, state_manager): + """Generates a hashed sparse cross from the input tensors.""" + feature_tensors = [] + for key in _collect_leaf_level_keys(self): + if isinstance(key, six.string_types): + feature_tensors.append(transformation_cache.get(key, state_manager)) + elif isinstance(key, (fc_old._CategoricalColumn, CategoricalColumn)): # pylint: disable=protected-access + ids_and_weights = key.get_sparse_tensors(transformation_cache, + state_manager) + if ids_and_weights.weight_tensor is not None: + raise ValueError( + 'crossed_column does not support weight_tensor, but the given ' + 'column populates weight_tensor. ' + 'Given column: {}'.format(key.name)) + feature_tensors.append(ids_and_weights.id_tensor) + else: + raise ValueError('Unsupported column type. Given: {}'.format(key)) + return sparse_ops.sparse_cross_hashed( + inputs=feature_tensors, + num_buckets=self.hash_bucket_size, + hash_key=self.hash_key) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + """Generates a hashed sparse cross from the input tensors.""" + feature_tensors = [] + for key in _collect_leaf_level_keys(self): + if isinstance(key, six.string_types): + feature_tensors.append(inputs.get(key)) + elif isinstance(key, (CategoricalColumn, fc_old._CategoricalColumn)): # pylint: disable=protected-access + ids_and_weights = key._get_sparse_tensors(inputs) # pylint: disable=protected-access + if ids_and_weights.weight_tensor is not None: + raise ValueError( + 'crossed_column does not support weight_tensor, but the given ' + 'column populates weight_tensor. ' + 'Given column: {}'.format(key.name)) + feature_tensors.append(ids_and_weights.id_tensor) + else: + raise ValueError('Unsupported column type. Given: {}'.format(key)) + return sparse_ops.sparse_cross_hashed( + inputs=feature_tensors, + num_buckets=self.hash_bucket_size, + hash_key=self.hash_key) + + @property + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.hash_bucket_size + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.num_buckets + + def get_sparse_tensors(self, transformation_cache, state_manager): + """See `CategoricalColumn` base class.""" + return CategoricalColumn.IdWeightPair( + transformation_cache.get(self, state_manager), None) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + """See `CategoricalColumn` base class.""" + del weight_collections + del trainable + return CategoricalColumn.IdWeightPair(inputs.get(self), None) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return list(self.keys) + + def get_config(self): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top + config = dict(zip(self._fields, self)) + config['keys'] = tuple([serialize_feature_column(fc) for fc in self.keys]) + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import deserialize_feature_column # pylint: disable=g-import-not-at-top + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['keys'] = tuple([ + deserialize_feature_column(c, custom_objects, columns_by_name) + for c in config['keys'] + ]) + return cls(**kwargs) + + +def _collect_leaf_level_keys(cross): + """Collects base keys by expanding all nested crosses. + + Args: + cross: A `CrossedColumn`. + + Returns: + A list of strings or `CategoricalColumn` instances. + """ + leaf_level_keys = [] + for k in cross.keys: + if isinstance(k, CrossedColumn): + leaf_level_keys.extend(_collect_leaf_level_keys(k)) + else: + leaf_level_keys.append(k) + return leaf_level_keys + + +def _prune_invalid_ids(sparse_ids, sparse_weights): + """Prune invalid IDs (< 0) from the input ids and weights.""" + is_id_valid = math_ops.greater_equal(sparse_ids.values, 0) + if sparse_weights is not None: + is_id_valid = math_ops.logical_and( + is_id_valid, + array_ops.ones_like(sparse_weights.values, dtype=dtypes.bool)) + sparse_ids = sparse_ops.sparse_retain(sparse_ids, is_id_valid) + if sparse_weights is not None: + sparse_weights = sparse_ops.sparse_retain(sparse_weights, is_id_valid) + return sparse_ids, sparse_weights + + +def _prune_invalid_weights(sparse_ids, sparse_weights): + """Prune invalid weights (< 0) from the input ids and weights.""" + if sparse_weights is not None: + is_weights_valid = math_ops.greater(sparse_weights.values, 0) + sparse_ids = sparse_ops.sparse_retain(sparse_ids, is_weights_valid) + sparse_weights = sparse_ops.sparse_retain(sparse_weights, is_weights_valid) + return sparse_ids, sparse_weights + + +@serialization.register_feature_column +class IndicatorColumn( + DenseColumn, + SequenceDenseColumn, + fc_old._DenseColumn, # pylint: disable=protected-access + fc_old._SequenceDenseColumn, # pylint: disable=protected-access + collections.namedtuple('IndicatorColumn', ('categorical_column'))): + """Represents a one-hot column for use in deep networks. + + Args: + categorical_column: A `CategoricalColumn` which is created by + `categorical_column_with_*` function. + """ + + @property + def _is_v2_column(self): + return ( + isinstance(self.categorical_column, fc_types.FeatureColumn) + and self.categorical_column._is_v2_column + ) # pylint: disable=protected-access + + @property + def name(self): + """See `FeatureColumn` base class.""" + return '{}_indicator'.format(self.categorical_column.name) + + def _transform_id_weight_pair(self, id_weight_pair, size): + id_tensor = id_weight_pair.id_tensor + weight_tensor = id_weight_pair.weight_tensor + + # If the underlying column is weighted, return the input as a dense tensor. + if weight_tensor is not None: + weighted_column = sparse_ops.sparse_merge( + sp_ids=id_tensor, sp_values=weight_tensor, vocab_size=int(size)) + # Remove (?, -1) index. + weighted_column = sparse_ops.sparse_slice(weighted_column, [0, 0], + weighted_column.dense_shape) + # Use scatter_nd to merge duplicated indices if existed, + # instead of sparse_tensor_to_dense. + return array_ops.scatter_nd(weighted_column.indices, + weighted_column.values, + weighted_column.dense_shape) + + dense_id_tensor = sparse_ops.sparse_tensor_to_dense( + id_tensor, default_value=-1) + + # One hot must be float for tf.concat reasons since all other inputs to + # input_layer are float32. + one_hot_id_tensor = array_ops.one_hot( + dense_id_tensor, depth=size, on_value=1.0, off_value=0.0) + + # Reduce to get a multi-hot per example. + return math_ops.reduce_sum(one_hot_id_tensor, axis=[-2]) + + def transform_feature(self, transformation_cache, state_manager): + """Returns dense `Tensor` representing feature. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Transformed feature `Tensor`. + + Raises: + ValueError: if input rank is not known at graph building time. + """ + id_weight_pair = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + return self._transform_id_weight_pair(id_weight_pair, + self.variable_shape[-1]) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + id_weight_pair = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + return self._transform_id_weight_pair(id_weight_pair, + self._variable_shape[-1]) + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return self.categorical_column.parse_example_spec + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + @property + def variable_shape(self): + """Returns a `TensorShape` representing the shape of the dense `Tensor`.""" + if isinstance(self.categorical_column, fc_types.FeatureColumn): + return tensor_shape.TensorShape([1, self.categorical_column.num_buckets]) + else: + return tensor_shape.TensorShape([1, self.categorical_column._num_buckets]) # pylint: disable=protected-access + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _variable_shape(self): + return tensor_shape.TensorShape([1, self.categorical_column._num_buckets]) # pylint: disable=protected-access + + def get_dense_tensor(self, transformation_cache, state_manager): + """Returns dense `Tensor` representing feature. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Dense `Tensor` created within `transform_feature`. + + Raises: + ValueError: If `categorical_column` is a `SequenceCategoricalColumn`. + """ + if isinstance(self.categorical_column, SequenceCategoricalColumn): + raise ValueError( + 'In indicator_column: {}. ' + 'categorical_column must not be of type SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use DenseFeatures, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'SequenceFeatures instead of DenseFeatures. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Feature has been already transformed. Return the intermediate + # representation created by transform_feature. + return transformation_cache.get(self, state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): + del weight_collections + del trainable + if isinstance( + self.categorical_column, + (SequenceCategoricalColumn, fc_old._SequenceCategoricalColumn)): # pylint: disable=protected-access + raise ValueError( + 'In indicator_column: {}. ' + 'categorical_column must not be of type _SequenceCategoricalColumn. ' + 'Suggested fix A: If you wish to use DenseFeatures, use a ' + 'non-sequence categorical_column_with_*. ' + 'Suggested fix B: If you wish to create sequence input, use ' + 'SequenceFeatures instead of DenseFeatures. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Feature has been already transformed. Return the intermediate + # representation created by transform_feature. + return inputs.get(self) + + def get_sequence_dense_tensor(self, transformation_cache, state_manager): + """See `SequenceDenseColumn` base class.""" + if not isinstance(self.categorical_column, SequenceCategoricalColumn): + raise ValueError( + 'In indicator_column: {}. ' + 'categorical_column must be of type SequenceCategoricalColumn ' + 'to use SequenceFeatures. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Feature has been already transformed. Return the intermediate + # representation created by transform_feature. + dense_tensor = transformation_cache.get(self, state_manager) + sparse_tensors = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sequence_dense_tensor(self, + inputs, + weight_collections=None, + trainable=None): + # Do nothing with weight_collections and trainable since no variables are + # created in this function. + del weight_collections + del trainable + if not isinstance( + self.categorical_column, + (SequenceCategoricalColumn, fc_old._SequenceCategoricalColumn)): # pylint: disable=protected-access + raise ValueError( + 'In indicator_column: {}. ' + 'categorical_column must be of type _SequenceCategoricalColumn ' + 'to use SequenceFeatures. ' + 'Suggested fix: Use one of sequence_categorical_column_with_*. ' + 'Given (type {}): {}'.format(self.name, type(self.categorical_column), + self.categorical_column)) + # Feature has been already transformed. Return the intermediate + # representation created by _transform_feature. + dense_tensor = inputs.get(self) + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + sequence_length = fc_utils.sequence_length_from_sparse_tensor( + sparse_tensors.id_tensor) + return SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=sequence_length) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.categorical_column] + + def get_config(self): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top + config = dict(zip(self._fields, self)) + config['categorical_column'] = serialize_feature_column( + self.categorical_column) + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import deserialize_feature_column # pylint: disable=g-import-not-at-top + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['categorical_column'] = deserialize_feature_column( + config['categorical_column'], custom_objects, columns_by_name) + return cls(**kwargs) + + +def _verify_static_batch_size_equality(tensors, columns): + """Verify equality between static batch sizes. + + Args: + tensors: iterable of input tensors. + columns: Corresponding feature columns. + + Raises: + ValueError: in case of mismatched batch sizes. + """ + # bath_size is a Dimension object. + expected_batch_size = None + for i in range(0, len(tensors)): + batch_size = tensor_shape.Dimension( + tensor_shape.dimension_value(tensors[i].shape[0])) + if batch_size.value is not None: + if expected_batch_size is None: + bath_size_column_index = i + expected_batch_size = batch_size + elif not expected_batch_size.is_compatible_with(batch_size): + raise ValueError( + 'Batch size (first dimension) of each feature must be same. ' + 'Batch size of columns ({}, {}): ({}, {})'.format( + columns[bath_size_column_index].name, columns[i].name, + expected_batch_size, batch_size)) + + +@serialization.register_feature_column +class SequenceCategoricalColumn( + CategoricalColumn, + fc_old._SequenceCategoricalColumn, # pylint: disable=protected-access + collections.namedtuple('SequenceCategoricalColumn', + ('categorical_column'))): + """Represents sequences of categorical data.""" + + @property + def _is_v2_column(self): + return ( + isinstance(self.categorical_column, fc_types.FeatureColumn) + and self.categorical_column._is_v2_column + ) # pylint: disable=protected-access + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.categorical_column.name + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return self.categorical_column.parse_example_spec + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _parse_example_spec(self): + return self.categorical_column._parse_example_spec # pylint: disable=protected-access + + def transform_feature(self, transformation_cache, state_manager): + """See `FeatureColumn` base class.""" + return self.categorical_column.transform_feature(transformation_cache, + state_manager) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _transform_feature(self, inputs): + return self.categorical_column._transform_feature(inputs) # pylint: disable=protected-access + + @property + def num_buckets(self): + """Returns number of buckets in this sparse feature.""" + return self.categorical_column.num_buckets + + @property + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _num_buckets(self): + return self.categorical_column._num_buckets # pylint: disable=protected-access + + def _get_sparse_tensors_helper(self, sparse_tensors): + id_tensor = sparse_tensors.id_tensor + weight_tensor = sparse_tensors.weight_tensor + # Expands third dimension, if necessary so that embeddings are not + # combined during embedding lookup. If the tensor is already 3D, leave + # as-is. + shape = array_ops.shape(id_tensor) + # Compute the third dimension explicitly instead of setting it to -1, as + # that doesn't work for dynamically shaped tensors with 0-length at runtime. + # This happens for empty sequences. + target_shape = [shape[0], shape[1], math_ops.reduce_prod(shape[2:])] + id_tensor = sparse_ops.sparse_reshape(id_tensor, target_shape) + if weight_tensor is not None: + weight_tensor = sparse_ops.sparse_reshape(weight_tensor, target_shape) + return CategoricalColumn.IdWeightPair(id_tensor, weight_tensor) + + def get_sparse_tensors(self, transformation_cache, state_manager): + """Returns an IdWeightPair. + + `IdWeightPair` is a pair of `SparseTensor`s which represents ids and + weights. + + `IdWeightPair.id_tensor` is typically a `batch_size` x `num_buckets` + `SparseTensor` of `int64`. `IdWeightPair.weight_tensor` is either a + `SparseTensor` of `float` or `None` to indicate all weights should be + taken to be 1. If specified, `weight_tensor` must have exactly the same + shape and indices as `sp_ids`. Expected `SparseTensor` is same as parsing + output of a `VarLenFeature` which is a ragged matrix. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + """ + sparse_tensors = self.categorical_column.get_sparse_tensors( + transformation_cache, state_manager) + return self._get_sparse_tensors_helper(sparse_tensors) + + @deprecation.deprecated(_FEATURE_COLUMN_DEPRECATION_DATE, + _FEATURE_COLUMN_DEPRECATION) + def _get_sparse_tensors(self, + inputs, + weight_collections=None, + trainable=None): + sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) # pylint: disable=protected-access + return self._get_sparse_tensors_helper(sparse_tensors) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.categorical_column] + + def get_config(self): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import serialize_feature_column # pylint: disable=g-import-not-at-top + config = dict(zip(self._fields, self)) + config['categorical_column'] = serialize_feature_column( + self.categorical_column) + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + from tensorflow.python.feature_column.serialization import deserialize_feature_column # pylint: disable=g-import-not-at-top + _check_config_keys(config, cls._fields) + kwargs = _standardize_and_copy_config(config) + kwargs['categorical_column'] = deserialize_feature_column( + config['categorical_column'], custom_objects, columns_by_name) + return cls(**kwargs) + + +def _check_config_keys(config, expected_keys): + """Checks that a config has all expected_keys.""" + if set(config.keys()) != set(expected_keys): + raise ValueError('Invalid config: {}, expected keys: {}'.format( + config, expected_keys)) + + +def _standardize_and_copy_config(config): + """Returns a shallow copy of config with lists turned to tuples. + + Keras serialization uses nest to listify everything. + This causes problems with the NumericColumn shape, which becomes + unhashable. We could try to solve this on the Keras side, but that + would require lots of tracking to avoid changing existing behavior. + Instead, we ensure here that we revive correctly. + + Args: + config: dict that will be used to revive a Feature Column + + Returns: + Shallow copy of config with lists turned to tuples. + """ + kwargs = config.copy() + for k, v in kwargs.items(): + if isinstance(v, list): + kwargs[k] = tuple(v) + + return kwargs + + +def _sanitize_column_name_for_variable_scope(name): + """Sanitizes user-provided feature names for use as variable scopes.""" + invalid_char = re.compile('[^A-Za-z0-9_.\\-]') + return invalid_char.sub('_', name) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_v2_types.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_v2_types.py new file mode 100644 index 0000000000000000000000000000000000000000..e76d4269f89de6d3eddc4f50911d31fe75483334 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/feature_column_v2_types.py @@ -0,0 +1,272 @@ +# 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. +# ============================================================================== +"""Types specific to tf.feature_column.""" +import abc + +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('__internal__.feature_column.FeatureColumn', v1=[]) +class FeatureColumn(object, metaclass=abc.ABCMeta): + """Represents a feature column abstraction. + + WARNING: Do not subclass this layer unless you know what you are doing: + the API is subject to future changes. + + To distinguish between the concept of a feature family and a specific binary + feature within a family, we refer to a feature family like "country" as a + feature column. For example, we can have a feature in a `tf.Example` format: + {key: "country", value: [ "US" ]} + In this example the value of feature is "US" and "country" refers to the + column of the feature. + + This class is an abstract class. Users should not create instances of this. + """ + + @abc.abstractproperty + def name(self): + """Returns string. Used for naming.""" + pass + + def __lt__(self, other): + """Allows feature columns to be sorted in Python 3 as they are in Python 2. + + Feature columns need to occasionally be sortable, for example when used as + keys in a features dictionary passed to a layer. + + In CPython, `__lt__` must be defined for all objects in the + sequence being sorted. + + If any objects in the sequence being sorted do not have an `__lt__` method + compatible with feature column objects (such as strings), then CPython will + fall back to using the `__gt__` method below. + https://docs.python.org/3/library/stdtypes.html#list.sort + + Args: + other: The other object to compare to. + + Returns: + True if the string representation of this object is lexicographically less + than the string representation of `other`. For FeatureColumn objects, + this looks like "<__main__.FeatureColumn object at 0xa>". + """ + return str(self) < str(other) + + def __gt__(self, other): + """Allows feature columns to be sorted in Python 3 as they are in Python 2. + + Feature columns need to occasionally be sortable, for example when used as + keys in a features dictionary passed to a layer. + + `__gt__` is called when the "other" object being compared during the sort + does not have `__lt__` defined. + Example: + ``` + # __lt__ only class + class A(): + def __lt__(self, other): return str(self) < str(other) + + a = A() + a < "b" # True + "0" < a # Error + + # __lt__ and __gt__ class + class B(): + def __lt__(self, other): return str(self) < str(other) + def __gt__(self, other): return str(self) > str(other) + + b = B() + b < "c" # True + "0" < b # True + ``` + + Args: + other: The other object to compare to. + + Returns: + True if the string representation of this object is lexicographically + greater than the string representation of `other`. For FeatureColumn + objects, this looks like "<__main__.FeatureColumn object at 0xa>". + """ + return str(self) > str(other) + + @abc.abstractmethod + def transform_feature(self, transformation_cache, state_manager): + """Returns intermediate representation (usually a `Tensor`). + + Uses `transformation_cache` to create an intermediate representation + (usually a `Tensor`) that other feature columns can use. + + Example usage of `transformation_cache`: + Let's say a Feature column depends on raw feature ('raw') and another + `FeatureColumn` (input_fc). To access corresponding `Tensor`s, + transformation_cache will be used as follows: + + ```python + raw_tensor = transformation_cache.get('raw', state_manager) + fc_tensor = transformation_cache.get(input_fc, state_manager) + ``` + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Transformed feature `Tensor`. + """ + pass + + @abc.abstractproperty + def parse_example_spec(self): + """Returns a `tf.Example` parsing spec as dict. + + It is used for get_parsing_spec for `tf.io.parse_example`. Returned spec is + a dict from keys ('string') to `VarLenFeature`, `FixedLenFeature`, and other + supported objects. Please check documentation of `tf.io.parse_example` for + all supported spec objects. + + Let's say a Feature column depends on raw feature ('raw') and another + `FeatureColumn` (input_fc). One possible implementation of + parse_example_spec is as follows: + + ```python + spec = {'raw': tf.io.FixedLenFeature(...)} + spec.update(input_fc.parse_example_spec) + return spec + ``` + """ + pass + + def create_state(self, state_manager): + """Uses the `state_manager` to create state for the FeatureColumn. + + Args: + state_manager: A `StateManager` to create / access resources such as + lookup tables and variables. + """ + pass + + @abc.abstractproperty + def _is_v2_column(self): + """Returns whether this FeatureColumn is fully conformant to the new API. + + This is needed for composition type cases where an EmbeddingColumn etc. + might take in old categorical columns as input and then we want to use the + old API. + """ + pass + + @abc.abstractproperty + def parents(self): + """Returns a list of immediate raw feature and FeatureColumn dependencies. + + For example: + # For the following feature columns + a = numeric_column('f1') + c = crossed_column(a, 'f2') + # The expected parents are: + a.parents = ['f1'] + c.parents = [a, 'f2'] + """ + pass + + def get_config(self): + """Returns the config of the feature column. + + A FeatureColumn config is a Python dictionary (serializable) containing the + configuration of a FeatureColumn. The same FeatureColumn can be + reinstantiated later from this configuration. + + The config of a feature column does not include information about feature + columns depending on it nor the FeatureColumn class name. + + Example with (de)serialization practices followed in this file: + ```python + class SerializationExampleFeatureColumn( + FeatureColumn, collections.namedtuple( + 'SerializationExampleFeatureColumn', + ('dimension', 'parent', 'dtype', 'normalizer_fn'))): + + def get_config(self): + # Create a dict from the namedtuple. + # Python attribute literals can be directly copied from / to the config. + # For example 'dimension', assuming it is an integer literal. + config = dict(zip(self._fields, self)) + + # (De)serialization of parent FeatureColumns should use the provided + # (de)serialize_feature_column() methods that take care of de-duping. + config['parent'] = serialize_feature_column(self.parent) + + # Many objects provide custom (de)serialization e.g: for tf.DType + # tf.DType.name, tf.as_dtype() can be used. + config['dtype'] = self.dtype.name + + # Non-trivial dependencies should be Keras-(de)serializable. + config['normalizer_fn'] = generic_utils.serialize_keras_object( + self.normalizer_fn) + + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + # This should do the inverse transform from `get_config` and construct + # the namedtuple. + kwargs = config.copy() + kwargs['parent'] = deserialize_feature_column( + config['parent'], custom_objects, columns_by_name) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + kwargs['normalizer_fn'] = generic_utils.deserialize_keras_object( + config['normalizer_fn'], custom_objects=custom_objects) + return cls(**kwargs) + + ``` + Returns: + A serializable Dict that can be used to deserialize the object with + from_config. + """ + return self._get_config() + + def _get_config(self): + raise NotImplementedError('Must be implemented in subclasses.') + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """Creates a FeatureColumn from its config. + + This method should be the reverse of `get_config`, capable of instantiating + the same FeatureColumn from the config dictionary. See `get_config` for an + example of common (de)serialization practices followed in this file. + + TODO(b/118939620): This is a private method until consensus is reached on + supporting object deserialization deduping within Keras. + + Args: + config: A Dict config acquired with `get_config`. + custom_objects: Optional dictionary mapping names (strings) to custom + classes or functions to be considered during deserialization. + columns_by_name: A Dict[String, FeatureColumn] of existing columns in + order to avoid duplication. Should be passed to any calls to + deserialize_feature_column(). + + Returns: + A FeatureColumn for the input config. + """ + return cls._from_config(config, custom_objects, columns_by_name) + + @classmethod + def _from_config(cls, config, custom_objects=None, columns_by_name=None): + raise NotImplementedError('Must be implemented in subclasses.') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/sequence_feature_column.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/sequence_feature_column.py new file mode 100644 index 0000000000000000000000000000000000000000..05dabd003dc733fb74f9781da30ec15f7f0434e8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/sequence_feature_column.py @@ -0,0 +1,509 @@ +# 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. +# ============================================================================== +"""This API defines FeatureColumn for sequential input. + +NOTE: This API is a work in progress and will likely be changing frequently. +""" + +import collections + +from tensorflow.python.feature_column import feature_column_v2 as fc +from tensorflow.python.feature_column import serialization +from tensorflow.python.feature_column import utils as fc_utils +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import parsing_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +_FEATURE_COLUMN_DEPRECATION_WARNING = """\ + Warning: tf.feature_column is not recommended for new code. Instead, + feature preprocessing can be done directly using either [Keras preprocessing + layers](https://www.tensorflow.org/guide/migrate/migrating_feature_columns) + or through the one-stop utility [`tf.keras.utils.FeatureSpace`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/FeatureSpace) + built on top of them. See the [migration guide](https://tensorflow.org/guide/migrate) + for details. + """ + +_FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING = ( + 'Use Keras preprocessing layers instead, either directly or via the ' + '`tf.keras.utils.FeatureSpace` utility. Each of `tf.feature_column.*` has ' + 'a functional equivalent in `tf.keras.layers` for feature preprocessing ' + 'when training a Keras model.') + + +# pylint: disable=protected-access +def concatenate_context_input(context_input, sequence_input): + """Replicates `context_input` across all timesteps of `sequence_input`. + + Expands dimension 1 of `context_input` then tiles it `sequence_length` times. + This value is appended to `sequence_input` on dimension 2 and the result is + returned. + + Args: + context_input: A `Tensor` of dtype `float32` and shape `[batch_size, d1]`. + sequence_input: A `Tensor` of dtype `float32` and shape `[batch_size, + padded_length, d0]`. + + Returns: + A `Tensor` of dtype `float32` and shape `[batch_size, padded_length, + d0 + d1]`. + + Raises: + ValueError: If `sequence_input` does not have rank 3 or `context_input` does + not have rank 2. + """ + seq_rank_check = check_ops.assert_rank( + sequence_input, + 3, + message='sequence_input must have rank 3', + data=[array_ops.shape(sequence_input)]) + seq_type_check = check_ops.assert_type( + sequence_input, + dtypes.float32, + message='sequence_input must have dtype float32; got {}.'.format( + sequence_input.dtype)) + ctx_rank_check = check_ops.assert_rank( + context_input, + 2, + message='context_input must have rank 2', + data=[array_ops.shape(context_input)]) + ctx_type_check = check_ops.assert_type( + context_input, + dtypes.float32, + message='context_input must have dtype float32; got {}.'.format( + context_input.dtype)) + with ops.control_dependencies( + [seq_rank_check, seq_type_check, ctx_rank_check, ctx_type_check]): + padded_length = array_ops.shape(sequence_input)[1] + tiled_context_input = array_ops.tile( + array_ops.expand_dims(context_input, 1), + array_ops.concat([[1], [padded_length], [1]], 0)) + return array_ops.concat([sequence_input, tiled_context_input], 2) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.sequence_categorical_column_with_identity') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def sequence_categorical_column_with_identity(key, + num_buckets, + default_value=None): + """Returns a feature column that represents sequences of integers. + + Pass this to `embedding_column` or `indicator_column` to convert sequence + categorical data into dense representation for input to sequence NN, such as + RNN. + + Example: + + ```python + watches = sequence_categorical_column_with_identity( + 'watches', num_buckets=1000) + watches_embedding = embedding_column(watches, dimension=10) + columns = [watches_embedding] + + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + sequence_feature_layer = SequenceFeatures(columns) + sequence_input, sequence_length = sequence_feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + + rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size) + rnn_layer = tf.keras.layers.RNN(rnn_cell) + outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask) + ``` + + Args: + key: A unique string identifying the input feature. + num_buckets: Range of inputs. Namely, inputs are expected to be in the range + `[0, num_buckets)`. + default_value: If `None`, this column's graph operations will fail for + out-of-range inputs. Otherwise, this value must be in the range `[0, + num_buckets)`, and will replace out-of-range inputs. + + Returns: + A `SequenceCategoricalColumn`. + + Raises: + ValueError: if `num_buckets` is less than one. + ValueError: if `default_value` is not in range `[0, num_buckets)`. + """ + return fc.SequenceCategoricalColumn( + fc.categorical_column_with_identity( + key=key, num_buckets=num_buckets, default_value=default_value)) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.sequence_categorical_column_with_hash_bucket') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def sequence_categorical_column_with_hash_bucket(key, + hash_bucket_size, + dtype=dtypes.string): + """A sequence of categorical terms where ids are set by hashing. + + Pass this to `embedding_column` or `indicator_column` to convert sequence + categorical data into dense representation for input to sequence NN, such as + RNN. + + Example: + + ```python + tokens = sequence_categorical_column_with_hash_bucket( + 'tokens', hash_bucket_size=1000) + tokens_embedding = embedding_column(tokens, dimension=10) + columns = [tokens_embedding] + + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + sequence_feature_layer = SequenceFeatures(columns) + sequence_input, sequence_length = sequence_feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + + rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size) + rnn_layer = tf.keras.layers.RNN(rnn_cell) + outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask) + ``` + + Args: + key: A unique string identifying the input feature. + hash_bucket_size: An int > 1. The number of buckets. + dtype: The type of features. Only string and integer types are supported. + + Returns: + A `SequenceCategoricalColumn`. + + Raises: + ValueError: `hash_bucket_size` is not greater than 1. + ValueError: `dtype` is neither string nor integer. + """ + return fc.SequenceCategoricalColumn( + fc.categorical_column_with_hash_bucket( + key=key, hash_bucket_size=hash_bucket_size, dtype=dtype)) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.sequence_categorical_column_with_vocabulary_file') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def sequence_categorical_column_with_vocabulary_file(key, + vocabulary_file, + vocabulary_size=None, + num_oov_buckets=0, + default_value=None, + dtype=dtypes.string): + """A sequence of categorical terms where ids use a vocabulary file. + + Pass this to `embedding_column` or `indicator_column` to convert sequence + categorical data into dense representation for input to sequence NN, such as + RNN. + + Example: + + ```python + states = sequence_categorical_column_with_vocabulary_file( + key='states', vocabulary_file='/us/states.txt', vocabulary_size=50, + num_oov_buckets=5) + states_embedding = embedding_column(states, dimension=10) + columns = [states_embedding] + + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + sequence_feature_layer = SequenceFeatures(columns) + sequence_input, sequence_length = sequence_feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + + rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size) + rnn_layer = tf.keras.layers.RNN(rnn_cell) + outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask) + ``` + + Args: + key: A unique string identifying the input feature. + vocabulary_file: The vocabulary file name. + vocabulary_size: Number of the elements in the vocabulary. This must be no + greater than length of `vocabulary_file`, if less than length, later + values are ignored. If None, it is set to the length of `vocabulary_file`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of + the input value. A positive `num_oov_buckets` can not be specified with + `default_value`. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + dtype: The type of features. Only string and integer types are supported. + + Returns: + A `SequenceCategoricalColumn`. + + Raises: + ValueError: `vocabulary_file` is missing or cannot be opened. + ValueError: `vocabulary_size` is missing or < 1. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: `dtype` is neither string nor integer. + """ + return fc.SequenceCategoricalColumn( + fc.categorical_column_with_vocabulary_file( + key=key, + vocabulary_file=vocabulary_file, + vocabulary_size=vocabulary_size, + num_oov_buckets=num_oov_buckets, + default_value=default_value, + dtype=dtype)) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.sequence_categorical_column_with_vocabulary_list') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def sequence_categorical_column_with_vocabulary_list(key, + vocabulary_list, + dtype=None, + default_value=-1, + num_oov_buckets=0): + """A sequence of categorical terms where ids use an in-memory list. + + Pass this to `embedding_column` or `indicator_column` to convert sequence + categorical data into dense representation for input to sequence NN, such as + RNN. + + Example: + + ```python + colors = sequence_categorical_column_with_vocabulary_list( + key='colors', vocabulary_list=('R', 'G', 'B', 'Y'), + num_oov_buckets=2) + colors_embedding = embedding_column(colors, dimension=3) + columns = [colors_embedding] + + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + sequence_feature_layer = SequenceFeatures(columns) + sequence_input, sequence_length = sequence_feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + + rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size) + rnn_layer = tf.keras.layers.RNN(rnn_cell) + outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask) + ``` + + Args: + key: A unique string identifying the input feature. + vocabulary_list: An ordered iterable defining the vocabulary. Each feature + is mapped to the index of its value (if present) in `vocabulary_list`. + Must be castable to `dtype`. + dtype: The type of features. Only string and integer types are supported. If + `None`, it will be inferred from `vocabulary_list`. + default_value: The integer ID value to return for out-of-vocabulary feature + values, defaults to `-1`. This can not be specified with a positive + `num_oov_buckets`. + num_oov_buckets: Non-negative integer, the number of out-of-vocabulary + buckets. All out-of-vocabulary inputs will be assigned IDs in the range + `[len(vocabulary_list), len(vocabulary_list)+num_oov_buckets)` based on a + hash of the input value. A positive `num_oov_buckets` can not be specified + with `default_value`. + + Returns: + A `SequenceCategoricalColumn`. + + Raises: + ValueError: if `vocabulary_list` is empty, or contains duplicate keys. + ValueError: `num_oov_buckets` is a negative integer. + ValueError: `num_oov_buckets` and `default_value` are both specified. + ValueError: if `dtype` is not integer or string. + """ + return fc.SequenceCategoricalColumn( + fc.categorical_column_with_vocabulary_list( + key=key, + vocabulary_list=vocabulary_list, + dtype=dtype, + default_value=default_value, + num_oov_buckets=num_oov_buckets)) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('feature_column.sequence_numeric_column') +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def sequence_numeric_column(key, + shape=(1,), + default_value=0., + dtype=dtypes.float32, + normalizer_fn=None): + """Returns a feature column that represents sequences of numeric data. + + Example: + + ```python + temperature = sequence_numeric_column('temperature') + columns = [temperature] + + features = tf.io.parse_example(..., features=make_parse_example_spec(columns)) + sequence_feature_layer = SequenceFeatures(columns) + sequence_input, sequence_length = sequence_feature_layer(features) + sequence_length_mask = tf.sequence_mask(sequence_length) + + rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size) + rnn_layer = tf.keras.layers.RNN(rnn_cell) + outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask) + ``` + + Args: + key: A unique string identifying the input features. + shape: The shape of the input data per sequence id. E.g. if `shape=(2,)`, + each example must contain `2 * sequence_length` values. + default_value: A single value compatible with `dtype` that is used for + padding the sparse data into a dense `Tensor`. + dtype: The type of values. + normalizer_fn: If not `None`, a function that can be used to normalize the + value of the tensor after `default_value` is applied for parsing. + Normalizer function takes the input `Tensor` as its argument, and returns + the output `Tensor`. (e.g. lambda x: (x - 3.0) / 4.2). Please note that + even though the most common use case of this function is normalization, it + can be used for any kind of Tensorflow transformations. + + Returns: + A `SequenceNumericColumn`. + + Raises: + TypeError: if any dimension in shape is not an int. + ValueError: if any dimension in shape is not a positive integer. + ValueError: if `dtype` is not convertible to `tf.float32`. + """ + shape = fc._check_shape(shape=shape, key=key) + if not (dtype.is_integer or dtype.is_floating): + raise ValueError('dtype must be convertible to float. ' + 'dtype: {}, key: {}'.format(dtype, key)) + if normalizer_fn is not None and not callable(normalizer_fn): + raise TypeError( + 'normalizer_fn must be a callable. Given: {}'.format(normalizer_fn)) + + return SequenceNumericColumn( + key, + shape=shape, + default_value=default_value, + dtype=dtype, + normalizer_fn=normalizer_fn) + + +def _assert_all_equal_and_return(tensors, name=None): + """Asserts that all tensors are equal and returns the first one.""" + with ops.name_scope(name, 'assert_all_equal', values=tensors): + if len(tensors) == 1: + return tensors[0] + assert_equal_ops = [] + for t in tensors[1:]: + assert_equal_ops.append(check_ops.assert_equal(tensors[0], t)) + with ops.control_dependencies(assert_equal_ops): + return array_ops.identity(tensors[0]) + + +@serialization.register_feature_column +class SequenceNumericColumn( + fc.SequenceDenseColumn, + collections.namedtuple( + 'SequenceNumericColumn', + ('key', 'shape', 'default_value', 'dtype', 'normalizer_fn'))): + """Represents sequences of numeric data.""" + + @property + def _is_v2_column(self): + return True + + @property + def name(self): + """See `FeatureColumn` base class.""" + return self.key + + @property + def parse_example_spec(self): + """See `FeatureColumn` base class.""" + return {self.key: parsing_ops.VarLenFeature(self.dtype)} + + def transform_feature(self, transformation_cache, state_manager): + """See `FeatureColumn` base class. + + In this case, we apply the `normalizer_fn` to the input tensor. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + + Returns: + Normalized input tensor. + """ + input_tensor = transformation_cache.get(self.key, state_manager) + if self.normalizer_fn is not None: + input_tensor = self.normalizer_fn(input_tensor) + return input_tensor + + @property + def variable_shape(self): + """Returns a `TensorShape` representing the shape of sequence input.""" + return tensor_shape.TensorShape(self.shape) + + def get_sequence_dense_tensor(self, transformation_cache, state_manager): + """Returns a `TensorSequenceLengthPair`. + + Args: + transformation_cache: A `FeatureTransformationCache` object to access + features. + state_manager: A `StateManager` to create / access resources such as + lookup tables. + """ + sp_tensor = transformation_cache.get(self, state_manager) + dense_tensor = sparse_ops.sparse_tensor_to_dense( + sp_tensor, default_value=self.default_value) + # Reshape into [batch_size, T, variable_shape]. + dense_shape = array_ops.concat( + [array_ops.shape(dense_tensor)[:1], [-1], self.variable_shape], axis=0) + dense_tensor = array_ops.reshape(dense_tensor, shape=dense_shape) + + # Get the number of timesteps per example + # For the 2D case, the raw values are grouped according to num_elements; + # for the 3D case, the grouping happens in the third dimension, and + # sequence length is not affected. + if sp_tensor.shape.ndims == 2: + num_elements = self.variable_shape.num_elements() + else: + num_elements = 1 + seq_length = fc_utils.sequence_length_from_sparse_tensor( + sp_tensor, num_elements=num_elements) + + return fc.SequenceDenseColumn.TensorSequenceLengthPair( + dense_tensor=dense_tensor, sequence_length=seq_length) + + @property + def parents(self): + """See 'FeatureColumn` base class.""" + return [self.key] + + def get_config(self): + """See 'FeatureColumn` base class.""" + config = dict(zip(self._fields, self)) + config['dtype'] = self.dtype.name + return config + + @classmethod + def from_config(cls, config, custom_objects=None, columns_by_name=None): + """See 'FeatureColumn` base class.""" + fc._check_config_keys(config, cls._fields) + kwargs = fc._standardize_and_copy_config(config) + kwargs['dtype'] = dtypes.as_dtype(config['dtype']) + return cls(**kwargs) + + +# pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/serialization.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..88797d9f95d7b521f353213b11d2a713ec460d6a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/serialization.py @@ -0,0 +1,353 @@ +# 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. +# ============================================================================== +"""FeatureColumn serialization, deserialization logic.""" + +import six + +from tensorflow.python.feature_column import feature_column_v2_types as fc_types +from tensorflow.python.ops import init_ops +from tensorflow.python.util import deprecation +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +_FEATURE_COLUMN_DEPRECATION_WARNING = """\ + Warning: tf.feature_column is not recommended for new code. Instead, + feature preprocessing can be done directly using either [Keras preprocessing + layers](https://www.tensorflow.org/guide/migrate/migrating_feature_columns) + or through the one-stop utility [`tf.keras.utils.FeatureSpace`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/FeatureSpace) + built on top of them. See the [migration guide](https://tensorflow.org/guide/migrate) + for details. + """ + +_FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING = ( + 'Use Keras preprocessing layers instead, either directly or via the ' + '`tf.keras.utils.FeatureSpace` utility. Each of `tf.feature_column.*` has ' + 'a functional equivalent in `tf.keras.layers` for feature preprocessing ' + 'when training a Keras model.') + +_FEATURE_COLUMNS = [init_ops.TruncatedNormal] + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export( + '__internal__.feature_column.serialize_feature_column', + v1=[]) +@deprecation.deprecated(None, _FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNING) +def serialize_feature_column(fc): + """Serializes a FeatureColumn or a raw string key. + + This method should only be used to serialize parent FeatureColumns when + implementing FeatureColumn.get_config(), else serialize_feature_columns() + is preferable. + + This serialization also keeps information of the FeatureColumn class, so + deserialization is possible without knowing the class type. For example: + + a = numeric_column('x') + a.get_config() gives: + { + 'key': 'price', + 'shape': (1,), + 'default_value': None, + 'dtype': 'float32', + 'normalizer_fn': None + } + While serialize_feature_column(a) gives: + { + 'class_name': 'NumericColumn', + 'config': { + 'key': 'price', + 'shape': (1,), + 'default_value': None, + 'dtype': 'float32', + 'normalizer_fn': None + } + } + + Args: + fc: A FeatureColumn or raw feature key string. + + Returns: + Keras serialization for FeatureColumns, leaves string keys unaffected. + + Raises: + ValueError if called with input that is not string or FeatureColumn. + """ + if isinstance(fc, six.string_types): + return fc + elif isinstance(fc, fc_types.FeatureColumn): + return {'class_name': fc.__class__.__name__, 'config': fc.get_config()} + else: + raise ValueError('Instance: {} is not a FeatureColumn'.format(fc)) + + +@doc_controls.header(_FEATURE_COLUMN_DEPRECATION_WARNING) +@tf_export('__internal__.feature_column.deserialize_feature_column', v1=[]) +def deserialize_feature_column(config, + custom_objects=None, + columns_by_name=None): + """Deserializes a `config` generated with `serialize_feature_column`. + + This method should only be used to deserialize parent FeatureColumns when + implementing FeatureColumn.from_config(), else deserialize_feature_columns() + is preferable. Returns a FeatureColumn for this config. + + Args: + config: A Dict with the serialization of feature columns acquired by + `serialize_feature_column`, or a string representing a raw column. + custom_objects: A Dict from custom_object name to the associated keras + serializable objects (FeatureColumns, classes or functions). + columns_by_name: A Dict[String, FeatureColumn] of existing columns in order + to avoid duplication. + + Raises: + ValueError if `config` has invalid format (e.g: expected keys missing, + or refers to unknown classes). + + Returns: + A FeatureColumn corresponding to the input `config`. + """ + # TODO(b/118939620): Simplify code if Keras utils support object deduping. + if isinstance(config, six.string_types): + return config + # A dict from class_name to class for all FeatureColumns in this module. + # FeatureColumns not part of the module can be passed as custom_objects. + module_feature_column_classes = { + cls.__name__: cls for cls in _FEATURE_COLUMNS + } + if columns_by_name is None: + columns_by_name = {} + + (cls, cls_config) = _class_and_config_for_serialized_keras_object( + config, + module_objects=module_feature_column_classes, + custom_objects=custom_objects, + printable_module_name='feature_column_v2') + + if not issubclass(cls, fc_types.FeatureColumn): + raise ValueError( + 'Expected FeatureColumn class, instead found: {}'.format(cls)) + + # Always deserialize the FeatureColumn, in order to get the name. + new_instance = cls.from_config( # pylint: disable=protected-access + cls_config, + custom_objects=custom_objects, + columns_by_name=columns_by_name) + + # If the name already exists, re-use the column from columns_by_name, + # (new_instance remains unused). + return columns_by_name.setdefault( + _column_name_with_class_name(new_instance), new_instance) + + +def serialize_feature_columns(feature_columns): + """Serializes a list of FeatureColumns. + + Returns a list of Keras-style config dicts that represent the input + FeatureColumns and can be used with `deserialize_feature_columns` for + reconstructing the original columns. + + Args: + feature_columns: A list of FeatureColumns. + + Returns: + Keras serialization for the list of FeatureColumns. + + Raises: + ValueError if called with input that is not a list of FeatureColumns. + """ + return [serialize_feature_column(fc) for fc in feature_columns] + + +def deserialize_feature_columns(configs, custom_objects=None): + """Deserializes a list of FeatureColumns configs. + + Returns a list of FeatureColumns given a list of config dicts acquired by + `serialize_feature_columns`. + + Args: + configs: A list of Dicts with the serialization of feature columns acquired + by `serialize_feature_columns`. + custom_objects: A Dict from custom_object name to the associated keras + serializable objects (FeatureColumns, classes or functions). + + Returns: + FeatureColumn objects corresponding to the input configs. + + Raises: + ValueError if called with input that is not a list of FeatureColumns. + """ + columns_by_name = {} + return [ + deserialize_feature_column(c, custom_objects, columns_by_name) + for c in configs + ] + + +def _column_name_with_class_name(fc): + """Returns a unique name for the feature column used during deduping. + + Without this two FeatureColumns that have the same name and where + one wraps the other, such as an IndicatorColumn wrapping a + SequenceCategoricalColumn, will fail to deserialize because they will have the + same name in columns_by_name, causing the wrong column to be returned. + + Args: + fc: A FeatureColumn. + + Returns: + A unique name as a string. + """ + return fc.__class__.__name__ + ':' + fc.name + + +def _serialize_keras_object(instance): + """Serialize a Keras object into a JSON-compatible representation.""" + _, instance = tf_decorator.unwrap(instance) + if instance is None: + return None + + if hasattr(instance, 'get_config'): + name = instance.__class__.__name__ + config = instance.get_config() + serialization_config = {} + for key, item in config.items(): + if isinstance(item, six.string_types): + serialization_config[key] = item + continue + + # Any object of a different type needs to be converted to string or dict + # for serialization (e.g. custom functions, custom classes) + try: + serialized_item = _serialize_keras_object(item) + if isinstance(serialized_item, dict) and not isinstance(item, dict): + serialized_item['__passive_serialization__'] = True + serialization_config[key] = serialized_item + except ValueError: + serialization_config[key] = item + + return {'class_name': name, 'config': serialization_config} + if hasattr(instance, '__name__'): + return instance.__name__ + raise ValueError('Cannot serialize', instance) + + +def _deserialize_keras_object(identifier, + module_objects=None, + custom_objects=None, + printable_module_name='object'): + """Turns the serialized form of a Keras object back into an actual object.""" + if identifier is None: + return None + + if isinstance(identifier, dict): + # In this case we are dealing with a Keras config dictionary. + config = identifier + (cls, cls_config) = _class_and_config_for_serialized_keras_object( + config, module_objects, custom_objects, printable_module_name) + + if hasattr(cls, 'from_config'): + arg_spec = tf_inspect.getfullargspec(cls.from_config) + custom_objects = custom_objects or {} + + if 'custom_objects' in arg_spec.args: + return cls.from_config( + cls_config, custom_objects=dict(list(custom_objects.items()))) + return cls.from_config(cls_config) + else: + # Then `cls` may be a function returning a class. + # in this case by convention `config` holds + # the kwargs of the function. + custom_objects = custom_objects or {} + return cls(**cls_config) + elif isinstance(identifier, six.string_types): + object_name = identifier + if custom_objects and object_name in custom_objects: + obj = custom_objects.get(object_name) + else: + obj = module_objects.get(object_name) + if obj is None: + raise ValueError('Unknown ' + printable_module_name + ': ' + + object_name) + # Classes passed by name are instantiated with no args, functions are + # returned as-is. + if tf_inspect.isclass(obj): + return obj() + return obj + elif tf_inspect.isfunction(identifier): + # If a function has already been deserialized, return as is. + return identifier + else: + raise ValueError('Could not interpret serialized %s: %s' % + (printable_module_name, identifier)) + + +def _class_and_config_for_serialized_keras_object( + config, + module_objects=None, + custom_objects=None, + printable_module_name='object'): + """Returns the class name and config for a serialized keras object.""" + if (not isinstance(config, dict) or 'class_name' not in config or + 'config' not in config): + raise ValueError('Improper config format: ' + str(config)) + + class_name = config['class_name'] + cls = _get_registered_object( + class_name, custom_objects=custom_objects, module_objects=module_objects) + if cls is None: + raise ValueError('Unknown ' + printable_module_name + ': ' + class_name) + + cls_config = config['config'] + + deserialized_objects = {} + for key, item in cls_config.items(): + if isinstance(item, dict) and '__passive_serialization__' in item: + deserialized_objects[key] = _deserialize_keras_object( + item, + module_objects=module_objects, + custom_objects=custom_objects, + printable_module_name='config_item') + elif (isinstance(item, six.string_types) and + tf_inspect.isfunction(_get_registered_object(item, custom_objects))): + # Handle custom functions here. When saving functions, we only save the + # function's name as a string. If we find a matching string in the custom + # objects during deserialization, we convert the string back to the + # original function. + # Note that a potential issue is that a string field could have a naming + # conflict with a custom function name, but this should be a rare case. + # This issue does not occur if a string field has a naming conflict with + # a custom object, since the config of an object will always be a dict. + deserialized_objects[key] = _get_registered_object(item, custom_objects) + for key, item in deserialized_objects.items(): + cls_config[key] = deserialized_objects[key] + + return (cls, cls_config) + + +def _get_registered_object(name, custom_objects=None, module_objects=None): + if custom_objects and name in custom_objects: + return custom_objects[name] + elif module_objects and name in module_objects: + return module_objects[name] + return None + + +def register_feature_column(fc): + """Decorator that registers a FeatureColumn for serialization.""" + _FEATURE_COLUMNS.append(fc) + return fc diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..28cfc664e58a8eeea7c710d702bb55db5172da46 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/feature_column/utils.py @@ -0,0 +1,150 @@ +# 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 functions common to multiple feature column files.""" + +import six + +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.util import nest + + +def sequence_length_from_sparse_tensor(sp_tensor, num_elements=1): + """Returns a [batch_size] Tensor with per-example sequence length.""" + with ops.name_scope(None, 'sequence_length') as name_scope: + row_ids = sp_tensor.indices[:, 0] + column_ids = sp_tensor.indices[:, 1] + # Add one to convert column indices to element length + column_ids += array_ops.ones_like(column_ids) + # Get the number of elements we will have per example/row + seq_length = math_ops.segment_max(column_ids, segment_ids=row_ids) + + # The raw values are grouped according to num_elements; + # how many entities will we have after grouping? + # Example: orig tensor [[1, 2], [3]], col_ids = (0, 1, 1), + # row_ids = (0, 0, 1), seq_length = [2, 1]. If num_elements = 2, + # these will get grouped, and the final seq_length is [1, 1] + seq_length = math_ops.cast( + math_ops.ceil(seq_length / num_elements), dtypes.int64) + + # If the last n rows do not have ids, seq_length will have shape + # [batch_size - n]. Pad the remaining values with zeros. + n_pad = array_ops.shape(sp_tensor)[:1] - array_ops.shape(seq_length)[:1] + padding = array_ops.zeros(n_pad, dtype=seq_length.dtype) + return array_ops.concat([seq_length, padding], axis=0, name=name_scope) + + +def assert_string_or_int(dtype, prefix): + if (dtype != dtypes.string) and (not dtype.is_integer): + raise ValueError( + '{} dtype must be string or integer. dtype: {}.'.format(prefix, dtype)) + + +def assert_key_is_string(key): + if not isinstance(key, six.string_types): + raise ValueError( + 'key must be a string. Got: type {}. Given key: {}.'.format( + type(key), key)) + + +def check_default_value(shape, default_value, dtype, key): + """Returns default value as tuple if it's valid, otherwise raises errors. + + This function verifies that `default_value` is compatible with both `shape` + and `dtype`. If it is not compatible, it raises an error. If it is compatible, + it casts default_value to a tuple and returns it. `key` is used only + for error message. + + Args: + shape: An iterable of integers specifies the shape of the `Tensor`. + default_value: If a single value is provided, the same value will be applied + as the default value for every item. If an iterable of values is + provided, the shape of the `default_value` should be equal to the given + `shape`. + dtype: defines the type of values. Default value is `tf.float32`. Must be a + non-quantized, real integer or floating point type. + key: Column name, used only for error messages. + + Returns: + A tuple which will be used as default value. + + Raises: + TypeError: if `default_value` is an iterable but not compatible with `shape` + TypeError: if `default_value` is not compatible with `dtype`. + ValueError: if `dtype` is not convertible to `tf.float32`. + """ + if default_value is None: + return None + + if isinstance(default_value, int): + return _create_tuple(shape, default_value) + + if isinstance(default_value, float) and dtype.is_floating: + return _create_tuple(shape, default_value) + + if callable(getattr(default_value, 'tolist', None)): # Handles numpy arrays + default_value = default_value.tolist() + + if nest.is_nested(default_value): + if not _is_shape_and_default_value_compatible(default_value, shape): + raise ValueError( + 'The shape of default_value must be equal to given shape. ' + 'default_value: {}, shape: {}, key: {}'.format( + default_value, shape, key)) + # Check if the values in the list are all integers or are convertible to + # floats. + is_list_all_int = all( + isinstance(v, int) for v in nest.flatten(default_value)) + is_list_has_float = any( + isinstance(v, float) for v in nest.flatten(default_value)) + if is_list_all_int: + return _as_tuple(default_value) + if is_list_has_float and dtype.is_floating: + return _as_tuple(default_value) + raise TypeError('default_value must be compatible with dtype. ' + 'default_value: {}, dtype: {}, key: {}'.format( + default_value, dtype, key)) + + +def _create_tuple(shape, value): + """Returns a tuple with given shape and filled with value.""" + if shape: + return tuple([_create_tuple(shape[1:], value) for _ in range(shape[0])]) + return value + + +def _as_tuple(value): + if not nest.is_nested(value): + return value + return tuple([_as_tuple(v) for v in value]) + + +def _is_shape_and_default_value_compatible(default_value, shape): + """Verifies compatibility of shape and default_value.""" + # Invalid condition: + # * if default_value is not a scalar and shape is empty + # * or if default_value is an iterable and shape is not empty + if nest.is_nested(default_value) != bool(shape): + return False + if not shape: + return True + if len(default_value) != shape[0]: + return False + for i in range(shape[0]): + if not _is_shape_and_default_value_compatible(default_value[i], shape[1:]): + return False + return True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/flags_pybind.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/flags_pybind.pyi new file mode 100644 index 0000000000000000000000000000000000000000..90aa0a7d76114b2bd2e5f125423af303e78ca245 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/flags_pybind.pyi @@ -0,0 +1,32 @@ +# 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. +# ============================================================================== + +class Flag: + def __init__(self, *args, **kwargs) -> None: ... + def reset(self, arg0: bool) -> None: ... + def value(self) -> bool: ... + +class Flags: + enable_nested_function_shape_inference: Flag + enable_quantized_dtypes_training: Flag + graph_building_optimization: Flag + more_stack_traces: Flag + op_building_optimization: Flag + replicate_small_constants: Flag + saved_model_fingerprinting: Flag + test_only_experiment_1: Flag + test_only_experiment_2: Flag + tf_shape_default_int64: Flag + def __init__(self) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_dtypes.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_dtypes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b3514b9ea55bb643738423730120526bfb0c333e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_dtypes.pyi @@ -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. +# ============================================================================== + +class DType: + def __init__(self, arg0: object) -> None: ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + @property + def _type_enum(self) -> int: ... + @property + def as_datatype_enum(self) -> int: ... + @property + def is_bool(self) -> bool: ... + @property + def is_complex(self) -> bool: ... + @property + def is_floating(self) -> bool: ... + @property + def is_integer(self) -> bool: ... + @property + def is_numeric(self) -> bool: ... + @property + def is_numpy_compatible(self) -> bool: ... + @property + def is_quantized(self) -> bool: ... + @property + def is_unsigned(self) -> bool: ... + @property + def name(self) -> str: ... + @property + def size(self) -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_errors_test_helper.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_errors_test_helper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..07166dca5034eefa2d00672668f5273d46f4e4d3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_errors_test_helper.pyi @@ -0,0 +1,17 @@ +# 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. +# ============================================================================== + +def TestRaiseFromStatus(arg0: int) -> int: ... +def TestRaiseFromTFStatus(arg0: int) -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_op_def_library_pybind.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_op_def_library_pybind.pyi new file mode 100644 index 0000000000000000000000000000000000000000..625dc6fc2a04bb9e4c549008428dccfba99e544d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_op_def_library_pybind.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def process_inputs(arg0: str, arg1: int, arg2: dict) -> tuple: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_op_def_registry.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_op_def_registry.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9326a378934bb2dbbbff717b180b1d4e4efa33e4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_op_def_registry.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def get(arg0: str) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_proto_comparators.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_proto_comparators.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8ca7ab03551be56b3a1364b82cadcfaa6c970dda --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_proto_comparators.pyi @@ -0,0 +1,19 @@ +# 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. +# ============================================================================== + +class ProtoComparisonOptions: + def __init__(self, arg0: bool) -> None: ... + +def EqualsGraphDef(arg0: str, arg1: str, arg2: ProtoComparisonOptions) -> bool: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_python_memory_checker_helper.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_python_memory_checker_helper.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e8ce979c9398ae2a2d98f3706679e5aed3d04fce --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_python_memory_checker_helper.pyi @@ -0,0 +1,18 @@ +# 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. +# ============================================================================== + +from typing import Callable + +def mark_stack_trace_and_call(arg0: Callable) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_dispatcher.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_dispatcher.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b4451d9e8c926bebcac07bb19c453adc1f5b7d8f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_dispatcher.pyi @@ -0,0 +1,60 @@ +# 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. +# ============================================================================== + +from typing import ClassVar + +MATCH: MatchType +MATCH_DISPATCHABLE: MatchType +NO_MATCH: MatchType + +class MatchType: + __members__: ClassVar[dict] = ... # read-only + MATCH: ClassVar[MatchType] = ... + MATCH_DISPATCHABLE: ClassVar[MatchType] = ... + NO_MATCH: ClassVar[MatchType] = ... + __entries: ClassVar[dict] = ... + def __init__(self, value: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __setstate__(self, state: int) -> None: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + +class PySignatureChecker: + def __init__(self, arg0: list[tuple[int,PyTypeChecker]]) -> None: ... + def CheckCanonicalizedArgs(self, arg0: tuple) -> bool: ... + +class PyTypeChecker: + def __init__(self, *args, **kwargs) -> None: ... + def Check(self, arg0: object) -> MatchType: ... + def cache_size(self) -> int: ... + def cost(self) -> int: ... + +class PythonAPIDispatcher: + def __init__(self, arg0: str, arg1: list[str], arg2: object) -> None: ... + def Dispatch(self, arg0: object, arg1: object) -> object: ... + def Register(self, arg0: PySignatureChecker, arg1: object) -> None: ... + def Unregister(self, arg0: object) -> None: ... + +def MakeInstanceChecker(*args) -> PyTypeChecker: ... +def MakeListChecker(arg0: PyTypeChecker) -> PyTypeChecker: ... +def MakeUnionChecker(arg0: list[PyTypeChecker]) -> PyTypeChecker: ... +def register_dispatchable_type(arg0: object) -> object: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_info.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_info.pyi new file mode 100644 index 0000000000000000000000000000000000000000..e64b364a5d970cb3fc3b195714b3ded9cc6dfef9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_info.pyi @@ -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. +# ============================================================================== + +from typing import Any + +class InferredAttributes: + def __init__(self, *args, **kwargs) -> None: ... + @property + def lengths(self) -> list[int]: ... + @property + def type_lists(self) -> Any: ... + @property + def types(self) -> Any: ... + +class PythonAPIInfo: + def __init__(self, arg0: str) -> None: ... + def DebugInfo(self) -> str: ... + def InferredLengthAttrs(self) -> list[str]: ... + def InferredTypeAttrs(self) -> list[str]: ... + def InferredTypeListAttrs(self) -> list[str]: ... + def InitializeFromParamSpecs(self, arg0: dict[str,str], arg1: dict[str,str], arg2: list[str], arg3: object) -> None: ... + def InitializeFromRegisteredOp(self, arg0: str) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_parameter_converter.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_parameter_converter.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7f5cf048c43669105d3002963d4d1db1564bffe6 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_api_parameter_converter.pyi @@ -0,0 +1,18 @@ +# 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. +# ============================================================================== + +from typing import Any + +def Convert(*args, **kwargs) -> Any: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_op_gen.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_op_gen.pyi new file mode 100644 index 0000000000000000000000000000000000000000..1099ad8f42050f03600addef212e29611b095cc9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_pywrap_python_op_gen.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def GetPythonWrappers(arg0: bytes) -> bytes: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_test_metrics_util.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_test_metrics_util.pyi new file mode 100644 index 0000000000000000000000000000000000000000..32d9a3fe47c565e18bf51f4b479bb3e220bcf31f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/_test_metrics_util.pyi @@ -0,0 +1,16 @@ +# 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. +# ============================================================================== + +def test_counter_value(arg0: str, arg1: str) -> int: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/auto_control_deps.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/auto_control_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..9a23b038dd0e241003efa6979bab2f5b126d9d01 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/auto_control_deps.py @@ -0,0 +1,651 @@ +# 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. +# ============================================================================== +"""AutomaticControlDependencies and related functionality.""" + +import collections +import enum + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import auto_control_deps_utils as utils +from tensorflow.python.framework import dtypes as dtypes_module +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.framework import registry +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_decorator + +# LINT.IfChange +# Op types that should not run in program order, e.g. because they need to run +# asynchronously to avoid deadlock. + +ASYNC_STATEFUL_OPS = frozenset(( + "CollectiveGather", + "CollectiveReduce", + "CollectiveBcastSend", + "CollectiveBcastSendV2", + "CollectiveBcastRecv", + "CollectiveBcastRecvV2", + "NcclAllReduce", + # We do not add "Send" here since we want it to be added as a control output + # in order to avoid being pruned. + "Recv", + "CollectiveInitializeCommunicator", + "CollectiveAssignGroupV2", +)) + +LEGACY_RANDOM_OPS = frozenset(( + # These may be used in variable initializers -- thus their execution should + # not be dependent on other stateful operations. This is because although + # according to program order, tf.Variables may be created in sequence, + # their initialization happens outside of the program order (specifically, + # in graph mode their initialization happens by calling a grouped + # initializer operation or in eager mode, where initialization is lifted + # out of the tf.function and executed the first time the function is + # executed). + # + # Unless there is a specific dependency between the initializers + # themselves (e.g. one initializer depends on a Variable whose value depends + # on another initializer), the initialization can happen in any order so + # long as it's before the associated Variable read operations. + # + # Note that in general the randomness of legacy random operations is only + # guaranteed by providing a graph-level and op-level seed (and ordering of + # the same op across multiple iterations of a while_loop is specifically not + # guaranteed; see the discussion below). + # + # There is a possible race condition inside while_loop where the same + # random OpKernel instantiation is reused across multiple steps + # of the loop. Since legacy Random OpKernels have an internal rng state, + # automatic dependency tracking across loop steps would likely + # fix this race; and for that case this denylist is problematic. + # However, since automatic dependency tracking inside while loops is not + # currently supported, and there are no other examples of OpKernel reuse + # (each OpKernel is associated with a unique op in graph mode), + # this denylist has no effect on the aforementioned behavior. + # + # TODO(ebrevdo,skyewm): Modify the check against this denylist to + # only occur when the op is inside a "variable initialization scope"; and + # add proper autodeps inside while_loops that respects this updated check. + "RandomUniform", + "RandomUniformInt", + "RandomStandardNormal", + "ParameterizedTruncatedNormal", + "TruncatedNormal", + "RandomShuffle", + "Multinomial", + "RandomGamma", + "RandomGammaGrad", + "RandomPoisson", + "RandomPoissonV2", +)) + +MUST_RUN_ORDER_INSENSITIVE_STATEFUL_OPS = frozenset(( + "InfeedEnqueue", + "InfeedEnqueueTuple", + "EnqueueTPUEmbeddingSparseBatch", + "EnqueueTPUEmbeddingIntegerBatch", + "EnqueueTPUEmbeddingSparseTensorBatch", + "EnqueueTPUEmbeddingRaggedTensorBatch", + "EnqueueTPUEmbeddingArbitraryTensorBatch", + "DynamicEnqueueTPUEmbeddingArbitraryTensorBatch", +)) + +# These ops are order-insensitive ans should in theory run, but at the moment +# they either always have the necessary data dependencies, or have workarounds +# in existing code that would break when adding new control deps. This +# inconsistency should be eventually fixed, but it would be more effective to +# retire the list instead. +SKIPPED_ORDER_INSENSITIVE_STATEFUL_OPS = frozenset(( + "CudnnRNN", + "CudnnRNNBackprop", + "CudnnRNNV2", + "CudnnRNNV3", + "CudnnRNNBackpropV2", + "CudnnRNNBackpropV3", + "RestoreV2", + "SaveV2", +)) +# LINT.ThenChange(//tensorflow/core/grappler/optimizers/function_optimizer.cc) + +# Op types that are marked as stateless, but should be allowlisted to add auto +# control dependencies. +_ALLOWLIST_STATELESS_OPS = [ + # As TPU collective ops are blocking, if there are more than one collective + # op in the function, we need to make sure different collectives ops are + # scheduled in certain orders. Otherwise if at the same time all the + # replicas are launching different collective ops/programs, it may cause + # deadlock. + "AllToAll", + "CrossReplicaSum", + "CollectivePermute", +] + + +def op_is_stateful(op): + # pylint: disable=protected-access + ret = ((op._is_stateful and + ((op.type not in ASYNC_STATEFUL_OPS) and + (op.type not in LEGACY_RANDOM_OPS) and + (op.type not in SKIPPED_ORDER_INSENSITIVE_STATEFUL_OPS))) or + (op.type in _ALLOWLIST_STATELESS_OPS)) + return ret + + +class ResourceType(enum.Enum): + READ_ONLY = "read-only" + READ_WRITE = "read-write" + + +def collective_manager_ids_from_op(op): + """Returns CollectiveManager ID from the op if one exists, else None. + + CollectiveManager adds collective and no_op operations tagged with an ID, + unique to the manager object. This function extracts that ID, or None, if the + node was not generated by a CollectiveManager. + + Args: + op: `Operation` to get the collective manager ID from. + + Returns: + List of CollectiveManager IDs used by the op. + """ + if op.type == "CollectiveReduce": + try: + return [op.get_attr("_collective_manager_id")] + except ValueError: + pass + elif op.type == "StatefulPartitionedCall": + try: + return op.get_attr(utils.COLLECTIVE_MANAGER_IDS) + except ValueError: + pass + return [] + + +class AutomaticControlDependencies(object): + """Context manager to automatically add control dependencies. + + Code under this context manager will act as if a sensible set of control + dependencies were present. More specifically: + 1. All stateful ops in the scope will execute (with the exception of ops in + ASYNC_STATEFUL_OPS and LEGACY_RANDOM_OPS) + 2. Stateful ops which modify the same resource will execute in program order + + Note: creating variables in an automatic control dependencies context is not + supported (the value of the variables will never change as they will keep + getting reinitialized). + + NOT THREAD SAFE + """ + + def __init__(self): + self._returned_tensors = object_identity.ObjectIdentitySet() + self.ops_which_must_run = set() + self._independent_ops = [] + + def mark_as_return(self, tensor): + """Acts like identity but marks the `Tensor` as a return value. + + This will possibly return a copy of the `Tensor`. Usage: + + ``` + with AutomaticControlDependencies() as a: + ... + t = a.mark_as_return(t) + _ = ...(t...) # i.e. it's safe to use t here + ``` + + Args: + tensor: the `Tensor` to be marked + + Returns: + a copy of the `Tensor`. + """ + if isinstance(tensor, indexed_slices.IndexedSlices): + values = array_ops.identity(tensor.values) + indices = array_ops.identity(tensor.indices) + self._returned_tensors.add(indices) + self._returned_tensors.add(values) + return indexed_slices.IndexedSlices( + values, indices, dense_shape=tensor.dense_shape) + elif isinstance(tensor, sparse_tensor.SparseTensor): + values = array_ops.identity(tensor.values) + indices = array_ops.identity(tensor.indices) + self._returned_tensors.add(indices) + self._returned_tensors.add(values) + return sparse_tensor.SparseTensor( + indices, values, dense_shape=tensor.dense_shape) + elif isinstance(tensor, tensor_array_ops.TensorArray): + flow = array_ops.identity(tensor.flow) + self._returned_tensors.add(flow) + return tensor_array_ops.build_ta_with_new_flow(tensor, flow) + # We want to make the return values depend on the stateful operations, but + # we don't want to introduce a cycle, so we make the return value the result + # of a new identity operation that the stateful operations definitely don't + # depend on. + tensor = array_ops.identity(tensor) + self._returned_tensors.add(tensor) + return tensor + + def run_independently(self, op): + """Marks the given op as independent. + + Overrides any other rule for the op. + + Independent ops are guaranteed to execute before the return values, but + are allowed to run in parallel with everything else. Use in programs which + can guarantee that an op has side effects that don't affect any other op. + + Args: + op: An operation + """ + self._independent_ops.append(op) + op._set_attr("_independent_side_effects", attr_value_pb2.AttrValue(b=True)) # pylint: disable=protected-access + + def __enter__(self): + if context.executing_eagerly(): + return self + # This code assumes no other thread is adding ops to the graph while + # we're adding ops to the graph. + # TODO(apassos): Fix this by locking the graph or using a temporary + # graph (but that would mess up devices and collections at least, + # probably other things as well). + g = ops.get_default_graph() + self._graph = g + g._add_control_dependencies = True # pylint: disable=protected-access + g.experimental_acd_manager = self + self._n_operations = g.num_operations() + return self + + def _process_switch(self, switch_op, ops_which_must_run, + last_write_to_resource, merge_for_resource): + """Processes a switch node for a resource input. + + When tensorflow creates a cond, it creates a control flow context for each + branch of the cond. Each external tensor accessed by that branch is routed + through a switch op, which gets created in the graph _after_ the op which + uses that tensor get created. + + If the resource comes from another switch op we process that one first. + + _process_switch creates a corresponding merge node for the switch node. This + merge node is added to the outer control flow context of the switch + node. We also ensure that: + + 1. The switch node executes after the previous op which used the resource + tensor + + 2. Any op which uses a resource output of the switch node executes before + the merge for the switch node. + + 3. The next op which uses the input resource to the switch node (which + might be another switch node for the other branch of the conditional) + will execute after the merge node is done. + + 4. The merge node is marked as must_run so it will run even if no + subsequent operation uses the resource. + + Args: + switch_op: the switch op to be processed + ops_which_must_run: the set of ops which must run + last_write_to_resource: map from resource tensor to last op updating + it + merge_for_resource: map from resource tensor to merge which must follow + all usages of it. + """ + # pylint: disable=protected-access + inp = switch_op.inputs[0] + input_id = ops.tensor_id(inp) + if inp.dtype == dtypes_module.resource and inp.op.type == "Switch": + self._process_switch(inp.op, ops_which_must_run, last_write_to_resource, + merge_for_resource) + output = switch_op.outputs[0] + output_id = ops.tensor_id(output) + if output_id in merge_for_resource: + return + new_merge = control_flow_ops.merge( + switch_op.outputs, name="artificial_merge") + new_merge[0].op._control_flow_context = ( + switch_op._control_flow_context.outer_context) + # Ensures the merge always runs + ops_which_must_run.add(new_merge[0].op) + if input_id in last_write_to_resource: + # Ensures the switch executes after the previous op using the resource. + switch_op._add_control_input(last_write_to_resource[input_id]) + # Ensure the next op outside the cond happens after the merge. + last_write_to_resource[input_id] = new_merge[0].op + if input_id in merge_for_resource: + merge_for_resource[input_id]._add_control_input(new_merge[0].op) + for o in switch_op.outputs: + # Ensures the merge will execute after all ops inside the cond + merge_for_resource[ops.tensor_id(o)] = new_merge[0].op + + def __exit__(self, unused_type, unused_value, unused_traceback): + # pylint: disable=protected-access + if context.executing_eagerly(): + return + + if self._graph is not ops.get_default_graph(): + raise RuntimeError( + "Within the automatic control dependency context, the default graph" + f" cannot change. Upon entry it was {self._graph}, but on exit it" + f" changed to {ops.get_default_graph()}") + + outer_graph = getattr(self._graph, "outer_graph", None) + if outer_graph is not None: + self._graph._add_control_dependencies = outer_graph._add_control_dependencies + else: + self._graph._add_control_dependencies = False + self._graph.experimental_acd_manager = None + + # map from resource tensor to the last op which wrote to it + last_write_to_resource = {} + # map from resource tensor to the list of reads from it since the last + # write or since the beginning of the function. + reads_since_last_write_to_resource = collections.defaultdict(list) + # CollectiveManager manager_ids within a particular function call should not + # be needed outside of that function call. So we keep them separate (though + # the general idea of the maps is the same, in the future, we'll need to + # correctly thread the control output outside). + # Map from collective manager scope to the last op which used it + collective_manager_scopes_opened = {} + collective_manager_scopes_used = {} + # set of conditional and loop exits + ops_which_must_run = set() + # merge which must depend on ops which use this resource + merge_for_resource = {} + + new_operations = self._graph.get_operations()[self._n_operations:] + + # Ensures that uses of resource tensors get serialized properly and all + # execute. This is done by keeping a map from resource tensor to the last op + # in graph-construction order which used it (last_write_to_resource). + # + # Conditionals are written in TensorFlow such that every external tensor + # accessed in the conditional goes through a switch op and every return + # tensor (it's guaranteed that there will be at least one) goes through a + # merge op. + # + # To handle conditionals, switches are handled in a special way (see + # comments for _process_switch). Merge nodes created by TF's conditional + # logic (as opposed to by _process_switch) are forced to run and also get a + # control dependency added to them to ensure all stateful ops inside their + # control flow context run. + # + # We also ensure that if an op is using a resource output by a switch node + # (that is, a resource tensor for which there's a value in + # merge_for_resource) this op will run before the merge for that resource. + # + # We try to add control inputs to nodes respecting their control flow + # contexts to avoid dead nodes propagating everywhere and leading to + # "retval[0] doesn't have value" errors. If a node gets a control dependency + # on a dead node (i.e. a note from an untaken control flow branch) that node + # will be marked as dead unless it's a merge node. + # + # TODO(apassos): serialize non-resource-taking stateful ops as well, and + # test that it works. Support while loops. Support init_scope escaping from + # this. + for op in new_operations: + # TODO(apassos) make this code safely support while loops. + if control_flow_util.IsInWhileLoop(op): + continue + control_inputs = set() + + if op.type in MUST_RUN_ORDER_INSENSITIVE_STATEFUL_OPS: + # This will add it to self._independent_ops, but also mark it with an + # attribute. + self.run_independently(op) + + if op in self._independent_ops: + ops_which_must_run.add(op) + continue + + # Ensure stateful ops run. + # Read-only ops are added to control outputs if the read value is + # consumed. This covers the case when the read value is returned from + # the function since that goes through a tf.identity in mark_as_return. + if ((op_def_registry.get(op.type) is None) or + (op_is_stateful(op) and + (op.type not in utils.RESOURCE_READ_OPS or + any(output.consumers() for output in op.outputs)))): + ops_which_must_run.add(op) + + # Make a note of all opened manager_ids. + if op.type == "NoOp": + try: + collective_manager_scopes_opened[op.get_attr( + "_collective_manager_id")] = op + except ValueError: + pass + # Ignore switches (they're handled separately) + if op.type == "Switch" and op.inputs[0].dtype == dtypes_module.resource: + continue + # Make merges trigger all other computation which must run + # TODO(mdan): Don't do this. Write a transform to chains instead. + # See core/common_runtime/control_flow_deps_to_chains.cc. + if op.type == "Merge": + for o in ops_which_must_run: + op._add_control_input(o) + for inp in o.inputs: + input_id = ops.tensor_id(inp) + if input_id in last_write_to_resource: + last_write_to_resource[input_id] = op + ops_which_must_run = set([op]) + continue + + resource_inputs = set() + # Check for any resource inputs. If we find any, we update control_inputs + # and last_write_to_resource. + for inp, resource_type in _get_resource_inputs(op): + is_read = resource_type == ResourceType.READ_ONLY + input_id = ops.tensor_id(inp) + + # If the op receives the same resource tensor twice as an input, we skip + # to avoid the op getting a control dependency on itself. + if input_id in resource_inputs: + continue + + resource_inputs.add(input_id) + # Deal with switches, finally. + if inp.op.type == "Switch": + self._process_switch(inp.op, ops_which_must_run, + last_write_to_resource, merge_for_resource) + is_building_function = op.graph.building_function + # Ensure uses of resources are serialized + if input_id in last_write_to_resource: + if is_building_function or ( + last_write_to_resource[input_id]._control_flow_context + is op._control_flow_context): + control_inputs.add(last_write_to_resource[input_id]) + # Ensure merges happen after the closing of a cond block + if input_id in merge_for_resource: + merge_for_resource[input_id]._add_control_input(op) + if is_read: + reads_since_last_write_to_resource[input_id].append(op) + else: + control_inputs.update(reads_since_last_write_to_resource[input_id]) + reads_since_last_write_to_resource[input_id] = [] + last_write_to_resource[input_id] = op + + if (op_is_stateful(op) and not resource_inputs + and op._control_flow_context is None): + if None in last_write_to_resource: + op._add_control_input(last_write_to_resource[None]) + last_write_to_resource[None] = op + + # Ensure ordering of collective ops + manager_ids = collective_manager_ids_from_op(op) + for manager_id in manager_ids: + if manager_id in collective_manager_scopes_opened: + # Chain this function call if the scope was opened. + op._add_control_input(collective_manager_scopes_opened[manager_id]) + collective_manager_scopes_opened[manager_id] = op + else: + # If this op is in a scope not created here, create a chain starting + # at this op. + if manager_id in collective_manager_scopes_used: + op._add_control_input(collective_manager_scopes_used[manager_id]) + collective_manager_scopes_used[manager_id] = op + + if control_inputs and not is_building_function: + control_inputs = [ + c for c in control_inputs + if c._control_flow_context is op._control_flow_context + ] + + op._add_control_inputs(control_inputs) + + # Ensure all ops which must run do run + self.ops_which_must_run.update(ops_which_must_run) + + control_output_op = None + for idx, r in enumerate( + nest.flatten(list(self._returned_tensors), expand_composites=True)): + if self.ops_which_must_run: + updated_ops_which_must_run = [] + if r.graph.building_function: + # There may be many stateful ops in the graph. Adding them as + # control inputs to each function output could create excessive + # control edges in the graph. Thus we create an intermediate No-op to + # chain the control dependencies between stateful ops and function + # outputs. + if idx == 0: + control_output_op = control_flow_ops.no_op() + control_output_op._add_control_inputs(self.ops_which_must_run) + updated_ops_which_must_run = [control_output_op] + else: + updated_ops_which_must_run = [ + o for o in self.ops_which_must_run + if o._control_flow_context is r.op._control_flow_context + ] + r.op._add_control_inputs(updated_ops_which_must_run) + + self.collective_manager_ids_used = collective_manager_scopes_used + + +_acd_resource_resolvers_registry = registry.Registry("acd_resource_resolvers") + + +def register_acd_resource_resolver(f): + """Register a function for resolving resources touched by an op. + + `f` is called for every Operation added in the ACD context with the op's + original resource reads and writes. `f` is expected to update the sets of + resource reads and writes in-place and return True if it updated either of the + sets, False otherwise. + + Example: + @register_acd_resource_resolver + def identity_resolver(op, resource_reads, resource_writes): + # op: The `Operation` being processed by ACD currently. + # resource_reads: An `ObjectIdentitySet` of read-only resources. + # resource_writes: An `ObjectIdentitySet` of read-write resources. + def update(resource_inputs): + to_remove = [] + to_add = [] + for resource in resource_inputs: + if resource.op.type == "Identity": + to_remove.append(resource) + to_add.extend(resource.op.inputs) + for t in to_remove: + resource_inputs.discard(t) + resource_inputs.update(to_add) + return to_add or to_remove + return update(resource_reads) or update(resource_writes) + + Args: + f: Python function with signature + (Operation, ObjectIdentitySet, ObjectIdentitySet) -> bool + + Returns: + The function `f` after adding it to the registry. + """ + _acd_resource_resolvers_registry.register(f) + return f + + +@register_acd_resource_resolver +def _identity_resolver(op, resource_reads, resource_writes): + """Replaces Identity output with its input in resource_inputs.""" + del op + def update(resource_inputs): + to_remove = [] + to_add = [] + for resource in resource_inputs: + if resource.op.type == "Identity": + to_remove.append(resource) + to_add.extend(resource.op.inputs) + for t in to_remove: + resource_inputs.discard(t) + resource_inputs.update(to_add) + return to_add or to_remove + + return update(resource_reads) or update(resource_writes) + + +def _get_resource_inputs(op): + """Returns an iterable of resources touched by this `op`.""" + reads, writes = utils.get_read_write_resource_inputs(op) + saturated = False + while not saturated: + saturated = True + for key in _acd_resource_resolvers_registry.list(): + # Resolvers should return true if they are updating the list of + # resource_inputs. + # TODO(srbs): An alternate would be to just compare the old and new set + # but that may not be as fast. + updated = _acd_resource_resolvers_registry.lookup(key)(op, reads, writes) + if updated: + # Conservatively remove any resources from `reads` that are also writes. + reads = reads.difference(writes) + saturated = saturated and not updated + + # Note: A resource handle that is not written to is treated as read-only. We + # don't have a special way of denoting an unused resource. + for t in reads: + yield (t, ResourceType.READ_ONLY) + for t in writes: + yield (t, ResourceType.READ_WRITE) + + +def automatic_control_dependencies(f): + """Wraps f to automatically insert control dependencies. + + The inserted dependencies ensure that: + 1. All stateful ops in f run when the result of f runs + 2. Updates to the same resources happen in order. + + Args: + f: the function to be wrapped. + + Returns: + The wrapped function. + """ + + def wrapper(*args, **kwargs): + with AutomaticControlDependencies() as a: + result = f(*args, **kwargs) + result_flat = [a.mark_as_return(t) for t in nest.flatten(result)] + return nest.pack_sequence_as(result, result_flat) + + return tf_decorator.make_decorator(f, wrapper) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/auto_control_deps_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/auto_control_deps_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e66a96783efbf5769217aedd8e68083aa769a650 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/auto_control_deps_utils.py @@ -0,0 +1,168 @@ +# 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. +# ============================================================================== +"""Utilities for AutomaticControlDependencies.""" + +from tensorflow.python.framework import dtypes +from tensorflow.python.util import object_identity + +READ_ONLY_RESOURCE_INPUTS_ATTR = "_read_only_resource_inputs" +RESOURCE_READ_OPS = set() + + +COLLECTIVE_MANAGER_IDS = "_collective_manager_ids" + + +def register_read_only_resource_op(op_type): + """Declares that `op_type` does not update its touched resource.""" + RESOURCE_READ_OPS.add(op_type) + + +def get_read_only_resource_input_indices_graph(func_graph): + """Returns sorted list of read-only resource indices in func_graph.inputs.""" + result = [] + # A cache to store the read only resource inputs of an Op. + # Operation -> ObjectIdentitySet of resource handles. + op_read_only_resource_inputs = {} + for input_index, t in enumerate(func_graph.inputs): + if t.dtype != dtypes.resource: + continue + read_only = True + for op in t.consumers(): + if op in op_read_only_resource_inputs: + if t not in op_read_only_resource_inputs[op]: + read_only = False + break + else: + indices = _get_read_only_resource_input_indices_op(op) + op_read_only_resource_inputs[op] = object_identity.ObjectIdentitySet( + [op.inputs[i] for i in indices]) + if t not in op_read_only_resource_inputs[op]: + read_only = False + break + if read_only: + result.append(input_index) + return result + + +def _get_read_only_resource_input_indices_op(op): + """Returns sorted list of read-only resource indices in op.inputs.""" + if op.type in RESOURCE_READ_OPS: + return [i for i, t in enumerate(op.inputs) if t.dtype == dtypes.resource] + + try: + read_only_input_indices = op.get_attr(READ_ONLY_RESOURCE_INPUTS_ATTR) + except ValueError: + # Attr was not set. Add all resource inputs to `writes` and return. + return [] + + read_only_index = 0 + result = [] + for i, t in enumerate(op.inputs): + if read_only_index >= len(read_only_input_indices): + break + if op.inputs[i].dtype != dtypes.resource: + continue + if (read_only_index < len(read_only_input_indices) and + i == read_only_input_indices[read_only_index]): + result.append(i) + read_only_index += 1 + + return result + + +def get_read_write_resource_inputs(op): + """Returns a tuple of resource reads, writes in op.inputs. + + Args: + op: Operation + + Returns: + A 2-tuple of ObjectIdentitySets, the first entry containing read-only + resource handles and the second containing read-write resource handles in + `op.inputs`. + """ + reads = object_identity.ObjectIdentitySet() + writes = object_identity.ObjectIdentitySet() + + if op.type in RESOURCE_READ_OPS: + # Add all resource inputs to `reads` and return. + reads.update(t for t in op.inputs if t.dtype == dtypes.resource) + return (reads, writes) + + try: + read_only_input_indices = op.get_attr(READ_ONLY_RESOURCE_INPUTS_ATTR) + except ValueError: + # Attr was not set. Add all resource inputs to `writes` and return. + writes.update(t for t in op.inputs if t.dtype == dtypes.resource) + return (reads, writes) + + read_only_index = 0 + for i, t in enumerate(op.inputs): + if op.inputs[i].dtype != dtypes.resource: + continue + if (read_only_index < len(read_only_input_indices) and + i == read_only_input_indices[read_only_index]): + reads.add(op.inputs[i]) + read_only_index += 1 + else: + writes.add(op.inputs[i]) + return (reads, writes) + + +def _op_writes_to_resource(handle, op): + """Returns whether op writes to resource handle. + + Args: + handle: Resource handle. Must be an input of `op`. + op: Operation. + + Returns: + Returns False if op is a read-only op registered using + `register_read_only_resource_op` or if `handle` is an input at one of + the indices in the `READ_ONLY_RESOURCE_INPUTS_ATTR` attr of the op, True + otherwise. + + Raises: + ValueError: if `handle` is not an input of `op`. + """ + if op.type in RESOURCE_READ_OPS: + return False + input_index = _input_index(op, handle) + try: + read_only_input_indices = op.get_attr(READ_ONLY_RESOURCE_INPUTS_ATTR) + except ValueError: + # Attr was not set. Conservatively assume that the resource is written to. + return True + return input_index not in read_only_input_indices + + +def _input_index(op, handle): + """Returns the index of `handle` in `op.inputs`. + + Args: + op: Operation. + handle: Resource handle. + + Returns: + Index in `op.inputs` receiving the resource `handle`. + + Raises: + ValueError: If handle and its replicated input are both not found in + `op.inputs`. + """ + for i, t in enumerate(op.inputs): + if handle is t: + return i + raise ValueError(f"{handle!s} not in list of inputs for op: {op!r}") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/byte_swap_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/byte_swap_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..432744c89bd3d9b66a631a6b35a306765af244bf --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/byte_swap_tensor.py @@ -0,0 +1,103 @@ +# 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. +# ============================================================================== + +"""Utilities for byte swapping the tensor content.""" + +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.python.framework import dtypes + +# Based on tensor_bundle/byte_swap.cc +byte_swappable = [ + dtypes.float16, + dtypes.float32, + dtypes.float64, + dtypes.bfloat16, + dtypes.complex64, + dtypes.complex128, + dtypes.uint16, + dtypes.uint32, + dtypes.uint64, + dtypes.int16, + dtypes.int32, + dtypes.int64, + dtypes.qint16, + dtypes.quint16, + dtypes.qint32, +] + + +def byte_swap_tensor_content(tensor, from_endiness, to_endiness): + """Byte swaps. + + Args: + tensor: Target tensor to change endiness. + from_endiness: The original endianness format. "big" or "little" + to_endiness: The target endianness format. "big" or "little" + """ + if tensor.dtype in byte_swappable: + tshape = tensor.tensor_shape.dim + tensor_bytes = tensor.tensor_content + if tensor_bytes: + tensor_size = 1 + for sz in tshape: + if sz.size != 0: + tensor_size = tensor_size * sz.size + chunksize = int(len(tensor_bytes) / tensor_size) + # Split tensor_data into chunks for byte swapping. + to_swap = [ + tensor_bytes[i : i + chunksize] + for i in range(0, len(tensor_bytes), chunksize) + ] + # Swap and replace tensor_content. + tensor.tensor_content = b"".join( + [ + int.from_bytes(byteswap, from_endiness).to_bytes( + chunksize, to_endiness + ) + for byteswap in to_swap + ] + ) + + +def swap_tensor_content_in_graph_function( + graph_def, from_endiness, to_endiness +): + """Fix endiness of tensor contents. + + Args: + graph_def: Target graph_def to change endiness. + from_endiness: The original endianness format. "big" or "little" + to_endiness: The target endianness format. "big" or "little" + """ + if isinstance(graph_def, meta_graph_pb2.MetaGraphDef): + functions = graph_def.graph_def.library.function + elif isinstance(graph_def, graph_pb2.GraphDef): + functions = graph_def.library.function + else: + return + for function in functions: + node_def = function.node_def + for node in node_def: + if node.op == "Const": + tensor = node.attr["value"].tensor + byte_swap_tensor_content(tensor, from_endiness, to_endiness) + + +def swap_tensor_content_in_graph_node(graph_def, from_endiness, to_endiness): + for node in graph_def.node: + if node.op == "Const": + tensor = node.attr["value"].tensor + byte_swap_tensor_content(tensor, from_endiness, to_endiness) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/c_api_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/c_api_util.py new file mode 100644 index 0000000000000000000000000000000000000000..9a866366f4520d87cdb531285c75e2a9d133333c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/c_api_util.py @@ -0,0 +1,237 @@ +# 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 using the TensorFlow C API.""" + +import contextlib +from tensorflow.core.framework import api_def_pb2 +from tensorflow.core.framework import op_def_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.util import compat +from tensorflow.python.util import tf_contextlib + + +class AlreadyGarbageCollectedError(Exception): + + def __init__(self, name, obj_type): + super(AlreadyGarbageCollectedError, + self).__init__(f"{name} of type {obj_type} has already been garbage " + f"collected and cannot be called.") + + +# FIXME(b/235488206): Convert all Scoped objects to the context manager +# to protect against deletion during use when the object is attached to +# an attribute. +class UniquePtr(object): + """Wrapper around single-ownership C-API objects that handles deletion.""" + + __slots__ = ["_obj", "deleter", "name", "type_name"] + + def __init__(self, name, obj, deleter): + # '_' prefix marks _obj private, but unclear if it is required also to + # maintain a special CPython destruction order. + self._obj = obj + self.name = name + # Note: when we're destructing the global context (i.e when the process is + # terminating) we may have already deleted other modules. By capturing the + # DeleteGraph function here, we retain the ability to cleanly destroy the + # graph at shutdown, which satisfies leak checkers. + self.deleter = deleter + self.type_name = str(type(obj)) + + @contextlib.contextmanager + def get(self): + """Yields the managed C-API Object, guaranteeing aliveness. + + This is a context manager. Inside the context the C-API object is + guaranteed to be alive. + + Raises: + AlreadyGarbageCollectedError: if the object is already deleted. + """ + # Thread-safety: self.__del__ never runs during the call of this function + # because there is a reference to self from the argument list. + if self._obj is None: + raise AlreadyGarbageCollectedError(self.name, self.type_name) + yield self._obj + + def __del__(self): + obj = self._obj + if obj is not None: + self._obj = None + self.deleter(obj) + + +class ScopedTFStatus(object): + """Wrapper around TF_Status that handles deletion.""" + + __slots__ = ["status"] + + def __init__(self): + self.status = c_api.TF_NewStatus() + + def __del__(self): + # Note: when we're destructing the global context (i.e when the process is + # terminating) we can have already deleted other modules. + if c_api is not None and c_api.TF_DeleteStatus is not None: + c_api.TF_DeleteStatus(self.status) + + +class ScopedTFImportGraphDefOptions(object): + """Wrapper around TF_ImportGraphDefOptions that handles deletion.""" + + __slots__ = ["options"] + + def __init__(self): + self.options = c_api.TF_NewImportGraphDefOptions() + + def __del__(self): + # Note: when we're destructing the global context (i.e when the process is + # terminating) we can have already deleted other modules. + if c_api is not None and c_api.TF_DeleteImportGraphDefOptions is not None: + c_api.TF_DeleteImportGraphDefOptions(self.options) + + +class ScopedTFImportGraphDefResults(object): + """Wrapper around TF_ImportGraphDefOptions that handles deletion.""" + + __slots__ = ["results"] + + def __init__(self, results): + self.results = results + + def __del__(self): + # Note: when we're destructing the global context (i.e when the process is + # terminating) we can have already deleted other modules. + if c_api is not None and c_api.TF_DeleteImportGraphDefResults is not None: + c_api.TF_DeleteImportGraphDefResults(self.results) + + +class ScopedTFFunction(UniquePtr): + """Wrapper around TF_Function that handles deletion.""" + + def __init__(self, func, name): + super(ScopedTFFunction, self).__init__( + name=name, obj=func, deleter=c_api.TF_DeleteFunction) + + +class ScopedTFBuffer(object): + """An internal class to help manage the TF_Buffer lifetime.""" + + __slots__ = ["buffer"] + + def __init__(self, buf_string): + self.buffer = c_api.TF_NewBufferFromString(compat.as_bytes(buf_string)) + + def __del__(self): + c_api.TF_DeleteBuffer(self.buffer) + + +class ApiDefMap(object): + """Wrapper around Tf_ApiDefMap that handles querying and deletion. + + The OpDef protos are also stored in this class so that they could + be queried by op name. + """ + + __slots__ = ["_api_def_map", "_op_per_name"] + + def __init__(self): + op_def_proto = op_def_pb2.OpList() + buf = c_api.TF_GetAllOpList() + try: + op_def_proto.ParseFromString(c_api.TF_GetBuffer(buf)) + self._api_def_map = c_api.TF_NewApiDefMap(buf) + finally: + c_api.TF_DeleteBuffer(buf) + + self._op_per_name = {} + for op in op_def_proto.op: + self._op_per_name[op.name] = op + + def __del__(self): + # Note: when we're destructing the global context (i.e when the process is + # terminating) we can have already deleted other modules. + if c_api is not None and c_api.TF_DeleteApiDefMap is not None: + c_api.TF_DeleteApiDefMap(self._api_def_map) + + def put_api_def(self, text): + c_api.TF_ApiDefMapPut(self._api_def_map, text, len(text)) + + def get_api_def(self, op_name): + api_def_proto = api_def_pb2.ApiDef() + buf = c_api.TF_ApiDefMapGet(self._api_def_map, op_name, len(op_name)) + try: + api_def_proto.ParseFromString(c_api.TF_GetBuffer(buf)) + finally: + c_api.TF_DeleteBuffer(buf) + return api_def_proto + + def get_op_def(self, op_name): + if op_name in self._op_per_name: + return self._op_per_name[op_name] + raise ValueError(f"No op_def found for op name {op_name}.") + + def op_names(self): + return self._op_per_name.keys() + + +@tf_contextlib.contextmanager +def tf_buffer(data=None): + """Context manager that creates and deletes TF_Buffer. + + Example usage: + with tf_buffer() as buf: + # get serialized graph def into buf + ... + proto_data = c_api.TF_GetBuffer(buf) + graph_def.ParseFromString(compat.as_bytes(proto_data)) + # buf has been deleted + + with tf_buffer(some_string) as buf: + c_api.TF_SomeFunction(buf) + # buf has been deleted + + Args: + data: An optional `bytes`, `str`, or `unicode` object. If not None, the + yielded buffer will contain this data. + + Yields: + Created TF_Buffer + """ + if data: + buf = c_api.TF_NewBufferFromString(compat.as_bytes(data)) + else: + buf = c_api.TF_NewBuffer() + try: + yield buf + finally: + c_api.TF_DeleteBuffer(buf) + + +def tf_output(c_op, index): + """Returns a wrapped TF_Output with specified operation and index. + + Args: + c_op: wrapped TF_Operation + index: integer + + Returns: + Wrapped TF_Output + """ + ret = c_api.TF_Output() + ret.oper = c_op + ret.index = index + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/combinations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/combinations.py new file mode 100644 index 0000000000000000000000000000000000000000..70f8e54149673791637a05889007af0e57d330ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/combinations.py @@ -0,0 +1,83 @@ +# 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. +# ============================================================================== +"""This module customizes `test_combinations` for Tensorflow. + +Additionally it provides `generate()`, `combine()` and `times()` with Tensorflow +customizations as a default. +""" + +import functools + +from tensorflow.python import tf2 +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_combinations +from tensorflow.python.util.tf_export import tf_export + + +class EagerGraphCombination(test_combinations.TestCombination): + """Run the test in Graph or Eager mode. + + The optional `mode` parameter controls the test's execution mode. Its + accepted values are "graph" or "eager" literals. + """ + + def context_managers(self, kwargs): + mode = kwargs.pop("mode", None) + if mode is None: + return [] + elif mode == "eager": + return [context.eager_mode()] + elif mode == "graph": + return [ops.Graph().as_default(), context.graph_mode()] + else: + raise ValueError( + "Argument 'mode' must be either 'eager' or 'graph'. " + f"Received: {mode}.") + + def parameter_modifiers(self): + return [test_combinations.OptionalParameter("mode")] + + +class TFVersionCombination(test_combinations.TestCombination): + """Control the execution of the test in TF1.x and TF2. + + If TF2 is enabled then a test with TF1 test is going to be skipped and vice + versa. + + Test targets continuously run in TF2 thanks to the tensorflow.v2 TAP target. + A test can be run in TF2 with bazel by passing --test_env=TF2_BEHAVIOR=1. + """ + + def should_execute_combination(self, kwargs): + tf_api_version = kwargs.pop("tf_api_version", None) + if tf_api_version == 1 and tf2.enabled(): + return (False, "Skipping a TF1.x test when TF2 is enabled.") + elif tf_api_version == 2 and not tf2.enabled(): + return (False, "Skipping a TF2 test when TF2 is not enabled.") + return (True, None) + + def parameter_modifiers(self): + return [test_combinations.OptionalParameter("tf_api_version")] + + +generate = functools.partial( + test_combinations.generate, + test_combinations=(EagerGraphCombination(), TFVersionCombination())) +combine = test_combinations.combine +times = test_combinations.times +NamedObject = test_combinations.NamedObject + +tf_export("__internal__.test.combinations.generate", v1=[])(generate) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/common_shapes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/common_shapes.py new file mode 100644 index 0000000000000000000000000000000000000000..8d86ec68c069fe4228d56e5d69deb0a40bd2449c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/common_shapes.py @@ -0,0 +1,108 @@ +# 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 library of common shape functions.""" +import itertools + +from tensorflow.python.framework import tensor_shape + + +def _broadcast_shape_helper(shape_x, shape_y): + """Helper functions for is_broadcast_compatible and broadcast_shape. + + Args: + shape_x: A `TensorShape` + shape_y: A `TensorShape` + + Returns: + Returns None if the shapes are not broadcast compatible, + a list of the broadcast dimensions otherwise. + """ + # To compute the broadcasted dimensions, we zip together shape_x and shape_y, + # and pad with 1 to make them the same length. + broadcasted_dims = reversed( + list( + itertools.zip_longest( + reversed(shape_x.dims), + reversed(shape_y.dims), + fillvalue=tensor_shape.Dimension(1)))) + # Next we combine the dimensions according to the numpy broadcasting rules. + # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html + return_dims = [] + for (dim_x, dim_y) in broadcasted_dims: + if dim_x.value is None or dim_y.value is None: + # One or both dimensions is unknown. If either dimension is greater than + # 1, we assume that the program is correct, and the other dimension will + # be broadcast to match it. + # TODO(mrry): If we eliminate the shape checks in C++, we must still + # assert that the unknown dim is either 1 or the same as the known dim. + if dim_x.value is not None and dim_x.value > 1: + return_dims.append(dim_x) + elif dim_y.value is not None and dim_y.value > 1: + return_dims.append(dim_y) + else: + return_dims.append(None) + elif dim_x.value == 1: + # We will broadcast dim_x to dim_y. + return_dims.append(dim_y) + elif dim_y.value == 1: + # We will broadcast dim_y to dim_x. + return_dims.append(dim_x) + elif dim_x.value == dim_y.value: + # The dimensions are compatible, so output is the same size in that + # dimension. + return_dims.append(dim_x.merge_with(dim_y)) + else: + return None + return return_dims + + +def is_broadcast_compatible(shape_x, shape_y): + """Returns True if `shape_x` and `shape_y` are broadcast compatible. + + Args: + shape_x: A `TensorShape` + shape_y: A `TensorShape` + + Returns: + True if a shape exists that both `shape_x` and `shape_y` can be broadcasted + to. False otherwise. + """ + if shape_x.ndims is None or shape_y.ndims is None: + return False + return _broadcast_shape_helper(shape_x, shape_y) is not None + + +def broadcast_shape(shape_x, shape_y): + """Returns the broadcasted shape between `shape_x` and `shape_y`. + + Args: + shape_x: A `TensorShape` + shape_y: A `TensorShape` + + Returns: + A `TensorShape` representing the broadcasted shape. + + Raises: + ValueError: If the two shapes can not be broadcasted. + """ + if shape_x.ndims is None or shape_y.ndims is None: + return tensor_shape.unknown_shape() + return_dims = _broadcast_shape_helper(shape_x, shape_y) + if return_dims is None: + raise ValueError('Incompatible shapes for broadcasting. Two shapes are ' + 'compatible if for each dimension pair they are either ' + 'equal or one of them is 1. ' + f'Received: {shape_x} and {shape_y}.') + return tensor_shape.TensorShape(return_dims) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/composite_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/composite_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..05b4f672793f3e36cbc2bd70067e9c443d9f5864 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/composite_tensor.py @@ -0,0 +1,144 @@ +# 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. +# ============================================================================== +"""Tensor-like objects that are composed from tf.Tensors.""" + +import abc + +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.CompositeTensor", v1=[]) +class CompositeTensor(metaclass=abc.ABCMeta): + """Abstract base class for Tensor-like objects that are composed from Tensors. + + Each `CompositeTensor` can be decomposed into a structured collection of + component `tf.Tensor`s, and reconstructed from those components. + + The `tensorflow.python.util.nest` module has support for treating composite + tensors as structure, which makes it easy to flatten and reconstruct + composite tensors (or larger structures that contain composite tensors). + E.g.: + + ```python + ct = ... # Create a composite tensor. + flat_list_of_tensors = nest.flatten(ct, expand_composites=True) + transformed_list_of_tensors = ... # do something with the flat tensors. + result = nest.pack_sequence_as(ct, transformed_list_of_tensors, + expand_composites=True) + ``` + """ + + @abc.abstractproperty + def _type_spec(self): + """A `TypeSpec` describing the type of this value.""" + raise NotImplementedError(f"{type(self).__name__}._type_spec()") + + def _shape_invariant_to_type_spec(self, shape): + """Returns a TypeSpec given a shape invariant (used by `tf.while_loop`). + + Args: + shape: A `tf.TensorShape` object. The shape invariant for this + `CompositeTensor`, or `None` if a default shape invariant should be used + (based on the value of this `CompositeTensor`). + + Returns: + A nested structure whose values are `tf.TensorShape` objects, specifying + the shape invariants for the tensors that comprise this `CompositeTensor`. + """ + # New TypeSpec subclasses generally do not need to implement this -- + # this method is used for backwards compatibility. Users of tf.while_loop + # can specify a type by passing in TypeSpec instead. + raise NotImplementedError( + f"{type(self).__name__}._shape_invariant_to_type_spec") + + def _consumers(self): + """Returns a list of `Operation`s that consume this `CompositeTensor`. + + Returns: + A list of `Operation`s. + + Raises: + RuntimeError: If this method is called while executing eagerly. + """ + consumers = nest.flatten([ + component.consumers() + for component in nest.flatten(self, expand_composites=True) + if getattr(component, "graph", None) is not None + ]) + return list(set(consumers)) + + def __tf_tracing_type__(self, context): + return self._type_spec.__tf_tracing_type__(context) + + def _convert_variables_to_tensors(self): + """Converts ResourceVariable components to Tensors. + + Override this method to explicitly convert ResourceVariables embedded in the + CompositeTensor to Tensors. By default, it returns the CompositeTensor + unchanged. + + Returns: + A CompositeTensor with all its ResourceVariable components converted to + Tensors. + """ + return self + + +_pywrap_utils.RegisterType("CompositeTensor", CompositeTensor) + + +def replace_composites_with_components(structure): + """Recursively replaces CompositeTensors with their components. + + Args: + structure: A `nest`-compatible structure, possibly containing composite + tensors. + + Returns: + A copy of `structure`, where each composite tensor has been replaced by + its components. The result will contain no composite tensors. + Note that `nest.flatten(replace_composites_with_components(structure))` + returns the same value as `nest.flatten(structure)`. + """ + if isinstance(structure, CompositeTensor): + return replace_composites_with_components( + structure._type_spec._to_components(structure)) # pylint: disable=protected-access + elif not nest.is_nested(structure): + return structure + else: + return nest.map_structure( + replace_composites_with_components, structure, expand_composites=False) + + +def convert_variables_to_tensors(composite_tensor): + return composite_tensor._convert_variables_to_tensors() # pylint: disable=protected-access + + +# @TODO(edloper): Can we replace convert_to_tensor_or_xyz with just +# convert_to_tensor_or_composite? Alternatively, should composite tensors +# register a dispatch override for tf.convert_to_tensor? + +# Note about the internal encoding of composite tensors when they are "lowered" +# from Python objects to tensors. The usual encoding is "component encoding" +# which uses the dense tensors that represent a composite tensor. +# A second encoding, "batchable tensor list encoding", is used by datasets +# and map_fn which in addition to supporting batching also can use ops +# for encoding and decoding, e.g. for encoding/decoding to/from a +# single variant that represents a composite tensor. Some internal properties +# for type specs for composite tensors use `flat` as a nickname for +# "batchable tensor list encoding". (e.g. `flat_tensor_specs`). diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/composite_tensor_gradient.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/composite_tensor_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..48ca71ce0f45cc567bb9a00ade3108ee27996826 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/composite_tensor_gradient.py @@ -0,0 +1,185 @@ +# Copyright 2022 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Gradient support for Composite Tensors.""" + +import abc +import sys + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.util import nest + + +# pylint:disable=g-import-not-at-top +if sys.version_info >= (3, 8): + from typing import Protocol + from typing import runtime_checkable +else: + from typing_extensions import Protocol + from typing_extensions import runtime_checkable +# pylint:enable=g-import-not-at-top + + +# TODO(xjun): Add CompositeTensorGradient support for SparseTensor, +# StructuredTensor, and MaskedTensor. +class CompositeTensorGradient(object, metaclass=abc.ABCMeta): + """Class used to help compute gradients for CompositeTensors. + + This abstract base class defines two methods: `get_gradient_components`, which + returns the components of a value that should be included in gradients; and + `replace_gradient_components`, which replaces the gradient components in a + value. These methods can be used to compute the gradient of a `y` with + respect to `x` (`grad(y, x)`) as follows: + + * If `y` is a `CompositeTensor` with `CompositeTensorGradient` `cg` = + `y.__composite_gradient__`, then `grad(y, x)` = + `grad(cg.get_gradient_components(y), x)`. + + * If `x` is a `CompositeTensor` with `CompositeTensorGradient` `cg` = + 'x.__composite_gradient__', then `grad(y, x)` = + `cg.replace_gradient_components(x, grad(y, cg.get_gradient_components(x))`. + """ + + @abc.abstractmethod + def get_gradient_components(self, value): + """Returns the components of `value` that should be included in gradients. + + This method may not call TensorFlow ops, since any new ops added to the + graph would not be propertly tracked by the gradient mechanisms. + + Args: + value: A `CompositeTensor` value. + + Returns: + A nested structure of `Tensor` or `IndexedSlices`. + """ + raise NotImplementedError( + f"{type(self).__name__}.get_gradient_components()") + + @abc.abstractmethod + def replace_gradient_components(self, value, component_grads): + """Replaces the gradient components in `value` with `component_grads`. + + Args: + value: A value with its gradient components compatible with + `component_grads`. + component_grads: A nested structure of `Tensor` or `IndexedSlices` or + `None` (for unconnected gradients). + + Returns: + A copy of `value`, where the components that should be included in + gradients have been replaced by `component_grads`; or `None` (if + `component_grads` includes `None`). + """ + raise NotImplementedError( + f"{type(self).__name__}.replace_gradient_components()") + + +@runtime_checkable +class CompositeTensorGradientProtocol(Protocol): + """Protocol for adding gradient support to CompositeTensors.""" + __composite_gradient__: CompositeTensorGradient + + +class WithValuesCompositeTensorGradient(CompositeTensorGradient): + """CompositeTensorGradient based on `T.values` and `T.with_values`.""" + + def get_gradient_components(self, value): + return value.values + + def replace_gradient_components(self, value, component_grads): + return value.with_values(component_grads) + + +def _get_tensors_for_gradient(x): + """Returns the Tensors in `x` that should be differentiated. + + Args: + x: A `Tensor` or `CompositeTensor`. + + Returns: + A `Tensor` or a nested structure of `Tensor`. + """ + if not isinstance(x, composite_tensor.CompositeTensor): + return x + + if not isinstance(x, CompositeTensorGradientProtocol): + raise ValueError( + f"Type {type(x).__name__} is not supported as a gradient source or " + "gradient target.") + composite_gradient = x.__composite_gradient__ + gradient_components = composite_gradient.get_gradient_components(x) + if gradient_components is x: + return x + return nest.map_structure(_get_tensors_for_gradient, gradient_components) + + +def _replace_tensors_for_gradient(x, grad): + """Replaces the tensors in `x` that should be differentiated with `grad`. + + Args: + x: A `Tensor` or `CompositeTensor`. + grad: A nested structure of `Tensor`, with the same structure as the value + returned by `_get_tensors_for_gradient(x)`. + + Returns: + A `Tensor` or `CompositeTensor`. + """ + if not isinstance(x, composite_tensor.CompositeTensor): + return grad + + if not isinstance(x, CompositeTensorGradientProtocol): + raise ValueError( + f"Type {type(x).__name__} is not supported as a gradient source.") + + composite_gradient = x.__composite_gradient__ + x_components = composite_gradient.get_gradient_components(x) + if x_components is x: + grad_components = grad + else: + grad_components = nest.map_structure_up_to(x_components, + _replace_tensors_for_gradient, + x_components, grad) + if grad_components is None: + return None + return composite_gradient.replace_gradient_components(x, grad_components) + + +def get_flat_tensors_for_gradients(xs): + """Returns a flat list of Tensors that should be differentiated for `xs`. + + Args: + xs: A list of `Tensor`s or `CompositeTensor`s. + + Returns: + A flat list of `Tensor`s constructed from `xs`, where `Tensor` values are + left as-is, and `CompositeTensor`s are replaced with + `_get_tensors_for_gradient(x)`. + """ + return nest.flatten([_get_tensors_for_gradient(x) for x in xs]) + + +def replace_flat_tensors_for_gradients(xs, flat_grads): + """Replaces Tensors that should be differentiated in `xs` with `flat_grads`. + + Args: + xs: A list of `Tensor`s or `CompositeTensor`s. + flat_grads: A list of `Tensor`. + + Returns: + A list of `Tensor` or `CompositeTensor`. + """ + xs_structure = [_get_tensors_for_gradient(x) for x in xs] + grads = nest.pack_sequence_as(xs_structure, flat_grads) + return [_replace_tensors_for_gradient(x, grad) for x, grad in zip(xs, grads)] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/config.py new file mode 100644 index 0000000000000000000000000000000000000000..228bacb7f6443d117e623d2952cb386c23685a17 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/config.py @@ -0,0 +1,1103 @@ +# 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. +# ============================================================================== +"""Functions for configuring TensorFlow execution.""" + +from typing import Union + +from tensorflow.python.eager import context +from tensorflow.python.framework import errors +from tensorflow.python.util import _pywrap_determinism +from tensorflow.python.util import _pywrap_tensor_float_32_execution +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('config.experimental.tensor_float_32_execution_enabled') +def tensor_float_32_execution_enabled(): + """Returns whether TensorFloat-32 is enabled. + + By default, TensorFloat-32 is enabled, but this can be changed with + `tf.config.experimental.enable_tensor_float_32_execution`. + + Returns: + True if TensorFloat-32 is enabled (the default) and False otherwise + """ + return _pywrap_tensor_float_32_execution.is_enabled() + + +# TODO(b/280688352): Rename or rework this function to make it appear less +# specific to GPUs. TPUs use bfloat16 instead of TensorFloat-32 by default for +# matmuls, yet on TPUs this function also can used to increase the precision of +# matmuls to FP32 by passing enabled=False. It is misleading how the words +# "tensor_float_32" appear in the API name, yet this API affects TPUs which do +# not use TensorFloat-32. +@tf_export('config.experimental.enable_tensor_float_32_execution') +def enable_tensor_float_32_execution(enabled): + """Enable or disable the use of TensorFloat-32 on supported hardware. + + [TensorFloat-32](https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format), + or TF32 for short, is a math mode for NVIDIA Ampere GPUs and above. + TensorFloat-32 execution causes certain float32 ops, such as matrix + multiplications and convolutions, to run much faster on such GPUs but with + reduced precision. This reduced precision should not impact convergence of + deep learning models in practice. + + TensorFloat-32 is enabled by default. TensorFloat-32 is only supported on + NVIDIA GPUs starting with the Ampere generation, so older NVIDIA GPUs will use + the full float32 precision regardless of whether TensorFloat-32 is enabled or + not. If you want to use the full float32 precision on all GPUs, you can + disable TensorFloat-32 execution with this function. For example: + + ```python + x = tf.fill((1024, 1024), 1.0001) + y = tf.fill((1024, 1024), 1.) + # TensorFloat-32 is enabled, so matmul is run with reduced precision + print(tf.linalg.matmul(x, y)[0, 0]) # 1024.0 + tf.config.experimental.enable_tensor_float_32_execution(False) + # Matmul is run with full precision + print(tf.linalg.matmul(x, y)[0, 0]) # ~1024.1 + ``` + + To check whether TensorFloat-32 execution is currently enabled, use + `tf.config.experimental.tensor_float_32_execution_enabled`. + + If TensorFloat-32 is enabled, float32 inputs of supported ops, such as + `tf.linalg.matmul`, will be rounded from 23 bits of precision to 10 bits of + precision in most cases. This allows the ops to execute much faster by + utilizing the GPU's tensor cores. TensorFloat-32 has the same dynamic range as + float32, meaning it is no more likely to underflow or overflow than float32. + Ops still use float32 accumulation when TensorFloat-32 is enabled. Enabling or + disabling TensorFloat-32 only affects Ampere GPUs and above. + + Note TensorFloat-32 is not always used in supported ops, as only inputs of + certain shapes are supported. Support for more input shapes and more ops may + be added in the future. As a result, precision of float32 ops may decrease in + minor versions of TensorFlow. + + TensorFloat-32 is also used for some complex64 ops. Currently, TensorFloat-32 + is used in fewer cases for complex64 as it is for float32. + + Simiarly to GPUs, TPUs also run certain float32 ops, like matrix + multiplications and convolutions, with lower precision by default. Unlike + GPUs, TPUs use bfloat16 precision instead of TensorFloat-32 precision for such + ops. Disabling TensorFloat-32 with this function also causes TPUs to run + float32 ops with the full float32 precision but with lower performance. + + Args: + enabled: Bool indicating whether to enable TensorFloat-32 execution. + """ + _pywrap_tensor_float_32_execution.enable(enabled) + + +@tf_export('config.threading.get_intra_op_parallelism_threads') +def get_intra_op_parallelism_threads(): + """Get number of threads used within an individual op for parallelism. + + Certain operations like matrix multiplication and reductions can utilize + parallel threads for speed ups. A value of 0 means the system picks an + appropriate number. + + Returns: + Number of parallel threads + """ + return context.context().intra_op_parallelism_threads + + +@tf_export('config.threading.set_intra_op_parallelism_threads') +def set_intra_op_parallelism_threads(num_threads): + """Set number of threads used within an individual op for parallelism. + + Certain operations like matrix multiplication and reductions can utilize + parallel threads for speed ups. A value of 0 means the system picks an + appropriate number. + + Args: + num_threads: Number of parallel threads + """ + context.context().intra_op_parallelism_threads = num_threads + + +@tf_export('config.threading.get_inter_op_parallelism_threads') +def get_inter_op_parallelism_threads(): + """Get number of threads used for parallelism between independent operations. + + Determines the number of threads used by independent non-blocking operations. + 0 means the system picks an appropriate number. + + Returns: + Number of parallel threads + """ + return context.context().inter_op_parallelism_threads + + +@tf_export('config.threading.set_inter_op_parallelism_threads') +def set_inter_op_parallelism_threads(num_threads): + """Set number of threads used for parallelism between independent operations. + + Determines the number of threads used by independent non-blocking operations. + 0 means the system picks an appropriate number. + + Args: + num_threads: Number of parallel threads + """ + context.context().inter_op_parallelism_threads = num_threads + + +@tf_export('config.optimizer.get_jit') +def get_optimizer_jit() -> str: + """Returns JIT compilation configuration for code inside `tf.function`. + + Possible return values: + -`"autoclustering"` if + [autoclustering](https://www.tensorflow.org/xla#auto-clustering) is enabled + - `""` when no default compilation is applied. + """ + if context.context().optimizer_jit: + return 'autoclustering' + return '' + + +@tf_export('config.optimizer.set_jit') +@deprecation.deprecated_arg_values( + None, + '`True` setting is deprecated, use `autoclustering` instead.', + warn_once=True, + jit_config=True) +def set_optimizer_jit(enabled: Union[bool, str]): + """Configure JIT compilation. + + Note: compilation is only applied to code that is compiled into a + graph (in TF2 that's only a code inside `tf.function`). + + Args: + enabled: JIT compilation configuration. + Possible values: + - `"autoclustering"` (`True` is a deprecated alias): perform + [autoclustering](https://www.tensorflow.org/xla#auto-clustering) + (automatically identify and compile clusters of nodes) on all graphs + using + [XLA](https://www.tensorflow.org/xla). + - `False`: do not automatically compile any graphs. + """ + autoclustering_enabled = enabled in (True, 'autoclustering') + context.context().optimizer_jit = autoclustering_enabled + + +@tf_export('config.optimizer.get_experimental_options') +def get_optimizer_experimental_options(): + """Get experimental optimizer options. + + Refer to tf.config.optimizer.set_experimental_options for a list of current + options. + + Note that optimizations are only applied in graph mode, (within tf.function). + In addition, as these are experimental options, the list is subject to change. + + Returns: + Dictionary of configured experimental optimizer options + """ + return context.context().get_optimizer_experimental_options() + + +@tf_export('config.optimizer.set_experimental_options') +def set_optimizer_experimental_options(options): + """Set experimental optimizer options. + + Note that optimizations are only applied in graph mode, (within tf.function). + In addition, as these are experimental options, the list is subject to change. + + Args: + options: Dictionary of experimental optimizer options to configure. + Valid keys: + - layout_optimizer: Optimize tensor layouts e.g. This will try to use NCHW + layout on GPU which is faster. + - constant_folding: Fold constants Statically infer the value of tensors + when possible, and materialize the result using constants. + - shape_optimization: Simplify computations made on shapes. + - remapping: Remap subgraphs onto more efficient implementations. + - arithmetic_optimization: Simplify arithmetic ops with common + sub-expression elimination and arithmetic simplification. + - dependency_optimization: Control dependency optimizations. Remove + redundant control dependencies, which may enable other optimization. + This optimizer is also essential for pruning Identity and NoOp nodes. + - loop_optimization: Loop optimizations. + - function_optimization: Function optimizations and inlining. + - debug_stripper: Strips debug-related nodes from the graph. + - disable_model_pruning: Disable removal of unnecessary ops from the graph + - scoped_allocator_optimization: Try to allocate some independent Op + outputs contiguously in order to merge or eliminate downstream Ops. + - pin_to_host_optimization: Force small ops onto the CPU. + - implementation_selector: Enable the swap of kernel implementations based + on the device placement. + - auto_mixed_precision: Change certain float32 ops to float16 on Volta + GPUs and above. Without the use of loss scaling, this can cause + numerical underflow (see + `keras.mixed_precision.experimental.LossScaleOptimizer`). + - disable_meta_optimizer: Disable the entire meta optimizer. + - min_graph_nodes: The minimum number of nodes in a graph to optimizer. + For smaller graphs, optimization is skipped. + - auto_parallel: Automatically parallelizes graphs by splitting along + the batch dimension + """ + context.context().set_optimizer_experimental_options(options) + + +@tf_export('config.get_soft_device_placement') +def get_soft_device_placement(): + """Return status of soft device placement flag. + + If enabled, ops can be placed on different devices than the device explicitly + assigned by the user. This potentially has a large performance cost due to an + increase in data communication between devices. + + Some cases where soft_device_placement would modify device assignment are: + 1. no GPU/TPU implementation for the OP + 2. no GPU devices are known or registered + 3. need to co-locate with reftype input(s) which are from CPU + 4. an OP can not be compiled by XLA. Common for TPU which always requires + the XLA compiler. + + For TPUs, if this option is true, a feature called automatic outside + compilation is enabled. Automatic outside compilation will move uncompilable + ops within a TPU program to instead run on the host. This can be used when + encountering compilation failures due to unsupported ops. + + Returns: + A boolean indicating if soft placement is enabled. + """ + return context.context().soft_device_placement + + +@tf_export('config.set_soft_device_placement') +def set_soft_device_placement(enabled): + """Enable or disable soft device placement. + + If enabled, ops can be placed on different devices than the device explicitly + assigned by the user. This potentially has a large performance cost due to an + increase in data communication between devices. + + Some cases where soft_device_placement would modify device assignment are: + 1. no GPU/TPU implementation for the OP + 2. no GPU devices are known or registered + 3. need to co-locate with reftype input(s) which are from CPU + 4. an OP can not be compiled by XLA. Common for TPU which always requires + the XLA compiler. + + For TPUs, if this option is true, a feature called automatic outside + compilation is enabled. Automatic outside compilation will move uncompilable + ops within a TPU program to instead run on the host. This can be used when + encountering compilation failures due to unsupported ops. + + Note: by default soft device placement is enabled when running in eager mode + (for convenience) and disabled in graph mode (for performance). + + Args: + enabled: A boolean indicating whether to enable soft placement. + """ + context.context().soft_device_placement = enabled + + +@tf_export('config.experimental.get_device_policy') +def get_device_policy(): + """Gets the current device policy. + + The device policy controls how operations requiring inputs on a specific + device (e.g., on GPU:0) handle inputs on a different device (e.g. GPU:1). + + This function only gets the device policy for the current thread. Any + subsequently started thread will again use the default policy. + + Returns: + Current thread device policy + """ + device_policy = context.context().device_policy + if device_policy == context.DEVICE_PLACEMENT_SILENT: + return 'silent' + elif device_policy == context.DEVICE_PLACEMENT_SILENT_FOR_INT32: + return 'silent_for_int32' + elif device_policy == context.DEVICE_PLACEMENT_WARN: + return 'warn' + elif device_policy == context.DEVICE_PLACEMENT_EXPLICIT: + return 'explicit' + else: + # pylint: disable-next=no-value-for-parameter + raise errors.InternalError( + f'Got an invalid device policy: {device_policy!r}.') + + +@tf_export('config.experimental.set_device_policy') +def set_device_policy(device_policy): + """Sets the current thread device policy. + + The device policy controls how operations requiring inputs on a specific + device (e.g., on GPU:0) handle inputs on a different device (e.g. GPU:1). + + When using the default, an appropriate policy will be picked automatically. + The default policy may change over time. + + This function only sets the device policy for the current thread. Any + subsequently started thread will again use the default policy. + + Args: + device_policy: A device policy. + Valid values: + - None: Switch to a system default. + - 'warn': Copies the tensors which are not on the right device and logs a + warning. + - 'explicit': Raises an error if the placement is not as required. + - 'silent': Silently copies the tensors. Note that this may hide + performance problems as there is no notification provided when + operations are blocked on the tensor being copied between devices. + - 'silent_for_int32': silently copies `int32` tensors, raising errors on + the other ones. + + Raises: + ValueError: If an invalid `device_policy` is passed. + """ + if device_policy == 'silent': + context.context().device_policy = context.DEVICE_PLACEMENT_SILENT + elif device_policy == 'silent_for_int32': + context.context().device_policy = context.DEVICE_PLACEMENT_SILENT_FOR_INT32 + elif device_policy == 'warn': + context.context().device_policy = context.DEVICE_PLACEMENT_WARN + elif device_policy == 'explicit': + context.context().device_policy = context.DEVICE_PLACEMENT_EXPLICIT + elif device_policy is None: + context.context().device_policy = None + else: + raise ValueError( + f'Invalid argument `device_policy`: {device_policy!r}. Please refer to ' + 'https://www.tensorflow.org/api_docs/python/tf/config/experimental/set_device_policy ' + 'for valid `device_policy` arguments.') + + +@tf_export('config.experimental.get_synchronous_execution') +def get_synchronous_execution(): + """Gets whether operations are executed synchronously or asynchronously. + + TensorFlow can execute operations synchronously or asynchronously. If + asynchronous execution is enabled, operations may return "non-ready" handles. + + Returns: + Current thread execution mode + """ + return context.context().execution_mode == context.SYNC + + +@tf_export('config.experimental.set_synchronous_execution') +def set_synchronous_execution(enable): + """Specifies whether operations are executed synchronously or asynchronously. + + TensorFlow can execute operations synchronously or asynchronously. If + asynchronous execution is enabled, operations may return "non-ready" handles. + + When `enable` is set to None, an appropriate value will be picked + automatically. The value picked may change between TensorFlow releases. + + Args: + enable: Whether operations should be dispatched synchronously. + Valid values: + - None: sets the system default. + - True: executes each operation synchronously. + - False: executes each operation asynchronously. + """ + if enable is None: + context.context().execution_mode = None + elif enable: + context.context().execution_mode = context.SYNC + else: + context.context().execution_mode = context.ASYNC + + +@tf_export('config.list_physical_devices', + 'config.experimental.list_physical_devices') +@deprecation.deprecated_endpoints('config.experimental.list_physical_devices') +def list_physical_devices(device_type=None): + """Return a list of physical devices visible to the host runtime. + + Physical devices are hardware devices present on the host machine. By default + all discovered CPU and GPU devices are considered visible. + + This API allows querying the physical hardware resources prior to runtime + initialization. Thus, giving an opportunity to call any additional + configuration APIs. This is in contrast to `tf.config.list_logical_devices`, + which triggers runtime initialization in order to list the configured devices. + + The following example lists the number of visible GPUs on the host. + + >>> physical_devices = tf.config.list_physical_devices('GPU') + >>> print("Num GPUs:", len(physical_devices)) + Num GPUs: ... + + However, the number of GPUs available to the runtime may change during runtime + initialization due to marking certain devices as not visible or configuring + multiple logical devices. + + Args: + device_type: (optional string) Only include devices matching this device + type. For example "CPU" or "GPU". + Notes: 1. If provided with any numerical values or any string other than + supported device type such as 'CPU' it returns an empty list instead of + raising error. 2. For default value it returns all physical devices + + Returns: + List of discovered `tf.config.PhysicalDevice` objects + """ + return context.context().list_physical_devices(device_type) + + +@tf_export('config.list_logical_devices', + 'config.experimental.list_logical_devices') +@deprecation.deprecated_endpoints('config.experimental.list_logical_devices') +def list_logical_devices(device_type=None): + """Return a list of logical devices created by runtime. + + Logical devices may correspond to physical devices or remote devices in the + cluster. Operations and tensors may be placed on these devices by using the + `name` of the `tf.config.LogicalDevice`. + + Calling `tf.config.list_logical_devices` triggers the runtime to configure any + `tf.config.PhysicalDevice` visible to the runtime, thereby preventing + further configuration. To avoid runtime initialization, call + `tf.config.list_physical_devices` instead. + + For example: + + >>> logical_devices = tf.config.list_logical_devices('GPU') + >>> if len(logical_devices) > 0: + ... # Allocate on GPU:0 + ... with tf.device(logical_devices[0].name): + ... one = tf.constant(1) + ... # Allocate on GPU:1 + ... with tf.device(logical_devices[1].name): + ... two = tf.constant(2) + + Args: + device_type: (optional string) Only include devices matching this device + type. For example "CPU" or "GPU". + Notes: 1. If provided with any numerical values or any string other than + supported device type such as 'CPU' it returns an empty list instead of + raising error. 2. For default value it returns all logical devices + + Returns: + List of initialized `LogicalDevice`s + """ + return context.context().list_logical_devices(device_type=device_type) + + +@tf_export('config.get_visible_devices', + 'config.experimental.get_visible_devices') +@deprecation.deprecated_endpoints('config.experimental.get_visible_devices') +def get_visible_devices(device_type=None): + """Get the list of visible physical devices. + + Returns the list of `PhysicalDevice`s currently marked as visible to the + runtime. A visible device will have at least one `LogicalDevice` associated + with it once the runtime is initialized. + + The following example verifies all visible GPUs have been disabled: + + >>> physical_devices = tf.config.list_physical_devices('GPU') + >>> try: + ... # Disable all GPUS + ... tf.config.set_visible_devices([], 'GPU') + ... visible_devices = tf.config.get_visible_devices() + ... for device in visible_devices: + ... assert device.device_type != 'GPU' + ... except: + ... # Invalid device or cannot modify virtual devices once initialized. + ... pass + + Args: + device_type: (optional string) Only include devices matching this device + type. For example "CPU" or "GPU". + + Returns: + List of visible `PhysicalDevice`s + """ + return context.context().get_visible_devices(device_type) + + +@tf_export('config.set_visible_devices', + 'config.experimental.set_visible_devices') +@deprecation.deprecated_endpoints('config.experimental.set_visible_devices') +def set_visible_devices(devices, device_type=None): + """Set the list of visible devices. + + Specifies which `PhysicalDevice` objects are visible to the runtime. + TensorFlow will only allocate memory and place operations on visible + physical devices, as otherwise no `LogicalDevice` will be created on them. + By default all discovered devices are marked as visible. + + The following example demonstrates disabling the first GPU on the machine. + + >>> physical_devices = tf.config.list_physical_devices('GPU') + >>> try: + ... # Disable first GPU + ... tf.config.set_visible_devices(physical_devices[1:], 'GPU') + ... logical_devices = tf.config.list_logical_devices('GPU') + ... # Logical device was not created for first GPU + ... assert len(logical_devices) == len(physical_devices) - 1 + ... except: + ... # Invalid device or cannot modify virtual devices once initialized. + ... pass + + Args: + devices: List of `PhysicalDevice`s to make visible + device_type: (optional) Only configure devices matching this device type. + For example "CPU" or "GPU". Other devices will be left unaltered. + + Raises: + ValueError: If argument validation fails. + RuntimeError: Runtime is already initialized. + """ + context.context().set_visible_devices(devices, device_type) + + +# TODO(b/188089869): Redesign memory stats related APIs before move them out of +# experimental. +@tf_export('config.experimental.get_memory_info') +def get_memory_info(device): + """Get memory info for the chosen device, as a dict. + + This function returns a dict containing information about the device's memory + usage. For example: + + >>> if tf.config.list_physical_devices('GPU'): + ... # Returns a dict in the form {'current': , + ... # 'peak': } + ... tf.config.experimental.get_memory_info('GPU:0') + + Currently returns the following keys: + - `'current'`: The current memory used by the device, in bytes. + - `'peak'`: The peak memory used by the device across the run of the + program, in bytes. Can be reset with + `tf.config.experimental.reset_memory_stats`. + + More keys may be added in the future, including device-specific keys. + + Currently only supports GPU and TPU. If called on a CPU device, an exception + will be raised. + + For GPUs, TensorFlow will allocate all the memory by default, unless changed + with `tf.config.experimental.set_memory_growth`. The dict specifies only the + current and peak memory that TensorFlow is actually using, not the memory that + TensorFlow has allocated on the GPU. + + Args: + device: Device string to get the memory information for, e.g. `"GPU:0"`, + `"TPU:0"`. See https://www.tensorflow.org/api_docs/python/tf/device for + specifying device strings. + + Returns: + A dict with keys `'current'` and `'peak'`, specifying the current and peak + memory usage respectively. + + Raises: + ValueError: No device found with the device name, like '"nonexistent"'. + ValueError: Invalid device name, like '"GPU"', '"CPU:GPU"', '"CPU:"'. + ValueError: Multiple devices matched with the device name. + ValueError: Memory statistics not tracked, like '"CPU:0"'. + """ + return context.context().get_memory_info(device) + + +# TODO(b/188089869): Redesign memory stats related APIs before move them out of +# experimental. +# TODO(b/189498350): Unify the behavior on CPU, GPU and TPU. +@tf_export('config.experimental.reset_memory_stats') +def reset_memory_stats(device): + """Resets the tracked memory stats for the chosen device. + + This function sets the tracked peak memory for a device to the device's + current memory usage. This allows you to measure the peak memory usage for a + specific part of your program. For example: + + >>> if tf.config.list_physical_devices('GPU'): + ... # Sets the peak memory to the current memory. + ... tf.config.experimental.reset_memory_stats('GPU:0') + ... # Creates the first peak memory usage. + ... x1 = tf.ones(1000 * 1000, dtype=tf.float64) + ... del x1 # Frees the memory referenced by `x1`. + ... peak1 = tf.config.experimental.get_memory_info('GPU:0')['peak'] + ... # Sets the peak memory to the current memory again. + ... tf.config.experimental.reset_memory_stats('GPU:0') + ... # Creates the second peak memory usage. + ... x2 = tf.ones(1000 * 1000, dtype=tf.float32) + ... del x2 + ... peak2 = tf.config.experimental.get_memory_info('GPU:0')['peak'] + ... assert peak2 < peak1 # tf.float32 consumes less memory than tf.float64. + + Currently only supports GPU and TPU. If called on a CPU device, an exception + will be raised. + + Args: + device: Device string to reset the memory stats, e.g. `"GPU:0"`, `"TPU:0"`. + See https://www.tensorflow.org/api_docs/python/tf/device for specifying + device strings. + + Raises: + ValueError: No device found with the device name, like '"nonexistent"'. + ValueError: Invalid device name, like '"GPU"', '"CPU:GPU"', '"CPU:"'. + ValueError: Multiple devices matched with the device name. + ValueError: Memory statistics not tracked or clearing memory statistics not + supported, like '"CPU:0"'. + """ + context.context().reset_memory_stats(device) + + +@deprecation.deprecated( + None, + "Use tf.config.experimental.get_memory_info(device)['current'] instead.") +@tf_export('config.experimental.get_memory_usage') +def get_memory_usage(device): + """Get the current memory usage, in bytes, for the chosen device. + + This function is deprecated in favor of + `tf.config.experimental.get_memory_info`. Calling this function is equivalent + to calling `tf.config.experimental.get_memory_info()['current']`. + + See https://www.tensorflow.org/api_docs/python/tf/device for specifying device + strings. + + For example: + + >>> gpu_devices = tf.config.list_physical_devices('GPU') + >>> if gpu_devices: + ... tf.config.experimental.get_memory_usage('GPU:0') + + Does not work for CPU. + + For GPUs, TensorFlow will allocate all the memory by default, unless changed + with `tf.config.experimental.set_memory_growth`. This function only returns + the memory that TensorFlow is actually using, not the memory that TensorFlow + has allocated on the GPU. + + Args: + device: Device string to get the bytes in use for, e.g. `"GPU:0"` + + Returns: + Total memory usage in bytes. + + Raises: + ValueError: Non-existent or CPU device specified. + """ + return get_memory_info(device)['current'] + + +@tf_export('config.experimental.get_memory_growth') +def get_memory_growth(device): + """Get if memory growth is enabled for a `PhysicalDevice`. + + If memory growth is enabled for a `PhysicalDevice`, the runtime initialization + will not allocate all memory on the device. + + For example: + + >>> physical_devices = tf.config.list_physical_devices('GPU') + >>> try: + ... tf.config.experimental.set_memory_growth(physical_devices[0], True) + ... assert tf.config.experimental.get_memory_growth(physical_devices[0]) + ... except: + ... # Invalid device or cannot modify virtual devices once initialized. + ... pass + + Args: + device: `PhysicalDevice` to query + + Returns: + A boolean indicating the memory growth setting for the `PhysicalDevice`. + + Raises: + ValueError: Invalid `PhysicalDevice` specified. + """ + return context.context().get_memory_growth(device) + + +@tf_export('config.experimental.set_memory_growth') +def set_memory_growth(device, enable): + """Set if memory growth should be enabled for a `PhysicalDevice`. + + If memory growth is enabled for a `PhysicalDevice`, the runtime initialization + will not allocate all memory on the device. Memory growth cannot be configured + on a `PhysicalDevice` with virtual devices configured. + + For example: + + >>> physical_devices = tf.config.list_physical_devices('GPU') + >>> try: + ... tf.config.experimental.set_memory_growth(physical_devices[0], True) + ... except: + ... # Invalid device or cannot modify virtual devices once initialized. + ... pass + + Args: + device: `PhysicalDevice` to configure + enable: (Boolean) Whether to enable or disable memory growth + + Raises: + ValueError: Invalid `PhysicalDevice` specified. + RuntimeError: Runtime is already initialized. + """ + context.context().set_memory_growth(device, enable) + + +@tf_export('config.experimental.get_device_details') +def get_device_details(device): + """Returns details about a physical devices. + + This API takes in a `tf.config.PhysicalDevice` returned by + `tf.config.list_physical_devices`. It returns a dict with string keys + containing various details about the device. Each key is only supported by a + subset of devices, so you should not assume the returned dict will have any + particular key. + + >>> gpu_devices = tf.config.list_physical_devices('GPU') + >>> if gpu_devices: + ... details = tf.config.experimental.get_device_details(gpu_devices[0]) + ... details.get('device_name', 'Unknown GPU') + + Currently, details are only returned for GPUs. This function returns an + empty dict if passed a non-GPU device. + + The returned dict may have the following keys: + * `'device_name'`: A human-readable name of the device as a string, e.g. + "Titan V". Unlike `tf.config.PhysicalDevice.name`, this will be the same for + multiple devices if each device is the same model. Currently only available + for GPUs. + * `'compute_capability'`: The + [compute capability](https://developer.nvidia.com/cuda-gpus) of the device + as a tuple of two ints, in the form `(major_version, minor_version)`. Only + available for NVIDIA GPUs + + Note: This is similar to `tf.sysconfig.get_build_info` in that both functions + can return information relating to GPUs. However, this function returns + run-time information about a specific device (such as a GPU's compute + capability), while `tf.sysconfig.get_build_info` returns compile-time + information about how TensorFlow was built (such as what version of CUDA + TensorFlow was built for). + + Args: + device: A `tf.config.PhysicalDevice` returned by + `tf.config.list_physical_devices` or `tf.config.get_visible_devices`. + + Returns: + A dict with string keys. + """ + return context.context().get_device_details(device) + + +@tf_export('config.get_logical_device_configuration', + 'config.experimental.get_virtual_device_configuration') +@deprecation.deprecated_endpoints( + 'config.experimental.get_virtual_device_configuration') +def get_logical_device_configuration(device): + """Get the virtual device configuration for a `tf.config.PhysicalDevice`. + + Returns the list of `tf.config.LogicalDeviceConfiguration` + objects previously configured by a call to + `tf.config.set_logical_device_configuration`. + + For example: + + >>> physical_devices = tf.config.list_physical_devices('CPU') + >>> assert len(physical_devices) == 1, "No CPUs found" + >>> configs = tf.config.get_logical_device_configuration( + ... physical_devices[0]) + >>> try: + ... assert configs is None + ... tf.config.set_logical_device_configuration( + ... physical_devices[0], + ... [tf.config.LogicalDeviceConfiguration(), + ... tf.config.LogicalDeviceConfiguration()]) + ... configs = tf.config.get_logical_device_configuration( + ... physical_devices[0]) + ... assert len(configs) == 2 + ... except: + ... # Cannot modify virtual devices once initialized. + ... pass + + Args: + device: `PhysicalDevice` to query + + Returns: + List of `tf.config.LogicalDeviceConfiguration` objects or + `None` if no virtual device configuration has been set for this physical + device. + """ + return context.context().get_logical_device_configuration(device) + + +@tf_export('config.set_logical_device_configuration', + 'config.experimental.set_virtual_device_configuration') +@deprecation.deprecated_endpoints( + 'config.experimental.set_virtual_device_configuration') +def set_logical_device_configuration(device, logical_devices): + """Set the logical device configuration for a `tf.config.PhysicalDevice`. + + A visible `tf.config.PhysicalDevice` will by default have a single + `tf.config.LogicalDevice` associated with it once the runtime is initialized. + Specifying a list of `tf.config.LogicalDeviceConfiguration` objects allows + multiple devices to be created on the same `tf.config.PhysicalDevice`. + + Logical device configurations can be modified by calling this function as + long as the runtime is uninitialized. After the runtime is initialized + calling this function raises a RuntimeError. + + The following example splits the CPU into 2 logical devices: + + >>> physical_devices = tf.config.list_physical_devices('CPU') + >>> assert len(physical_devices) == 1, "No CPUs found" + >>> # Specify 2 virtual CPUs. Note currently memory limit is not supported. + >>> try: + ... tf.config.set_logical_device_configuration( + ... physical_devices[0], + ... [tf.config.LogicalDeviceConfiguration(), + ... tf.config.LogicalDeviceConfiguration()]) + ... logical_devices = tf.config.list_logical_devices('CPU') + ... assert len(logical_devices) == 2 + ... + ... tf.config.set_logical_device_configuration( + ... physical_devices[0], + ... [tf.config.LogicalDeviceConfiguration(), + ... tf.config.LogicalDeviceConfiguration(), + ... tf.config.LogicalDeviceConfiguration(), + ... tf.config.LogicalDeviceConfiguration()]) + ... except: + ... # Cannot modify logical devices once initialized. + ... pass + + The following example splits the GPU into 2 logical devices with 100 MB each: + + >>> physical_devices = tf.config.list_physical_devices('GPU') + >>> try: + ... tf.config.set_logical_device_configuration( + ... physical_devices[0], + ... [tf.config.LogicalDeviceConfiguration(memory_limit=100), + ... tf.config.LogicalDeviceConfiguration(memory_limit=100)]) + ... + ... logical_devices = tf.config.list_logical_devices('GPU') + ... assert len(logical_devices) == len(physical_devices) + 1 + ... + ... tf.config.set_logical_device_configuration( + ... physical_devices[0], + ... [tf.config.LogicalDeviceConfiguration(memory_limit=10), + ... tf.config.LogicalDeviceConfiguration(memory_limit=10)]) + ... except: + ... # Invalid device or cannot modify logical devices once initialized. + ... pass + + Args: + device: The `PhysicalDevice` to configure. + logical_devices: (optional) List of `tf.config.LogicalDeviceConfiguration` + objects to allocate for the specified `PhysicalDevice`. If None, the + default configuration will be used. + + Raises: + ValueError: If argument validation fails. + RuntimeError: Runtime is already initialized. + """ + context.context().set_logical_device_configuration(device, logical_devices) + + +@tf_export('config.experimental.enable_mlir_bridge') +def enable_mlir_bridge(): + """Enables experimental MLIR-Based TensorFlow Compiler Bridge. + + TensorFlow Compiler Bridge (TF Bridge) is responsible for translating parts + of TensorFlow graph into a form that can be accepted as an input by a backend + compiler such as XLA. + """ + context.context().enable_mlir_bridge = True + + +@tf_export('config.experimental.disable_mlir_bridge') +def disable_mlir_bridge(): + """Disables experimental MLIR-Based TensorFlow Compiler Bridge.""" + context.context().enable_mlir_bridge = False + + +@tf_export('config.experimental.enable_op_determinism', v1=[]) +def enable_op_determinism(): + """Configures TensorFlow ops to run deterministically. + + When op determinism is enabled, TensorFlow ops will be deterministic. This + means that if an op is run multiple times with the same inputs on the same + hardware, it will have the exact same outputs each time. This is useful for + debugging models. Note that determinism in general comes at the expense of + lower performance and so your model may run slower when op determinism is + enabled. + + If you want your TensorFlow program to run deterministically, put the + following code near the start of your program. + + ```python + tf.keras.utils.set_random_seed(1) + tf.config.experimental.enable_op_determinism() + ``` + + Calling `tf.keras.utils.set_random_seed` sets the Python seed, the NumPy seed, + and the TensorFlow seed. Setting these seeds is necessary to ensure any random + numbers your program generates are also deterministic. + + By default, op determinism is not enabled, so ops might return different + results when run with the same inputs. These differences are often caused by + the use of asynchronous threads within the op nondeterministically changing + the order in which floating-point numbers are added. Most of these cases of + nondeterminism occur on GPUs, which have thousands of hardware threads that + are used to run ops. Enabling determinism directs such ops to use a different + algorithm, one that does not use threads in a nondeterministic way. + + Another potential source of nondeterminism is `tf.data` based data processing. + Typically, this can introduce nondeterminsm due to the use of parallelism in + methods such as `Dataset.map` producing inputs or running stateful ops in a + nondeterministic order. Enabling determinism will remove such sources of + nondeterminism. + + Enabling determinism will likely make your model or your `tf.data` data + processing slower. For example, `Dataset.map` can become several orders of + magnitude slower when the map function has random ops or other stateful ops. + See the “Determinism and tf.data” section below for more details. In future + TensorFlow releases, we plan on improving the performance of determinism, + especially for common scenarios such as `Dataset.map`. + + Certain ops will raise an `UnimplementedError` because they do not yet have a + deterministic implementation. Additionally, due to bugs, some ops might be + nondeterministic and not raise an `UnimplementedError`. If you encounter such + ops, please [file an issue](https://github.com/tensorflow/tensorflow/issues). + + An example of enabling determinism follows. The + `tf.nn.softmax_cross_entropy_with_logits` op is run multiple times and the + output is shown to be the same each time. This example would likely fail when + run on a GPU if determinism were not enabled, because + `tf.nn.softmax_cross_entropy_with_logits` uses a nondeterministic algorithm on + GPUs by default. + + ```python + labels = tf.random.normal((1, 10000)) + logits = tf.random.normal((1, 10000)) + output = tf.nn.softmax_cross_entropy_with_logits(labels=labels, + logits=logits) + for _ in range(5): + output2 = tf.nn.softmax_cross_entropy_with_logits(labels=labels, + logits=logits) + tf.debugging.assert_equal(output, output2) + ``` + + ## Writing deterministic models + + You can make your models deterministic by enabling op determinism. This + means that you can train a model and finish each run with exactly the same + trainable variables. This also means that the inferences of your + previously-trained model will be exactly the same on each run. Typically, + models can be made deterministic by simply setting the seeds and enabling + op determinism, as in the example above. However, to guarantee that your + model operates deterministically, you must meet all the following + requirements: + + * Call `tf.config.experimental.enable_op_determinism()`, as mentioned above. + * Reproducibly reset any pseudorandom number generators (PRNGs) you’re using, + such as by setting the seeds for the default PRNGs in TensorFlow, Python, + and NumPy, as mentioned above. Note that certain newer NumPy classes like + ` numpy.random.default_rng` ignore the global NumPy seed, so a seed must be + explicitly passed to such classes, if used. + * Use the same hardware configuration in every run. + * Use the same software environment in every run (OS, checkpoints, version of + CUDA and TensorFlow, environmental variables, etc). Note that determinism is + not guaranteed across different versions of TensorFlow. + * Do not use constructs outside TensorFlow that are nondeterministic, such as + reading from `/dev/random` or using multiple threads/processes in ways that + influence TensorFlow’s behavior. + * Ensure your input pipeline is deterministic. If you use `tf.data`, this is + done automatically (at the expense of performance). See "Determinism and + tf.data" below for more information. + * Do not use `tf.compat.v1.Session` and + `tf.distribute.experimental.ParameterServerStrategy`, which can introduce + nondeterminism. Besides ops (including `tf.data` ops), these are the only + known potential sources of nondeterminism within TensorFlow, (if you + find more, please file an issue). Note that `tf.compat.v1.Session` is + required to use the TF1 API, so determinism cannot be guaranteed when using + the TF1 API. + * Do not use nondeterministic custom ops. + + ## Additional details on determinism + + For stateful ops to be deterministic, the state of the system must be the same + every time the op is run. For example the output of `tf.Variable.sparse_read` + (obviously) depends on both the variable value and the `indices` function + parameter. When determinism is enabled, the side effects of stateful ops are + deterministic. + + TensorFlow’s random ops, such as `tf.random.normal`, will raise a + `RuntimeError` if determinism is enabled and a seed has not been set. However, + attempting to generate nondeterministic random numbers using Python or NumPy + will not raise such errors. Make sure you remember to set the Python and NumPy + seeds. Calling `tf.keras.utils.set_random_seed` is an easy way to set all + three seeds. + + Note that latency, memory consumption, throughput, and other performance + characteristics are *not* made deterministic by enabling op determinism. + Only op outputs and side effects are made deterministic. Additionally, a model + may nondeterministically raise a `tf.errors.ResourceExhaustedError` from a + lack of memory due to the fact that memory consumption is nondeterministic. + + ## Determinism and tf.data + + Enabling deterministic ops makes `tf.data` deterministic in several ways: + + 1. For dataset methods with a `deterministic` argument, such as `Dataset.map` + and `Dataset.batch`, the `deterministic` argument is overridden to be + `True` irrespective of its setting. + 2. The `tf.data.Option.experimental_deterministic` option is overridden to be + `True` irrespective of its setting.. + 3. In `Dataset.map` and `Dataset.interleave`, if the map or interleave + function has stateful random ops or other stateful ops, the function will + run serially instead of in parallel. This means the `num_parallel_calls` + argument to `map` and `interleave` is effectively ignored. + 4. Prefetching with `Dataset.prefetch` will be disabled if any function run + as part of the input pipeline has certain stateful ops. Similarly, any + dataset method with a `num_parallel_calls` argument will be made to run + serially if any function in the input pipeline has such stateful ops. + Legacy random ops such as `tf.random.normal` will *not* cause such datasets + to be changed, but most other stateful ops will. + + Unfortunately, due to (3), performance can be greatly reduced when stateful + ops are used in `Dataset.map` due to no longer running the map function in + parallel. A common example of stateful ops used in `Dataset.map` are random + ops, such as `tf.random.normal`, which are typically used for distortions. One + way to work around this is to use stateless random ops instead. Alternatively + you can hoist all random ops into its own separate `Dataset.map` call, making + the original `Dataset.map` call stateless and thus avoid the need to serialize + its execution. + + (4) can also cause performance to be reduced, but occurs less frequently than + (3) because legacy random ops do not cause (4) to take effect. However, unlike + (3), when there are non-random stateful ops in a user-defined function, every + `map` and `interleave` dataset is affected, instead of just the `map` or + `interleave` dataset with the function that has stateful ops. Additionally, + `prefetch` datasets and any dataset with the `num_parallel_calls` argument are + also affected. + """ + _pywrap_determinism.enable(True) + + +def disable_op_determinism(): + """Disables op determinism.""" + _pywrap_determinism.enable(False) + + +def is_op_determinism_enabled(): + """Returns True if op determinism is enabled.""" + return _pywrap_determinism.is_enabled() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/constant_op.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/constant_op.py new file mode 100644 index 0000000000000000000000000000000000000000..9c2d8d21a7c0b8f2943440dad0e77b0d2abe2909 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/constant_op.py @@ -0,0 +1,471 @@ +# 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. +# ============================================================================== +"""Operations that generate constants. + +See the [constants guide](https://tensorflow.org/api_guides/python/constant_op). +""" + +# Must be separate from array_ops to avoid a cyclic dependency. + +from typing import Union +import numpy as np +from tensorflow.core.framework import types_pb2 +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.eager import context +from tensorflow.python.eager import execute +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.profiler import trace +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util.tf_export import tf_export + + +def _eager_reshape(tensor, shape, ctx): + """Eager-only version of Reshape op; requires tensor is an eager Tensor.""" + attr_t = tensor._datatype_enum() # pylint: disable=protected-access + attr_tshape, (shape,) = execute.args_to_matching_eager( + [shape], ctx, [dtypes.int32, dtypes.int64], dtypes.int32) + inputs_flat = [tensor, shape] + attrs = ("T", attr_t, "Tshape", attr_tshape) + [result] = execute.execute( + b"Reshape", 1, inputs=inputs_flat, attrs=attrs, ctx=ctx) + return result + + +def _eager_fill(dims, value, ctx): + """Eager-only version of Fill op; requires value is an eager Tensor.""" + attr_t = value.dtype.as_datatype_enum + dims = convert_to_eager_tensor(dims, ctx, dtypes.int32) + inputs_flat = [dims, value] + attrs = ("T", attr_t, "index_type", types_pb2.DT_INT32) + [result] = execute.execute( + b"Fill", 1, inputs=inputs_flat, attrs=attrs, ctx=ctx) + return result + + +def _eager_identity(tensor, ctx): + """Eager-only version of Identity op; requires tensor is an eager Tensor.""" + attrs = ("T", tensor.dtype.as_datatype_enum) + [result] = execute.execute( + b"Identity", 1, inputs=[tensor], attrs=attrs, ctx=ctx) + return result + + +def convert_to_eager_tensor(value, ctx, dtype=None) -> ops._EagerTensorBase: + """Converts the given `value` to an `EagerTensor`. + + Note that this function could return cached copies of created constants for + performance reasons. + + Args: + value: value to convert to EagerTensor. + ctx: value of context.context(). + dtype: optional desired dtype of the converted EagerTensor. + + Returns: + EagerTensor created from value. + + Raises: + TypeError: if `dtype` is not compatible with the type of t. + """ + if isinstance(value, np.ndarray): + # Make a copy explicitly because the EagerTensor might share the underlying + # memory with the input array. Without this copy, users will be able to + # modify the EagerTensor after its creation by changing the input array. + value = value.copy() + if isinstance(value, ops.EagerTensor): + if dtype is not None and value.dtype != dtype: + raise TypeError(f"Expected tensor {value} with dtype {dtype!r}, but got " + f"dtype {value.dtype!r}.") + return value + if dtype is not None: + try: + dtype = dtype.as_datatype_enum + except AttributeError: + dtype = dtypes.as_dtype(dtype).as_datatype_enum + ctx.ensure_initialized() + return ops.EagerTensor(value, ctx.device_name, dtype) + + +@tf_export(v1=["constant"]) +def constant_v1( + value, dtype=None, shape=None, name="Const", verify_shape=False +) -> Union[ops.Operation, ops._EagerTensorBase]: + """Creates a constant tensor. + + The resulting tensor is populated with values of type `dtype`, as + specified by arguments `value` and (optionally) `shape` (see examples + below). + + The argument `value` can be a constant value, or a list of values of type + `dtype`. If `value` is a list, then the length of the list must be less + than or equal to the number of elements implied by the `shape` argument (if + specified). In the case where the list length is less than the number of + elements specified by `shape`, the last element in the list will be used + to fill the remaining entries. + + The argument `shape` is optional. If present, it specifies the dimensions of + the resulting tensor. If not present, the shape of `value` is used. + + If the argument `dtype` is not specified, then the type is inferred from + the type of `value`. + + For example: + + ```python + # Constant 1-D Tensor populated with value list. + tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7] + + # Constant 2-D tensor populated with scalar value -1. + tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.] + [-1. -1. -1.]] + ``` + + `tf.constant` differs from `tf.fill` in a few ways: + + * `tf.constant` supports arbitrary constants, not just uniform scalar + Tensors like `tf.fill`. + * `tf.constant` creates a `Const` node in the computation graph with the + exact value at graph construction time. On the other hand, `tf.fill` + creates an Op in the graph that is expanded at runtime. + * Because `tf.constant` only embeds constant values in the graph, it does + not support dynamic shapes based on other runtime Tensors, whereas + `tf.fill` does. + + Args: + value: A constant value (or list) of output type `dtype`. + + dtype: The type of the elements of the resulting tensor. + + shape: Optional dimensions of resulting tensor. + + name: Optional name for the tensor. + + verify_shape: Boolean that enables verification of a shape of values. + + Returns: + A Constant Tensor. + + Raises: + TypeError: if shape is incorrectly specified or unsupported. + """ + return _constant_impl(value, dtype, shape, name, verify_shape=verify_shape, + allow_broadcast=False) + + +@tf_export("constant", v1=[]) +def constant( + value, dtype=None, shape=None, name="Const" +) -> Union[ops.Operation, ops._EagerTensorBase]: + """Creates a constant tensor from a tensor-like object. + + Note: All eager `tf.Tensor` values are immutable (in contrast to + `tf.Variable`). There is nothing especially _constant_ about the value + returned from `tf.constant`. This function is not fundamentally different from + `tf.convert_to_tensor`. The name `tf.constant` comes from the `value` being + embedded in a `Const` node in the `tf.Graph`. `tf.constant` is useful + for asserting that the value can be embedded that way. + + If the argument `dtype` is not specified, then the type is inferred from + the type of `value`. + + >>> # Constant 1-D Tensor from a python list. + >>> tf.constant([1, 2, 3, 4, 5, 6]) + + >>> # Or a numpy array + >>> a = np.array([[1, 2, 3], [4, 5, 6]]) + >>> tf.constant(a) + + + If `dtype` is specified, the resulting tensor values are cast to the requested + `dtype`. + + >>> tf.constant([1, 2, 3, 4, 5, 6], dtype=tf.float64) + + + If `shape` is set, the `value` is reshaped to match. Scalars are expanded to + fill the `shape`: + + >>> tf.constant(0, shape=(2, 3)) + + >>> tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) + + + `tf.constant` has no effect if an eager Tensor is passed as the `value`, it + even transmits gradients: + + >>> v = tf.Variable([0.0]) + >>> with tf.GradientTape() as g: + ... loss = tf.constant(v + v) + >>> g.gradient(loss, v).numpy() + array([2.], dtype=float32) + + But, since `tf.constant` embeds the value in the `tf.Graph` this fails for + symbolic tensors: + + >>> with tf.compat.v1.Graph().as_default(): + ... i = tf.compat.v1.placeholder(shape=[None, None], dtype=tf.float32) + ... t = tf.constant(i) + Traceback (most recent call last): + ... + TypeError: ... + + `tf.constant` will create tensors on the current device. Inputs which are + already tensors maintain their placements unchanged. + + Related Ops: + + * `tf.convert_to_tensor` is similar but: + * It has no `shape` argument. + * Symbolic tensors are allowed to pass through. + + >>> with tf.compat.v1.Graph().as_default(): + ... i = tf.compat.v1.placeholder(shape=[None, None], dtype=tf.float32) + ... t = tf.convert_to_tensor(i) + + * `tf.fill`: differs in a few ways: + * `tf.constant` supports arbitrary constants, not just uniform scalar + Tensors like `tf.fill`. + * `tf.fill` creates an Op in the graph that is expanded at runtime, so it + can efficiently represent large tensors. + * Since `tf.fill` does not embed the value, it can produce dynamically + sized outputs. + + Args: + value: A constant value (or list) of output type `dtype`. + dtype: The type of the elements of the resulting tensor. + shape: Optional dimensions of resulting tensor. + name: Optional name for the tensor. + + Returns: + A Constant Tensor. + + Raises: + TypeError: if shape is incorrectly specified or unsupported. + ValueError: if called on a symbolic tensor. + """ + return _constant_impl(value, dtype, shape, name, verify_shape=False, + allow_broadcast=True) + + +def _constant_impl( + value, dtype, shape, name, verify_shape, allow_broadcast +) -> Union[ops.Operation, ops._EagerTensorBase]: + """Implementation of constant.""" + ctx = context.context() + if ctx.executing_eagerly(): + if trace.enabled: + with trace.Trace("tf.constant"): + return _constant_eager_impl(ctx, value, dtype, shape, verify_shape) + return _constant_eager_impl(ctx, value, dtype, shape, verify_shape) + + const_tensor = ops._create_graph_constant( # pylint: disable=protected-access + value, dtype, shape, name, verify_shape, allow_broadcast + ) + return const_tensor + + +def _constant_eager_impl( + ctx, value, dtype, shape, verify_shape +) -> ops._EagerTensorBase: + """Creates a constant on the current device.""" + t = convert_to_eager_tensor(value, ctx, dtype) + if shape is None: + return t + shape = tensor_shape.as_shape(shape) + if shape == t.shape: + return t + if verify_shape: + raise TypeError(f"Expected Tensor {t} (converted from {value}) with shape " + f"{tuple(shape)}, but got shape {tuple(t.shape)}.") + num_t = t.shape.num_elements() + # TODO(josh11b): Implement shape -> eager tensor conversion. + if num_t == shape.num_elements(): + return _eager_reshape(t, shape.as_list(), ctx) + if num_t == 1: + if t.dtype == dtypes.bool: + # We don't have a Fill kernel for bool dtype on GPU. So we first run + # Fill on CPU and then copy to GPU if needed. + with ops.device("/device:CPU:0"): + x = _eager_fill(shape.as_list(), _eager_identity(t, ctx), ctx) + return _eager_identity(x, ctx) + else: + return _eager_fill(shape.as_list(), t, ctx) + raise TypeError("Eager execution of tf.constant with unsupported shape. " + f"Tensor {t} (converted from {value}) has {num_t:d} " + f"elements, but got `shape` {shape} with " + f"{shape.num_elements()} elements).") + + +def is_constant(tensor_or_op): + if isinstance(tensor_or_op, tensor_lib.Tensor): + op = tensor_or_op.op + else: + op = tensor_or_op + return op.type == "Const" + + +def _constant_tensor_conversion_function(v, dtype=None, name=None, + as_ref=False): + _ = as_ref + return constant(v, dtype=dtype, name=name) + +# Register the conversion function for the "unconvertible" types +# as a conversion to a constant. +tensor_conversion_registry.register_tensor_conversion_function_internal( + tensor_conversion_registry._CONSTANT_OP_CONVERTIBLES, # pylint: disable=protected-access + _constant_tensor_conversion_function, + 0) + +tensor_conversion_registry.register_tensor_conversion_function( + (list, tuple), _constant_tensor_conversion_function, 100) +tensor_conversion_registry.register_tensor_conversion_function( + object, _constant_tensor_conversion_function, 200) + + +def _tensor_shape_tensor_conversion_function(s, + dtype=None, + name=None, + as_ref=False): + """Function to convert TensorShape to Tensor.""" + _ = as_ref + if not s.is_fully_defined(): + raise ValueError( + f"Cannot convert a partially known TensorShape {s} to a Tensor.") + s_list = s.as_list() + int64_value = 0 + for dim in s_list: + if dim >= 2**31: + int64_value = dim + break + + if dtype is not None: + if dtype not in (dtypes.int32, dtypes.int64): + raise TypeError(f"Cannot convert TensorShape {s} to dtype {dtype}. " + "Allowed dtypes are tf.int32 and tf.int64.") + if dtype == dtypes.int32 and int64_value: + raise ValueError(f"Cannot convert TensorShape {s} to dtype int32; " + f"a dimension is too large. Consider using tf.int64.") + else: + dtype = dtypes.int64 if int64_value else dtypes.int32 + if name is None: + name = "shape_as_tensor" + return constant(s_list, dtype=dtype, name=name) + + +tensor_conversion_registry.register_tensor_conversion_function( + tensor_shape.TensorShape, _tensor_shape_tensor_conversion_function, 100) + + +def _dimension_tensor_conversion_function(d, + dtype=None, + name=None, + as_ref=False): + """Function to convert Dimension to Tensor.""" + _ = as_ref + if d.value is None: + raise ValueError(f"Cannot convert unknown Dimension {d} to a Tensor.") + if dtype is not None: + if dtype not in (dtypes.int32, dtypes.int64): + raise TypeError(f"Cannot convert Dimension {d} to dtype {dtype}. " + "Allowed dtypes are tf.int32 and tf.int64.") + else: + dtype = dtypes.int32 + if name is None: + name = "shape_as_tensor" + return constant(d.value, dtype=dtype, name=name) + + +tensor_conversion_registry.register_tensor_conversion_function( + tensor_shape.Dimension, _dimension_tensor_conversion_function, 100) + + +class _ConstantTensorCodec: + """Codec for Tensor.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, tensor_lib.Tensor) + + def do_encode(self, tensor_value, encode_fn): + """Returns an encoded `TensorProto` for the given `tf.Tensor`.""" + del encode_fn + encoded_tensor = struct_pb2.StructuredValue() + if isinstance(tensor_value, ops.EagerTensor): + encoded_tensor.tensor_value.CopyFrom( + tensor_util.make_tensor_proto(tensor_value.numpy()) + ) + else: + if tensor_value.op.type == "Const": + encoded_tensor.tensor_value.CopyFrom(tensor_value.op.get_attr("value")) + else: + raise nested_structure_coder.NotEncodableError( + f"No encoder for object {str(tensor_value)} of type" + f" {type(tensor_value)}." + ) + return encoded_tensor + + def can_decode(self, value): + return value.HasField("tensor_value") + + def do_decode(self, value, decode_fn): + """Returns the `tf.Tensor` encoded by the proto `value`.""" + del decode_fn + tensor_proto = value.tensor_value + tensor = constant(tensor_util.MakeNdarray(tensor_proto)) + return tensor + + +nested_structure_coder.register_codec(_ConstantTensorCodec()) + + +class _NumpyCodec: + """Codec for Numpy.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, np.ndarray) + + def do_encode(self, numpy_value, encode_fn): + """Returns an encoded `TensorProto` for `np.ndarray`.""" + del encode_fn + encoded_numpy = struct_pb2.StructuredValue() + encoded_numpy.numpy_value.CopyFrom( + tensor_util.make_tensor_proto(numpy_value) + ) + return encoded_numpy + + def can_decode(self, value): + return value.HasField("numpy_value") + + def do_decode(self, value, decode_fn): + """Returns the `np.ndarray` encoded by the proto `value`.""" + del decode_fn + tensor_proto = value.numpy_value + numpy = tensor_util.MakeNdarray(tensor_proto) + return numpy + + +nested_structure_coder.register_codec(_NumpyCodec()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..9ec5bcd808a4ca94207bdccfa6141e836b739023 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py @@ -0,0 +1,1336 @@ +# 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. +# ============================================================================== +"""Helpers to convert variables to constants in TensorFlow 2.0.""" + +import collections +import numpy as np + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import tensor_shape_pb2 +from tensorflow.core.framework import variable_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.eager import context +from tensorflow.python.eager import wrap_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import graph_util +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_util +from tensorflow.python.grappler import tf_optimizer +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training.saver import export_meta_graph +from tensorflow.python.util import deprecation +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +# Used in _FunctionConverterDataInGraph(). +VAR_ASSIGN_COLLECTION = "extra_var_assign_ops" +_CONDITIONAL_OPS = set(["If", "StatelessIf"]) +_LOOP_OPS = set(["While", "StatelessWhile"]) +_CONTROL_FLOW_OPS = _CONDITIONAL_OPS.union(_LOOP_OPS) + + +class _TensorData( + collections.namedtuple("_TensorData", ["numpy", "dtype", "index"])): + """Data about a tensor that was converted to a constant.""" + __slots__ = () + + @property + def dtype_attr(self): + return attr_value_pb2.AttrValue(type=self.dtype) + + +class _EndPoint(collections.namedtuple("_EndPoint", ["convertible", "index"])): + """An endpoint in a graph.""" + __slots__ = () + + def __str__(self): + return "{}[{}]".format(self.convertible, self.index) + + +class _Edge(collections.namedtuple("_Edge", ["source", "destination"])): + """A directed graph edge.""" + __slots__ = () + + def __str__(self): + return "{} -> {}".format(self.source, self.destination) + + +class _Convertible(object): + """An entity that can have variables converted to constants.""" + + def __init__(self, enclosing_graph): + self._enclosing_graph = enclosing_graph + self._outgoing_edges = [] + self._converted_self = None + + def converted_self(self): + """A copy of this Convertible to be modified during conversion. + + Returns: + Implementations should return the copied instance, which in turn should + be contained in converted_enclosing_graph(). This instance is the one that + will be modified during conversion. Its main use will be in the + implementations of convert_variable_to_constant(). + """ + raise NotImplementedError + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + """Converts a variable in this Convertible and its dependencies. + + This method should make sure that a converted copy of itself is present in + the converted graph, and that all Convertibles depending on this one also go + through the same process. + + Args: + incoming_edge: The graph edge into this Convertible that is being + converted to a constant. + tensor_data: The tensor representing the constant. + """ + raise NotImplementedError + + def create_edges(self): + """Calls add_outgoing_edge for all edges known to this Convertible. + + This is used to build the graph dependencies, so that conversion of + variables to constants can be properly propagated through the graph. Usually + this method will call add_outgoing_edge() to all the Convertible inputs. + """ + raise NotImplementedError + + def add_outgoing_edge(self, edge): + """Adds an outgoing edge to the Convertible's list of edges. + + Args: + edge: The outgoing edge (its source should be 'self'). + """ + self._outgoing_edges.append(edge) + + @property + def converted_enclosing_graph(self): + """The graph being converted.""" + return self._enclosing_graph.converted_self() + + @property + def outgoing_edges(self): + """The list of edges starting at this Convertible.""" + return self._outgoing_edges + + +class _Function(_Convertible): + """A library function Convertible. + + Edges into functions are edges from node _inputs_ into function _inputs_: + Functions get their input from their callers, not from node outputs, and the + callers in turn get those values as inputs. + """ + + def __init__(self, function, enclosing_graph): + super(_Function, self).__init__(enclosing_graph) + self._function = function + self._nodes = { + n.name: + _Node.new(node=n, function=self, enclosing_graph=enclosing_graph) + for n in function.node_def + } + + def __str__(self): + return self.function.signature.name + + @property + def function(self): + return self._function + + @property + def nodes(self): + return self._nodes + + def converted_self(self): + """The Function copy to be converted. + + The copy will be renamed according to the graph's converted_function_name + map, to ensure the name does not match anything currently in TensorFlow's + function cache. + + Returns: + The function instance to be converted. + """ + if self._converted_self is None: + old_name = self.function.signature.name + new_name = self._enclosing_graph.converted_function_names[old_name] + self.converted_enclosing_graph.rename_function(old_name, new_name) + self._converted_self = self.converted_enclosing_graph.functions[new_name] + return self._converted_self + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + """Converts one function argument into a constant. + + Args: + incoming_edge: The edge into the argument to be converted. + tensor_data: The constant value. + """ + index = incoming_edge.destination.index + for edge in self.outgoing_edges: + if edge.source.index == index: + edge.destination.convertible.convert_variable_to_constant( + edge, tensor_data) + + function = self.converted_self().function + function.signature.input_arg[index].type = tensor_data.dtype + # TODO(b/176982859): Find a more satisfying way to update shape information + # than clearing it, or migrate users to a workflow that does not require + # freezing. + if "_input_shapes" in function.attr: + function.attr["_input_shapes"].list.shape[index].unknown_rank = True + del function.attr["_input_shapes"].list.shape[index].dim[:] + arg_attrs = function.arg_attr[index].attr + if "_output_shapes" in arg_attrs: + arg_attrs["_output_shapes"].list.shape[0].unknown_rank = True + del arg_attrs["_output_shapes"].list.shape[0].dim[:] + + def create_edges(self): + for n in self._nodes.values(): + n.create_edges() + + +class _Node(_Convertible): + """A Convertible NodeDef.""" + + def __init__(self, node, function, enclosing_graph): + super(_Node, self).__init__(enclosing_graph) + self._node = node + self._function = function + + def __str__(self): + return self._node.name + + @staticmethod + def new(node, function, enclosing_graph): + """Creates a new _Node base on its operation type.""" + if node.op in ["VariableV2", "VarHandleOp", "Placeholder"]: + return _VarHandle(node, function, enclosing_graph) + elif node.op == "Case": + return _Case(node, function, enclosing_graph) + elif node.op == "Merge": + return _Merge(node, function, enclosing_graph) + elif node.op == "PartitionedCall": + return _PartitionedCall(node, function, enclosing_graph) + elif node.op == "StatefulPartitionedCall": + return _PartitionedCall(node, function, enclosing_graph) + elif node.op == "ReadVariableOp": + return _ReadVariable(node, function, enclosing_graph) + elif node.op == "ResourceGather": + return _ResourceGather(node, function, enclosing_graph) + elif node.op == "ResourceGatherNd": + return _ResourceGatherNd(node, function, enclosing_graph) + elif node.op in ["If", "StatelessIf"]: + return _If(node, function, enclosing_graph) + elif node.op in ["While", "StatelessWhile"]: + return _While(node, function, enclosing_graph) + elif node.op in [ + "Enter", "Exit", "Identity", "NextIteration", "Switch", "_SwitchN"]: + return _Intermediate(node, function, enclosing_graph) + else: + return _Node(node, function, enclosing_graph) + + @property + def node(self): + return self._node + + @property + def container(self): + """The node container (either a graph or a function).""" + if self._function is not None: + return self._function.function + return self._enclosing_graph.graph_def + + def converted_self(self): + """The NodeDef to be converted. + + Returns: + The NodeDef to be converted, which can come from either a graph for a + function. Derived classes should call this (via 'super') to make sure the + node is retrieved from the right place. + """ + if self._converted_self is None: + source = self._function or self._enclosing_graph + self._converted_self = source.converted_self().nodes[self._node.name] + return self._converted_self + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + pass + + def create_edges(self): + for index, name in enumerate(self._node.input): + # Discard edges from control inputs. + if name[0] == "^": + continue + source = self.resolve_input(name) + source.convertible.add_outgoing_edge( + _Edge(source, _EndPoint(self, index))) + + def resolve_input(self, input_name): + """Resolves an input into its _EndPoint. + + A NodeDef's input name can refer to either global NodeDefs (in the + GraphDef's node list), a NodeDef in a function's node list, or a Function + (in the GraphDef's function library). The name can also carry semantic + information, depending on whether it starts with "^". This method handles + all that logic in order to find the object to which the input name refers + to. + + Args: + input_name: The input name to resolve. + + Returns: + The object referred to by 'input_name'. + """ + + # The logic below oversimplifies the semantics, but is good enough for the + # purposes of converting to constants. The introduction of new types of + # operations may change this, forcing the code to be more generic. + # + # In particular, we are assuming that the lack of an index suffix means + # ":0", when it could mean "all the outputs of a node." This works now + # because converting to constants relies very little on output types, and + # when it does it specializes its treatment in dedicated classes. + name_elts = input_name.split(":") + source_name = name_elts[0] + if source_name[0] == "^": + source_name = source_name[1:] + source_index = 0 + if len(name_elts) > 1 and name_elts[-1].isnumeric(): + source_index = int(name_elts[-1]) + + if self._function is None: + return _EndPoint(self._enclosing_graph.nodes[source_name], source_index) + + if source_index != 0 or source_name in self._function.nodes: + return _EndPoint(self._function.nodes[source_name], source_index) + + inputs = [i.name for i in self._function.function.signature.input_arg] + return _EndPoint(self._function, inputs.index(source_name)) + + def update_dtype(self, attr_name, index, dtype): + """Changes the type of a given input. + + Args: + attr_name: The NodeDef attribute containing the type to change. + index: The index of the input type to change. + dtype: The type to change to. + """ + attr = self._node.attr[attr_name] + num_types = 0 + # Check for various 'oneof' possibilities, and update the type if + # index in range. + if attr.HasField("list"): + types = attr.list.type + num_types = len(types) + if num_types > index: + types[index] = dtype + return + elif attr.HasField("type"): + num_types = 1 + if index == 0: + attr.type = dtype + return + raise ValueError(f"`index` {index:d} is out of range for " + f"node({self._node.name}).attr({attr_name}), which has " + f"{num_types:d} elements.") + + +class _Intermediate(_Node): + """Specialization of _Node to intermediate ops.""" + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + node = self.converted_self() + node.update_dtype("T", incoming_edge.destination.index, tensor_data.dtype) + if "_output_shapes" in node.node.attr: + del node.node.attr["_output_shapes"] + for edge in self.outgoing_edges: + edge.destination.convertible.convert_variable_to_constant( + edge, tensor_data) + + +class _Merge(_Node): + """Specialization of _Node to Merge ops.""" + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + # The Merge operation has a single type for all its inputs, the number of + # which is reflected in the "N" attribute. For the time being, we assume + # that unilaterally changing all of them at once is ok. + super(_Merge, self).convert_variable_to_constant( + _Edge(incoming_edge.source, + _Edge(incoming_edge.destination.convertible, 0)), tensor_data) + + +class _VarHandle(_Node): + """Specialization of _Node to VarHandleOp.""" + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + tensor_proto = tensor_util.make_tensor_proto(tensor_data.numpy, + tensor_data.dtype, + tensor_data.numpy.shape) + + node = self.converted_self().node + node.Clear() + node.name = self._node.name + node.op = "Const" + node.attr["dtype"].CopyFrom(tensor_data.dtype_attr) + node.attr["value"].tensor.CopyFrom(tensor_proto) + + for edge in self.outgoing_edges: + edge.destination.convertible.convert_variable_to_constant( + edge, tensor_data) + + +class _ResourceGather(_Node): + """Specialization of _Node to ResourceGather.""" + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + # We currently skip the conversion if this is inside a function. + if self._function is not None: + return + if self._node.attr["batch_dims"].i != 0: + raise ValueError("batch_dims must be 0 for freeze_graph, but got " + f"node({self._node.name}).attr('batch_dims') = " + f"{self._node.attr['batch_dims'].i}.") + axis_node_name = self._node.name + "/axis" + axis_dtype = self._node.attr["Tindices"] + axis_data = np.array(self._node.attr["batch_dims"].i) + converted_graph = self._enclosing_graph.converted_self() + # Add Const axis node, or get it if it exists to avoid duplicates. + if axis_node_name not in converted_graph.nodes: + converted_graph.nodes[axis_node_name] = _Node.new( + node=converted_graph.graph_def.node.add(), + function=self._function, + enclosing_graph=converted_graph) + output_axis_node = converted_graph.nodes[axis_node_name].node + output_axis_node.name = axis_node_name + output_axis_node.op = "Const" + output_axis_node.attr["dtype"].CopyFrom(axis_dtype) + tensor = tensor_util.make_tensor_proto( + axis_data, dtype=axis_dtype.type, shape=axis_data.shape) + output_axis_node.attr["value"].tensor.CopyFrom(tensor) + + output_node = self.converted_self().node + output_node.Clear() + output_node.name = self._node.name + output_node.op = "GatherV2" + output_node.input.extend( + [self._node.input[0], self._node.input[1], axis_node_name]) + output_node.attr["Tparams"].CopyFrom(self._node.attr["dtype"]) + output_node.attr["Tindices"].CopyFrom(self._node.attr["Tindices"]) + output_node.attr["Taxis"].CopyFrom(axis_dtype) + if "_class" in self._node.attr: + output_node.attr["_class"].CopyFrom(self._node.attr["_class"]) + + +class _ResourceGatherNd(_Node): + """Specialization of _Node to ResourceGatherNd.""" + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + output_node = self.converted_self().node + output_node.Clear() + output_node.name = self._node.name + output_node.op = "GatherNd" + output_node.input.extend([self._node.input[0], self._node.input[1]]) + output_node.attr["Tparams"].CopyFrom(self._node.attr["dtype"]) + output_node.attr["Tindices"].CopyFrom(self._node.attr["Tindices"]) + if "_class" in self._node.attr: + output_node.attr["_class"].CopyFrom(self._node.attr["_class"]) + + +class _ReadVariable(_Node): + """Specialization of _Node to ReadVariableOp.""" + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + node = self.converted_self().node + node.Clear() + node.name = self._node.name + node.op = "Identity" + + node.input.append(self._node.input[0]) + node.attr["T"].CopyFrom(self._node.attr["dtype"]) + if "_class" in self._node.attr: + node.attr["_class"].CopyFrom(self._node.attr["_class"]) + + # If the ReadVariableOp is part of a function, then every node having the + # ReadVariableOp one as its input will refer to it using a ":value" + # syntax. We need to change that to ":output". + if self._function is not None: + for edge in self.outgoing_edges: + index = edge.destination.index + dest = edge.destination.convertible.converted_self() + if isinstance(dest, _Node): + input_name_parts = dest.node.input[index].split(":") + if len(input_name_parts) > 1 and input_name_parts[1] == "value": + input_name_parts[1] = "output" + dest.node.input[index] = ":".join(input_name_parts) + + +class _FunctionCaller(_Node): + """A base class for Convertibles that reference functions.""" + + def __init__(self, node, function, enclosing_graph, first_function_input, + type_attribute, function_attributes): + """Initializes a _FunctionCaller. + + Args: + node: As in _Node. + function: As in _Node. + enclosing_graph: As in _Node. + first_function_input: The index of the first NodeDef input that is tied to + the function inputs. It is assumed that the rest of the NodeDef inputs + map one to one to function inputs. + type_attribute: The name of the NodeDef attribute that defines the input + types. It is assumed that the types listed here map one-to-one with the + function inputs (that is, they do _not_ specify types for inputs that + are not passed to functions). + function_attributes: The names of the NodeDef attributes containing + references to functions. + """ + super(_FunctionCaller, self).__init__(node, function, enclosing_graph) + self._first_function_input = first_function_input + self._type_attribute = type_attribute + self._function_attributes = function_attributes + + def converted_self(self): + if self._converted_self is None: + node = super(_FunctionCaller, self).converted_self().node + converted_names = self._enclosing_graph.converted_function_names + for attr_name in self._function_attributes: + attr = node.attr[attr_name] + if attr.HasField( + "func") and self._enclosing_graph.is_converted_function( + attr.func.name): + attr.func.name = converted_names[attr.func.name] + elif attr.HasField("list"): + for func in attr.list.func: + if self._enclosing_graph.is_converted_function(func.name): + func.name = converted_names[func.name] + return self._converted_self + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + index = incoming_edge.destination.index + # The loop below is reasonable but not correct in general: + # The outgoing edges going into the functions are correct, because the + # inputs map to the function inputs. But the edges going into other nodes do + # not take into account the logic of the body function, which may do + # arbitrary things to the node's output: + # + # while x < 0: + # return y + # + # In this case, the node's ":0" output may map to its ":1 input". For the + # time being, then, we only process edges into functions. + for edge in self.outgoing_edges: + dest = edge.destination.convertible + if edge.source.index == index and isinstance(dest, _Function): + dest.convert_variable_to_constant(edge, tensor_data) + + node = self.converted_self() + if index >= self._first_function_input: + node.update_dtype(self._type_attribute, + index - self._first_function_input, tensor_data.dtype) + + def create_edges(self): + """Creates edges related to a function caller. + + Edges from a function caller to its called functions are always edges from + _inputs_ to _inputs_: a FunctionDef input is given by the caller, based on + its own inputs. + """ + super(_FunctionCaller, self).create_edges() + for attr_name in self._function_attributes: + attr = self._node.attr[attr_name] + if attr.HasField("func"): + function = self._enclosing_graph.functions[attr.func.name] + for index in range(len(self._node.input) - self._first_function_input): + self.add_outgoing_edge( + _Edge( + _EndPoint(self, index + self._first_function_input), + _EndPoint(function, index))) + elif attr.HasField("list"): + for func in attr.list.func: + function = self._enclosing_graph.functions[func.name] + for index in range( + len(self._node.input) - self._first_function_input): + self.add_outgoing_edge( + _Edge( + _EndPoint(self, index + self._first_function_input), + _EndPoint(function, index))) + + +class _If(_FunctionCaller): + """Specialization of _Node to If-like operations.""" + + def __init__(self, node, function, enclosing_graph): + super(_If, self).__init__( + node, + function, + enclosing_graph, + first_function_input=1, + type_attribute="Tin", + function_attributes=["then_branch", "else_branch"]) + + +class _Case(_FunctionCaller): + """Specialization of _Node to Case-like operations.""" + + def __init__(self, node, function, enclosing_graph): + super(_Case, self).__init__( + node, + function, + enclosing_graph, + first_function_input=1, + type_attribute="Tin", + function_attributes=["branches"]) + + +class _PartitionedCall(_FunctionCaller): + """Specialization of _Node to PartitionedCall-like operations.""" + + def __init__(self, node, function, enclosing_graph): + super(_PartitionedCall, self).__init__( + node, + function, + enclosing_graph, + first_function_input=0, + type_attribute="Tin", + function_attributes=["f"]) + + +class _While(_FunctionCaller): + """Specialization of _Node to While-like operations.""" + + def __init__(self, node, function, enclosing_graph): + super(_While, self).__init__( + node, + function, + enclosing_graph, + first_function_input=0, + type_attribute="T", + function_attributes=["body", "cond"]) + + def convert_variable_to_constant(self, incoming_edge, tensor_data): + super(_While, self).convert_variable_to_constant(incoming_edge, tensor_data) + node = self.converted_self() + if node.node.attr["output_shapes"].list.shape: + node.node.attr["output_shapes"].list.shape[ + incoming_edge.destination.index].CopyFrom( + tensor_shape_pb2.TensorShapeProto(dim=[ + tensor_shape_pb2.TensorShapeProto.Dim(size=dim) + for dim in tensor_data.numpy.shape + ])) + + # The while's body inputs and outputs have the same type, so here we can go + # ahead and change that function's output type. + body_name = self._node.attr["body"].func.name + body = self._enclosing_graph.functions[body_name].converted_self().function + body.signature.output_arg[ + incoming_edge.destination.index].type = tensor_data.dtype + + +class _GraphDef(_Convertible): + """A convertible GraphDef.""" + + def __init__(self, graph_def): + super(_GraphDef, self).__init__(enclosing_graph=None) + self._graph_def = graph_def + self._nodes = { + n.name: _Node.new(node=n, function=None, enclosing_graph=self) + for n in graph_def.node + } + self._functions = { + f.signature.name: _Function(f, enclosing_graph=self) + for f in graph_def.library.function + } + self.create_edges() + self._converted_function_names = None + + @property + def graph_def(self): + return self._graph_def + + @property + def nodes(self): + return self._nodes + + @property + def functions(self): + return self._functions + + @property + def converted_function_names(self): + """Map from original to new function names. + + In order to avoid conflicts (two functions with the same name, one converted + and one not), we need to change the name of every converted function to + something that is hopefully unique. + + Returns: + Map from original to new suggested function names. + """ + if self._converted_function_names is None: + parsed_names = [] # List of (id, base_name, original_name) + for name in self.functions: + elements = name.rsplit("_", 1) + if len(elements) == 2 and elements[1].isnumeric(): + parsed_names.append((int(elements[1]), elements[0], name)) + else: + parsed_names.append((-1, name, name)) + self._converted_function_names = { + name: "{}_frozen_{}".format(base_name, ops.uid()) + for (_, base_name, name) in sorted(parsed_names) + } + + return self._converted_function_names + + def rename_function(self, old_name, new_name): + func = self.functions.pop(old_name) + func.function.signature.name = new_name + self.functions[new_name] = func + + def is_converted_function(self, function_name): + # Only converted functions will be renamed. + return (function_name not in self.converted_self().functions) and ( + function_name in self.converted_function_names) + + def converted_self(self): + if self._converted_self is None: + copied_graph = graph_pb2.GraphDef() + copied_graph.CopyFrom(self._graph_def) + self._converted_self = _GraphDef(copied_graph) + return self._converted_self + + def create_edges(self): + for n in self._nodes.values(): + n.create_edges() + for f in self._functions.values(): + f.create_edges() + + +class _ConverterData(object): + """Container for constant conversion supporting data. + + The data includes the graph being converted, and the pre-converted + tensors. This class will be specialized for ConcreteFunction and Session-based + conversions, as the means to obtain that data is different for each case. + """ + + def __init__(self, + graph_def, + variable_names_allowlist=None, + variable_names_denylist=None): + self._graph_def = graph_def + self._tensor_data = {} + self._build_node_defs_list() + self._variable_names_allowlist = variable_names_allowlist + self._variable_names_denylist = variable_names_denylist + + @property + def graph_def(self): + """The graph to be converted.""" + return self._graph_def + + @property + def node_defs(self): + """All the node defs in the graph to be converted. + + Returns: + A map from node name to the NodeDef for all NodeDefs in the graph, as well + as all control flow NodeDefs in the functions. + """ + return self._node_defs + + @property + def tensor_data(self): + """A map from tensor name to its converted _TensorData.""" + return self._tensor_data + + def _should_convert(self, name): + """Checks whether to convert the given variable name to a constant.""" + return (self._variable_names_allowlist is None or + name in self._variable_names_allowlist) and ( + self._variable_names_denylist is None or + name not in self._variable_names_denylist) + + def _build_node_defs_list(self): + """Builds the list of NodeDefs in the GraphDef. + + This list consists of all NodeDefs in the main graph as well as all control + flow NodeDefs in the functions. + + The remaining NodeDefs in the functions are not included because the op + names + are not unique and the variables are handled differently than the main + graph. + The control flow ops need to be extracted because they are need their + attributes to be updated similar to the control flow ops in the main graph. + """ + self._node_defs = {node.name: node for node in self._graph_def.node} + + if self._graph_def.library: + for func in self._graph_def.library.function: + self._node_defs.update({ + node.name: node + for node in func.node_def + if node.op in _CONTROL_FLOW_OPS + }) + + +class _FunctionConverterData(_ConverterData): + """Container for ConcreteFunction-based conversion data.""" + + def __init__(self, + func, + lower_control_flow, + aggressive_inlining, + variable_names_allowlist=None, + variable_names_denylist=None): + """Creates the conversion data for the given function. + + Args: + func: ConcreteFunction. + lower_control_flow: Boolean indicating whether or not to lower control + flow ops such as If and While. + aggressive_inlining: Boolean indicating whether or not to do aggressive + function inlining (might be unsafe if function has stateful ops, not + properly connected to control outputs). + variable_names_allowlist: The set of variable names to convert (by + default, all variables are converted). + variable_names_denylist: The set of variable names to omit converting to + constants. + """ + + self._func = func + # Inline the graph in order to remove functions when possible. + graph_def = _run_inline_graph_optimization(func, lower_control_flow, + aggressive_inlining) + super(_FunctionConverterData, self).__init__( + graph_def, + variable_names_allowlist=variable_names_allowlist, + variable_names_denylist=variable_names_denylist) + + self._build_tensor_data() + + def _eval(self, tensor): + """Returns the value in the tensor. Must be implemented in sub-classes.""" + raise errors.UnimplementedError( + "The evaluation method should be implemented in sub-classes.") + + def _build_tensor_data(self): + """Caches the tensor data for all Placeholders in the given function.""" + map_index_to_variable = {} + for var in self._func.graph.variables: + for idx, captured_input in enumerate(self._func.captured_inputs): + if var.handle is captured_input: # pylint: disable=protected-access + map_index_to_variable[idx] = var + break + + # Iterates through all captures which are represented as Placeholders. + for idx, (val_tensor, name_tensor) in enumerate(self._func.graph.captures): + tensor_name = name_tensor.name.split(":")[0] + if not self._should_convert(tensor_name): + continue + if idx in map_index_to_variable: + data = self._eval(map_index_to_variable[idx]) + else: + if val_tensor.dtype == dtypes.resource: + logging.vlog(1, "Skip converting resource tensor %s" % tensor_name) + continue + data = np.array(self._eval(val_tensor)) + + self._tensor_data[tensor_name] = _TensorData( + numpy=data, + dtype=dtypes.as_dtype(data.dtype).as_datatype_enum, + index=idx) + + # Get data for VariableV2 ops (reference variables) that cannot be lifted. + for node in self.node_defs.values(): + if node.op == "VariableV2": + if not self._should_convert(node.name): + continue + if node.name not in self.tensor_data: + with self._func.graph.as_default(): + identity_node = array_ops.identity( + self._func.graph.as_graph_element(node.name + ":0")) + pruned_graph = self._func.prune([], [identity_node.name])()[0] + self._tensor_data[node.name] = _TensorData( + numpy=pruned_graph.numpy(), + dtype=node.attr["dtype"].type, + index=None) + + +class _FunctionConverterDataInEager(_FunctionConverterData): + """Container for ConcreteFunction-based conversion data in Eager mode.""" + + def _eval(self, tensor): + """Returns the value in the tensor. Must be implemented in sub-classes.""" + return tensor.numpy() + + +class _FunctionConverterDataInGraph(_FunctionConverterData): + """Container for ConcreteFunction-based conversion data in Graph mode.""" + + def __init__(self, + func, + lower_control_flow, + aggressive_inlining, + variable_names_allowlist=None, + variable_names_denylist=None, + session=None): + """Creates the conversion data for the given function. + + Args: + func: ConcreteFunction. + lower_control_flow: Boolean indicating whether or not to lower control + flow ops such as If and While. + aggressive_inlining: Boolean indicating whether or not to do aggressive + function inlining (might be unsafe if function has stateful ops, not + properly connected to control outputs). + variable_names_allowlist: The set of variable names to convert (by + default, all variables are converted). + variable_names_denylist: The set of variable names to omit converting to + constants. + session: Session object. + """ + self._session = session + + session.run(variables.global_variables_initializer()) + # Run extra assignment ops if needed. + # These assignments are run sequentially to ensure order. + for op in ops.get_default_graph().get_collection(VAR_ASSIGN_COLLECTION): + session.run(op) + + super(_FunctionConverterDataInGraph, self).__init__( + func, + lower_control_flow, + aggressive_inlining, + variable_names_allowlist, + variable_names_denylist) + + def _eval(self, tensor): + """Returns the value in the tensor. Must be implemented in sub-classes.""" + return self._session.run(tensor) + + +class _SessionConverterData(_ConverterData): + """Container for Session-based conversion data.""" + + def __init__(self, + session, + graph_def, + output_node_names, + variable_names_allowlist=None, + variable_names_denylist=None): + graph_def = graph_util.extract_sub_graph(graph_def, output_node_names) + super(_SessionConverterData, self).__init__( + graph_def, + variable_names_allowlist=variable_names_allowlist, + variable_names_denylist=variable_names_denylist) + + nodes_to_convert = [] + tensor_names_to_convert = [] + for node in self.graph_def.node: + if node.op in ["Variable", "VariableV2", "VarHandleOp"]: + tensor_name = node.name + if not self._should_convert(tensor_name): + continue + if node.op == "VarHandleOp": + tensor_name = tensor_name + "/Read/ReadVariableOp" + nodes_to_convert.append(node) + tensor_names_to_convert.append(tensor_name + ":0") + + if tensor_names_to_convert: + converted_tensors = session.run(tensor_names_to_convert) + for node, tensor_value in zip(nodes_to_convert, converted_tensors): + self._tensor_data[node.name] = _TensorData( + numpy=tensor_value, dtype=node.attr["dtype"].type, index=None) + + +def disable_lower_using_switch_merge(graph_def): + """Set '_lower_using_switch_merge' attributes to False. + + Sets the attribute to False in the NodeDefs in the main graph and the NodeDefs + in each function's graph. + + Args: + graph_def: GraphDef proto. + + Returns: + GraphDef + """ + output_graph_def = graph_pb2.GraphDef() + output_graph_def.CopyFrom(graph_def) + + def disable_control_flow_lowering(node): + if node.op in _CONTROL_FLOW_OPS: + node.attr["_lower_using_switch_merge"].b = False + + for node in output_graph_def.node: + disable_control_flow_lowering(node) + + if output_graph_def.library: + for func in output_graph_def.library.function: + for node in func.node_def: + disable_control_flow_lowering(node) + return output_graph_def + + +def _run_inline_graph_optimization(func, lower_control_flow, + aggressive_inlining): + """Apply function inline optimization to the graph. + + Returns the GraphDef after Grappler's function inlining optimization is + applied. This optimization does not work on models with control flow. + + Args: + func: ConcreteFunction. + lower_control_flow: Boolean indicating whether or not to lower control flow + ops such as If and While. (default True) + aggressive_inlining: Boolean indicating whether or not to do aggressive + function inlining (might be unsafe if function has stateful ops not + properly connected to control outputs). + + Returns: + GraphDef + """ + graph_def = func.graph.as_graph_def() + if not lower_control_flow: + graph_def = disable_lower_using_switch_merge(graph_def) + + # In some cases, a secondary implementation of the function (e.g. for GPU) is + # written to the "api_implements" attribute. (e.g. `tf.keras.layers.LSTM` in + # TF2 produces a CuDNN-based RNN for GPU). + # This function suppose to inline all functions calls, but "api_implements" + # prevents this from happening. Removing the attribute solves the problem. + # To learn more about "api_implements", see: + # tensorflow/core/grappler/optimizers/implementation_selector.h + for function in graph_def.library.function: + if "api_implements" in function.attr: + del function.attr["api_implements"] + + meta_graph = export_meta_graph(graph_def=graph_def, graph=func.graph) + + # Clear the initializer_name for the variables collections, since they are not + # needed after saved to saved_model. + for name in [ + "variables", "model_variables", "trainable_variables", "local_variables" + ]: + raw_list = [] + for raw in meta_graph.collection_def["variables"].bytes_list.value: + variable = variable_pb2.VariableDef() + variable.ParseFromString(raw) + variable.ClearField("initializer_name") + raw_list.append(variable.SerializeToString()) + meta_graph.collection_def[name].bytes_list.value[:] = raw_list + + # Add a collection 'train_op' so that Grappler knows the outputs. + fetch_collection = meta_graph_pb2.CollectionDef() + for array in func.inputs + func.outputs: + fetch_collection.node_list.value.append(array.name) + meta_graph.collection_def["train_op"].CopyFrom(fetch_collection) + + # Initialize RewriterConfig with everything disabled except function inlining. + config = config_pb2.ConfigProto() + rewrite_options = config.graph_options.rewrite_options + rewrite_options.min_graph_nodes = -1 # do not skip small graphs + rewrite_options.optimizers.append("function") + if aggressive_inlining: + rewrite_options.function_optimization =\ + rewriter_config_pb2.RewriterConfig.AGGRESSIVE + return tf_optimizer.OptimizeGraph(config, meta_graph) + + +def _construct_concrete_function(func, output_graph_def, + converted_input_indices): + """Constructs a concrete function from the `output_graph_def`. + + Args: + func: ConcreteFunction + output_graph_def: GraphDef proto. + converted_input_indices: Set of integers of input indices that were + converted to constants. + + Returns: + ConcreteFunction. + """ + # Create a ConcreteFunction from the new GraphDef. + input_tensors = func.graph.internal_captures + converted_inputs = object_identity.ObjectIdentitySet( + [input_tensors[index] for index in converted_input_indices]) + not_converted_inputs = [ + tensor for tensor in func.inputs if tensor not in converted_inputs + ] + not_converted_inputs_map = { + tensor.name: tensor for tensor in not_converted_inputs + } + + new_input_names = [tensor.name for tensor in not_converted_inputs] + new_output_names = [tensor.name for tensor in func.outputs] + + # Remove old functions to use updated functions from graph def. + for f in output_graph_def.library.function: + if context.context().has_function(f.signature.name): + context.context().remove_function(f.signature.name) + + new_func = wrap_function.function_from_graph_def(output_graph_def, + new_input_names, + new_output_names) + + # Manually propagate shape for input tensors where the shape is not correctly + # propagated. Scalars shapes are lost when wrapping the function. + for input_tensor in new_func.inputs: + input_tensor.set_shape(not_converted_inputs_map[input_tensor.name].shape) + return new_func + + +def _replace_variables_by_constants(converter_data): + """Replaces variables by constants on a given graph. + + Given a _ConverterData instance with converted variables in its tensor_data + field, create a new graph where the respective variables are replaced with the + converted constants. + + Args: + converter_data: A pre-populated _ConverterData instance. + + Returns: + The converted graph. + """ + input_graph = _GraphDef(converter_data.graph_def) + + for tensor_name, tensor_data in converter_data.tensor_data.items(): + input_graph.nodes[tensor_name].convert_variable_to_constant( + None, tensor_data) + + converted_graph = input_graph.converted_self().graph_def + + converted_input_indices = { + t.index + for t in converter_data.tensor_data.values() + if t.index is not None + } + + return converted_graph, converted_input_indices + + +def convert_variables_to_constants_v2(func, + lower_control_flow=True, + aggressive_inlining=False): + """Replaces all the variables in a graph with constants of the same values. + + TensorFlow 2.0 function for converting all Variable ops into Const ops holding + the same values. This makes it possible to describe the network fully with a + single GraphDef file, and allows the removal of a lot of ops related to + loading and saving the variables. This function runs Grappler's function + inlining optimization in order to return a single subgraph. + + The current implementation only works for graphs that do not contain any + control flow or embedding related ops. + + Args: + func: ConcreteFunction. + lower_control_flow: Boolean indicating whether or not to lower control flow + ops such as If and While. (default True) + aggressive_inlining: Boolean indicating whether or not to do aggressive + function inlining (might be unsafe if function has stateful ops, not + properly connected to control outputs). (default False) + + Returns: + ConcreteFunction containing a simplified version of the original. + """ + + converter_data = _FunctionConverterDataInEager( + func=func, + lower_control_flow=lower_control_flow, + aggressive_inlining=aggressive_inlining) + + output_graph_def, converted_input_indices = _replace_variables_by_constants( + converter_data=converter_data) + + return _construct_concrete_function(func, output_graph_def, + converted_input_indices) + + +def convert_var_to_const_function_in_v1(func, + lower_control_flow=True, + aggressive_inlining=False): + """Replaces all the variables in a graph with constants of the same values. + + This function works as same as convert_variables_to_constants_v2, but it + should be used in Graph mode. It is a temporary solution when users want to + integrate their models written in TF2 with infra that requires TF1 mode. + + The current implementation only works for graphs that do not contain any + control flow or embedding related ops. + + The function must be called in a Session context. + + Args: + func: ConcreteFunction. + lower_control_flow: Boolean indicating whether or not to lower control flow + ops such as If and While. (default True) + aggressive_inlining: Boolean indicating whether or not to do aggressive + function inlining (might be unsafe if function has stateful ops, not + properly connected to control outputs). (default False) + + Raises: + RuntimeError: If no Session context is present. + + Returns: + ConcreteFunction containing a simplified version of the original. + """ + + session = ops.get_default_session() + if session is None: + raise RuntimeError( + "The conversion must be carried out in a Session context.") + + converter_data = _FunctionConverterDataInGraph( + func=func, + lower_control_flow=lower_control_flow, + aggressive_inlining=aggressive_inlining, + session=session) + + output_graph_def, converted_input_indices = _replace_variables_by_constants( + converter_data=converter_data) + + return _construct_concrete_function(func, output_graph_def, + converted_input_indices) + + +def convert_variables_to_constants_v2_as_graph(func, + lower_control_flow=True, + aggressive_inlining=False): + """Replaces all the variables in a graph with constants of the same values. + + This function works as same as convert_variables_to_constants_v2, but it + returns the intermediate `GraphDef` as well. This `GraphDef` contains all the + debug information after all the transformations in the frozen phase. + + Args: + func: ConcreteFunction. + lower_control_flow: Boolean indicating whether or not to lower control flow + ops such as If and While. (default True) + aggressive_inlining: Boolean indicating whether or not to do aggressive + function inlining (might be unsafe if function has stateful ops, not + properly connected to control outputs). + + Returns: + ConcreteFunction containing a simplified version of the original, and also + the intermediate GraphDef containing the node debug information for the + transformations in the frozen phase. + """ + converter_data = _FunctionConverterDataInEager( + func=func, + lower_control_flow=lower_control_flow, + aggressive_inlining=aggressive_inlining) + + output_graph_def, converted_input_indices = _replace_variables_by_constants( + converter_data=converter_data) + + frozen_func = _construct_concrete_function(func, output_graph_def, + converted_input_indices) + return frozen_func, output_graph_def + + +def convert_variables_to_constants_from_session_graph( + session, + graph_def, + output_node_names, + variable_names_allowlist=None, + variable_names_denylist=None): + """Replaces all the variables in a graph with constants of the same values. + + This function works similarly to convert_variables_to_constants_v2, but it + retrieves the constant values from a Session instead of from a + ConcreteFunction. This is useful when converting graphs generated from + TensorFlow V1, where ConcreteFunctions are not available. This also differs + from graph_util.convert_variables_to_constants in that it supports resource + variables when V2 control flow constructions are present. + + Args: + session: Active TensorFlow session containing the variables. + graph_def: A GraphDef to convert. + output_node_names: List of name strings for the result nodes of the graph. + variable_names_allowlist: The set of variable names to convert (by default, + all variables are converted). + variable_names_denylist: The set of variable names to omit converting to + constants. + + Returns: + An optimized GraphDef. + """ + graph_def, _ = _replace_variables_by_constants( + converter_data=_SessionConverterData( + session=session, + graph_def=graph_def, + output_node_names=output_node_names, + variable_names_allowlist=variable_names_allowlist, + variable_names_denylist=variable_names_denylist)) + return graph_def + + +@deprecation.deprecated( + date=None, + instructions="This API was designed for TensorFlow v1. See " + "https://www.tensorflow.org/guide/migrate for instructions on how to " + "migrate your code to TensorFlow v2." +) +@tf_export(v1=["graph_util.convert_variables_to_constants"]) +def convert_variables_to_constants(sess, + input_graph_def, + output_node_names, + variable_names_whitelist=None, + variable_names_blacklist=None): + """Replaces all the variables in a graph with constants of the same values. + + If you have a trained graph containing Variable ops, it can be convenient to + convert them all to Const ops holding the same values. This makes it possible + to describe the network fully with a single GraphDef file, and allows the + removal of a lot of ops related to loading and saving the variables. + + Args: + sess: Active TensorFlow session containing the variables. + input_graph_def: GraphDef object holding the network. + output_node_names: List of name strings for the result nodes of the graph. + variable_names_whitelist: The set of variable names to convert (by default, + all variables are converted). + variable_names_blacklist: The set of variable names to omit converting to + constants. + + Returns: + GraphDef containing a simplified version of the original. + + Raises: + RuntimeError: if a DT_RESOURCE op is found whose ancestor Variables are both + denylisted AND whitelisted for freezing. + """ + ret = convert_variables_to_constants_from_session_graph( + session=sess, + graph_def=input_graph_def, + output_node_names=output_node_names, + variable_names_allowlist=variable_names_whitelist, + variable_names_denylist=variable_names_blacklist) + return ret diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/cpp_shape_inference_pb2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/cpp_shape_inference_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..5e26d70fd19047e4f6160f9f07bb2d9d6017a89c --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/cpp_shape_inference_pb2.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: tensorflow/python/framework/cpp_shape_inference.proto +"""Generated protocol buffer code.""" +from google.protobuf.internal import builder as _builder +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from tensorflow.core.framework import full_type_pb2 as tensorflow_dot_core_dot_framework_dot_full__type__pb2 +from tensorflow.core.framework import tensor_shape_pb2 as tensorflow_dot_core_dot_framework_dot_tensor__shape__pb2 +from tensorflow.core.framework import types_pb2 as tensorflow_dot_core_dot_framework_dot_types__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n5tensorflow/python/framework/cpp_shape_inference.proto\x12\ntensorflow\x1a)tensorflow/core/framework/full_type.proto\x1a,tensorflow/core/framework/tensor_shape.proto\x1a%tensorflow/core/framework/types.proto\"\x9b\x03\n\x17\x43ppShapeInferenceResult\x12+\n\x05shape\x18\x01 \x01(\x0b\x32\x1c.tensorflow.TensorShapeProto\x12\x43\n\x0bhandle_data\x18\x04 \x01(\x0b\x32..tensorflow.CppShapeInferenceResult.HandleData\x1a\x93\x01\n\x12HandleShapeAndType\x12+\n\x05shape\x18\x01 \x01(\x0b\x32\x1c.tensorflow.TensorShapeProto\x12#\n\x05\x64type\x18\x02 \x01(\x0e\x32\x14.tensorflow.DataType\x12%\n\x04type\x18\x04 \x01(\x0b\x32\x17.tensorflow.FullTypeDefJ\x04\x08\x03\x10\x04\x1al\n\nHandleData\x12\x0e\n\x06is_set\x18\x01 \x01(\x08\x12N\n\x0eshape_and_type\x18\x02 \x03(\x0b\x32\x36.tensorflow.CppShapeInferenceResult.HandleShapeAndTypeJ\x04\x08\x02\x10\x03J\x04\x08\x03\x10\x04\"e\n\x1d\x43ppShapeInferenceInputsNeeded\x12\x1c\n\x14input_tensors_needed\x18\x01 \x03(\x05\x12&\n\x1einput_tensors_as_shapes_needed\x18\x02 \x03(\x05\x42\x61Z\\github.com/tensorflow/tensorflow/tensorflow/go/python/framework/cpp_shape_inference_go_proto\xf8\x01\x01\x62\x06proto3') + +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals()) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'tensorflow.python.framework.cpp_shape_inference_pb2', globals()) +if _descriptor._USE_C_DESCRIPTORS == False: + + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b'Z\\github.com/tensorflow/tensorflow/tensorflow/go/python/framework/cpp_shape_inference_go_proto\370\001\001' + _CPPSHAPEINFERENCERESULT._serialized_start=198 + _CPPSHAPEINFERENCERESULT._serialized_end=609 + _CPPSHAPEINFERENCERESULT_HANDLESHAPEANDTYPE._serialized_start=340 + _CPPSHAPEINFERENCERESULT_HANDLESHAPEANDTYPE._serialized_end=487 + _CPPSHAPEINFERENCERESULT_HANDLEDATA._serialized_start=489 + _CPPSHAPEINFERENCERESULT_HANDLEDATA._serialized_end=597 + _CPPSHAPEINFERENCEINPUTSNEEDED._serialized_start=611 + _CPPSHAPEINFERENCEINPUTSNEEDED._serialized_end=712 +# @@protoc_insertion_point(module_scope) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/device.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/device.py new file mode 100644 index 0000000000000000000000000000000000000000..ba5b51f2bfd0d1f8398b8aa1e86daf2c279f4f02 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/device.py @@ -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. +# ============================================================================== + +"""Class to represent a device.""" + +from tensorflow.python import tf2 +from tensorflow.python.framework import device_spec + +if tf2.enabled(): + DeviceSpec = device_spec.DeviceSpecV2 +else: + DeviceSpec = device_spec.DeviceSpecV1 + + +def check_valid(spec): + """Check that a device spec is valid. + + Args: + spec: a string. + + Raises: + An exception if the spec is invalid. + """ + # Construct a DeviceSpec. It will assert a failure if spec is invalid. + DeviceSpec.from_string(spec) + + +def is_device_spec(obj): + """Abstract away the fact that DeviceSpecV2 is the base class.""" + return isinstance(obj, device_spec.DeviceSpecV2) + + +def canonical_name(device): + """Returns a canonical name for the given `DeviceSpec` or device name.""" + if device is None: + return "" + if is_device_spec(device): + return device.to_string() + else: + device = DeviceSpec.from_string(device) + return device.to_string() + + +# Performance caches +_cached_mergers = {} +_string_merge_cache = {} + + +def merge_device(spec): + """Returns a device function that merges devices specifications. + + This can be used to merge partial specifications of devices. The + innermost setting for a device field takes precedence. For example: + + with tf.device(merge_device("/device:GPU:0")) + # Nodes created here have device "/device:GPU:0" + with tf.device(merge_device("/job:worker")): + # Nodes created here have device "/job:worker/device:GPU:0" + with tf.device(merge_device("/device:CPU:0")): + # Nodes created here have device "/job:worker/device:CPU:0" + with tf.device(merge_device("/job:ps")): + # Nodes created here have device "/job:ps/device:CPU:0" + + Args: + spec: A `DeviceSpec` or a device spec string (partially) describing the + device that should be used for all nodes created in the scope of + the returned device function's with block. + + Returns: + A MergeDevice object with the above-described behavior. + + Raises: + ValueError: if the spec was not valid. + """ + + if isinstance(spec, MergeDevice): + return spec + + merger = _cached_mergers.get(spec) + if merger: + return merger + merger = MergeDevice(spec) + # No locking needed, since updates are stateless. + _cached_mergers[spec] = merger + return merger + + +class MergeDevice(object): + """Wraps a device specification (DeviceSpec or str) with merge functionality. + + When called, this class will merge a node_def with its own spec. It also + exposes a `shortcut_string_merge` method which can significantly improve + performance of device placement. + """ + + __slots__ = ["_spec"] + + def __init__(self, spec): + if isinstance(spec, device_spec.DeviceSpecV2): + self._spec = spec + elif isinstance(spec, device_spec.DeviceSpecV1): + # Capture a snapshot of spec. + self._spec = spec.__class__.from_string(spec.to_string()) + else: + self._spec = DeviceSpec.from_string(spec) + + def __call__(self, node_def): + # In general a user may create a device function which takes into account + # arbitrary properties of an op. (For instance dynamically placing ops based + # on type.) So even though the standard DeviceSpec route only uses the + # device attribute, we take an entire node_def to maintain a consistent + # signature with general device functions. + current_device = DeviceSpec.from_string(node_def.device or "") + return self._spec.make_merged_spec(current_device) + + def shortcut_string_merge(self, node_def): + """Merge a node def without materializing a full DeviceSpec object. + + Often a device merge is invoked in order to generate a string which can be + passed into the c api. In such a case, we can cache the + node_def.device -> merge_result_string + + map, and in most cases avoid: + - Materializing a copy of self._spec (In the case of DeviceSpecV1) + - Materializing a DeviceSpec for node_def.device + - A DeviceSpec.merge_from invocation + + In practice the cache hit rate for this function is very high, because the + number of invocations when iterating through the device stack is much + larger than the number of devices. + + Args: + node_def: An Operation (or Operation-like) to merge device constraints + with self._spec + + Returns: + A string containing the merged device specification. + """ + device = node_def.device or "" + + merge_key = (self._spec, device) + result = _string_merge_cache.get(merge_key) + if result is None: + # This update is not atomic, however because the merge is stateless + # we don't need to lock when updating the cache. + result = self.__call__(node_def).to_string() + _string_merge_cache[merge_key] = result + + return result + + def __repr__(self): + return "{} (spec: {})".format( + super(MergeDevice, self).__repr__(), self._spec.to_string()) + + @property + def is_null_merge(self): + """Indicate whether the wrapped spec is empty. + + In the degenerate case where self._spec is an empty specification, a caller + may wish to skip a merge step entirely. (However this class does not have + enough information to make that determination.) + + Returns: + A boolean indicating whether a device merge will be trivial. + """ + return not bool(self._spec.to_string()) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/device_spec.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/device_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..6d83cf6c050b4d1a28d032e21df70bdd38b02c68 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/device_spec.py @@ -0,0 +1,485 @@ +# 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. +# ============================================================================== +"""Class to represent a device.""" + +from tensorflow.python.util.tf_export import tf_export +from tensorflow.python import pywrap_tfe + +# EPU represents for TPU embedding for now. Subject to change in future. +_VALID_DEVICE_TYPES = frozenset({"CPU", "GPU", "TPU", "CUSTOM", "EPU"}) + +# ============================================================================== +# == Global Implementation Details ============================================= +# ============================================================================== +_STRING_TO_COMPONENTS_CACHE = {} +_COMPONENTS_TO_STRING_CACHE = {} + + +def _as_str_or_none(inp): + return None if inp is None else str(inp) + + +def _as_int_or_none(inp): + return None if inp is None else int(inp) + + +def _as_device_str_or_none(device_type): + # For backwards compatibility only, we support lowercase variants of + # cpu and gpu but turn them into uppercase here. + if device_type in ("cpu", "gpu"): + return device_type.upper() + return _as_str_or_none(device_type) + + +@tf_export("DeviceSpec", v1=[]) +class DeviceSpecV2(object): + """Represents a (possibly partial) specification for a TensorFlow device. + + `DeviceSpec`s are used throughout TensorFlow to describe where state is stored + and computations occur. Using `DeviceSpec` allows you to parse device spec + strings to verify their validity, merge them or compose them programmatically. + + Example: + + ```python + # Place the operations on device "GPU:0" in the "ps" job. + device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0) + with tf.device(device_spec.to_string()): + # Both my_var and squared_var will be placed on /job:ps/device:GPU:0. + my_var = tf.Variable(..., name="my_variable") + squared_var = tf.square(my_var) + ``` + + With eager execution disabled (by default in TensorFlow 1.x and by calling + disable_eager_execution() in TensorFlow 2.x), the following syntax + can be used: + + ```python + tf.compat.v1.disable_eager_execution() + + # Same as previous + device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0) + # No need of .to_string() method. + with tf.device(device_spec): + my_var = tf.Variable(..., name="my_variable") + squared_var = tf.square(my_var) + ``` + + If a `DeviceSpec` is partially specified, it will be merged with other + `DeviceSpec`s according to the scope in which it is defined. `DeviceSpec` + components defined in inner scopes take precedence over those defined in + outer scopes. + + ```python + gpu0_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0) + with tf.device(DeviceSpec(job="train").to_string()): + with tf.device(gpu0_spec.to_string()): + # Nodes created here will be assigned to /job:ps/device:GPU:0. + with tf.device(DeviceSpec(device_type="GPU", device_index=1).to_string()): + # Nodes created here will be assigned to /job:train/device:GPU:1. + ``` + + A `DeviceSpec` consists of 5 components -- each of + which is optionally specified: + + * Job: The job name. + * Replica: The replica index. + * Task: The task index. + * Device type: The device type string (e.g. "CPU" or "GPU"). + * Device index: The device index. + """ + + __slots__ = ("_job", "_replica", "_task", "_device_type", "_device_index", + "_as_string", "_hash") + + def __init__(self, + job=None, + replica=None, + task=None, + device_type=None, + device_index=None): + """Create a new `DeviceSpec` object. + + Args: + job: string. Optional job name. + replica: int. Optional replica index. + task: int. Optional task index. + device_type: Optional device type string (e.g. "CPU" or "GPU") + device_index: int. Optional device index. If left unspecified, device + represents 'any' device_index. + """ + self._job = _as_str_or_none(job) + self._replica = _as_int_or_none(replica) + self._task = _as_int_or_none(task) + self._device_type = _as_device_str_or_none(device_type) + self._device_index = _as_int_or_none(device_index) + self._as_string = self._components_to_string( + job=self._job, + replica=self._replica, + task=self._task, + device_type=self._device_type, + device_index=self._device_index) + self._hash = hash(self.to_string()) + + def to_string(self): + """Return a string representation of this `DeviceSpec`. + + Returns: + a string of the form + /job:/replica:/task:/device::. + """ + return self._as_string + + @classmethod + def from_string(cls, spec): + """Construct a `DeviceSpec` from a string. + + Args: + spec: a string of the form + /job:/replica:/task:/device:CPU: or + /job:/replica:/task:/device:GPU: as cpu and gpu are + mutually exclusive. All entries are optional. + + Returns: + A DeviceSpec. + """ + return cls(*cls._string_to_components(spec)) + + def parse_from_string(self, spec): + """Parse a `DeviceSpec` name into its components. + + **2.x behavior change**: + + In TensorFlow 1.x, this function mutates its own state and returns itself. + In 2.x, DeviceSpecs are immutable, and this function will return a + DeviceSpec which contains the spec. + + * Recommended: + + ``` + # my_spec and my_updated_spec are unrelated. + my_spec = tf.DeviceSpec.from_string("/CPU:0") + my_updated_spec = tf.DeviceSpec.from_string("/GPU:0") + with tf.device(my_updated_spec): + ... + ``` + + * Will work in 1.x and 2.x (though deprecated in 2.x): + + ``` + my_spec = tf.DeviceSpec.from_string("/CPU:0") + my_updated_spec = my_spec.parse_from_string("/GPU:0") + with tf.device(my_updated_spec): + ... + ``` + + * Will NOT work in 2.x: + + ``` + my_spec = tf.DeviceSpec.from_string("/CPU:0") + my_spec.parse_from_string("/GPU:0") # <== Will not update my_spec + with tf.device(my_spec): + ... + ``` + + In general, `DeviceSpec.from_string` should completely replace + `DeviceSpec.parse_from_string`, and `DeviceSpec.replace` should + completely replace setting attributes directly. + + Args: + spec: an optional string of the form + /job:/replica:/task:/device:CPU: or + /job:/replica:/task:/device:GPU: as cpu and gpu are + mutually exclusive. All entries are optional. + + Returns: + The `DeviceSpec`. + + Raises: + ValueError: if the spec was not valid. + """ + return self.from_string(spec) + + def make_merged_spec(self, dev): + """Returns a new DeviceSpec which incorporates `dev`. + + When combining specs, `dev` will take precedence over the current spec. + So for instance: + ``` + first_spec = tf.DeviceSpec(job=0, device_type="CPU") + second_spec = tf.DeviceSpec(device_type="GPU") + combined_spec = first_spec.make_merged_spec(second_spec) + ``` + + is equivalent to: + ``` + combined_spec = tf.DeviceSpec(job=0, device_type="GPU") + ``` + + Args: + dev: a `DeviceSpec` + + Returns: + A new `DeviceSpec` which combines `self` and `dev` + """ + return self.__class__(*self._get_combined_properties(dev)) + + def replace(self, **kwargs): + """Convenience method for making a new DeviceSpec by overriding fields. + + For instance: + ``` + my_spec = DeviceSpec=(job="my_job", device="CPU") + my_updated_spec = my_spec.replace(device="GPU") + my_other_spec = my_spec.replace(device=None) + ``` + + Args: + **kwargs: This method takes the same args as the DeviceSpec constructor + + Returns: + A DeviceSpec with the fields specified in kwargs overridden. + """ + init_kwargs = dict( + job=self.job, + replica=self.replica, + task=self.task, + device_type=self.device_type, + device_index=self.device_index) + + # Explicitly provided kwargs take precedence. + init_kwargs.update(kwargs) + return self.__class__(**init_kwargs) + + @property + def job(self): + return self._job + + @property + def replica(self): + return self._replica + + @property + def task(self): + return self._task + + @property + def device_type(self): + return self._device_type + + @property + def device_index(self): + return self._device_index + + def _get_combined_properties(self, dev): + """Combine the current DeviceSpec with another DeviceSpec. + + The combination of DeviceSpecs is will give priority to dev. + + Args: + dev: a `DeviceSpec` + + Returns: + A tuple of (job, replica, task, device_type, device_index) which + represents the combination of self and dev. + """ + return ( + dev.job if dev.job is not None else self.job, + dev.replica if dev.replica is not None else self.replica, + dev.task if dev.task is not None else self.task, + dev.device_type if dev.device_type is not None else self.device_type, + dev.device_index if dev.device_index is not None else self.device_index, + ) + + @staticmethod + def _get_valid_device_types(): + valid_device_types = set({}) + physical_devices = pywrap_tfe.TF_ListPluggablePhysicalDevices() + for device in physical_devices: + valid_device_types.add(device.decode().split(":")[1]) + valid_device_types = valid_device_types | _VALID_DEVICE_TYPES + return valid_device_types + + @staticmethod + def _string_to_components(spec=None): + """Stateless portion of device spec string parsing. + + Args: + spec: An optional string specifying a device specification. + + Returns: + The parsed components of `spec`. Note that the result of this function + must go through attribute setters of DeviceSpec, and should therefore NOT + be used directly. + """ + cached_result = _STRING_TO_COMPONENTS_CACHE.get(spec) + if cached_result is not None: + return cached_result + + raw_spec = spec # keep a copy of the original to update the cache + job, replica, task, device_type, device_index = None, None, None, None, None + + spec = spec or "" + splits = [x.split(":") for x in spec.split("/")] + valid_device_types = DeviceSpecV2._get_valid_device_types() + for y in splits: + ly = len(y) + if y: + # NOTE(taylorrobie): these will go through setters later. + if ly == 2 and y[0] == "job": + job = y[1] + elif ly == 2 and y[0] == "replica": + replica = y[1] + elif ly == 2 and y[0] == "task": + task = y[1] + elif ((ly == 1 or ly == 2) and (y[0].upper() in valid_device_types)): + if device_type is not None: + raise ValueError(f"Multiple device types are not allowed " + f"while parsing the device spec: {spec}.") + device_type = y[0].upper() + if ly == 2 and y[1] != "*": + device_index = int(y[1]) + elif ly == 3 and y[0] == "device": + if device_type is not None: + raise ValueError(f"Multiple device types are not allowed " + f"while parsing the device spec: {spec}.") + device_type = y[1] + if y[2] != "*": + device_index = int(y[2]) + elif ly and y[0] != "": # pylint: disable=g-explicit-bool-comparison + raise ValueError(f"Unknown attribute '{y[0]}' is encountered " + f"while parsing the device spec: '{spec}'.") + + output = (job, replica, task, device_type, device_index) + _STRING_TO_COMPONENTS_CACHE[raw_spec] = output + return output + + @staticmethod + def _components_to_string(job, replica, task, device_type, device_index): + """Stateless portion of `to_string` (separated to allow caching).""" + key = (job, replica, task, device_type, device_index) + cached_result = _COMPONENTS_TO_STRING_CACHE.get(key) + if cached_result is not None: + return cached_result + + output = [] + if job is not None: + output.append("/job:" + job) + if replica is not None: + output.append("/replica:" + str(replica)) + if task is not None: + output.append("/task:" + str(task)) + if device_type is not None: + device_index_string = "*" + if device_index is not None: + # Unlike the others, device_index is stored as an int. + device_index_string = str(device_index) + output.append("/device:%s:%s" % (device_type, device_index_string)) + + output = "".join(output) + _COMPONENTS_TO_STRING_CACHE[key] = output + return output + + def __eq__(self, other): + """Checks if the `other` DeviceSpec is same as the current instance, eg have + + same value for all the internal fields. + + Args: + other: Another DeviceSpec + + Returns: + Return `True` if `other` is also a DeviceSpec instance and has same value + as the current instance. + Return `False` otherwise. + """ + return (isinstance(other, self.__class__) and + self.to_string() == other.to_string()) + + def __hash__(self): + return self._hash + + def __repr__(self): + return ( + f"") + + +@tf_export(v1=["DeviceSpec"]) # pylint: disable=missing-docstring +class DeviceSpecV1(DeviceSpecV2): + __doc__ = DeviceSpecV2.__doc__ + __slots__ = DeviceSpecV2.__slots__ + + @DeviceSpecV2.job.setter + def job(self, job): + self._job = _as_str_or_none(job) + self._as_string, self._hash = None, None + + @DeviceSpecV2.replica.setter + def replica(self, replica): + self._replica = _as_int_or_none(replica) + self._as_string, self._hash = None, None + + @DeviceSpecV2.task.setter + def task(self, task): + self._task = _as_int_or_none(task) + self._as_string, self._hash = None, None + + @DeviceSpecV2.device_type.setter + def device_type(self, device_type): + self._device_type = _as_device_str_or_none(device_type) + self._as_string, self._hash = None, None + + @DeviceSpecV2.device_index.setter + def device_index(self, device_index): + self._device_index = _as_int_or_none(device_index) + self._as_string, self._hash = None, None + + def __hash__(self): + if self._hash is None: + self._hash = hash(self.to_string()) + return self._hash + + def to_string(self): + if self._as_string is None: + self._as_string = self._components_to_string( + job=self.job, + replica=self.replica, + task=self.task, + device_type=self.device_type, + device_index=self.device_index) + return self._as_string + + def parse_from_string(self, spec): + (self.job, self.replica, self.task, self.device_type, + self.device_index) = self._string_to_components(spec) + + return self + + def merge_from(self, dev): + """Merge the properties of "dev" into this `DeviceSpec`. + + Note: Will be removed in TensorFlow 2.x since DeviceSpecs will become + immutable. + + Args: + dev: a `DeviceSpec`. + """ + (self.job, self.replica, self.task, self.device_type, + self.device_index) = self._get_combined_properties(dev) + + # Use parent class docstrings for public methods. + to_string.__doc__ = DeviceSpecV2.to_string.__doc__ + parse_from_string.__doc__ = DeviceSpecV2.parse_from_string.__doc__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/dtypes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..c4ae5fd573ef28bf192678564b00f9f322272dbe --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/dtypes.py @@ -0,0 +1,853 @@ +# 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. +# ============================================================================== +"""Library of dtypes (Tensor element types).""" +import abc +import builtins +import dataclasses +from typing import Type, Sequence, Optional + +import ml_dtypes +import numpy as np + +from tensorflow.core.framework import types_pb2 +# We need to import pywrap_tensorflow prior to the bfloat wrapper to avoid +# protobuf errors where a file is defined twice on MacOS. +# pylint: disable=invalid-import-order,g-bad-import-order +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python.framework import _dtypes +from tensorflow.python.framework import cpp_shape_inference_pb2 +from tensorflow.python.types import doc_typealias +from tensorflow.python.util.tf_export import tf_export +from tensorflow.python.types import trace +from tensorflow.core.function import trace_type +from tensorflow.tools.docs import doc_controls + + +class DTypeMeta(type(_dtypes.DType), abc.ABCMeta): + pass + + +@dataclasses.dataclass(frozen=True) +class HandleData: + """Holds resource/variant tensor specific data.""" + shape_inference: Optional[ + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData + ] = None + alias_id: Optional[int] = None + + +@tf_export("dtypes.DType", "DType") +class DType( + _dtypes.DType, + trace.TraceType, + trace_type.Serializable, + metaclass=DTypeMeta): + """Represents the type of the elements in a `Tensor`. + + `DType`'s are used to specify the output data type for operations which + require it, or to inspect the data type of existing `Tensor`'s. + + Examples: + + >>> tf.constant(1, dtype=tf.int64) + + >>> tf.constant(1.0).dtype + tf.float32 + + See `tf.dtypes` for a complete list of `DType`'s defined. + """ + __slots__ = ["_handle_data"] + + def __init__(self, type_enum, handle_data=None): + super().__init__(type_enum) + + # Resource and Variant dtypes have additional handle data information that + # is necessary for manipulating those Tensors. + if handle_data is not None and not isinstance(handle_data, HandleData): + raise TypeError("handle_data must be of the type HandleData") + + self._handle_data = handle_data + + @property + def _is_ref_dtype(self): + """Returns `True` if this `DType` represents a reference type.""" + return self._type_enum > 100 + + @property + def _as_ref(self): + """Returns a reference `DType` based on this `DType`.""" + if self._is_ref_dtype: + return self + else: + return _INTERN_TABLE[self._type_enum + 100] + + @property + def base_dtype(self): + """Returns a non-reference `DType` based on this `DType` (for TF1). + + Programs written for TensorFlow 2.x do not need this attribute. + It exists only for compatibility with TensorFlow 1.x, which used + reference `DType`s in the implementation of `tf.compat.v1.Variable`. + In TensorFlow 2.x, `tf.Variable` is implemented without reference types. + """ + if self._is_ref_dtype: + return _INTERN_TABLE[self._type_enum - 100] + else: + return self + + @property + def real_dtype(self): + """Returns the `DType` corresponding to this `DType`'s real part.""" + base = self.base_dtype + if base == complex64: + return float32 + elif base == complex128: + return float64 + else: + return self + + @property + def as_numpy_dtype(self): + """Returns a Python `type` object based on this `DType`.""" + return _TF_TO_NP[self._type_enum] + + @property + def min(self): + """Returns the minimum representable value in this data type. + + Raises: + TypeError: if this is a non-numeric, unordered, or quantized type. + + """ + if (self.is_quantized or + self.base_dtype in (bool, string, complex64, complex128)): + raise TypeError(f"Cannot find minimum value of {self} with " + f"{'quantized type' if self.is_quantized else 'type'} " + f"{self.base_dtype}.") + + # There is no simple way to get the min value of a dtype, we have to check + # float and int types separately. + try: + return ml_dtypes.finfo(self.as_numpy_dtype).min + except: # bare except as possible raises by finfo not documented + try: + return ml_dtypes.iinfo(self.as_numpy_dtype).min + except: + raise TypeError(f"Cannot find minimum value of {self}.") + + @property + def max(self): + """Returns the maximum representable value in this data type. + + Raises: + TypeError: if this is a non-numeric, unordered, or quantized type. + + """ + if (self.is_quantized or + self.base_dtype in (bool, string, complex64, complex128)): + raise TypeError(f"Cannot find maximum value of {self} with " + f"{'quantized type' if self.is_quantized else 'type'} " + f"{self.base_dtype}.") + + # there is no simple way to get the max value of a dtype, we have to check + # float and int types separately + try: + return ml_dtypes.finfo(self.as_numpy_dtype).max + except: # bare except as possible raises by finfo not documented + try: + return ml_dtypes.iinfo(self.as_numpy_dtype).max + except: + raise TypeError(f"Cannot find maximum value of {self}.") + + @property + def limits(self, clip_negative=True): + """Return intensity limits, i.e. + + (min, max) tuple, of the dtype. + Args: + clip_negative : bool, optional If True, clip the negative range (i.e. + return 0 for min intensity) even if the image dtype allows negative + values. Returns + min, max : tuple Lower and upper intensity limits. + """ + if self.as_numpy_dtype in dtype_range: + min, max = dtype_range[self.as_numpy_dtype] # pylint: disable=redefined-builtin + else: + raise ValueError(str(self) + " does not have defined limits.") + + if clip_negative: + min = 0 # pylint: disable=redefined-builtin + return min, max + + def is_compatible_with(self, other): + """Returns True if the `other` DType will be converted to this DType (TF1). + + Programs written for TensorFlow 2.x do not need this function. + Instead, they can do equality comparison on `DType` objects directly: + `tf.as_dtype(this) == tf.as_dtype(other)`. + + This function exists only for compatibility with TensorFlow 1.x, where it + additionally allows conversion from a reference type (used by + `tf.compat.v1.Variable`) to its base type. + + Args: + other: A `DType` (or object that may be converted to a `DType`). + + Returns: + True if a Tensor of the `other` `DType` will be implicitly converted to + this `DType`. + """ + other = as_dtype(other) + return self._type_enum in (other.as_datatype_enum, + other.base_dtype.as_datatype_enum) + + def is_subtype_of(self, other: trace.TraceType) -> bool: + """See tf.types.experimental.TraceType base class.""" + return self == other + + def most_specific_common_supertype( + self, types: Sequence[trace.TraceType]) -> Optional["DType"]: + """See tf.types.experimental.TraceType base class.""" + return self if all(self == other for other in types) else None + + @doc_controls.do_not_doc_inheritable + def placeholder_value(self, placeholder_context): + """See tf.types.experimental.TraceType base class.""" + return super().placeholder_value(placeholder_context) + + @doc_controls.do_not_doc_inheritable + def from_tensors(self, tensors): + """See tf.types.experimental.TraceType base class.""" + return super().from_tensors(tensors) + + @doc_controls.do_not_doc_inheritable + def to_tensors(self, value): + """See tf.types.experimental.TraceType base class.""" + return super().to_tensors(value) + + @doc_controls.do_not_doc_inheritable + def flatten(self): + """See tf.types.experimental.TraceType base class.""" + return super().flatten() + + @doc_controls.do_not_doc_inheritable + def cast(self, value, cast_context): + """See tf.types.experimental.TraceType base class.""" + return super().cast(value, cast_context) + + @classmethod + def experimental_type_proto(cls) -> Type[types_pb2.SerializedDType]: + """Returns the type of proto associated with DType serialization.""" + return types_pb2.SerializedDType + + @classmethod + def experimental_from_proto(cls, proto: types_pb2.SerializedDType) -> "DType": + """Returns a Dtype instance based on the serialized proto.""" + return DType(proto.datatype) + + def experimental_as_proto(self) -> types_pb2.SerializedDType: + """Returns a proto representation of the Dtype instance.""" + return types_pb2.SerializedDType(datatype=self._type_enum) + + def __eq__(self, other): + """Returns True iff this DType refers to the same type as `other`.""" + if other is None: + return False + + if type(other) != DType: # pylint: disable=unidiomatic-typecheck + try: + other = as_dtype(other) + except TypeError: + return False + + return self._type_enum == other._type_enum # pylint: disable=protected-access + + def __ne__(self, other): + """Returns True iff self != other.""" + return not self.__eq__(other) + + # "If a class that overrides __eq__() needs to retain the implementation + # of __hash__() from a parent class, the interpreter must be told this + # explicitly by setting __hash__ = .__hash__." + # TODO(slebedev): Remove once __eq__ and __ne__ are implemented in C++. + __hash__ = _dtypes.DType.__hash__ + + def __reduce__(self): + return as_dtype, (self.name,) + +trace_type.register_serializable(DType) + +# Define data type range of numpy dtype +dtype_range = { + np.bool_: (False, True), + np.uint8: (0, 255), + np.uint16: (0, 65535), + np.int8: (-128, 127), + np.int16: (-32768, 32767), + np.int64: (-2**63, 2**63 - 1), + np.uint64: (0, 2**64 - 1), + np.int32: (-2**31, 2**31 - 1), + np.uint32: (0, 2**32 - 1), + np.float32: (-1, 1), + np.float64: (-1, 1) +} + +# Define standard wrappers for the types_pb2.DataType enum. +resource = DType(types_pb2.DT_RESOURCE) +doc_typealias.document( + obj=resource, + doc="Handle to a mutable, dynamically allocated resource.") +tf_export("dtypes.resource", "resource").export_constant(__name__, "resource") + +variant = DType(types_pb2.DT_VARIANT) +doc_typealias.document( + obj=variant, + doc="Data of arbitrary type (known at runtime).") +tf_export("dtypes.variant", "variant").export_constant(__name__, "variant") + +uint8 = DType(types_pb2.DT_UINT8) +doc_typealias.document( + obj=uint8, + doc="Unsigned 8-bit (byte) integer.") +tf_export("dtypes.uint8", "uint8").export_constant(__name__, "uint8") + +uint16 = DType(types_pb2.DT_UINT16) +doc_typealias.document( + obj=uint16, + doc="Unsigned 16-bit (word) integer.") +tf_export("dtypes.uint16", "uint16").export_constant(__name__, "uint16") + +uint32 = DType(types_pb2.DT_UINT32) +doc_typealias.document( + obj=uint32, + doc="Unsigned 32-bit (dword) integer.") +tf_export("dtypes.uint32", "uint32").export_constant(__name__, "uint32") + +uint64 = DType(types_pb2.DT_UINT64) +doc_typealias.document( + obj=uint64, + doc="Unsigned 64-bit (qword) integer.") +tf_export("dtypes.uint64", "uint64").export_constant(__name__, "uint64") + +int8 = DType(types_pb2.DT_INT8) +doc_typealias.document( + obj=int8, + doc="Signed 8-bit integer.") +tf_export("dtypes.int8", "int8").export_constant(__name__, "int8") + +int16 = DType(types_pb2.DT_INT16) +doc_typealias.document( + obj=int16, + doc="Signed 16-bit integer.") +tf_export("dtypes.int16", "int16").export_constant(__name__, "int16") + +int32 = DType(types_pb2.DT_INT32) +doc_typealias.document( + obj=int32, + doc="Signed 32-bit integer.") +tf_export("dtypes.int32", "int32").export_constant(__name__, "int32") + +int64 = DType(types_pb2.DT_INT64) +doc_typealias.document( + obj=int64, + doc="Signed 64-bit integer.") +tf_export("dtypes.int64", "int64").export_constant(__name__, "int64") + +float16 = DType(types_pb2.DT_HALF) +half = float16 +doc_typealias.document( + obj=float16, + doc="16-bit (half precision) floating-point.") +tf_export("dtypes.float16", "float16").export_constant(__name__, "float16") +tf_export("dtypes.half", "half").export_constant(__name__, "half") + +float32 = DType(types_pb2.DT_FLOAT) +doc_typealias.document( + obj=float32, + doc="32-bit (single precision) floating-point.") +tf_export("dtypes.float32", "float32").export_constant(__name__, "float32") + +float64 = DType(types_pb2.DT_DOUBLE) +doc_typealias.document( + obj=float64, + doc="64-bit (double precision) floating-point.") +tf_export("dtypes.float64", "float64").export_constant(__name__, "float64") +double = float64 +tf_export("dtypes.double", "double").export_constant(__name__, "double") + +complex64 = DType(types_pb2.DT_COMPLEX64) +doc_typealias.document( + obj=complex64, + doc="64-bit complex.") +tf_export("dtypes.complex64", + "complex64").export_constant(__name__, "complex64") + +complex128 = DType(types_pb2.DT_COMPLEX128) +doc_typealias.document( + obj=complex128, + doc="128-bit complex.") +tf_export("dtypes.complex128", + "complex128").export_constant(__name__, "complex128") + +string = DType(types_pb2.DT_STRING) +doc_typealias.document( + obj=string, + doc="Variable-length string, represented as byte array.") +tf_export("dtypes.string", "string").export_constant(__name__, "string") + +bool = DType(types_pb2.DT_BOOL) # pylint: disable=redefined-builtin +doc_typealias.document( + obj=bool, + doc="Boolean.") +tf_export("dtypes.bool", "bool").export_constant(__name__, "bool") + +qint8 = DType(types_pb2.DT_QINT8) +doc_typealias.document( + obj=qint8, + doc="Signed quantized 8-bit integer.") +tf_export("dtypes.qint8", "qint8").export_constant(__name__, "qint8") + +qint16 = DType(types_pb2.DT_QINT16) +doc_typealias.document( + obj=qint16, + doc="Signed quantized 16-bit integer.") +tf_export("dtypes.qint16", "qint16").export_constant(__name__, "qint16") + +qint32 = DType(types_pb2.DT_QINT32) +doc_typealias.document( + obj=qint32, + doc="signed quantized 32-bit integer.") +tf_export("dtypes.qint32", "qint32").export_constant(__name__, "qint32") + +quint8 = DType(types_pb2.DT_QUINT8) +doc_typealias.document( + obj=quint8, + doc="Unsigned quantized 8-bit integer.") +tf_export("dtypes.quint8", "quint8").export_constant(__name__, "quint8") + +quint16 = DType(types_pb2.DT_QUINT16) +doc_typealias.document( + obj=quint16, + doc="Unsigned quantized 16-bit integer.") +tf_export("dtypes.quint16", "quint16").export_constant(__name__, "quint16") + +bfloat16 = DType(types_pb2.DT_BFLOAT16) +doc_typealias.document( + obj=bfloat16, + doc="16-bit bfloat (brain floating point).") +tf_export("dtypes.bfloat16", "bfloat16").export_constant(__name__, "bfloat16") + +float8_e5m2 = DType(types_pb2.DT_FLOAT8_E5M2) +doc_typealias.document( + obj=float8_e5m2, + doc="8-bit float with 5 exponent bits and 2 mantissa bits.") +tf_export("dtypes.experimental.float8_e5m2", + "experimental.float8_e5m2").export_constant(__name__, "float8_e5m2") + +float8_e4m3fn = DType(types_pb2.DT_FLOAT8_E4M3FN) +doc_typealias.document( + obj=float8_e4m3fn, + doc="8-bit float with 4 exponent bits and 3 mantissa bits, with extended " + "finite range. This type has no representation for inf, and only two NaN " + "values: 0xFF for negative NaN, and 0x7F for positive NaN.") +tf_export("dtypes.experimental.float8_e4m3fn", + "experimental.float8_e4m3fn").export_constant(__name__, + "float8_e4m3fn") + +int4 = DType(types_pb2.DT_INT4) +doc_typealias.document(obj=int4, doc="Signed 4-bit integer.") +tf_export("dtypes.experimental.int4", "experimental.int4").export_constant( + __name__, "int4" +) + +uint4 = DType(types_pb2.DT_UINT4) +doc_typealias.document(obj=uint4, doc="Unsigned 4-bit integer.") +tf_export("dtypes.experimental.uint4", "experimental.uint4").export_constant( + __name__, "uint4" +) + +resource_ref = DType(types_pb2.DT_RESOURCE_REF) +variant_ref = DType(types_pb2.DT_VARIANT_REF) +float16_ref = DType(types_pb2.DT_HALF_REF) +half_ref = float16_ref +float32_ref = DType(types_pb2.DT_FLOAT_REF) +float64_ref = DType(types_pb2.DT_DOUBLE_REF) +double_ref = float64_ref +int32_ref = DType(types_pb2.DT_INT32_REF) +uint32_ref = DType(types_pb2.DT_UINT32_REF) +uint8_ref = DType(types_pb2.DT_UINT8_REF) +uint16_ref = DType(types_pb2.DT_UINT16_REF) +int16_ref = DType(types_pb2.DT_INT16_REF) +int8_ref = DType(types_pb2.DT_INT8_REF) +string_ref = DType(types_pb2.DT_STRING_REF) +complex64_ref = DType(types_pb2.DT_COMPLEX64_REF) +complex128_ref = DType(types_pb2.DT_COMPLEX128_REF) +int64_ref = DType(types_pb2.DT_INT64_REF) +uint64_ref = DType(types_pb2.DT_UINT64_REF) +bool_ref = DType(types_pb2.DT_BOOL_REF) +qint8_ref = DType(types_pb2.DT_QINT8_REF) +quint8_ref = DType(types_pb2.DT_QUINT8_REF) +qint16_ref = DType(types_pb2.DT_QINT16_REF) +quint16_ref = DType(types_pb2.DT_QUINT16_REF) +qint32_ref = DType(types_pb2.DT_QINT32_REF) +bfloat16_ref = DType(types_pb2.DT_BFLOAT16_REF) +float8_e5m2_ref = DType(types_pb2.DT_FLOAT8_E5M2_REF) +float8_e4m3fn_ref = DType(types_pb2.DT_FLOAT8_E4M3FN_REF) +int4_ref = DType(types_pb2.DT_INT4_REF) +uint4_ref = DType(types_pb2.DT_UINT4_REF) + +# Maintain an intern table so that we don't have to create a large +# number of small objects. +_INTERN_TABLE = { + types_pb2.DT_HALF: float16, + types_pb2.DT_FLOAT: float32, + types_pb2.DT_DOUBLE: float64, + types_pb2.DT_INT32: int32, + types_pb2.DT_UINT8: uint8, + types_pb2.DT_UINT16: uint16, + types_pb2.DT_UINT32: uint32, + types_pb2.DT_UINT64: uint64, + types_pb2.DT_INT16: int16, + types_pb2.DT_INT8: int8, + types_pb2.DT_STRING: string, + types_pb2.DT_COMPLEX64: complex64, + types_pb2.DT_COMPLEX128: complex128, + types_pb2.DT_INT64: int64, + types_pb2.DT_BOOL: bool, + types_pb2.DT_QINT8: qint8, + types_pb2.DT_QUINT8: quint8, + types_pb2.DT_QINT16: qint16, + types_pb2.DT_QUINT16: quint16, + types_pb2.DT_QINT32: qint32, + types_pb2.DT_BFLOAT16: bfloat16, + types_pb2.DT_FLOAT8_E5M2: float8_e5m2, + types_pb2.DT_FLOAT8_E4M3FN: float8_e4m3fn, + types_pb2.DT_INT4: int4, + types_pb2.DT_UINT4: uint4, + types_pb2.DT_RESOURCE: resource, + types_pb2.DT_VARIANT: variant, + types_pb2.DT_HALF_REF: float16_ref, + types_pb2.DT_FLOAT_REF: float32_ref, + types_pb2.DT_DOUBLE_REF: float64_ref, + types_pb2.DT_INT32_REF: int32_ref, + types_pb2.DT_UINT32_REF: uint32_ref, + types_pb2.DT_UINT8_REF: uint8_ref, + types_pb2.DT_UINT16_REF: uint16_ref, + types_pb2.DT_INT16_REF: int16_ref, + types_pb2.DT_INT8_REF: int8_ref, + types_pb2.DT_STRING_REF: string_ref, + types_pb2.DT_COMPLEX64_REF: complex64_ref, + types_pb2.DT_COMPLEX128_REF: complex128_ref, + types_pb2.DT_INT64_REF: int64_ref, + types_pb2.DT_UINT64_REF: uint64_ref, + types_pb2.DT_BOOL_REF: bool_ref, + types_pb2.DT_QINT8_REF: qint8_ref, + types_pb2.DT_QUINT8_REF: quint8_ref, + types_pb2.DT_QINT16_REF: qint16_ref, + types_pb2.DT_QUINT16_REF: quint16_ref, + types_pb2.DT_QINT32_REF: qint32_ref, + types_pb2.DT_BFLOAT16_REF: bfloat16_ref, + types_pb2.DT_FLOAT8_E5M2_REF: float8_e5m2_ref, + types_pb2.DT_FLOAT8_E4M3FN_REF: float8_e4m3fn_ref, + types_pb2.DT_INT4_REF: int4_ref, + types_pb2.DT_UINT4_REF: uint4_ref, + types_pb2.DT_RESOURCE_REF: resource_ref, + types_pb2.DT_VARIANT_REF: variant_ref, +} + +# Standard mappings between types_pb2.DataType values and string names. +_TYPE_TO_STRING = { + types_pb2.DT_HALF: "float16", + types_pb2.DT_FLOAT: "float32", + types_pb2.DT_DOUBLE: "float64", + types_pb2.DT_INT32: "int32", + types_pb2.DT_UINT8: "uint8", + types_pb2.DT_UINT16: "uint16", + types_pb2.DT_UINT32: "uint32", + types_pb2.DT_UINT64: "uint64", + types_pb2.DT_INT16: "int16", + types_pb2.DT_INT8: "int8", + types_pb2.DT_STRING: "string", + types_pb2.DT_COMPLEX64: "complex64", + types_pb2.DT_COMPLEX128: "complex128", + types_pb2.DT_INT64: "int64", + types_pb2.DT_BOOL: "bool", + types_pb2.DT_QINT8: "qint8", + types_pb2.DT_QUINT8: "quint8", + types_pb2.DT_QINT16: "qint16", + types_pb2.DT_QUINT16: "quint16", + types_pb2.DT_QINT32: "qint32", + types_pb2.DT_BFLOAT16: "bfloat16", + types_pb2.DT_FLOAT8_E5M2: "float8_e5m2", + types_pb2.DT_FLOAT8_E4M3FN: "float8_e4m3fn", + types_pb2.DT_INT4: "int4", + types_pb2.DT_UINT4: "uint4", + types_pb2.DT_RESOURCE: "resource", + types_pb2.DT_VARIANT: "variant", + types_pb2.DT_HALF_REF: "float16_ref", + types_pb2.DT_FLOAT_REF: "float32_ref", + types_pb2.DT_DOUBLE_REF: "float64_ref", + types_pb2.DT_INT32_REF: "int32_ref", + types_pb2.DT_UINT32_REF: "uint32_ref", + types_pb2.DT_UINT8_REF: "uint8_ref", + types_pb2.DT_UINT16_REF: "uint16_ref", + types_pb2.DT_INT16_REF: "int16_ref", + types_pb2.DT_INT8_REF: "int8_ref", + types_pb2.DT_STRING_REF: "string_ref", + types_pb2.DT_COMPLEX64_REF: "complex64_ref", + types_pb2.DT_COMPLEX128_REF: "complex128_ref", + types_pb2.DT_INT64_REF: "int64_ref", + types_pb2.DT_UINT64_REF: "uint64_ref", + types_pb2.DT_BOOL_REF: "bool_ref", + types_pb2.DT_QINT8_REF: "qint8_ref", + types_pb2.DT_QUINT8_REF: "quint8_ref", + types_pb2.DT_QINT16_REF: "qint16_ref", + types_pb2.DT_QUINT16_REF: "quint16_ref", + types_pb2.DT_QINT32_REF: "qint32_ref", + types_pb2.DT_BFLOAT16_REF: "bfloat16_ref", + types_pb2.DT_FLOAT8_E5M2_REF: "float8_e5m2_ref", + types_pb2.DT_FLOAT8_E4M3FN_REF: "float8_e4m3fn_ref", + types_pb2.DT_INT4_REF: "int4_ref", + types_pb2.DT_UINT4_REF: "uint4_ref", + types_pb2.DT_RESOURCE_REF: "resource_ref", + types_pb2.DT_VARIANT_REF: "variant_ref", +} +_STRING_TO_TF = { + value: _INTERN_TABLE[key] for key, value in _TYPE_TO_STRING.items() +} +# Add non-canonical aliases. +_STRING_TO_TF["half"] = float16 +_STRING_TO_TF["half_ref"] = float16_ref +_STRING_TO_TF["float"] = float32 +_STRING_TO_TF["float_ref"] = float32_ref +_STRING_TO_TF["double"] = float64 +_STRING_TO_TF["double_ref"] = float64_ref + +# Numpy representation for quantized dtypes. +# +# These are magic strings that are used in the swig wrapper to identify +# quantized types. +# TODO(mrry,keveman): Investigate Numpy type registration to replace this +# hard-coding of names. +_np_qint8 = np.dtype([("qint8", np.int8)]) +_np_quint8 = np.dtype([("quint8", np.uint8)]) +_np_qint16 = np.dtype([("qint16", np.int16)]) +_np_quint16 = np.dtype([("quint16", np.uint16)]) +_np_qint32 = np.dtype([("qint32", np.int32)]) + +# _np_bfloat16, _np_float8*, _np_(u)int4 are defined by module imports. +_np_bfloat16 = ml_dtypes.bfloat16 +_np_float8_e4m3fn = ml_dtypes.float8_e4m3fn +_np_float8_e4m3fnuz = ml_dtypes.float8_e4m3fnuz +_np_float8_e4m3b11fnuz = ml_dtypes.float8_e4m3b11fnuz +_np_float8_e5m2 = ml_dtypes.float8_e5m2 +_np_float8_e5m2fnuz = ml_dtypes.float8_e5m2fnuz +_np_int4 = ml_dtypes.int4 +_np_uint4 = ml_dtypes.uint4 + +# Custom struct dtype for directly-fed ResourceHandles of supported type(s). +np_resource = np.dtype([("resource", np.ubyte)]) + +# Standard mappings between types_pb2.DataType values and numpy.dtypes. +_NP_TO_TF = { + np.float16: float16, + np.float32: float32, + np.float64: float64, + np.int32: int32, + np.int64: int64, + np.uint8: uint8, + np.uint16: uint16, + np.uint32: uint32, + np.uint64: uint64, + np.int16: int16, + np.int8: int8, + np.complex64: complex64, + np.complex128: complex128, + np.object_: string, + np.bytes_: string, + np.str_: string, + np.bool_: bool, + _np_qint8: qint8, + _np_quint8: quint8, + _np_qint16: qint16, + _np_quint16: quint16, + _np_qint32: qint32, + _np_bfloat16: bfloat16, + _np_float8_e5m2: float8_e5m2, + _np_float8_e4m3fn: float8_e4m3fn, + _np_int4: int4, + _np_uint4: uint4, +} + +# Map (some) NumPy platform dtypes to TF ones using their fixed-width +# synonyms. Note that platform dtypes are not always simples aliases, +# i.e. reference equality is not guaranteed. See e.g. numpy/numpy#9799. +for pdt in [ + np.intc, + np.uintc, + np.int_, + np.uint, + np.longlong, + np.ulonglong, +]: + if pdt not in _NP_TO_TF: + _NP_TO_TF[pdt] = next( + _NP_TO_TF[dt] for dt in _NP_TO_TF if dt == pdt().dtype) # pylint: disable=no-value-for-parameter + +TF_VALUE_DTYPES = set(_NP_TO_TF.values()) + +_TF_TO_NP = { + types_pb2.DT_HALF: np.float16, + types_pb2.DT_FLOAT: np.float32, + types_pb2.DT_DOUBLE: np.float64, + types_pb2.DT_INT32: np.int32, + types_pb2.DT_UINT8: np.uint8, + types_pb2.DT_UINT16: np.uint16, + types_pb2.DT_UINT32: np.uint32, + types_pb2.DT_UINT64: np.uint64, + types_pb2.DT_INT16: np.int16, + types_pb2.DT_INT8: np.int8, + # NOTE(touts): For strings we use object as it supports variable length + # strings. + types_pb2.DT_STRING: object, + types_pb2.DT_COMPLEX64: np.complex64, + types_pb2.DT_COMPLEX128: np.complex128, + types_pb2.DT_INT64: np.int64, + types_pb2.DT_BOOL: np.bool_, + types_pb2.DT_QINT8: _np_qint8, + types_pb2.DT_QUINT8: _np_quint8, + types_pb2.DT_QINT16: _np_qint16, + types_pb2.DT_QUINT16: _np_quint16, + types_pb2.DT_QINT32: _np_qint32, + types_pb2.DT_BFLOAT16: _np_bfloat16, + types_pb2.DT_FLOAT8_E5M2: _np_float8_e5m2, + types_pb2.DT_FLOAT8_E4M3FN: _np_float8_e4m3fn, + types_pb2.DT_INT4: _np_int4, + types_pb2.DT_UINT4: _np_uint4, + # Ref types + types_pb2.DT_HALF_REF: np.float16, + types_pb2.DT_FLOAT_REF: np.float32, + types_pb2.DT_DOUBLE_REF: np.float64, + types_pb2.DT_INT32_REF: np.int32, + types_pb2.DT_UINT32_REF: np.uint32, + types_pb2.DT_UINT8_REF: np.uint8, + types_pb2.DT_UINT16_REF: np.uint16, + types_pb2.DT_INT16_REF: np.int16, + types_pb2.DT_INT8_REF: np.int8, + types_pb2.DT_STRING_REF: np.object_, + types_pb2.DT_COMPLEX64_REF: np.complex64, + types_pb2.DT_COMPLEX128_REF: np.complex128, + types_pb2.DT_INT64_REF: np.int64, + types_pb2.DT_UINT64_REF: np.uint64, + types_pb2.DT_BOOL_REF: np.bool_, + types_pb2.DT_QINT8_REF: _np_qint8, + types_pb2.DT_QUINT8_REF: _np_quint8, + types_pb2.DT_QINT16_REF: _np_qint16, + types_pb2.DT_QUINT16_REF: _np_quint16, + types_pb2.DT_QINT32_REF: _np_qint32, + types_pb2.DT_BFLOAT16_REF: _np_bfloat16, + types_pb2.DT_FLOAT8_E5M2_REF: _np_float8_e5m2, + types_pb2.DT_FLOAT8_E4M3FN_REF: _np_float8_e4m3fn, + types_pb2.DT_INT4_REF: _np_int4, + types_pb2.DT_UINT4_REF: _np_uint4, +} + +_QUANTIZED_DTYPES_NO_REF = frozenset([qint8, quint8, qint16, quint16, qint32]) +_QUANTIZED_DTYPES_REF = frozenset( + [qint8_ref, quint8_ref, qint16_ref, quint16_ref, qint32_ref]) +QUANTIZED_DTYPES = _QUANTIZED_DTYPES_REF.union(_QUANTIZED_DTYPES_NO_REF) +tf_export( + "dtypes.QUANTIZED_DTYPES", + v1=["dtypes.QUANTIZED_DTYPES", + "QUANTIZED_DTYPES"]).export_constant(__name__, "QUANTIZED_DTYPES") + +_PYTHON_TO_TF = { + builtins.float: float32, + builtins.bool: bool, + builtins.object: string +} + +_ANY_TO_TF = {} +_ANY_TO_TF.update(_INTERN_TABLE) +_ANY_TO_TF.update(_STRING_TO_TF) +_ANY_TO_TF.update(_PYTHON_TO_TF) +_ANY_TO_TF.update(_NP_TO_TF) + +# Ensure no collisions. +assert len(_ANY_TO_TF) == sum( + len(d) for d in [_INTERN_TABLE, _STRING_TO_TF, _PYTHON_TO_TF, _NP_TO_TF]) + + +@tf_export("dtypes.as_dtype", "as_dtype") +def as_dtype(type_value): + """Converts the given `type_value` to a `tf.DType`. + + Inputs can be existing `tf.DType` objects, a [`DataType` + enum](https://www.tensorflow.org/code/tensorflow/core/framework/types.proto), + a string type name, or a + [`numpy.dtype`](https://numpy.org/doc/stable/reference/generated/numpy.dtype.html). + + Examples: + >>> tf.as_dtype(2) # Enum value for float64. + tf.float64 + + >>> tf.as_dtype('float') + tf.float32 + + >>> tf.as_dtype(np.int32) + tf.int32 + + Note: `DType` values are interned (i.e. a single instance of each dtype is + stored in a map). When passed a new `DType` object, `as_dtype` always returns + the interned value. + + Args: + type_value: A value that can be converted to a `tf.DType` object. + + Returns: + A `DType` corresponding to `type_value`. + + Raises: + TypeError: If `type_value` cannot be converted to a `DType`. + """ + if isinstance(type_value, DType): + if type_value._handle_data is None: # pylint:disable=protected-access + return _INTERN_TABLE[type_value.as_datatype_enum] + else: + return type_value + + if isinstance(type_value, np.dtype): + try: + return _NP_TO_TF[type_value.type] + except KeyError: + pass + + try: + return _ANY_TO_TF[type_value] + except (KeyError, TypeError): + # TypeError indicates that type_value is not hashable. + pass + + if hasattr(type_value, "dtype"): + try: + return _NP_TO_TF[np.dtype(type_value.dtype).type] + except (KeyError, TypeError): + pass + + if isinstance(type_value, _dtypes.DType): + return _INTERN_TABLE[type_value.as_datatype_enum] + + raise TypeError(f"Cannot convert the argument `type_value`: {type_value!r} " + "to a TensorFlow DType.") diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/error_interpolation.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/error_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..76c727a5fe5ea173252eab648c5150aaf39fb369 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/error_interpolation.py @@ -0,0 +1,438 @@ +# 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. +# ============================================================================== +"""Function for interpolating formatted errors from the TensorFlow runtime. + +Exposes the function `interpolate` to interpolate messages with tags of the form +{{type name}}. +""" + +import collections +import os +import re +import site +import traceback + +from tensorflow.python.util import tf_stack + +_NAME_REGEX = r"[A-Za-z0-9_.][A-Za-z0-9_.\-/]*?" +_TAG_REGEX = fr"{{{{(?P{_NAME_REGEX}) (?P{_NAME_REGEX})}}}}" +_INTERPOLATION_REGEX = fr"(?P.*?)(?P{_TAG_REGEX})" +_INTERPOLATION_PATTERN = re.compile(_INTERPOLATION_REGEX, re.DOTALL) + +_ParseTag = collections.namedtuple("_ParseTag", ["type", "name"]) + + +# Remove the last three path components from this module's file (i.e. +# python/framework/error_interpolation.py) so that we have an absolute path +# prefix to the root of the installation. +_FRAMEWORK_COMMON_PREFIX = os.path.dirname( + os.path.dirname(os.path.dirname(__file__))) + +# Sub-directories under the common prefix that are considered part of the +# framework. +# Note that keras code lives outside of tensorflow directory, we need to walk +# up the directory tree and find it. +_FRAMEWORK_PATH_PREFIXES = [ + os.path.join(_FRAMEWORK_COMMON_PREFIX, "python") + os.sep, + os.path.join(_FRAMEWORK_COMMON_PREFIX, "contrib") + os.sep, + os.path.join(os.path.dirname(_FRAMEWORK_COMMON_PREFIX), + "py", "keras") + os.sep, +] + +# Patterns of filename patterns that should be considered internal to +# the TensorFlow framework. +_FRAMEWORK_FILENAME_PATTERNS = [ + re.compile(r" + with tf.device(some_func): + The first line will have no padding to its left by default. Subsequent + lines will have two spaces of left-padding. Use the prefix argument + to increase indentation. + """ + if not device_assignment_list: + message = "No device assignments were active during op '%s' creation." + message %= name + return prefix + message + + str_list = [] + str_list.append( + "%sDevice assignments active during op '%s' creation:" % (prefix, name)) + + for traceable_obj in device_assignment_list: + location_summary = "<{file}:{line}>".format( + file=traceable_obj.filename, line=traceable_obj.lineno) + subs = { + "prefix": prefix, + "indent": " ", + "dev_name": traceable_obj.obj, + "loc": location_summary, + } + str_list.append( + "{prefix}{indent}with tf.device({dev_name}): {loc}".format(**subs)) + + return "\n".join(str_list) + + +def _compute_device_assignment_summary_from_op(op, prefix=""): + # pylint: disable=protected-access + return _compute_device_summary_from_list(op.name, op._device_assignments, + prefix) + # pylint: enable=protected-access + + +def _compute_colocation_summary_from_dict(name, colocation_dict, prefix=""): + """Return a summary of an op's colocation stack. + + Args: + name: The op name. + colocation_dict: The op._colocation_dict. + prefix: An optional string prefix used before each line of the multi- + line string returned by this function. + + Returns: + A multi-line string similar to: + Node-device colocations active during op creation: + with tf.compat.v1.colocate_with(test_node_1): + with tf.compat.v1.colocate_with(test_node_2): + The first line will have no padding to its left by default. Subsequent + lines will have two spaces of left-padding. Use the prefix argument + to increase indentation. + """ + if not colocation_dict: + message = "No node-device colocations were active during op '%s' creation." + message %= name + return prefix + message + + str_list = [] + str_list.append("%sNode-device colocations active during op '%s' creation:" % + (prefix, name)) + + for coloc_name, location in colocation_dict.items(): + location_summary = "<{file}:{line}>".format( + file=location.filename, line=location.lineno) + subs = { + "prefix": prefix, + "indent": " ", + "name": coloc_name, + "loc": location_summary, + } + str_list.append( + "{prefix}{indent}with tf.colocate_with({name}): {loc}".format(**subs)) + + return "\n".join(str_list) + + +def _compute_colocation_summary_from_op(op, prefix=""): + """Fetch colocation file, line, and nesting and return a summary string.""" + # pylint: disable=protected-access + return _compute_colocation_summary_from_dict(op.name, op._colocation_dict, + prefix) + # pylint: enable=protected-access + + +def _is_framework_filename(filename): + """Returns whether a filename should be considered a part of the framework. + + A file is part of the framework if it does not match a pattern in + _EXTERNAL_FILENAME_PATTERNS and it either matches a pattern in + _FRAMEWORK_FILENAME_PATTERNS or starts with a _FRAMEWORK_PATH_PREFIXES prefix. + + Args: + filename: A filename string. + + Returns: + Whether the filename should be considered to be internal to the + TensorFlow framework for the purposes of reporting errors. + """ + for pattern in _EXTERNAL_FILENAME_PATTERNS: + if pattern.search(filename): + return False + for pattern in _FRAMEWORK_FILENAME_PATTERNS: + if pattern.search(filename): + return True + for prefix in _FRAMEWORK_PATH_PREFIXES: + if filename.startswith(prefix): + return True + return False + + +def _find_index_of_defining_frame(tb): + """Return index in op.traceback with first 'useful' frame. + + This method reads through the stack stored in op.traceback looking for the + innermost frame which (hopefully) belongs to the caller. It accomplishes this + by rejecting frames deemed to be part of the TensorFlow framework (by + pattern matching the filename). + + Args: + tb: A list of traceback frames (as from Operation.traceback). + + Returns: + Integer index into op.traceback where the first non-TF file was found + (innermost to outermost), or 0 (for the outermost stack frame) if all files + came from TensorFlow. + """ + # Index 0 of traceback is the outermost frame. + size = len(tb) + filenames = [frame.filename for frame in tb] + # We process the filenames from the innermost frame to outermost. + for idx, filename in enumerate(reversed(filenames)): + is_framework = _is_framework_filename(filename) + if not is_framework: + # Consider this to be the defining frame. + return size - idx - 1 + return 0 + + +# TODO(feyu): follow up with users of this function (saved model) +# to see what 'useful' means and whether we can obliviate this. +def _compute_useful_frames(tb, num): + """Return a list of frames, which form a 'useful' stack. + + Starting from the defining frame to the outermost one, this method computes + the contiguous portion of the 'useful' stack trace and returns the selected + frames. + + Args: + tb: A list of traceback frames (as from Operation.traceback). + num: total number of frames to return. + + Returns: + A list of frames. + """ + defining_frame_index = _find_index_of_defining_frame(tb) + # The stack trace is collected from two lines before the defining frame in the + # model file to the outermost with `num` frames at most. These two extra lines + # are included from the TensorFlow library to give the context which node is + # defined. + innermost_excluded = min(defining_frame_index + 2 + 1, len(tb)) + outermost_included = max(innermost_excluded - num, 0) + return tb[outermost_included:innermost_excluded] + + +def create_graph_debug_info_def(func_named_operations): + """Construct and returns a `GraphDebugInfo` protocol buffer. + + Args: + func_named_operations: An iterable of (func_name, op.Operation) tuples + where the Operation instances have a _traceback members. The func_name + should be the empty string for operations in the top-level Graph. + + Returns: + GraphDebugInfo protocol buffer. + + Raises: + TypeError: If the arguments are not of the correct proto buffer type. + """ + builder = tf_stack.GraphDebugInfoBuilder() + for func_name, op in func_named_operations: + if op.traceback is None: + continue + builder.AccumulateStackTrace( + func_name, op.name, _compute_useful_frames(op.traceback, 10) + ) + + return builder.Build() + + +def _compute_field_dict(op): + r"""Return a dictionary mapping interpolation tokens to values. + + Args: + op: op.Operation object. + + Returns: + A dictionary mapping string tokens to string values. The keys are shown + below along with example values. + { + "file": "tool_utils.py", + "lineno": "124", + "line": " source code line", + "defined_at": " (defined at tool_utils.py:124)", + "colocations": + '''Node-device colocations active during op creation: + with tf.compat.v1.colocate_with(test_node_1): + with tf.compat.v1.colocate_with(test_node_2): ''' + "devices": + '''Device assignments active during op 'foo' creation: + with tf.device(/cpu:0): + with tf.device(some_func): ''' + "devs_and_colocs": A concatenation of colocations and devices, e.g. + '''Node-device colocations active during op creation: + with tf.compat.v1.colocate_with(test_node_1): + with tf.compat.v1.colocate_with(test_node_2): ''' + Device assignments active during op 'foo' creation: + with tf.device(/cpu:0): + with tf.device(some_func): ''' + } + """ + # TODO(xjun): colocation and device info are not displayed. Consider + # removing them or using vlog. + colocation_summary = _compute_colocation_summary_from_op(op) + device_summary = _compute_device_assignment_summary_from_op(op) + combined_summary = "\n".join([colocation_summary, device_summary]) + + if op.traceback is None: + # Some ops synthesized on as part of function or control flow definition + # do not have tracebacks. + filename = "" + definition_traceback = "" + lineno = 0 + line = "" + defined_at = "" + else: + frame = op.traceback.last_user_frame() + filename = frame.filename + definition_traceback = traceback.format_list(op.traceback.get_user_frames()) + lineno = frame.lineno + line = frame.line + defined_at = f"{filename}:{lineno:d}" + + field_dict = { + "colocations": colocation_summary, + "devices": device_summary, + "devs_and_colocs": combined_summary, + "defined_at": defined_at, + "file": filename, + "lineno": lineno, + "line": line, + "definition_traceback": definition_traceback, + } + return field_dict + + +def _build_node_error_message(op): + """Returns the formatted error message for the given op. + + Args: + op: The node. + + Returns: + The formatted error message for the given op with traceback. + """ + node_error_message = [ + f"Detected at node {op.name!r} defined at (most recent call last):" + ] + field_dict = _compute_field_dict(op) + + # Add node traceback. + for frame in field_dict["definition_traceback"]: + if ">> @tf.function + ... def iterate_over(t): + ... a,b,c = t + ... return a + >>> + >>> iterate_over(tf.constant([1, 2, 3])) + Traceback (most recent call last): + ... + OperatorNotAllowedInGraphError: ... + + """ + pass + + +@tf_export("errors.OpError", v1=["errors.OpError", "OpError"]) +@deprecation.deprecated_endpoints("OpError") +class OpError(Exception): + """The base class for TensorFlow exceptions. + + Usually, TensorFlow will raise a more specific subclass of `OpError` from the + `tf.errors` module. + """ + + def __init__(self, node_def, op, message, error_code, *args): + """Creates a new `OpError` indicating that a particular op failed. + + Args: + node_def: The `node_def_pb2.NodeDef` proto representing the op that + failed, if known; otherwise None. + op: The `ops.Operation` that failed, if known; otherwise None. During + eager execution, this field is always `None`. + message: The message string describing the failure. + error_code: The `error_codes_pb2.Code` describing the error. + *args: If not empty, it should contain a dictionary describing details + about the error. This argument is inspired by Abseil payloads: + https://github.com/abseil/abseil-cpp/blob/master/absl/status/status.h + """ + super(OpError, self).__init__() + self._node_def = node_def + self._op = op + self._message = message + self._error_code = error_code + if args: + self._experimental_payloads = args[0] + else: + self._experimental_payloads = {} + + def __reduce__(self): + # Allow the subclasses to accept less arguments in their __init__. + init_argspec = tf_inspect.getargspec(self.__class__.__init__) + args = tuple(getattr(self, arg) for arg in init_argspec.args[1:]) + return self.__class__, args + + @property + def message(self): + """The error message that describes the error.""" + return self._message + + @property + def op(self): + """The operation that failed, if known. + + *N.B.* If the failed op was synthesized at runtime, e.g. a `Send` + or `Recv` op, there will be no corresponding + `tf.Operation` + object. In that case, this will return `None`, and you should + instead use the `tf.errors.OpError.node_def` to + discover information about the op. + + Returns: + The `Operation` that failed, or None. + """ + return self._op + + @property + def error_code(self): + """The integer error code that describes the error.""" + return self._error_code + + @property + def node_def(self): + """The `NodeDef` proto representing the op that failed.""" + return self._node_def + + @property + def experimental_payloads(self): + """A dictionary describing the details of the error.""" + return self._experimental_payloads + + def __str__(self): + if self._op is not None: + output = [ + "%s\n\nOriginal stack trace for %r:\n" % ( + self.message, + self._op.name, + ) + ] + curr_traceback_list = traceback.format_list(self._op.traceback or []) + output.extend(curr_traceback_list) + # pylint: disable=protected-access + original_op = self._op._original_op + # pylint: enable=protected-access + while original_op is not None: + output.append( + "\n...which was originally created as op %r, defined at:\n" % + (original_op.name,)) + prev_traceback_list = curr_traceback_list + curr_traceback_list = traceback.format_list(original_op.traceback or []) + + # Attempt to elide large common subsequences of the subsequent + # stack traces. + # + # TODO(mrry): Consider computing the actual longest common subsequence. + is_eliding = False + elide_count = 0 + last_elided_line = None + for line, line_in_prev in zip(curr_traceback_list, prev_traceback_list): + if line == line_in_prev: + if is_eliding: + elide_count += 1 + last_elided_line = line + else: + output.append(line) + is_eliding = True + elide_count = 0 + else: + if is_eliding: + if elide_count > 0: + output.extend([ + "[elided %d identical lines from previous traceback]\n" % + (elide_count - 1,), last_elided_line + ]) + is_eliding = False + output.extend(line) + + # pylint: disable=protected-access + original_op = original_op._original_op + # pylint: enable=protected-access + return "".join(output) + else: + return self.message + + +OK = error_codes_pb2.OK +tf_export("errors.OK").export_constant(__name__, "OK") +CANCELLED = error_codes_pb2.CANCELLED +tf_export("errors.CANCELLED").export_constant(__name__, "CANCELLED") +UNKNOWN = error_codes_pb2.UNKNOWN +tf_export("errors.UNKNOWN").export_constant(__name__, "UNKNOWN") +INVALID_ARGUMENT = error_codes_pb2.INVALID_ARGUMENT +tf_export("errors.INVALID_ARGUMENT").export_constant(__name__, + "INVALID_ARGUMENT") +DEADLINE_EXCEEDED = error_codes_pb2.DEADLINE_EXCEEDED +tf_export("errors.DEADLINE_EXCEEDED").export_constant(__name__, + "DEADLINE_EXCEEDED") +NOT_FOUND = error_codes_pb2.NOT_FOUND +tf_export("errors.NOT_FOUND").export_constant(__name__, "NOT_FOUND") +ALREADY_EXISTS = error_codes_pb2.ALREADY_EXISTS +tf_export("errors.ALREADY_EXISTS").export_constant(__name__, "ALREADY_EXISTS") +PERMISSION_DENIED = error_codes_pb2.PERMISSION_DENIED +tf_export("errors.PERMISSION_DENIED").export_constant(__name__, + "PERMISSION_DENIED") +UNAUTHENTICATED = error_codes_pb2.UNAUTHENTICATED +tf_export("errors.UNAUTHENTICATED").export_constant(__name__, "UNAUTHENTICATED") +RESOURCE_EXHAUSTED = error_codes_pb2.RESOURCE_EXHAUSTED +tf_export("errors.RESOURCE_EXHAUSTED").export_constant(__name__, + "RESOURCE_EXHAUSTED") +FAILED_PRECONDITION = error_codes_pb2.FAILED_PRECONDITION +tf_export("errors.FAILED_PRECONDITION").export_constant(__name__, + "FAILED_PRECONDITION") +ABORTED = error_codes_pb2.ABORTED +tf_export("errors.ABORTED").export_constant(__name__, "ABORTED") +OUT_OF_RANGE = error_codes_pb2.OUT_OF_RANGE +tf_export("errors.OUT_OF_RANGE").export_constant(__name__, "OUT_OF_RANGE") +UNIMPLEMENTED = error_codes_pb2.UNIMPLEMENTED +tf_export("errors.UNIMPLEMENTED").export_constant(__name__, "UNIMPLEMENTED") +INTERNAL = error_codes_pb2.INTERNAL +tf_export("errors.INTERNAL").export_constant(__name__, "INTERNAL") +UNAVAILABLE = error_codes_pb2.UNAVAILABLE +tf_export("errors.UNAVAILABLE").export_constant(__name__, "UNAVAILABLE") +DATA_LOSS = error_codes_pb2.DATA_LOSS +tf_export("errors.DATA_LOSS").export_constant(__name__, "DATA_LOSS") + + +@tf_export("errors.CancelledError") +class CancelledError(OpError): + """Raised when an operation is cancelled. + + For example, a long-running operation e.g.`tf.queue.QueueBase.enqueue`, or a + `tf.function` call may be cancelled by either running another operation e.g. + `tf.queue.QueueBase.close` or a remote worker failure. + + This long-running operation will fail by raising `CancelledError`. + + Example: + >>> q = tf.queue.FIFOQueue(10, tf.float32, ((),)) + >>> q.enqueue((10.0,)) + >>> q.close() + >>> q.enqueue((10.0,)) + Traceback (most recent call last): + ... + CancelledError: ... + + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `CancelledError`.""" + super(CancelledError, self).__init__(node_def, op, message, CANCELLED, + *args) + + +@tf_export("errors.UnknownError") +class UnknownError(OpError): + """Unknown error. + + An example of where this error may be returned is if a Status value + received from another address space belongs to an error-space that + is not known to this address space. Also, errors raised by APIs that + do not return enough error information may be converted to this + error. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `UnknownError`.""" + super(UnknownError, self).__init__(node_def, op, message, UNKNOWN, *args) + + +@tf_export("errors.InvalidArgumentError") +class InvalidArgumentError(OpError): + """Raised when an operation receives an invalid argument. + + This error is typically raised when an op receives mismatched arguments. + + Example: + + >>> tf.reshape([1, 2, 3], (2,)) + Traceback (most recent call last): + ... + InvalidArgumentError: ... + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `InvalidArgumentError`.""" + super(InvalidArgumentError, self).__init__(node_def, op, message, + INVALID_ARGUMENT, *args) + + +@tf_export("errors.DeadlineExceededError") +class DeadlineExceededError(OpError): + """Raised when a deadline expires before an operation could complete. + + This exception is not currently used. + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `DeadlineExceededError`.""" + super(DeadlineExceededError, self).__init__(node_def, op, message, + DEADLINE_EXCEEDED, *args) + + +@tf_export("errors.NotFoundError") +class NotFoundError(OpError): + """Raised when a requested entity (e.g., a file or directory) was not found. + + For example, running the + `tf.WholeFileReader.read` + operation could raise `NotFoundError` if it receives the name of a file that + does not exist. + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `NotFoundError`.""" + super(NotFoundError, self).__init__(node_def, op, message, NOT_FOUND, *args) + + +@tf_export("errors.AlreadyExistsError") +class AlreadyExistsError(OpError): + """Raised when an entity that we attempted to create already exists. + + An API raises this this error to avoid overwriting an existing resource, + value, etc. Calling a creation API multiple times with the same arguments + could raise this error if the creation API is not idempotent. + + For example, running an operation that saves a file + (e.g. `tf.saved_model.save`) + could potentially raise this exception if an explicit filename for an + existing file was passed. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `AlreadyExistsError`.""" + super(AlreadyExistsError, self).__init__(node_def, op, message, + ALREADY_EXISTS, *args) + + +@tf_export("errors.PermissionDeniedError") +class PermissionDeniedError(OpError): + """Raised when the caller does not have permission to run an operation. + + For example, running the + `tf.WholeFileReader.read` + operation could raise `PermissionDeniedError` if it receives the name of a + file for which the user does not have the read file permission. + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `PermissionDeniedError`.""" + super(PermissionDeniedError, self).__init__(node_def, op, message, + PERMISSION_DENIED, *args) + + +@tf_export("errors.UnauthenticatedError") +class UnauthenticatedError(OpError): + """Raised when the request does not have valid authentication credentials. + + This exception is not currently used. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `UnauthenticatedError`.""" + super(UnauthenticatedError, self).__init__(node_def, op, message, + UNAUTHENTICATED, *args) + + +@tf_export("errors.ResourceExhaustedError") +class ResourceExhaustedError(OpError): + """Raised when some resource has been exhausted while running operation. + + For example, this error might be raised if a per-user quota is + exhausted, or perhaps the entire file system is out of space. If running into + `ResourceExhaustedError` due to out of memory (OOM), try to use smaller batch + size or reduce dimension size of model weights. + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `ResourceExhaustedError`.""" + super(ResourceExhaustedError, self).__init__(node_def, op, message, + RESOURCE_EXHAUSTED, *args) + + +@tf_export("errors.FailedPreconditionError") +class FailedPreconditionError(OpError): + """Raised when some prerequisites are not met when running an operation. + + This typically indicates that system is not in state to execute the operation + and requires preconditions to be met before successfully executing current + operation. + + For example, this exception is commonly raised when running an operation + that reads a `tf.Variable` before it has been initialized. + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `FailedPreconditionError`.""" + super(FailedPreconditionError, self).__init__(node_def, op, message, + FAILED_PRECONDITION, *args) + + +@tf_export("errors.AbortedError") +class AbortedError(OpError): + """Raised when an operation was aborted, typically due to a concurrent action. + + For example, running a + `tf.queue.QueueBase.enqueue` + operation may raise `AbortedError` if a + `tf.queue.QueueBase.close` operation + previously ran. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `AbortedError`.""" + super(AbortedError, self).__init__(node_def, op, message, ABORTED, *args) + + +@tf_export("errors.OutOfRangeError") +class OutOfRangeError(OpError): + """Raised when an operation iterates past the valid range. + + Unlike `InvalidArgumentError`, this error indicates a problem may be fixed if + the system state changes. For example, if a list grows and the operation is + now within the valid range. `OutOfRangeError` overlaps with + `FailedPreconditionError` and should be preferred as the more specific error + when iterating or accessing a range. + + For example, iterating a TF dataset past the last item in the dataset will + raise this error. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `OutOfRangeError`.""" + super(OutOfRangeError, self).__init__(node_def, op, message, OUT_OF_RANGE, + *args) + + +@tf_export("errors.UnimplementedError") +class UnimplementedError(OpError): + """Raised when an operation has not been implemented. + + Some operations may raise this error when passed otherwise-valid + arguments that it does not currently support. For example, running + the `tf.nn.max_pool2d` operation + would raise this error if pooling was requested on the batch dimension, + because this is not yet supported. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `UnimplementedError`.""" + super(UnimplementedError, self).__init__(node_def, op, message, + UNIMPLEMENTED, *args) + + +@tf_export("errors.InternalError") +class InternalError(OpError): + """Raised when the system experiences an internal error. + + This exception is raised when some invariant expected by the runtime + has been broken. Catching this exception is not recommended. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `InternalError`.""" + super(InternalError, self).__init__(node_def, op, message, INTERNAL, *args) + + +@tf_export("errors.UnavailableError") +class UnavailableError(OpError): + """Raised when the runtime is currently unavailable. + + This exception is not currently used. + """ + + def __init__(self, node_def, op, message, *args): + """Creates an `UnavailableError`.""" + super(UnavailableError, self).__init__(node_def, op, message, UNAVAILABLE, + *args) + + +@tf_export("errors.DataLossError") +class DataLossError(OpError): + """Raised when unrecoverable data loss or corruption is encountered. + + This could be due to: + * A truncated file. + * A corrupted file. + * Specifying the wrong data format. + + For example, this may be raised by running a + `tf.WholeFileReader.read` + operation, if the file is truncated while it is being read. + """ + + def __init__(self, node_def, op, message, *args): + """Creates a `DataLossError`.""" + super(DataLossError, self).__init__(node_def, op, message, DATA_LOSS, *args) + + +_CODE_TO_EXCEPTION_CLASS = { + CANCELLED: CancelledError, + UNKNOWN: UnknownError, + INVALID_ARGUMENT: InvalidArgumentError, + DEADLINE_EXCEEDED: DeadlineExceededError, + NOT_FOUND: NotFoundError, + ALREADY_EXISTS: AlreadyExistsError, + PERMISSION_DENIED: PermissionDeniedError, + UNAUTHENTICATED: UnauthenticatedError, + RESOURCE_EXHAUSTED: ResourceExhaustedError, + FAILED_PRECONDITION: FailedPreconditionError, + ABORTED: AbortedError, + OUT_OF_RANGE: OutOfRangeError, + UNIMPLEMENTED: UnimplementedError, + INTERNAL: InternalError, + UNAVAILABLE: UnavailableError, + DATA_LOSS: DataLossError, +} + +_pywrap_py_exception_registry.PyExceptionRegistry_Init(_CODE_TO_EXCEPTION_CLASS) + +_EXCEPTION_CLASS_TO_CODE = { + class_: code for code, class_ in _CODE_TO_EXCEPTION_CLASS.items() +} + + +@tf_export(v1=["errors.exception_type_from_error_code"]) +def exception_type_from_error_code(error_code): + return _CODE_TO_EXCEPTION_CLASS[error_code] + + +@tf_export(v1=["errors.error_code_from_exception_type"]) +def error_code_from_exception_type(cls): + try: + return _EXCEPTION_CLASS_TO_CODE[cls] + except KeyError: + warnings.warn("Unknown class exception") + return UnknownError(None, None, "Unknown class exception", None) + + +def _make_specific_exception(node_def, op, message, error_code): + try: + exc_type = exception_type_from_error_code(error_code) + return exc_type(node_def, op, message) + except KeyError: + warnings.warn("Unknown error code: %d" % error_code) + return UnknownError(node_def, op, message, error_code) + + +# Named like a function for backwards compatibility with the +# @tf_contextlib.contextmanager version, which was switched to a class to avoid +# some object creation overhead. +# TODO(b/77295559): expand use of TF_Status* SWIG typemap and deprecate this. +@tf_export(v1=["errors.raise_exception_on_not_ok_status"]) # pylint: disable=invalid-name +class raise_exception_on_not_ok_status(object): + """Context manager to check for C API status.""" + + def __enter__(self): + self.status = c_api_util.ScopedTFStatus() + return self.status.status + + def __exit__(self, type_arg, value_arg, traceback_arg): + try: + if c_api.TF_GetCode(self.status.status) != 0: + raise _make_specific_exception( + None, None, compat.as_text(c_api.TF_Message(self.status.status)), + c_api.TF_GetCode(self.status.status)) + # Delete the underlying status object from memory otherwise it stays alive + # as there is a reference to status from this from the traceback due to + # raise. + finally: + del self.status + return False # False values do not suppress exceptions diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/extension_type.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/extension_type.py new file mode 100644 index 0000000000000000000000000000000000000000..d83e5b3b6d401ebe06b78dff87c0757008666144 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/extension_type.py @@ -0,0 +1,1319 @@ +# 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. +# ============================================================================== +"""User-defined ExtensionType classes.""" + +import abc +import typing +import warnings + +import typing_extensions + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import extension_type_field +from tensorflow.python.framework import immutable_dict +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import composite_tensor_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + +# Attribute used to keep track of when we're inside a user-defined constructor +# (in which case the fields of `self` may be modified). +_IN_CONSTRUCTOR = '_tf_extension_type_in_constructor' + +_MUTABLE_KERAS_PROPERTIES = [ + # Keras uses _keras_mask property to pass the mask around + '_keras_mask', +] + + +# ============================================================================== +# Utility functions +# ============================================================================== +def _create_object_from_type_and_dict(cls, obj_dict): + """Creates an object, bypassing the constructor. + + Creates an object of type `cls`, whose `__dict__` is updated to contain + `obj_dict`. + + Args: + cls: The type of the new object. + obj_dict: A `Mapping` that should be used to initialize the new object's + `__dict__`. + + Returns: + An object of type `cls`. + """ + value = object.__new__(cls) + value.__dict__.update(obj_dict) + return value + + +# ============================================================================== +# Metaclass for tf.ExtensionType +# ============================================================================== +class ExtensionTypeMetaclass(abc.ABCMeta): + """Metaclass for tf.ExtensionType types.""" + + def __init__(cls, name, bases, namespace): + # Don't transform base classes that are part of the framework -- only + # transform user classes. We identify classes that are part of the + # framework by setting '_tf_extension_type_do_not_transform_this_class=True' + # in the class definition. (Note: we check for this in the class namespace, + # so it is *not* ineherited.) + if not namespace.get( + '_tf_extension_type_do_not_transform_this_class', False + ): + _check_field_annotations(cls) + _add_extension_type_constructor(cls) + _add_type_spec(cls) + super(ExtensionTypeMetaclass, cls).__init__(name, bases, namespace) + + +# ============================================================================== +# Base class for user-defined types +# ============================================================================== +@tf_export('experimental.ExtensionType') +class ExtensionType( + composite_tensor.CompositeTensor, metaclass=ExtensionTypeMetaclass +): + """Base class for TensorFlow `ExtensionType` classes. + + Tensorflow `ExtensionType` classes are specialized Python classes that can be + used transparently with TensorFlow -- e.g., they can be used with ops + such as `tf.cond` or `tf.while_loop` and used as inputs or outputs for + `tf.function` and Keras layers. + + New `ExtensionType` classes are defined by creating a subclass of + `tf.ExtensionType` that + contains type annotations for all instance variables. The following type + annotations are supported: + + Type | Example + ------------------------- | -------------------------------------------- + Python integers | `i: int` + Python floats | `f: float` + Python strings | `s: str` + Python booleans | `b: bool` + Python None | `n: None` + Python tuple | `params: tuple[int, float, int, int]` + Python tuple w/ Ellipsis | `lengths: tuple[int, ...]` + Tensors | `t: tf.Tensor` + Composite Tensors | `rt: tf.RaggedTensor` + Extension Types | `m: MyMaskedTensor` + Tensor shapes | `shape: tf.TensorShape` + Tensor dtypes | `dtype: tf.DType` + Type unions | `length: typing.Union[int, float]` + Tuples | `params: typing.Tuple[int, float, int, int]` + Tuples w/ Ellipsis | `lengths: typing.Tuple[int, ...]` + Mappings | `tags: typing.Mapping[str, str]` + + Fields annotated with `typing.Mapping` will be stored using an immutable + mapping type. + + ExtensionType values are immutable -- i.e., once constructed, you can not + modify or delete any of their instance members. + + ### Examples + + >>> class MaskedTensor(ExtensionType): + ... values: tf.Tensor + ... mask: tf.Tensor + + >>> class Toy(ExtensionType): + ... name: str + ... price: tensor.Tensor + ... features: typing.Mapping[str, tf.Tensor] + + >>> class ToyStore(ExtensionType): + ... name: str + ... toys: typing.Tuple[Toy, ...] + """ + + # Let the metaclass know that it should *not* transform this class (since + # this class is part of the ExtensionType framework, and not a user class). + _tf_extension_type_do_not_transform_this_class = True + + def __init__(self, *args, **kwargs): + if type(self) is ExtensionType: # pylint: disable=unidiomatic-typecheck + raise AssertionError( + 'Cannot create an instance of ExtensionType ' + 'because ExtensionType is an abstract base class.' + ) + + # This class variable is used to cache the return value for + # _tf_extension_type_fields. + _tf_extension_type_cached_fields = None + + @classmethod + def _tf_extension_type_fields(cls): # pylint: disable=no-self-argument + """An ordered list describing the fields of this ExtensionType. + + Returns: + A list of `ExtensionTypeField` objects. Forward references are resolved + if possible, or left unresolved otherwise. + """ + if '_tf_extension_type_cached_fields' in cls.__dict__: # do not inherit. + return cls._tf_extension_type_cached_fields + + try: + # Using include_extras=False will replace all Annotated[T, ...] with T. + # The typing_extensions module is used since this is only supported in + # Python 3.9. + type_hints = typing_extensions.get_type_hints(cls, include_extras=False) + ok_to_cache = True # all forward references have been resolved. + except (NameError, AttributeError): + # Unresolved forward reference -- gather type hints manually. + # * NameError comes from an annotation like `Foo` where class + # `Foo` hasn't been defined yet. + # * AttributeError comes from an annotation like `foo.Bar`, where + # the module `foo` exists but `Bar` hasn't been defined yet. + # Note: If a user attempts to instantiate a `ExtensionType` type that + # still has unresolved forward references (e.g., because of a typo or a + # missing import), then the constructor will raise an exception. + type_hints = {} + for base in reversed(cls.__mro__): + type_hints.update(base.__dict__.get('__annotations__', {})) + ok_to_cache = False + + fields = [] + for name, value_type in type_hints.items(): + default = getattr( + cls, name, extension_type_field.ExtensionTypeField.NO_DEFAULT + ) + fields.append( + extension_type_field.ExtensionTypeField(name, value_type, default) + ) + fields = tuple(fields) + + if ok_to_cache: + cls._tf_extension_type_cached_fields = fields + + return fields + + @classmethod + def _tf_extension_type_has_field(cls, name): + return any(name == field.name for field in cls._tf_extension_type_fields()) + + def _tf_extension_type_convert_fields(self): + extension_type_field.convert_fields( + self._tf_extension_type_fields(), self.__dict__ + ) + + def __repr__(self): + fields = ', '.join( + [ + f'{field.name}={getattr(self, field.name)!r}' + for field in self._tf_extension_type_fields() + ] + ) + return f'{type(self).__qualname__}({fields})' + + def __setattr__(self, name, value): + if name in _MUTABLE_KERAS_PROPERTIES or ( + hasattr(self, _IN_CONSTRUCTOR) + and self._tf_extension_type_has_field(name) + ): + self.__dict__[name] = value + else: + raise AttributeError( + f'Cannot mutate attribute `{name}` ' + 'outside the custom constructor of ExtensionType.' + ) + + def __delattr__(self, name): + if name in _MUTABLE_KERAS_PROPERTIES or ( + hasattr(self, _IN_CONSTRUCTOR) + and self._tf_extension_type_has_field(name) + ): + del self.__dict__[name] + else: + raise AttributeError( + f'Cannot mutate attribute `{name}` ' + 'outside the custom constructor of ExtensionType.' + ) + + def __getattr__(self, name): + if name in _MUTABLE_KERAS_PROPERTIES: + return object.__getattribute__(self, name) + if '_tf_extension_type_packed_variant' in self.__dict__: + # Note: it's *not* ok to cache the results of unpack() here. In + # particular, it would be nice if we could do something like + # `self.__dict__.update(unpack(self).__dict__)`, but that (potentially) + # violates an invariant required by the `cond` operation. E.g., if we had + # `tf.cond(lambda: x.foo, lambda: x.bar)`, then tensor `x.bar` used in the + # "else" branch would be created by an op in the "then" branch (when + # looking up `x.foo`); and that's not allowed. + return getattr(unpack(self), name) + + raise AttributeError( + f'{type(self).__name__!r} object has no attribute {name!r}' + ) + + def __eq__(self, other): + if type(self) is not type(other): + return False + + if self._type_spec != other._type_spec: + return False + + self_tensors = nest.flatten(self, expand_composites=True) + other_tensors = nest.flatten(other, expand_composites=True) + if len(self_tensors) != len(other_tensors): + return False + conditions = [] + for t1, t2 in zip(self_tensors, other_tensors): + conditions.append( + math_ops.reduce_all( + gen_math_ops.equal( + array_ops.shape(t1), + array_ops.shape(t2), + incompatible_shape_error=False, + ) + ) + ) + # Explicitly check shape (values that have different shapes but broadcast + # to the same value are considered non-equal). + conditions.append( + math_ops.reduce_all( + gen_math_ops.equal(t1, t2, incompatible_shape_error=False) + ) + ) + return math_ops.reduce_all(array_ops_stack.stack(conditions)) + + def __ne__(self, other): + eq = self.__eq__(other) + if isinstance(eq, tensor.Tensor): + return math_ops.logical_not(eq) + else: + return not eq + + def __validate__(self): + """Perform post-construction validation.""" + + # This instance variable is used to cache the value for the _type_spec + # property. + _tf_extension_type_cached_type_spec = None + + @property + def _type_spec(self): # CompositeTensor API. + # Note: the TypeSpec contains all static (non-tensor) data from `self`. + if self._tf_extension_type_cached_type_spec is None: + assert not is_packed(self) # Packed version always caches TypeSpec. + self.__dict__['_tf_extension_type_cached_type_spec'] = ( + self.Spec.from_value(self) + ) + return self._tf_extension_type_cached_type_spec + + +@tf_export('experimental.extension_type.as_dict') +def as_dict(value): + """Extracts the attributes of `value` and their values to a dict format. + + Unlike `dataclasses.asdict()`, this function is not recursive and in case of + nested `ExtensionType` objects, only the top level object is converted to a + dict. + + Args: + value: An `ExtensionType` object. + + Returns: + A dict that contains the attributes of `value` and their values. + """ + return { + field.name: getattr(value, field.name) + for field in value._tf_extension_type_fields() # pylint: disable=protected-access + } + + +def pack(value): + """Returns a copy of `value` with fields packed in a single Variant. + + Args: + value: An `ExtensionType` object. + + Returns: + An `ExtensionType` object. + """ + if is_packed(value): + return value + + spec = value._type_spec._tf_extension_type_with_packed(True) # pylint: disable=protected-access + try: + variant = composite_tensor_ops.composite_tensor_to_variants(value) + except nested_structure_coder.NotEncodableError as e: + # Note: the only time `_TypeSpecCodec.can_encode` returns False is if the + # named type is not registered. The default error message would simply + # tell the user that there is no encoder for the object, so we provide + # a more useful message letting them know how to register the type. + raise ValueError( + 'ExtensionTypes must have a __name__ field in order to be packed.' + ) from e + + return _create_object_from_type_and_dict( + type(value), + { + '_tf_extension_type_cached_type_spec': spec, + '_tf_extension_type_packed_variant': variant, + }, + ) + + +def unpack(value): + """Returns a copy of `value` with individual fields stored in __dict__. + + Args: + value: An `ExtensionType` object. + + Returns: + An `ExtensionType` object. + """ + if not is_packed(value): + return value + + # pylint: disable=protected-access + variant = value._tf_extension_type_packed_variant + spec = value._tf_extension_type_cached_type_spec + spec = spec._tf_extension_type_with_packed(False) + return composite_tensor_ops.composite_tensor_from_variant(variant, spec) + + +def is_packed(value): + """Returns true if `value`'s fields are packed in a single Variant.""" + if not isinstance(value, ExtensionType): + raise ValueError( + 'Expected `value` to be an object of type ExtensionType,' + f'got an instance of {type(value)}.' + ) + return '_tf_extension_type_packed_variant' in value.__dict__ + + +# ============================================================================== +# Base class for the tf.ExtensionType TypeSpecs +# ============================================================================== + + +@tf_export('experimental.ExtensionTypeSpec') +class ExtensionTypeSpec(type_spec.TypeSpec): + """Base class for tf.ExtensionType TypeSpec.""" + + def _serialize(self): # TypeSpec API. + # Use a tuple of (name, value) pairs, to ensure we preserve field ordering. + fields = [f.name for f in self._tf_extension_type_fields()] + if self._tf_extension_type_is_packed: + fields.append('_tf_extension_type_is_packed') + return tuple( + (f, _change_nested_mappings_to(self.__dict__[f], dict)) for f in fields + ) + + @classmethod + def _deserialize(cls, state): # TypeSpec API. + state = _change_nested_mappings_to(state, immutable_dict.ImmutableDict) + return _create_object_from_type_and_dict(cls, state) + + def __reduce__(self): + # Use value_type instead of spec_type, as spec_type is a nested class. + # Pickle support of nested class requries Pickle protocol version 4, which + # is not enabled by default until py 3.8. + # + # https://www.python.org/dev/peps/pep-3154/#serializing-more-lookupable-objects + # https://docs.python.org/3/library/pickle.html#pickle.DEFAULT_PROTOCOL + return _deserialize_for_reduce, (self.value_type, self._serialize()) + + def _to_components(self, value): # TypeSpec API. + if self._tf_extension_type_is_packed: + return value._tf_extension_type_packed_variant # pylint: disable=protected-access + + tensor_or_composite = (tensor.Tensor, composite_tensor.CompositeTensor) + # Retireve fields by the order of spec dict to preserve field ordering. This + # is needed as nest.flatten would sort dictionary entries by key. + value_tuple = tuple(value.__dict__[key] for key in self.__dict__) + return tuple( + x + for x in nest.flatten(value_tuple) + if isinstance(x, tensor_or_composite) + ) + + def _from_components(self, components): # TypeSpec API. + if self._tf_extension_type_is_packed: + return _create_object_from_type_and_dict( + self.value_type, + { + '_tf_extension_type_cached_type_spec': self, + '_tf_extension_type_packed_variant': components, + }, + ) + + spec_tuple = tuple(self.__dict__.values()) + components_iter = iter(components) + flat = [ + next(components_iter) if isinstance(x, type_spec.TypeSpec) else x + for x in nest.flatten(spec_tuple) + ] + if list(components_iter): + raise ValueError( + 'Cannot build an ExtensionType instance from components ' + 'because more components are provided than the number expected ' + 'by the type spec.' + ) + value_tuple = nest.pack_sequence_as(spec_tuple, flat) + fields = dict(zip(self.__dict__.keys(), value_tuple)) + + # Build the new value. Bypass the constructor (__init__), in case the user + # who defined the ExtensionType used a custom constructor. + return _create_object_from_type_and_dict(self.value_type, fields) + + @property + def _component_specs(self): # TypeSpec API. + if self._tf_extension_type_is_packed: + return tensor.TensorSpec((), dtypes.variant) + + components = [] + + def push_if_type_spec(x): + if isinstance(x, type_spec.TypeSpec): + components.append(x) + + nest.map_structure(push_if_type_spec, tuple(self.__dict__.values())) + return tuple(components) + + @classmethod + def from_value(cls, value): + cached_spec = getattr(value, '_tf_extension_type_cached_type_spec', None) + if cached_spec is not None: + return cached_spec + + value_fields = value.__dict__ + spec_fields = nest.map_structure(_replace_tensor_with_spec, value_fields) + spec_fields.pop('_tf_extension_type_cached_fields', None) + return _create_object_from_type_and_dict(cls, spec_fields) + + def __setattr__(self, name, value): + if (hasattr(self, _IN_CONSTRUCTOR) + and self._tf_extension_type_has_field(name)): + self.__dict__[name] = value + elif name in type_spec.CACHED_FIXED_PROPERTIES: + super().__setattr__(name, value) + else: + raise AttributeError( + f'Cannot mutate attribute `{name}` ' + 'outside the custom constructor of ExtensionTypeSpec.' + ) + + def __delattr__(self, name): + if hasattr(self, _IN_CONSTRUCTOR) and self._tf_extension_type_has_field( + name + ): + del self.__dict__[name] + else: + raise AttributeError( + f'Cannot mutate attribute `{name}` ' + 'outside the custom constructor of ExtensionTypeSpec.' + ) + + def __validate__(self): + """Perform post-construction validation.""" + + @classmethod + def _tf_extension_type_fields(cls): + return cls.value_type._tf_extension_type_fields() # pylint: disable=protected-access + + @classmethod + def _tf_extension_type_has_field(cls, name): + return any(name == field.name for field in cls._tf_extension_type_fields()) + + def _tf_extension_type_convert_fields(self): + extension_type_field.convert_fields_for_spec( + self._tf_extension_type_fields(), self.__dict__ + ) + + def __repr__(self): + fields = ', '.join([f'{k}={v!r}' for (k, v) in self._serialize()]) + return f'{type(self).__qualname__}({fields})' + + _tf_extension_type_is_packed = False + + def _tf_extension_type_with_packed(self, value): + """Returns a copy of this `TypeSpec` with `packed=value`. + + Args: + value: A boolean value. + + Returns: + A copy of `self` with `_tf_extension_type_is_packed=value`. + """ + copy = _create_object_from_type_and_dict(type(self), self.__dict__) + copy.__dict__['_tf_extension_type_is_packed'] = value + return copy + + def _to_legacy_output_shapes(self): + """Returns the shape property.""" + try: + return self.shape + except AttributeError as e: + raise NotImplementedError( + 'It appears that the Spec of the ExtensionType is missing a shape' + ' property. In order to support tf.Data, it is recommended that you' + ' implement a shape property on the Spec.' + ) from e + + +class _ExtensionTypeSpecCodec: + """Codec for `tf.ExtensionTypeSpec`.""" + + def can_encode(self, pyobj): + """Returns true if `pyobj` can be encoded as an ExtensionTypeSpec.""" + if isinstance(pyobj, ExtensionTypeSpec): + try: + type_spec_registry.get_name(type(pyobj)) + return True + except ValueError: + return False + return False + + def do_encode(self, extension_type_spec_value, encode_fn): + """Returns an encoded proto for the given `tf.ExtensionTypeSpec`.""" + type_spec_class_name = type_spec_registry.get_name( + type(extension_type_spec_value) + ) + + type_state = extension_type_spec_value._serialize() # pylint: disable=protected-access + num_flat_components = len( + nest.flatten( + extension_type_spec_value._component_specs, expand_composites=True # pylint: disable=protected-access + ) + ) + encoded_type_spec = struct_pb2.StructuredValue() + encoded_type_spec.type_spec_value.CopyFrom( + struct_pb2.TypeSpecProto( + type_spec_class=struct_pb2.TypeSpecProto.EXTENSION_TYPE_SPEC, + type_state=encode_fn(type_state), + type_spec_class_name=type_spec_class_name, + num_flat_components=num_flat_components, + ) + ) + return encoded_type_spec + + def can_decode(self, value): + """Returns true if `value` can be decoded into a `tf.ExtensionTypeSpec`.""" + if value.HasField('type_spec_value'): + type_spec_class_enum = value.type_spec_value.type_spec_class + return ( + type_spec_class_enum == struct_pb2.TypeSpecProto.EXTENSION_TYPE_SPEC + ) + return False + + def do_decode(self, value, decode_fn): + """Returns the `tf.TypeSpec` encoded by the proto `value`.""" + type_spec_proto = value.type_spec_value + class_name = type_spec_proto.type_spec_class_name + + try: + type_spec_class = type_spec_registry.lookup(class_name) + except ValueError: + type_spec_class = AnonymousExtensionTypeSpec + warnings.warn( + f"The type '{class_name}' has not been registered. " + 'Falling back to using AnonymousExtensionTypeSpec ' + 'instead.' + ) + + # pylint: disable=protected-access + return type_spec_class._deserialize(decode_fn(type_spec_proto.type_state)) + + +nested_structure_coder.register_codec(_ExtensionTypeSpecCodec()) + + +@tf_export('experimental.ExtensionTypeBatchEncoder') +class ExtensionTypeBatchEncoder(type_spec.TypeSpecBatchEncoder): + """Class used to encode and decode extension type values for batching. + + In order to be batched and unbatched by APIs such as `tf.data.Dataset`, + `tf.keras`, and `tf.map_fn`, extension type values must be encoded as a list + of `tf.Tensor`s, where stacking, unstacking, or concatenating these encoded + tensors and then decoding the result must be equivalent to stacking, + unstacking, or concatenating the original values. `ExtensionTypeBatchEncoder`s + are responsible for implementing this encoding. + + The default `ExtensionTypeBatchEncoder` that is used by + `BatchableExtensionType` assumes that extension type values can be stacked, + unstacked, or concatenated by simply stacking, unstacking, or concatenating + every nested `Tensor`, `ExtensionType`, `CompositeTensor`, and `TensorShape` + field. + + Extension types where this is not the case will need to override + `__batch_encoder__` with a custom encoder that overrides the `batch`, + `unbatch`, `encode`, and `decode` methods. E.g.: + + >>> class CustomBatchEncoder(ExtensionTypeBatchEncoder): + ... pass # Override batch(), unbatch(), encode(), and decode(). + + >>> class CustomType(BatchableExtensionType): + ... x: tf.Tensor + ... y: tf.Tensor + ... shape: tf.TensorShape + ... __batch_encoder__ = CustomBatchEncoder() + + For example, `tf.RaggedTensor` and `tf.SparseTensor` both use custom batch + encodings which define ops to "box" and "unbox" individual values into + `tf.variant` tensors. + """ + + def batch(self, spec, batch_size): + """Returns the TypeSpec representing a batch of values described by `spec`. + + The default definition returns a `TypeSpec` that is equal to `spec`, except + that an outer axis with size `batch_size` is added to every nested + `TypeSpec` and `TensorShape` field. Subclasses may override this default + definition, when necessary. + + Args: + spec: The `TypeSpec` for an individual value. + batch_size: An `int` indicating the number of values that are batched + together, or `None` if the batch size is not known. + + Returns: + A `TypeSpec` for a batch of values. + """ + + def batch_field(f): + if isinstance(f, type_spec.BatchableTypeSpec): + return f.__batch_encoder__.batch(f, batch_size) + elif isinstance(f, tensor_shape.TensorShape): + return [batch_size] + f + else: + return f + + fields = tuple(spec.__dict__.items()) + batched_fields = nest.map_structure(batch_field, fields) + return _create_object_from_type_and_dict(type(spec), batched_fields) + + def unbatch(self, spec): + """Returns the TypeSpec for a single unbatched element in `spec`. + + The default definition returns a `TypeSpec` that is equal to `spec`, except + that the outermost axis is removed from every nested `TypeSpec`, and + `TensorShape` field. Subclasses may override this default definition, when + necessary. + + Args: + spec: The `TypeSpec` for a batch of values. + + Returns: + A `TypeSpec` for an individual value. + """ + + def unbatch_field(f): + if isinstance(f, type_spec.BatchableTypeSpec): + return f.__batch_encoder__.unbatch(f) + elif isinstance(f, tensor_shape.TensorShape): + return f[1:] + else: + return f + + fields = tuple(spec.__dict__.items()) + unbatched_fields = nest.map_structure(unbatch_field, fields) + return _create_object_from_type_and_dict(type(spec), unbatched_fields) + + def encode(self, spec, value, minimum_rank=0): + """Encodes `value` as a nest of batchable Tensors or CompositeTensors. + + The default definition returns a flat tuple of all the `Tensor`s, + `CompositeTensor`s, and `ExtensionType`s from a depth-first traversal of + `value`'s fields. Subclasses may override this default definition, when + necessary. + + Args: + spec: The TypeSpec of the value to encode. + value: A value compatible with `spec`. + minimum_rank: The minimum rank for the returned Tensors, CompositeTensors, + and ExtensionType values. This can be used to ensure that the encoded + values can be unbatched this number of times. If `minimum_rank>0`, + then `t.shape[:minimum_rank]` must be compatible for all values `t` + returned by `encode`. + + Returns: + A nest (as defined by `tf.nest`) of `tf.Tensor`s, batchable + `tf.CompositeTensor`s, or `tf.ExtensionType`s. Stacking, unstacking, or + concatenating these encoded values and then decoding the result must be + equivalent to stacking, unstacking, or concatenating the original values. + """ + return spec._to_components(value) # pylint: disable=protected-access + + def decode(self, spec, encoded_value): + """Decodes `value` from a batchable tensor encoding. + + See `encode` for a description of the default encoding. Subclasses may + override this default definition, when necessary. + + Args: + spec: The TypeSpec for the result value. If encoded values with spec `s` + were batched, then `spec` should be `s.batch(batch_size)`; or if encoded + values with spec `s` were unbatched, then `spec` should be + `s.unbatch()`. + encoded_value: A nest of values returned by `encode`; or a nest of values + that was formed by stacking, unstacking, or concatenating the + corresponding elements of values returned by `encode`. + + Returns: + A value compatible with `type_spec`. + """ + return spec._from_components(encoded_value) # pylint: disable=protected-access + + def encoding_specs(self, spec): + """Returns a list of `TensorSpec`(s) describing the encoding for `spec`. + + See `encode` for a description of the default encoding. Subclasses may + override this default definition, when necessary. + + Args: + spec: The TypeSpec whose encoding should be described. + + Returns: + A nest (as defined by `tf.nest) of `tf.TypeSpec`, describing the values + that are returned by `self.encode(spec, ...)`. All TypeSpecs in this + nest must be batchable. + """ + return spec._component_specs # pylint: disable=protected-access + + +class BatchableExtensionTypeSpec( + ExtensionTypeSpec, type_spec.BatchableTypeSpec +): + """Base class for TypeSpecs for BatchableExtensionTypes.""" + + __batch_encoder__ = ExtensionTypeBatchEncoder() + + def _batch(self, batch_size): + return self.__batch_encoder__.batch(self, batch_size) + + def _unbatch(self): + return self.__batch_encoder__.unbatch(self) + + def _to_tensor_list(self, value): + return type_spec.batchable_to_tensor_list(self, value) + + def _to_batched_tensor_list(self, value): + return type_spec.batchable_to_tensor_list(self, value, minimum_rank=1) + + def _from_compatible_tensor_list(self, tensor_list): + return type_spec.batchable_from_tensor_list(self, tensor_list) + + @property + def _flat_tensor_specs(self): + return type_spec.get_batchable_flat_tensor_specs(self) + + +@tf_export('experimental.BatchableExtensionType') +class BatchableExtensionType(ExtensionType): + """An ExtensionType that can be batched and unbatched. + + `BatchableExtensionType`s can be used with APIs that require batching or + unbatching, including `Keras`, `tf.data.Dataset`, and `tf.map_fn`. E.g.: + + >>> class Vehicle(tf.experimental.BatchableExtensionType): + ... top_speed: tf.Tensor + ... mpg: tf.Tensor + >>> batch = Vehicle([120, 150, 80], [30, 40, 12]) + >>> tf.map_fn(lambda vehicle: vehicle.top_speed * vehicle.mpg, batch, + ... fn_output_signature=tf.int32).numpy() + array([3600, 6000, 960], dtype=int32) + + An `ExtensionTypeBatchEncoder` is used by these APIs to encode `ExtensionType` + values. The default encoder assumes that values can be stacked, unstacked, or + concatenated by simply stacking, unstacking, or concatenating every nested + `Tensor`, `ExtensionType`, `CompositeTensor`, or `TensorShape` field. + Extension types where this is not the case will need to override + `__batch_encoder__` with a custom `ExtensionTypeBatchEncoder`. See + `tf.experimental.ExtensionTypeBatchEncoder` for more details. + """ + + # Let the metaclass know that it should *not* transform this class (since + # this class is part of the ExtensionType framework, and not a user class). + _tf_extension_type_do_not_transform_this_class = True + + +# For Pickle __reduce__ protocol: +def _deserialize_for_reduce(value_type, serialization): + return value_type.Spec._deserialize(serialization) # pylint: disable=protected-access + + +def _replace_tensor_with_spec(value): + if isinstance(value, tensor.Tensor): + # Note: we intentionally exclude `value.name` from the `TensorSpec`. + return tensor.TensorSpec(value.shape, value.dtype) + if hasattr(value, '_type_spec'): + return value._type_spec # pylint: disable=protected-access + return value + + +def _change_nested_mappings_to(value, new_type): + """Recursively replace mappings with `new_type`.""" + if isinstance(value, (dict, immutable_dict.ImmutableDict)): + return new_type( + [ + (k, _change_nested_mappings_to(v, new_type)) + for (k, v) in value.items() + ] + ) + elif isinstance(value, tuple): + return tuple(_change_nested_mappings_to(elt, new_type) for elt in value) + else: + return value + + +# ============================================================================== +# Helper methods for tf.ExtensionTypeMetaclass +# ============================================================================== + + +def _check_field_annotations(cls): + """Validates the field annotations for tf.ExtensionType subclass `cls`.""" + annotations = getattr(cls, '__annotations__', {}) + + # Check that no fields use reserved names. + for name, value in cls.__dict__.items(): + if name == 'Spec': + if not isinstance(value, type): + raise ValueError( + f'{cls.__qualname__}.Spec must be a nested class; got {value}.' + ) + if value.__bases__ != (type_spec.TypeSpec,) and value.__bases__ != ( + object, + ): + raise ValueError( + f'{cls.__qualname__}.Spec must be directly subclassed ' + 'from tf.TypeSpec.' + ) + elif extension_type_field.ExtensionTypeField.is_reserved_name(name): + raise ValueError( + f'The field annotations for {cls.__name__} are ' + f"invalid. Field '{name}' is reserved." + ) + for name in annotations: + if extension_type_field.ExtensionTypeField.is_reserved_name(name): + raise ValueError( + f'The field annotations for {cls.__name__} are ' + f"invalid. Field '{name}' is reserved." + ) + + # Check that all fields have type annotaitons. + for key, value in cls.__dict__.items(): + if not ( + key in annotations + or callable(value) + or key.startswith('_abc_') + or key == '_tf_extension_type_fields' + or key.startswith('__') + and key.endswith('__') + or isinstance(value, (property, classmethod, staticmethod)) + ): + raise ValueError( + f'The field annotations for {cls.__name__} are ' + f'invalid. Field {key} is missing a type annotation.' + ) + + +def _add_extension_type_constructor(cls): + """Creates a constructor for a ExtensionType or ExtensionTypeSpec subclass.""" + if '__init__' in cls.__dict__: + _wrap_user_constructor(cls) + else: + _build_extension_type_constructor(cls) + + +def _wrap_user_constructor(cls): + """Wraps a user-defined constructor for tf.ExtensionType subclass `cls`.""" + user_constructor = cls.__init__ + + def wrapped_init(self, *args, **kwargs): + self.__dict__[_IN_CONSTRUCTOR] = True + user_constructor(self, *args, **kwargs) + del self.__dict__[_IN_CONSTRUCTOR] + + self._tf_extension_type_convert_fields() # pylint: disable=protected-access + self.__validate__() + + cls.__init__ = tf_decorator.make_decorator(user_constructor, wrapped_init) + + +_NO_DEFAULT = extension_type_field.ExtensionTypeField.NO_DEFAULT + + +def _build_extension_type_constructor(cls): + """Builds a constructor for tf.ExtensionType subclass `cls`.""" + fields = cls._tf_extension_type_fields() # pylint: disable=protected-access + + # Mark any no-default fields that follow default fields as keyword_only. + got_default = False + keyword_only_start = len(fields) + for i in range(len(fields)): + if got_default: + if fields[i].default is _NO_DEFAULT: + keyword_only_start = i + break + elif fields[i].default is not _NO_DEFAULT: + got_default = True + + params = [] + for i, field in enumerate(fields): + if i < keyword_only_start: + kind = tf_inspect.Parameter.POSITIONAL_OR_KEYWORD + else: + kind = tf_inspect.Parameter.KEYWORD_ONLY + if field.default is _NO_DEFAULT: + default = tf_inspect.Parameter.empty + else: + default = field.default + params.append( + tf_inspect.Parameter( + field.name, kind, default=default, annotation=field.value_type + ) + ) + + signature = tf_inspect.Signature(params, return_annotation=cls.__name__) + + def __init__(self, *args, **kwargs): # pylint: disable=invalid-name + bound_args = signature.bind(*args, **kwargs) + bound_args.apply_defaults() + self.__dict__.update(bound_args.arguments) + self._tf_extension_type_convert_fields() # pylint: disable=protected-access + self.__validate__() + + # __signature__ is supported by some inspection/documentation tools + # (but note: typing.get_type_hints does not respect __signature__). + __init__.__signature__ = tf_inspect.Signature( + [tf_inspect.Parameter('self', tf_inspect.Parameter.POSITIONAL_OR_KEYWORD)] + + params, + return_annotation=cls, + ) + + cls.__init__ = __init__ + + +def _build_spec_constructor(cls): + """Builds a constructor for ExtensionTypeSpec subclass `cls`.""" + params = [] + kind = tf_inspect.Parameter.POSITIONAL_OR_KEYWORD + for field in cls._tf_extension_type_fields(): # pylint: disable=protected-access + params.append(tf_inspect.Parameter(field.name, kind)) + + signature = tf_inspect.Signature(params, return_annotation=cls.__name__) + + def __init__(self, *args, **kwargs): # pylint: disable=invalid-name + bound_args = signature.bind(*args, **kwargs) + bound_args.apply_defaults() + self.__dict__.update(bound_args.arguments) + self._tf_extension_type_convert_fields() # pylint: disable=protected-access + self.__validate__() + + # __signature__ is supported by some inspection/documentation tools. + __init__.__signature__ = tf_inspect.Signature( + [tf_inspect.Parameter('self', tf_inspect.Parameter.POSITIONAL_OR_KEYWORD)] + + params, + return_annotation=cls, + ) + + cls.__init__ = __init__ + + +def _add_type_spec(cls): + """Creates a nested TypeSpec class for tf.ExtensionType subclass `cls`.""" + spec_name = cls.__name__ + '.Spec' + spec_qualname = cls.__qualname__ + '.Spec' + + # Set __module__ explicitly as a dynamic created class has module='abc' + # by default. + spec_dict = {'value_type': cls, '__module__': cls.__module__} + + # Copy user-supplied customizations into the TypeSpec. + user_spec = cls.__dict__.get('Spec', None) + if user_spec is not None: + for name, value in user_spec.__dict__.items(): + if extension_type_field.ExtensionTypeField.is_reserved_name(name): + raise ValueError( + f"TypeSpec {spec_qualname} uses reserved name '{name}'." + ) + if cls._tf_extension_type_has_field(name): # pylint: disable=protected-access + raise ValueError( + f"TypeSpec {spec_qualname} defines a variable '{name}'" + f' which shadows a field in {cls.__qualname__}' + ) + if name in ('__module__', '__dict__', '__weakref__'): + continue + + spec_dict[name] = value + + if issubclass(cls, BatchableExtensionType): + type_spec_base = BatchableExtensionTypeSpec + if ( + hasattr(cls, '__batch_encoder__') + and '__batch_encoder__' not in spec_dict + ): + spec_dict['__batch_encoder__'] = cls.__batch_encoder__ + else: + type_spec_base = ExtensionTypeSpec + if hasattr(cls, '__batch_encoder__') or '__batch_encoder__' in spec_dict: + raise ValueError( + '__batch_encoder__ should only be defined for ' + 'BatchableExtensionType classes.' + ) + + # Build the TypeSpec and store it as a nested class inside `cls`. + spec = type(spec_name, (type_spec_base,), spec_dict) + spec.__qualname__ = spec_qualname + setattr(cls, 'Spec', spec) + + # Build a constructor for the TypeSpec class. + if '__init__' in spec.__dict__: + _wrap_user_constructor(spec) + else: + _build_spec_constructor(spec) + + cls.__abstractmethods__ -= {'_type_spec'} + + # If the user included an explicit `__name__` attribute, then use that to + # register the TypeSpec (so it can be used in SavedModel signatures). + if '__name__' in cls.__dict__: + type_spec_registry.register(cls.__dict__['__name__'] + '.Spec')(spec) + + +# ============================================================================== +# Anonymous ExtensionType +# ============================================================================== +class AnonymousExtensionType(ExtensionType): + """Fallback used to decode `tf.ExtensionType` when the original type is unavailable. + + When a SavedModel is serialized, the signatures of any functions in the + SavedModel can include `tf.ExtensionType` subclasses. These subclasses are + usually + registered, so they can be restored when the SavedModel is loaded. However, + if a SavedModel is loaded without first registering the ExtensionType types in + its + signature, then the SavedModel will fall back to using the + `AnonymousExtensionType` + type instead. + + If necessary, `AnonymousExtensionType` objects can be converted to a concrete + `tf.ExtensionType` subclass (and vice versa) using `reinterpret`. + """ + + # Let the metaclass know that it should *not* transform this class (since + # this class is part of the ExtensionType framework, and not a user class). + _tf_extension_type_do_not_transform_this_class = True + + def __init__(self, **fields): + for name in fields: + if extension_type_field.ExtensionTypeField.is_reserved_name(name) or ( + name.startswith('__') and name.endswith('__') + ): + raise ValueError( + f'Reserved field name {name} was encountered ' + 'when trying to instantiate an AnonymousExtensionType.' + ) + fields = [(k, _convert_anonymous_fields(v)) for (k, v) in fields.items()] + self.__dict__.update(fields) + self._tf_extension_type_convert_fields() + super().__init__() + + @classmethod + def _tf_extension_type_fields(cls): + return [ + extension_type_field.ExtensionTypeField(name, None) + for name in cls.__dict__ + if not extension_type_field.ExtensionTypeField.is_reserved_name(name) + ] + + def __setattr__(self, name, value): + raise AttributeError( + f'Cannot set attribute `{name}`. ' + 'AnonymousExtensionType instances are immutable.' + ) + + def __delattr__(self, name): + raise AttributeError( + f'Cannot delete attribute `{name}`. ' + 'AnonymousExtensionType instances are immutable.' + ) + + def _tf_extension_type_convert_fields(self): + fields = [ + (k, _convert_anonymous_fields(v)) + for (k, v) in self.__dict__.items() + if not extension_type_field.ExtensionTypeField.is_reserved_name(k) + ] + self.__dict__.update(fields) + + def __repr__(self): + fields = [ + f'{k}={v!r}' + for (k, v) in self.__dict__.items() + if not extension_type_field.ExtensionTypeField.is_reserved_name(k) + ] + return f'AnonymousExtensionType({", ".join(fields)})' + + _tf_extension_type_cached_type_spec = None + + @property + def _type_spec(self): # CompositeTensor API. + # Note: the TypeSpec contains all static (non-tensor) data from `self`. + if self._tf_extension_type_cached_type_spec is None: + spec = AnonymousExtensionTypeSpec.from_value(self) + self.__dict__['_tf_extension_type_cached_type_spec'] = spec + return self._tf_extension_type_cached_type_spec + + +@type_spec_registry.register('tf.AnonymousExtensionType.Spec') +class AnonymousExtensionTypeSpec(ExtensionTypeSpec): + """TypeSpec for AnonymousExtensionType.""" + + def __init__(self, **fields): + for name in fields: + if extension_type_field.ExtensionTypeField.is_reserved_name(name) or ( + name.startswith('__') and name.endswith('__') + ): + raise ValueError( + f'Reserved field name {name} was encountered ' + 'when trying to instantiate an AnonymousExtensionTypeSpec.' + ) + fields = [ + (k, _convert_anonymous_fields(v, for_spec=True)) + for (k, v) in fields.items() + ] + self.__dict__.update(fields) + super().__init__() + + value_type = AnonymousExtensionType # TypeSpec API. + + def _serialize(self): # TypeSpec API. + return tuple( + (name, _change_nested_mappings_to(value, dict)) + for (name, value) in self.__dict__.items() + if not extension_type_field.ExtensionTypeField.is_reserved_name(name) + ) + + def __setattr__(self, name, value): + if name in type_spec.CACHED_FIXED_PROPERTIES: + super().__setattr__(name, value) + else: + raise AttributeError( + f'Cannot set attribute `{name}`. ' + 'AnonymousExtensionTypeSpec instances are immutable.' + ) + + def __delattr__(self, name): + raise AttributeError( + f'Cannot delete attribute `{name}`. ' + 'AnonymousExtensionTypeSpec instances are immutable.' + ) + + +def _convert_anonymous_fields(value, for_spec=False): + """Type-checks and converts `value` for inclusion in an AnonymousExtensionType.""" + if isinstance( + value, + ( + int, + float, + bool, + str, + bytes, + type(None), + dtypes.DType, + tensor_shape.TensorShape, + ), + ): + return value + + if isinstance(value, tuple): + return tuple(_convert_anonymous_fields(v, for_spec) for v in value) + + if isinstance(value, typing.Mapping): + return immutable_dict.ImmutableDict( + [ + ( + _convert_anonymous_fields(k, for_spec), + _convert_anonymous_fields(v, for_spec), + ) + for (k, v) in value.items() + ] + ) + + if ( + isinstance(value, (tensor.Tensor, composite_tensor.CompositeTensor)) + and not for_spec + ): + return value + + if isinstance(value, type_spec.TypeSpec) and for_spec: + return value + + raise ValueError( + 'Cannot convert anonymous fields from ' + f'an unsupported `value` argument: {value!r}.' + ) + + +# ============================================================================== +# reinterpret +# ============================================================================== +def reinterpret(value, new_type): + """Converts a given `ExtensionType` to a new type with compatible fields. + + In particular, this can be used to convert a concrete subclass of + `ExtensionType` to an `AnonymousExtensionType`, or vice versa. When + converting to a non-anonymous ExtensionType, field values are type-checked to + ensure they are consistent with `new_type`'s type annotations, and validated + with `new_type.__validate__`. + + Args: + value: An instance of a subclass of `tf.ExtensionType` + new_type: A subclass of `tf.ExtensionType` + + Returns: + An instance of `new_type`, whose fields are copied from `value`. + """ + if not isinstance(value, ExtensionType): + raise ValueError( + 'reinterpret expects `value` to be a tf.ExtensionType instance; ' + f'got {value!r}' + ) + if not (isinstance(new_type, type) and issubclass(new_type, ExtensionType)): + raise ValueError( + 'reinterpret expects `new_type` to be a subclass of tf.ExtensionType; ' + f'got {new_type!r}' + ) + + fields = [ + item + for item in value.__dict__.items() + if not extension_type_field.ExtensionTypeField.is_reserved_name(item[0]) + ] + new_value = _create_object_from_type_and_dict(new_type, fields) + new_value._tf_extension_type_convert_fields() # pylint: disable=protected-access + new_value.__validate__() + return new_value diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/extension_type_field.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/extension_type_field.py new file mode 100644 index 0000000000000000000000000000000000000000..afd84fb7d9d1e74650b7850e203f698178056c3e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/extension_type_field.py @@ -0,0 +1,418 @@ +# 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. +# ============================================================================== +"""Meatadata about fields for user-defined ExtensionType classes.""" + +import collections +import collections.abc +import enum +import typing + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import immutable_dict +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import type_spec +from tensorflow.python.util import type_annotations + +# These names may not be used as the name for a ExtensionType field (to prevent +# name clashes). All names beginning with `'_tf_extension_type'` are also +# reserved. +RESERVED_FIELD_NAMES = [ + 'self', + # Name of the nested TypeSpec class. + 'Spec', + # Names defined by the CompositeTensor base class. + '_type_spec', + '_shape_invariant_to_type_spec', + '_consumers', + # Names defined by the TypeSpec base class. + 'value_type', + 'is_compatible_with', + 'most_specific_compatible_type', + '_with_tensor_ranks_only', + '_to_components', + '_from_components', + '_component_specs', + '_to_tensor_list', + '_from_tensor_list', + '_from_compatible_tensor_list', + '_flat_tensor_specs', + '_serialize', + '_deserialize', + '_to_legacy_output_types', + '_to_legacy_output_shapes', + '_to_legacy_output_classes', + # Used by Keras + '_keras_mask' +] + + +class Sentinel(object): + """Sentinel value that's not equal (w/ `is`) to any user value.""" + + def __init__(self, name): + self._name = name + + def __repr__(self): + return self._name + + +_NoneType = type(None) + + +def _issubclass(cls, clsinfo): + """Internal issubclass that doesn't raise TypeError.""" + try: + return issubclass(cls, clsinfo) + except TypeError: + # issubclass with GenericAlias instances raises TypeError. For example, + # `issubclass(tuple[int], composite_tensor.CompositeTensor)`. + return False + + +# ============================================================================== +# ExtensionTypeField +# ============================================================================== +class ExtensionTypeField( + collections.namedtuple('ExtensionTypeField', + ['name', 'value_type', 'default'])): + """Metadata about a single field in a `tf.ExtensionType` object.""" + + NO_DEFAULT = Sentinel('ExtensionTypeField.NO_DEFAULT') + + def __new__(cls, name, value_type, default=NO_DEFAULT): + """Constructs a new ExtensionTypeField containing metadata for a single field. + + Args: + name: The name of the new field (`str`). May not be a reserved name. + value_type: A python type expression constraining what values this field + can take. + default: The default value for the new field, or `NO_DEFAULT` if this + field has no default value. + + Returns: + A new `ExtensionTypeField`. + + Raises: + TypeError: If the type described by `value_type` is not currently + supported by `tf.ExtensionType`. + TypeError: If `default` is specified and its type does not match + `value_type`. + """ + try: + validate_field_value_type(value_type, allow_forward_references=True) + except TypeError as e: + raise TypeError(f'In field {name!r}: {e}') from e + + if default is not cls.NO_DEFAULT: + default = _convert_value(default, value_type, + (f'default value for {name}',), + _ConversionContext.DEFAULT) + return super(ExtensionTypeField, cls).__new__(cls, name, value_type, + default) + + @staticmethod + def is_reserved_name(name): + """Returns true if `name` is a reserved name.""" + return name in RESERVED_FIELD_NAMES or name.lower().startswith( + '_tf_extension_type') + + +def validate_field_value_type(value_type, + in_mapping_key=False, + allow_forward_references=False): + """Checks that `value_type` contains only supported type annotations. + + Args: + value_type: The type annotation to check. + in_mapping_key: True if `value_type` is nested in the key of a mapping. + allow_forward_references: If false, then raise an exception if a + `value_type` contains a forward reference (i.e., a string literal). + + Raises: + TypeError: If `value_type` contains an unsupported type annotation. + """ + if isinstance(value_type, str) or type_annotations.is_forward_ref(value_type): + if allow_forward_references: + return + else: + raise TypeError(f'Unresolved forward reference {value_type!r}') + + if value_type in (int, float, str, bytes, bool, None, _NoneType, + dtypes.DType): + return + elif (value_type in (tensor.Tensor, tensor_shape.TensorShape) or + (isinstance(value_type, type) and + _issubclass(value_type, composite_tensor.CompositeTensor))): + if in_mapping_key: + raise TypeError(f'Mapping had a key {value_type.__name__!r} with type ' + f'{type(value_type).__name__!r}') + elif (type_annotations.is_generic_tuple(value_type) or + type_annotations.is_generic_union(value_type)): + type_args = type_annotations.get_generic_type_args(value_type) + if (len(type_args) == 2 and type_args[1] is Ellipsis and + type_annotations.is_generic_tuple(value_type)): # `Tuple[X, ...]` + validate_field_value_type(type_args[0], in_mapping_key, + allow_forward_references) + else: + for arg in type_annotations.get_generic_type_args(value_type): + validate_field_value_type(arg, in_mapping_key, allow_forward_references) + elif type_annotations.is_generic_mapping(value_type): + key_type, value_type = type_annotations.get_generic_type_args(value_type) + validate_field_value_type(key_type, True, allow_forward_references) + validate_field_value_type(value_type, in_mapping_key, + allow_forward_references) + elif isinstance(value_type, type): + raise TypeError(f'Unsupported type annotation {value_type.__name__!r}') + else: + raise TypeError(f'Unsupported type annotation {value_type!r}') + + +# ============================================================================== +# Type-checking & conversion for ExtensionTypeField values +# ============================================================================== + + +class _ConversionContext(enum.Enum): + """Enum to indicate what kind of value is being converted. + + Used by `_convert_fields` and `_convert_value` and their helper methods. + """ + VALUE = 1 # Converting an ExtensionType field + SPEC = 2 # Converting an ExtensionType.Spec field + DEFAULT = 3 # Converting a default value for __init__ + + +def convert_fields(fields, field_values): + """Type-checks and converts each field in `field_values` (in place). + + Args: + fields: A list of `ExtensionTypeField` objects. + field_values: A `dict` mapping field names to values. Must contain an entry + for each field. I.e., `set(field_values.keys())` must be equal to + `set([f.name for f in fields])`. + + Raises: + ValueError: If the keys of `field_values` do not match the names of + the fields in `fields`. + TypeError: If any value in `field_values` does not have the type indicated + by the corresponding `ExtensionTypeField` object. + """ + _convert_fields(fields, field_values, context=_ConversionContext.VALUE) + + +def convert_fields_for_spec(fields, field_values): + """Type-checks and converts field values for a TypeSpec (in place). + + This is similar to `convert_fields`, except that we expect a `TypeSpec` for + tensor-like types. In particular, if the `value_type` of a field is + `tf.Tensor` or a `CompositeTensor` subclass, then the corresponding value in + `fields` is expected to contain a `TypeSpec` (rather than a value described by + that `TypeSpec`). + + Args: + fields: A list of `ExtensionTypeField` objects. + field_values: A `dict` mapping field names to values. Must contain an entry + for each field. I.e., `set(field_values.keys())` must be equal to + `set([f.name for f in fields])`. + + Raises: + ValueError: If the keys of `field_values` do not match the names of + the fields in `fields`. + TypeError: If any value in `field_values` does not have the type indicated + by the corresponding `ExtensionTypeField` object. + """ + _convert_fields(fields, field_values, context=_ConversionContext.SPEC) + + +def _convert_fields(fields, field_values, context): + """Type-checks and converts each field in `field_values` (in place). + + Args: + fields: A list of `ExtensionTypeField` objects. + field_values: A `dict` mapping field names to values. Must contain an entry + for each field. I.e., `set(field_values.keys())` must be equal to + `set([f.name for f in fields])`. + context: _ConversionContext, indicates what kind of value we are converting. + + Raises: + ValueError: If the keys of `field_values` do not match the names of + the fields in `fields`. + TypeError: If any value in `field_values` does not have the type indicated + by the corresponding `ExtensionTypeField` object. + """ + converted = {} + if len(fields) != len(field_values): + _report_field_mismatches(fields, field_values) + for field in fields: + if field.name not in field_values: + _report_field_mismatches(fields, field_values) + field_value = field_values[field.name] + converted[field.name] = _convert_value(field_value, field.value_type, + (field.name,), context) + field_values.update(converted) + + +def _convert_value(value, expected_type, path, + context=_ConversionContext.VALUE): + """Type-checks and converts a value. + + Args: + value: The value to type-check. + expected_type: The expected type for the value. + path: Tuple of `str` naming the value (used for exception messages). + context: _ConversionContext, indicates what kind of value we are converting. + + Returns: + A copy of `value`, converted to the expected type. + + Raises: + TypeError: If `value` can not be converted to the expected type. + """ + assert isinstance(path, tuple) + + if expected_type is None: + expected_type = _NoneType + + if expected_type is tensor.Tensor: + return _convert_tensor(value, path, context) + elif (isinstance(expected_type, type) and + _issubclass(expected_type, composite_tensor.CompositeTensor)): + return _convert_composite_tensor(value, expected_type, path, context) + elif expected_type is tensor_shape.TensorShape: + try: + return tensor_shape.as_shape(value) + except TypeError as e: + raise TypeError(f"{''.join(path)}: expected 'tf.TensorShape', got " + f'{type(value).__name__!r}') from e + elif expected_type is dtypes.DType: + try: + return dtypes.as_dtype(value) + except TypeError as e: + raise TypeError(f"{''.join(path)}: expected 'tf.DType', got " + f'{type(value).__name__!r}') from e + elif expected_type in (int, float, bool, str, bytes, _NoneType): + if not isinstance(value, expected_type): + raise TypeError(f'{"".join(path)}: expected {expected_type.__name__!r}, ' + f'got {type(value).__name__!r}') + return value + elif type_annotations.is_generic_tuple(expected_type): + return _convert_tuple(value, expected_type, path, context) + elif type_annotations.is_generic_mapping(expected_type): + return _convert_mapping(value, expected_type, path, context) + elif type_annotations.is_generic_union(expected_type): + return _convert_union(value, expected_type, path, context) + else: + raise TypeError(f'{"".join(path)}: Unsupported type annotation ' + f'{expected_type!r}') + + +def _convert_tensor(value, path, context): + """Converts `value` to a `Tensor`.""" + if context == _ConversionContext.SPEC: + if not (isinstance(value, type_spec.TypeSpec) and + value.value_type is tensor.Tensor): + raise TypeError( + f'{"".join(path)}: expected a TensorSpec, got ' + f'{type(value).__name__!r}') + return value + + if not isinstance(value, tensor.Tensor): + if context == _ConversionContext.DEFAULT: + # TODO(edloper): Convert the value to a numpy array? (Note: we can't just + # use `np.array(value)`, since the default dtypes for TF and numpy are + # different -- e.g., int->np.int64 but int->tf.int32. + return value + try: + value = ops.convert_to_tensor(value) + except (ValueError, TypeError) as e: + raise TypeError(f'{"".join(path)}: expected a Tensor, ' + f'got {type(value).__name__!r}') from e + return value + + +def _convert_composite_tensor(value, expected_type, path, context): + """Converts `value` to a value of type `expected_type`.""" + if context == _ConversionContext.SPEC: + if not (isinstance(value, type_spec.TypeSpec) and + _issubclass(value.value_type, expected_type)): + raise TypeError(f'{"".join(path)}: expected a TypeSpec for ' + f'{expected_type.__name__!r}, got ' + f'{type(value).__name__!r}') + return value + + if not isinstance(value, expected_type): + raise TypeError(f'{"".join(path)}: expected {expected_type.__name__!r}, ' + f'got {type(value).__name__!r}') + return value + + +def _convert_tuple(value, expected_type, path, context): + """Converts `value` to a tuple with type `expected_type`.""" + if not isinstance(value, typing.Sequence): + raise TypeError(f'{"".join(path)}: expected tuple, got ' + f'{type(value).__name__!r}') + element_types = type_annotations.get_generic_type_args(expected_type) + if len(element_types) == 2 and element_types[1] is Ellipsis: + return tuple([ + _convert_value(v, element_types[0], path + (f'[{i}]',), context) + for (i, v) in enumerate(value) + ]) + else: + if len(value) != len(element_types): + raise TypeError(f'{"".join(path)}: expected tuple with length ' + f'{len(element_types)}, got {type(value).__name__!r})') + return tuple([ + _convert_value(v, t, path + (f'[{i}]',), context) + for (i, (v, t)) in enumerate(zip(value, element_types)) + ]) + + +def _convert_mapping(value, expected_type, path, context): + """Converts `value` to a mapping with type `expected_type`.""" + if not isinstance(value, typing.Mapping): + raise TypeError(f'{"".join(path)}: expected mapping, got ' + f'{type(value).__name__!r}') + key_type, value_type = type_annotations.get_generic_type_args(expected_type) + return immutable_dict.ImmutableDict([ + (_convert_value(k, key_type, path + ('[]',), context), + _convert_value(v, value_type, path + (f'[{k!r}]',), context)) + for (k, v) in value.items() + ]) + + +def _convert_union(value, expected_type, path, context): + """Converts `value` to a value with any of the types in `expected_type`.""" + for type_option in type_annotations.get_generic_type_args(expected_type): + try: + return _convert_value(value, type_option, path, context) + except TypeError: + pass + raise TypeError(f'{"".join(path)}: expected {expected_type!r}, got ' + f'{type(value).__name__!r}') + + +def _report_field_mismatches(fields, field_values): + """Raises an exception with mismatches between fields and field_values.""" + expected = set(f.name for f in fields) + actual = set(field_values) + extra = actual - expected + if extra: + raise ValueError(f'Got unexpected fields: {extra}') + missing = expected - actual + if missing: + raise ValueError(f'Missing required fields: {missing}') diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/flexible_dtypes.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/flexible_dtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..029f89594880cbf0b7adb8286da8cc57ee18cdd4 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/flexible_dtypes.py @@ -0,0 +1,549 @@ +# 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. +# ============================================================================= +"""Auto dtype conversion semantics for TF.""" + +import numpy as np + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import weak_tensor +from tensorflow.python.ops import variables +from tensorflow.python.util import nest + + +# PromoMode Enum that denotes safe and all mode. +PromoMode = ops.PromoMode + +# Namings are similar to third_party/py/jax/_src/dtypes.py. +_b8 = (dtypes.bool, False) +_u8 = (dtypes.uint8, False) +_u16 = (dtypes.uint16, False) +_u32 = (dtypes.uint32, False) +_u64 = (dtypes.uint64, False) +_i8 = (dtypes.int8, False) +_i16 = (dtypes.int16, False) +_i32 = (dtypes.int32, False) +_i64 = (dtypes.int64, False) +_bf16 = (dtypes.bfloat16, False) +_f16 = (dtypes.float16, False) +_f32 = (dtypes.float32, False) +_f64 = (dtypes.float64, False) +_c64 = (dtypes.complex64, False) +_c128 = (dtypes.complex128, False) +# Weak dtypes +_i32w = (dtypes.int32, True) +_i64w = (dtypes.int64, True) +_f32w = (dtypes.float32, True) +_f64w = (dtypes.float64, True) +_c128w = (dtypes.complex128, True) +# String +_str = (dtypes.string, False) + +_all_dtypes = [ + _b8, + _u8, + _u16, + _u32, + _u64, + _i8, + _i16, + _i32, + _i64, + _bf16, + _f16, + _f32, + _f64, + _c64, + _c128, + _i32w, + _i64w, + _f32w, + _f64w, + _c128w, +] +# Python numbers +_pi = int # pylint: disable=invalid-name +_pf = float # pylint: disable=invalid-name +_pc = complex # pylint: disable=invalid-name + +# Mappings between types_pb2.DataType values and numpy.dtypes. +_NP_TO_TF = dtypes._NP_TO_TF # pylint: disable=protected-access + +# OP(arg1, arg2) => (res, weak_type, safety level) +# If promotion mode is SAFE, results corresponding to ALL will be disallowed. +# This map only contains one-way dtype promotion results and is used to generate +# _BINARY_DTYPE_RES_FULL. +_BINARY_DTYPE_RES_HALF = { + _b8: { + _b8: (_b8, PromoMode.SAFE), + _u8: (_u8, PromoMode.SAFE), + _u16: (_u16, PromoMode.SAFE), + _u32: (_u32, PromoMode.SAFE), + _u64: (_u64, PromoMode.SAFE), + _i8: (_i8, PromoMode.SAFE), + _i16: (_i16, PromoMode.SAFE), + _i32: (_i32, PromoMode.SAFE), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.SAFE), + _f16: (_f16, PromoMode.SAFE), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_i32w, PromoMode.SAFE), + _i64w: (_i64w, PromoMode.SAFE), + _f32w: (_f32w, PromoMode.SAFE), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _u8: { + _u8: (_u8, PromoMode.SAFE), + _u16: (_u16, PromoMode.SAFE), + _u32: (_u32, PromoMode.SAFE), + _u64: (_u64, PromoMode.SAFE), + _i8: (_i16, PromoMode.ALL), + _i16: (_i16, PromoMode.SAFE), + _i32: (_i32, PromoMode.SAFE), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.SAFE), + _f16: (_f16, PromoMode.SAFE), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_u8, PromoMode.SAFE), + _i64w: (_u8, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _u16: { + _u16: (_u16, PromoMode.SAFE), + _u32: (_u32, PromoMode.SAFE), + _u64: (_u64, PromoMode.SAFE), + _i8: (_i32, PromoMode.ALL), + _i16: (_i32, PromoMode.ALL), + _i32: (_i32, PromoMode.SAFE), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.ALL), + _f16: (_f16, PromoMode.ALL), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_u16, PromoMode.SAFE), + _i64w: (_u16, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _u32: { + _u32: (_u32, PromoMode.SAFE), + _u64: (_u64, PromoMode.SAFE), + _i8: (_i64, PromoMode.ALL), + _i16: (_i64, PromoMode.ALL), + _i32: (_i64, PromoMode.ALL), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.ALL), + _f16: (_f16, PromoMode.ALL), + _f32: (_f32, PromoMode.ALL), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.ALL), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_u32, PromoMode.SAFE), + _i64w: (_u32, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _u64: { + _u64: (_u64, PromoMode.SAFE), + _i8: (_f64w, PromoMode.ALL), + _i16: (_f64w, PromoMode.ALL), + _i32: (_f64w, PromoMode.ALL), + _i64: (_f64w, PromoMode.ALL), + _bf16: (_bf16, PromoMode.ALL), + _f16: (_f16, PromoMode.ALL), + _f32: (_f32, PromoMode.ALL), + _f64: (_f64, PromoMode.ALL), + _c64: (_c64, PromoMode.ALL), + _c128: (_c128, PromoMode.ALL), + _i32w: (_u64, PromoMode.SAFE), + _i64w: (_u64, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.ALL), + _c128w: (_c128w, PromoMode.ALL), + }, + _i8: { + _i8: (_i8, PromoMode.SAFE), + _i16: (_i16, PromoMode.SAFE), + _i32: (_i32, PromoMode.SAFE), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.SAFE), + _f16: (_f16, PromoMode.SAFE), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_i8, PromoMode.SAFE), + _i64w: (_i8, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _i16: { + _i16: (_i16, PromoMode.SAFE), + _i32: (_i32, PromoMode.SAFE), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.ALL), + _f16: (_f16, PromoMode.ALL), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_i16, PromoMode.SAFE), + _i64w: (_i16, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _i32: { + _i32: (_i32, PromoMode.SAFE), + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.ALL), + _f16: (_f16, PromoMode.ALL), + _f32: (_f32, PromoMode.ALL), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.ALL), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_i32, PromoMode.SAFE), + _i64w: (_i32, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _i64: { + _i64: (_i64, PromoMode.SAFE), + _bf16: (_bf16, PromoMode.ALL), + _f16: (_f16, PromoMode.ALL), + _f32: (_f32, PromoMode.ALL), + _f64: (_f64, PromoMode.ALL), + _c64: (_c64, PromoMode.ALL), + _c128: (_c128, PromoMode.ALL), + _i32w: (_i64, PromoMode.SAFE), + _i64w: (_i64, PromoMode.SAFE), + _f32w: (_f64w, PromoMode.ALL), + _f64w: (_f64w, PromoMode.ALL), + _c128w: (_c128w, PromoMode.ALL), + }, + _bf16: { + _bf16: (_bf16, PromoMode.SAFE), + _f16: (_f32, PromoMode.ALL), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_bf16, PromoMode.SAFE), + _i64w: (_bf16, PromoMode.SAFE), + _f32w: (_bf16, PromoMode.SAFE), + _f64w: (_bf16, PromoMode.SAFE), + _c128w: (_c64, PromoMode.ALL), + }, + _f16: { + _f16: (_f16, PromoMode.SAFE), + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_f16, PromoMode.SAFE), + _i64w: (_f16, PromoMode.SAFE), + _f32w: (_f16, PromoMode.SAFE), + _f64w: (_f16, PromoMode.SAFE), + _c128w: (_c64, PromoMode.ALL), + }, + _f32: { + _f32: (_f32, PromoMode.SAFE), + _f64: (_f64, PromoMode.SAFE), + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_f32, PromoMode.SAFE), + _i64w: (_f32, PromoMode.SAFE), + _f32w: (_f32, PromoMode.SAFE), + _f64w: (_f32, PromoMode.SAFE), + _c128w: (_c64, PromoMode.ALL), + }, + _f64: { + _f64: (_f64, PromoMode.SAFE), + _c64: (_c128, PromoMode.ALL), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_f64, PromoMode.SAFE), + _i64w: (_f64, PromoMode.SAFE), + _f32w: (_f64, PromoMode.SAFE), + _f64w: (_f64, PromoMode.SAFE), + _c128w: (_c128, PromoMode.SAFE), + }, + _c64: { + _c64: (_c64, PromoMode.SAFE), + _c128: (_c128, PromoMode.SAFE), + _i32w: (_c64, PromoMode.SAFE), + _i64w: (_c64, PromoMode.SAFE), + _f32w: (_c64, PromoMode.SAFE), + _f64w: (_c64, PromoMode.SAFE), + _c128w: (_c64, PromoMode.SAFE), + }, + _c128: { + _c128: (_c128, PromoMode.SAFE), + _i32w: (_c128, PromoMode.SAFE), + _i64w: (_c128, PromoMode.SAFE), + _f32w: (_c128, PromoMode.SAFE), + _f64w: (_c128, PromoMode.SAFE), + _c128w: (_c128, PromoMode.SAFE), + }, + _i32w: { + _i32w: (_i32w, PromoMode.SAFE), + _i64w: (_i64w, PromoMode.SAFE), + _f32w: (_f32w, PromoMode.SAFE), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _i64w: { + _i64w: (_i64w, PromoMode.SAFE), + _f32w: (_f32w, PromoMode.SAFE), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _f32w: { + _f32w: (_f32w, PromoMode.SAFE), + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _f64w: { + _f64w: (_f64w, PromoMode.SAFE), + _c128w: (_c128w, PromoMode.SAFE), + }, + _c128w: { + _c128w: (_c128w, PromoMode.SAFE), + }, +} + +# A full promotion table that contains two-way mappings. +# This table can be directly used for NumPy types as well, because +# e.g. `np.int32` == `tf.int32`. +_BINARY_DTYPE_RES_FULL = {} + + +def _initialize(): + """Generate the rest of the promotion table from the one-way promotion table. + + Returns: None + """ + for dtype1 in _all_dtypes: + _BINARY_DTYPE_RES_FULL[dtype1] = {} + for dtype2 in _all_dtypes: + try: + res = _BINARY_DTYPE_RES_HALF[dtype1][dtype2] + except KeyError: + res = _BINARY_DTYPE_RES_HALF[dtype2][dtype1] + + _BINARY_DTYPE_RES_FULL[dtype1][dtype2] = res + + # We do not support any conversions between string and others dtypes. + _BINARY_DTYPE_RES_FULL[_str] = {_str: (_str, PromoMode.SAFE)} + + +_initialize() + + +_all_str_dtypes = ( + np.dtype('object_'), + np.dtype('string_'), + np.dtype('unicode_'), + dtypes.string, +) + + +def _is_acceptable_input_type(x): + """Determines if x is an acceptable input type for auto dtype conversion semantics.""" + # List of composite types that are supported by the auto dtype conversion + # semantics. + supported_composite_types = ( + indexed_slices.IndexedSlices, + weak_tensor.WeakTensor, + variables.Variable, + ) + return isinstance(x, supported_composite_types) or not isinstance( + x, composite_tensor.CompositeTensor + ) + + +def _get_dtype_and_weakness(x): + """Returns a TF type and weak type information from x. + + Args: + x: an input scalar, array or a NumPy/TF/Python dtype. + + Raises: + OverflowError: if Python int x is too large to convert to int32. + NotImplementedError: when x is an unsupported input type. + + Returns: + TF type and weak type information inferred from x in the form of + (dtype, bool). + """ + if isinstance(x, weak_tensor.WeakTensor): + return (x.dtype, True) + if isinstance(x, dtypes.DType): + return (x, False) + # TODO(b/286585200): Add support for `AutoCastVariable` in Keras. + tf_dtype = getattr(x, 'dtype', None) + if isinstance(tf_dtype, dtypes.DType): + return (tf_dtype, False) + # `isinstance(tf_dtype, np.dtype)` handles classes that implement `dtype` + # using `np.dtype` (e.g. `xla_extension.Array`). + # This condition is put before e.g. python int/float because + # `isinstance(np.float64(1), float)` returns True. + if isinstance(x, (np.ndarray, np.generic)) or isinstance(tf_dtype, np.dtype): + # Use `dtypes.as_dtype(x.dtype)` because in `as_dtype`, the input will be + # compared against a list of types including TF Dtypes which are protobufs. + infer_dtype = dtypes.as_dtype(tf_dtype) + return (infer_dtype, False) + if isinstance(x, (bytes, str)) or tf_dtype in _all_str_dtypes: + return _str + try: + if x in _NP_TO_TF: + return (_NP_TO_TF[x], False) + except TypeError: + pass + # bool type check must happen before int type check because + # isinstance(True, int) == True (https://peps.python.org/pep-0285/). + if isinstance(x, bool) or x == bool: + return _b8 + # TODO(b/286585058): Update implementation depending on whether Python + # scalars are inferred to 32 bit or 64 bit. + if isinstance(x, _pi): + if x < np.iinfo(np.int32).min or x > np.iinfo(np.int32).max: + raise OverflowError(f'Python int {x} too large to convert to np.int32') + return _i32w + if x == int: + return _i32w + if isinstance(x, _pf) or x == float: + return _f32w + if isinstance(x, _pc) or x == complex: + return _c128w + if isinstance(x, tensor_shape.TensorShape): + # Since TensorShape is always integer value, return int32. + return _i32 + # Only support NumPy dtype objects with corresponding TF types. + if isinstance(x, np.dtype): + try: + np_dtype = dtypes.as_dtype(x) + return (np_dtype, False) + except TypeError as exc: + raise NotImplementedError( + f'Auto dtype conversion semantics does not support {x}. Try using a' + ' NumPy built-in dtype objects or cast them explicitly.' + ) from exc + raise NotImplementedError( + f'Auto dtype conversion semantics does not support {type(x)} type.' + ) + + +def _result_type_impl(*arrays_and_dtypes): + """Internal implementation of jnp_style_result_type. + + Args: + *arrays_and_dtypes: A list of Tensors, Variables, NumPy arrays or python + numbers. + + Returns: + The result promotion type from all the inputs. + + Raises: + TypeError: when the promotion between the input dtypes is disabled in the + current mode + + NotImplementedError: + (1) When arrays_and_dtypes contains an unsupported input type (e.g. + RaggedTensor). + (2) When there isn't a possible promotion for the input dtypes. + """ + promo_safety_mode = ops.get_dtype_conversion_mode() + # Drop None inputs and check if input type is supported. + valid_arrays_and_dtypes = [] + for inp in arrays_and_dtypes: + if inp is not None: + if _is_acceptable_input_type(inp): + valid_arrays_and_dtypes.append(inp) + else: + raise NotImplementedError( + 'Auto dtype conversion semantics does not support' + f' {type(inp)} type.' + ) + + dtypes_and_is_weak = [ + _get_dtype_and_weakness(x) for x in nest.flatten(valid_arrays_and_dtypes) + ] + + # If there are no valid inputs, return f32. + if not dtypes_and_is_weak: + # If dtypes_and_is_weak is an empty list, return weakly-typed f32. + dtypes_and_is_weak = [(dtypes.float32, True)] + + res = dtypes_and_is_weak[0] + for arg in dtypes_and_is_weak[1:]: + # Use `base_dtype` in case of `ref` types (for e.g. ref_variables). + res = (res[0].base_dtype, res[1]) + arg = (arg[0].base_dtype, arg[1]) + try: + res_next, allowed_mode = _BINARY_DTYPE_RES_FULL[res][arg] + except KeyError as exc: + # Throw NotImplementedError When there isn't a possible promotion for the + # input dtypes. We will proceed with the default system promotion if + # NotImplementedError is thrown. + raise NotImplementedError( + f'Implicit Conversion between {res[0]} and {arg[0]} is ' + 'not allowed. Please convert the input manually if you ' + 'need to.' + ) from exc + if allowed_mode.value > promo_safety_mode.value: + raise TypeError( + f'In promotion mode {promo_safety_mode}, implicit dtype ' + f'promotion between ({res[0]}, weak={res[1]}) and ' + f'({arg[0]}, weak={arg[1]}) is disallowed. ' + 'You need to explicitly specify the dtype in your op, ' + 'or relax your dtype promotion rules (such as from SAFE ' + 'mode to ALL mode).' + ) + res = res_next + + return res + + +def result_type(*arrays_and_dtypes): + """Determine the result promotion dtype using the JNP-like promotion system. + + Args: + *arrays_and_dtypes: A list of Tensors, Variables, NumPy arrays or python + numbers. + + Returns: + The result promotion type from all the inputs. + """ + # Make sure to catch NotImplementedError when using this method to account for + # inputs that are not supported yet. + return _result_type_impl(*arrays_and_dtypes) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/framework_lib.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/framework_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..34aa3435add619d63d3ce42deac08a4ede09f51e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/framework_lib.py @@ -0,0 +1,70 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +# pylint: disable=unused-import,g-bad-import-order +"""Classes and functions for building TensorFlow graphs.""" + +# Classes used when building a Graph. +from tensorflow.python.framework.device import DeviceSpec +from tensorflow.python.framework.indexed_slices import IndexedSlices +from tensorflow.python.framework.ops import Graph +from tensorflow.python.framework.ops import Operation +from tensorflow.python.framework.tensor import Tensor + +from tensorflow.python.framework.sparse_tensor import SparseTensor +from tensorflow.python.framework.sparse_tensor import SparseTensorValue + +# Utilities used when building a Graph. +from tensorflow.python.framework.indexed_slices import convert_to_tensor_or_indexed_slices +from tensorflow.python.framework.ops import device +from tensorflow.python.framework.ops import container +from tensorflow.python.framework.ops import name_scope +from tensorflow.python.framework.ops import op_scope +from tensorflow.python.framework.ops import colocate_with +from tensorflow.python.framework.ops import control_dependencies +from tensorflow.python.framework.ops import get_default_graph +from tensorflow.python.framework.ops import reset_default_graph +from tensorflow.python.framework.ops import GraphKeys +from tensorflow.python.framework.ops import add_to_collection +from tensorflow.python.framework.ops import add_to_collections +from tensorflow.python.framework.ops import get_collection +from tensorflow.python.framework.ops import get_collection_ref +from tensorflow.python.framework.ops import convert_to_tensor +from tensorflow.python.framework.random_seed import get_seed +from tensorflow.python.framework.random_seed import set_random_seed +from tensorflow.python.framework.sparse_tensor import convert_to_tensor_or_sparse_tensor +from tensorflow.python.framework.importer import import_graph_def + +# Utilities for working with Tensors +from tensorflow.python.framework.tensor_util import make_tensor_proto +from tensorflow.python.framework.tensor_util import MakeNdarray as make_ndarray + +# Needed when you defined a new Op in C++. +from tensorflow.python.framework.ops import RegisterGradient +from tensorflow.python.framework.ops import NotDifferentiable +from tensorflow.python.framework.ops import NoGradient +from tensorflow.python.framework.tensor_shape import Dimension +from tensorflow.python.framework.tensor_shape import TensorShape + +# Needed when interfacing tensorflow to new array libraries +from tensorflow.python.framework.tensor_conversion_registry import register_tensor_conversion_function + +# go/tf-wildcard-import +# pylint: disable=wildcard-import +from tensorflow.python.framework.dtypes import * # pylint: disable=redefined-builtin + +# Load a TensorFlow plugin +from tensorflow.python.framework.load_library import * +# pylint: enable=wildcard-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/func_graph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/func_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..1f189c265c3799402494c0aabcef263ea9498fe9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/func_graph.py @@ -0,0 +1,1277 @@ +# 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. +# ============================================================================== +"""FuncGraph and related functionality.""" + +import traceback +from typing import Any, Callable, Hashable +import weakref + +from tensorflow.core.function import trace_type +from tensorflow.core.function.capture import capture_container +from tensorflow.python.eager import context +from tensorflow.python.eager import execute +from tensorflow.python.eager.polymorphic_function import composite_tensor_utils +from tensorflow.python.framework import auto_control_deps +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import variable_scope +from tensorflow.python.saved_model import save_context +from tensorflow.python.types import core +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import variable_utils +from tensorflow.python.util.tf_export import tf_export + + +ALLOWLIST_COLLECTIONS = [ + ops.GraphKeys.GLOBAL_VARIABLES, + ops.GraphKeys.LOCAL_VARIABLES, + ops.GraphKeys.TRAINABLE_VARIABLES, + variable_scope._VARSTORE_KEY, # pylint: disable=protected-access + variable_scope._VARSCOPESTORE_KEY # pylint: disable=protected-access +] + + +class UnknownArgument(object): + """Signifies an argument which is not currently handled.""" + + +def convert_structure_to_signature(structure, arg_names=None, + signature_context=None): + """Convert a potentially nested structure to a signature. + + Args: + structure: Structure to convert, where top level collection is a list or a + tuple. + arg_names: Optional list of arguments that has equal number of elements as + `structure` and is used for naming corresponding TensorSpecs. + signature_context: TraceType InternalTracingContext to generate alias_ids + for mutable objects, like ResourceVariables. + + Returns: + Identical structure that has TensorSpec objects instead of Tensors and + UnknownArgument instead of any unsupported types. + """ + + def encode_arg(arg, path): + """A representation for this argument, for converting into signatures.""" + if isinstance(arg, tensor_lib.Tensor): + user_specified_name = None + try: + user_specified_name = compat.as_str( + arg.op.get_attr("_user_specified_name")) + except (ValueError, AttributeError): + pass + + if path and user_specified_name and user_specified_name != path[0]: + # The user has explicitly named the argument differently than the name + # of the function argument. + name = user_specified_name + else: + name = tensor_lib.sanitize_spec_name("_".join(str(p) for p in path)) + return tensor_lib.TensorSpec(arg.shape, arg.dtype, name) + if isinstance(arg, resource_variable_ops.ResourceVariable): + return trace_type.from_value(arg, signature_context) + if isinstance(arg, composite_tensor.CompositeTensor): + # TODO(b/133606651) Do we need to inject arg_name? + return arg._type_spec # pylint: disable=protected-access + if isinstance(arg, ( + int, + float, + bool, + str, + type(None), + dtypes.DType, + tensor_lib.TensorSpec, + type_spec.TypeSpec, + )): + return arg + return UnknownArgument() + + # We are using the flattened paths to name the TensorSpecs. We need an + # explicit name for them downstream. + flattened = nest.flatten_with_tuple_paths(structure) + if arg_names: + if len(arg_names) != len(structure): + raise ValueError( + "Passed in arg_names don't match actual signature (%s)." % arg_names) + # Replace all top-level names with their actual arg_names. If a path before + # was "(2,'a',1)", it will become "(arg_names[2],'a',1)". + flattened = [ + ((arg_names[path[0]],) + path[1:], arg) for path, arg in flattened + ] + + mapped = [encode_arg(arg, path) for path, arg in flattened] + return nest.pack_sequence_as(structure, mapped) + + +@tf_export("__internal__.FuncGraph", v1=[]) +class FuncGraph(ops.Graph): + """Graph representing a function body. + + Attributes: + name: The name of the function. + inputs: Placeholder tensors representing the inputs to this function. The + tensors are in this FuncGraph. This represents "regular" inputs as well as + captured inputs (i.e. the values of self.captures), with the regular + inputs coming first. + outputs: Tensors that will be returned by this function. The tensors are in + this FuncGraph. + control_outputs: Operations that must be executed before the function + represented by this graph can be said to have been executed. + structured_input_signature: A tuple of (args, kwargs), which are both + possibly-nested python objects that were received by this function. Note + that these structures might contain Python `None`s. + structured_outputs: A possibly-nested python object which will be returned + by this function. The Tensors in this structure are the same as those of + self.outputs. Note that this structure might contain Python `None`s. + variables: Variables that should be watched during function execution. + outer_graph: The graph this function is defined in. May be another FuncGraph + or the global default Graph. + captures: Maps external tensor -> internal tensor (i.e. input placeholder). + The entries are in the order they were captured. + seed: The graph-level random seed. + capture_by_value: If True, the func graph will capture Variables by value + instead of reference. + """ + + def __init__(self, + name, + collections=None, + capture_by_value=None, + structured_input_signature=None, + structured_outputs=None): + """Construct a new FuncGraph. + + The graph will inherit its graph key, collections, seed, and distribution + strategy stack from the current context or graph. + + Args: + name: the name of the function. + collections: a dictionary of collections this FuncGraph should start with. + If not specified (None), the FuncGraph will read (but not write to) the + outer graph's collections that are not allowlisted, and both read and + write to the outer graph's collections that are allowlisted. The current + allowlisted collections are the global variables, the local variables, + and the trainable variables. Defaults to None. + capture_by_value: An optional boolean. If True, the func graph will + capture Variables by value instead of reference. By default inherit from + outer graphs, and failing that will default to False. + structured_input_signature: Optional. The structured input signature to + use for initializing the FuncGraph. See the docstring for FuncGraph for + more information. + structured_outputs: Optional. The structured outputs to use for + initializing the FuncGraph. See the docstring for FuncGraph for more + information. + """ + super().__init__() + self.name = name + # TODO(panzf): Separate captures from non-captures inputs in self.inputs + self.inputs = [] + self.outputs = [] + self.control_outputs = [] + self.structured_input_signature = structured_input_signature + self.structured_outputs = structured_outputs + self._resource_tensor_inputs = object_identity.ObjectIdentitySet() + self._weak_variables = [] + self._watched_variables = object_identity.ObjectIdentityWeakSet() + self.is_control_flow_graph = False + + self._function_captures = capture_container.FunctionCaptures() + outer_graph = ops.get_default_graph() + self._weak_outer_graph = weakref.ref(outer_graph) + while outer_graph.building_function: + outer_graph = outer_graph.outer_graph + # If self._weak_outer_graph is deleted, we revert to the outermost Graph + # active when the FuncGraph was traced. This will not be a FuncGraph. + self._fallback_outer_graph = outer_graph + # If not None, records the names of output args of this function. Used to + # preserve the output names in the signature of a serialized+deserialized + # function. Private at the moment mostly because it's often out of date. + self._output_names = None + # Inherit capture-by-value from outer graph. + if capture_by_value is not None: + self.capture_by_value = capture_by_value + elif self.outer_graph is not None and isinstance(self.outer_graph, + FuncGraph): + self.capture_by_value = self.outer_graph.capture_by_value + else: + self.capture_by_value = False + + self._building_function = True + + graph = self.outer_graph + + if context.executing_eagerly(): + self.seed = context.global_seed() + # [for tf-data user migration from TF1.0 to 2.0] seed_used keep track of + # any None op_seed for random_op in the function, in which case we end up + # using function seed, which could be unintended behavior for the op. + self._seed_used = False + else: + self.seed = graph.seed + self._seed_used = False + # TODO(allenl): Figure out if we can remove colocation stack + # specialization (currently used in cond_v2), here and in the cache key. + self._colocation_stack = graph._colocation_stack.copy() # pylint: disable=protected-access + + if collections is None: + for collection_name in graph.get_all_collection_keys(): + if collection_name not in ALLOWLIST_COLLECTIONS: + self._collections[collection_name] = graph.get_collection( + collection_name) + for collection_name in ALLOWLIST_COLLECTIONS: + self._collections[collection_name] = graph.get_collection_ref( + collection_name) + else: + self._collections = collections + + # Keep track of whether this FuncGraph is exportable to SavedModel. Use + # `graph.mark_as_unsaveable(reason)` to mark this FuncGraph and any + # dependent functions as unsaveable. + self._saveable = True + self._saving_errors = set() + + # Keep track of callbacks to run when this graph exits default scope + self._scope_exit_callbacks = None + + def __str__(self): + return "FuncGraph(name=%s, id=%s)" % (self.name, id(self)) + + def watch_variable(self, v): + """Marks the variable v as accessed while building this graph.""" + # Don't watch `v` if it is one of ResourceVariable input arguments. + if (isinstance(v, resource_variable_ops.ResourceVariable) and + v.handle in self._resource_tensor_inputs): + return + + while self is not None and isinstance(self, FuncGraph): + self._watched_variables.add(v) + self = self.outer_graph + + def capture_call_time_value(self, + closure, + spec, + key=None, + default_value=None, + placeholder=None): + """Returns a placeholder which at call time has the value closure(). + + The `tf.function` supports the notion of captures, that is, it allows Python + functions to have closure variables, which bind over some value outside the + function. However, this name binding is "early binding" performed before the + program is run, i.e., + ``` + @tf.function + def f(): + return x + + x = tf.constant(1) + f() # returns 1 + + x = tf.constant(2) + f() # still returns 1! + ``` + while in Python, name binding is performed as the program is running. + ``` + def f(): + return x + + x = 1 + f() # returns 1 + + x = 2 + f() # returns 2 + ``` + `capture_call_time_value` allows tf.function to mimic late binding as a + Python function does, by passing in a `closure` callable argument to be + executed when the tf.function is invoked eagerly. E.g. + ``` + @tf.function + def f(): + return ops.get_default_graph.capture_call_time_value(lambda: x) + + x = tf.constant(1) + f() # returns 1 + + x = tf.constant(2) + f() # returns 2 + ``` + Note that a `capture_call_time_value` function itself does not work well in + the saving process (since the tf.function in which it's called is not + invoked eagerly) unless passed a `default_value` argument. At saving time, + the `default_value` argument is returned instead. + + Args: + closure: function which takes no arguments, to be evaluated at function + call time, returning a nest of tensors compatible with `spec`. + spec: nest of TypeSpec for the value to capture. + key: optional. If not None, multiple calls to lazy_capture with the same + key in the same graph will return the same placeholder, and the first + closure will be used at function call time. + default_value: optional value to return in environments that cannot safely + evaluate closure. + placeholder: optional. If not None, the graph will take the passed-in + `placeholder` as the internal capture instead of creating a new one. + This is useful when loading from a SavedModel. + + Returns: + Nest of placeholders which, at function call time, will be fed with the + result of calling closure(). + + Raises: + ValueError: at function call time, if the return value of closure() is + not compatible with `spec`. + """ + if key is None: + key = object() + if key not in self._function_captures.by_ref_internal: + trace_ctx = trace_type.InternalTracingContext(True) + spec = trace_type.from_value(spec, trace_ctx) + + if placeholder is None: + placeholder_ctx = trace_type.InternalPlaceholderContext(self) + placeholder = spec.placeholder_value(placeholder_ctx) + + def wrapped_closure(): + + # One major case requiring returning a `default_value` is when passing a + # concrete function to `save`, i.e. + # serving_fn = serve_fn.get_concrete_function(...) + # model.save(save_dir, signatures={"serving_default": serving_fn}) + # `serving_fn` has deferred captures added through + # `capture_call_time_value`. It can't be saved correctly since + # `wrapped_closure` will end up executing under a default Graph instead + # of FuncGraph. The user of `capture_call_time_value` also cannot + # conditionally avoid this call since presence of `save_context` when + # executing `wrapped_closure` is not known at tracing time of + # `serving_fn`. + if save_context.in_save_context() and default_value is not None: + return default_value + # TODO(wxinyi): raise an error if in save context but no default value. + + if not context.executing_eagerly(): + graph = ops.get_default_graph() + assert isinstance( + graph, + FuncGraph), "This API should only be used in TF2 enviroment." + + with graph.as_default(): + ret_nest = graph.capture_call_time_value( + closure, spec, key=key, default_value=default_value) + else: + ret_nest = closure() + + ret_nest = spec.cast(ret_nest, trace_type.InternalCastContext) + return spec.to_tensors(ret_nest) + + wrapped_closure.output_spec = spec + self._function_captures.add_or_replace( + key=key, + external=wrapped_closure, + internal=placeholder, + tracetype=spec, + is_by_ref=True) + return self._function_captures.by_ref_internal[key] + + def control_dependencies(self, control_inputs): + """Handles control dependencies. + + FuncGraph wraps Graph's control_dependencies logic by first filtering out + any external tensors / operations and storing them in the graph's + control_captures member. Any consumers of this function graph must then + decide how to handle the control captures. + + Args: + control_inputs: A list of `Operation` or `Tensor` objects which must be + executed or computed before running the operations defined in the + context. Can also be `None` to clear the control dependencies. + + Returns: + A context manager that specifies control dependencies for all + operations constructed within the context. + + Raises: + TypeError: If `control_inputs` is not a list of `Operation` or + `Tensor` objects. + """ + if control_inputs is None: + return super().control_dependencies(control_inputs) + + filtered_control_inputs = [] + for c in control_inputs: + # Check for _UnreadVariable + if (isinstance(c, indexed_slices.IndexedSlices) or + (hasattr(c, "_handle") and hasattr(c, "op"))): + c = c.op + graph_element = ops._as_graph_element(c) # pylint: disable=protected-access + if graph_element is None: + graph_element = c + if graph_element is not None and getattr(graph_element, "graph", + None) is not self: + self._function_captures.control.add(graph_element) + else: + filtered_control_inputs.append(graph_element) + return super().control_dependencies(filtered_control_inputs) + + def as_default(self): + outer_cm = super().as_default() + + @tf_contextlib.contextmanager + def inner_cm(): + """Context manager for copying distribute.Strategy scope information.""" + # pylint: disable=protected-access + # TODO(b/112906995, nareshmodi): distribution strategy depends on + # inheriting this stack from the default graph even in eager mode. Maybe + # it should be part of the eager context? This would also allow us to + # remove a get_default_graph() call from the function cache lookup. + graph = ops.get_default_graph() + old_strategy_stack = self._distribution_strategy_stack + self._distribution_strategy_stack = list( + graph._distribution_strategy_stack) + + # We ignore device placements from any outer scopes while tracing the + # function when possible, to avoid hard-coding them in the function + # graph. "Default" placements come from the PartitionedCallOp's placement, + # so that the same trace of the Python function may be placed on several + # different devices and saved functions may be placed on new devices when + # restored. + # However, we need to preserve the outer device stack in the following + # cases in non eager context: + # 1. device stack is callable + # 2. When using distribution strategy with legacy graph mode. + old_device_stack = self._device_function_stack + if (not context.executing_eagerly() and + (device_stack_has_callable(graph._device_function_stack) or + (self._distribution_strategy_stack and + not ops.executing_eagerly_outside_functions()))): + # Hard-code devices from device functions in the function body + self._device_function_stack = graph._device_function_stack.copy() + + old_creator_stack = self._variable_creator_stack + self._variable_creator_stack = graph._variable_creator_stack + # Inherit the graph key, since this is used for matching variables in + # optimizers. + old_graph_key = self._graph_key + self._graph_key = graph._graph_key + # pylint: enable=protected-access + + old_scope_exit_callbacks = self._scope_exit_callbacks + self._scope_exit_callbacks = [] + + with outer_cm as g: + try: + yield g + finally: + try: + for fn in self._scope_exit_callbacks: + fn() + finally: + self._scope_exit_callbacks = old_scope_exit_callbacks + self._distribution_strategy_stack = old_strategy_stack + self._device_function_stack = old_device_stack + self._variable_creator_stack = old_creator_stack + self._graph_key = old_graph_key + + return inner_cm() + + @property + def outer_graph(self): + """The Graph this FuncGraph is nested in. + + Functions may capture Tensors from graphs they are nested in (transitive). + + Returns: + A Graph object. Initially set to the current default graph when the + FuncGraph was created. If the previous `outer_graph` was deleted because + the function that owns it was deleted, `outer_graph` is reset to the + outermost default graph active when the FuncGraph was created. This + FuncGraph won't have captured anything from the new `outer_graph` (and + likely not from the previous setting, since that would have created a + strong reference), but it is returned so that FuncGraphs always have a + parent. + """ + current = self._weak_outer_graph() + if current is None: + return self._fallback_outer_graph + return current + + @outer_graph.setter + def outer_graph(self, new_outer_graph): + """Sets `outer_graph` to `new_outer_graph`.""" + self._weak_outer_graph = weakref.ref(new_outer_graph) + + @property + def output_types(self): + return [t.dtype for t in self.outputs] + + @property + def output_shapes(self): + return [t.shape for t in self.outputs] + + @property + def trainable_variables(self): + """A sequence of trainable variables accessed by this FuncGraph. + + Note that functions keep only weak references to variables. Calling the + function after a variable it accesses has been deleted is an error. + + Returns: + Sequence of trainable variables for this func graph. + """ + return tuple(v for v in self.variables if v.trainable) + + @property + def variables(self): + """A sequence of variables accessed by this FuncGraph. + + Note that functions keep only weak references to variables. Calling the + function after a variable it accesses has been deleted is an error. + + Returns: + Sequence of variables for this func graph. + """ + + def deref(weak_v): + v = weak_v() + if v is None: + raise AssertionError( + "Called a function referencing variables which have been deleted. " + "This likely means that function-local variables were created and " + "not referenced elsewhere in the program. This is generally a " + "mistake; consider storing variables in an object attribute on " + "first call.") + return v + + return tuple(deref(v) for v in self._weak_variables) + + @variables.setter + def variables(self, var_list): + self._weak_variables = [weakref.ref(v) for v in var_list] + + def _capture_by_value( + self, + op_type, + inputs, + dtypes, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True): + # When capturing by value, do the read outside + reverse_captures = dict((id(v), k) for k, v in self.captures) + uncaptured_inputs = [reverse_captures.get(id(t), t) for t in inputs] + with ops.init_scope(): + if context.executing_eagerly(): + attr_list = ("dtype", int(attrs["dtype"].type)) + value, = execute.execute( + compat.as_bytes(op_type), 1, uncaptured_inputs, attr_list, + context.context()) + else: + op = ops.get_default_graph()._create_op_internal( # pylint: disable=protected-access + op_type, uncaptured_inputs, dtypes, input_types, name, attrs, + op_def, compute_device) + value = op.outputs[0] + captured_value = self.capture(value) + return captured_value.op + + def _create_op_internal( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True): + """Like Graph.create_op, except handles external input tensors. + + This overload adds functionality to create_op to "capture" any external + input tensors, i.e. tensors from the eager context or outer function graphs + if this is a nested function. See `capture` for more information. + + Args: + op_type: The `Operation` type to create. This corresponds to the + `OpDef.name` field for the proto that defines the operation. + inputs: A list of `Tensor` objects that will be inputs to the `Operation`. + dtypes: (Optional) A list of `DType` objects that will be the types of the + tensors that the operation produces. + input_types: (Optional.) A list of `DType`s that will be the types of the + tensors that the operation consumes. By default, uses the base `DType` + of each input in `inputs`. Operations that expect reference-typed inputs + must specify `input_types` explicitly. + name: (Optional.) A string name for the operation. If not specified, a + name is generated based on `op_type`. + attrs: (Optional.) A dictionary where the key is the attribute name (a + string) and the value is the respective `attr` attribute of the + `NodeDef` proto that will represent the operation (an `AttrValue` + proto). + op_def: (Optional.) The `OpDef` proto that describes the `op_type` that + the operation will have. + compute_device: (Optional.) If True, device functions will be executed to + compute the device property of the Operation. + + Returns: + An `Operation` object. + """ + if self.capture_by_value and op_type in [ + "ReadVariableOp", "ResourceGather" + ]: + return self._capture_by_value(op_type, inputs, dtypes, input_types, name, + attrs, op_def, compute_device) + + # This capturing logic interacts poorly with control flow contexts which + # want to replace inputs of ops far too late in the process. This can lead + # the context to get confused and try to create an Enter for an Enter. We + # can detect this here and skip the additional Enter which can confuse loop + # validation logic. + if op_type == "Enter" and inputs[0].op.type == "Enter": + if inputs[0].op.get_attr("frame_name") == attrs["frame_name"].s: + return inputs[0].op + # Calling AddValue on the control flow contexts to force creation of the + # backward accumulators in the original graph before we create placeholders + # to capture the inputs. + ctxt = ops.get_default_graph()._control_flow_context # pylint: disable=protected-access + # Use a different list to avoid modifying the original inputs list. + captured_inputs = [] + for inp in inputs: + # TPU Estimator defines a control flow context with no AddValue method. + if ctxt is not None and hasattr(ctxt, "AddValue"): + inp = ctxt.AddValue(inp) + inp = self.capture(inp) + captured_inputs.append(inp) + return super()._create_op_internal( # pylint: disable=protected-access + op_type, captured_inputs, dtypes, input_types, name, attrs, op_def, + compute_device) + + def capture(self, tensor, name=None, shape=None): + return self._function_captures.capture_by_value(self, tensor, name) + + def _validate_in_scope(self, tensor): + inner_graph = tensor.graph + while inner_graph is not None and isinstance(inner_graph, FuncGraph): + if inner_graph is self: + try: + tb = tensor.op.traceback + except AttributeError: + tensor_traceback = "" + else: + tensor_traceback_list = [] + for frame in traceback.format_list(tb.get_user_frames()): + tensor_traceback_list.extend( + [f" {line}" for line in frame.split("\n") if line.strip()]) + tensor_traceback = "\n".join(tensor_traceback_list) + # Keep in sync with tfe_wrapper.cc. + # TODO(b/200991648): Unify those two paths. + raise errors.InaccessibleTensorError( + f"{tensor!r} is out of scope and cannot be used here. Use return " + "values, explicit Python locals or TensorFlow collections to " + "access it.\n" + "Please see https://www.tensorflow.org/guide/function#all_outputs_of_a_tffunction_must_be_return_values " # pylint: disable=line-too-long + "for more information.\n\n" + f"{tensor!r} was defined here:\n{tensor_traceback}\n\n" + f"The tensor {tensor!r} cannot be accessed from {self}, because " + f"it was defined in {tensor.graph}, which is out of scope.") + inner_graph = inner_graph.outer_graph + + # TODO(panzf): Rename this method along with usages in cond/while graph. + def _capture_helper(self, tensor, name): + return self._function_captures._create_placeholder_helper( # pylint: disable=protected-access + self, tensor, name) + + def _experimental_capture_side_input_by_ref(self, identifier: Hashable, + func: Callable[[], Any]) ->...: + """Implement capturing side input by reference for tf.function. + + Note that this API will only register the capture in the func_graph where + it is called. In the case of nested graph, like nested tf.function or + tf.while, the outer graph is not aware of this capture in the inner graph. + Thus, the outer tf.function will not retrace when the by-ref capture + changes. It's the user's responsibility to call this API in the outer + func_graph as well if proper retracing is needed. + + For example: + + ``` + x = 1 + + # Correct usage + @tf.function + def f_1(): + graph = tf.compat.v1.get_default_graph() + # Capture the same x for the outer tf.function + graph._experimental_capture_side_input_by_ref("x", lambda: x) + + @tf.function + def g(): + graph = tf.compat.v1.get_default_graph() + cap_x = graph._experimental_capture_side_input_by_ref("x", lambda: x) + return cap_x + 1 + + return g() + + # Incorrect usage + @tf.function + def f_2(): + + @tf.function + def g(): + graph = tf.compat.v1.get_default_graph() + cap_x = graph._experimental_capture_side_input_by_ref("x", lambda: x) + return cap_x + 1 + + return g() + + assert f_1() == 2 + assert f_2() == 2 + x = 2 + assert f_1() == 3 + assert f_2() == 2 # This is incorrect + ``` + + Args: + identifier: A hashable object as the key for the capture. + func: A Python function that takes no arguments and returns the value of + side input. The function is evaluated at function call time. + + Returns: + A nested structure with the same structure as the side input. Tensors + are replaced with placehoders, and non-tensors remain the same. + + """ + if context.executing_eagerly(): + return func() + + def maybe_convert_to_tensor(): + value = func() + if not (isinstance(value, core.Value) or isinstance(value, core.Symbol)): + value = constant_op.constant(value) + return value + + placeholder = self._function_captures._capture_by_ref( # pylint: disable=protected-access + self, maybe_convert_to_tensor, identifier) + return placeholder + + @property + def captures(self): + """Order list of tuples containing external and internal captures.""" + return self._function_captures.by_val_capture_tuples + + def add_capture(self, tensor, placeholder): + """Capture a specific tensor and utilize the provided placeholder. + + Args: + tensor: Tensor to captures. + placeholder: Provided placeholder for the tensor. + """ + self._function_captures.add_or_replace( + key=id(tensor), + external=tensor, + internal=placeholder, + is_by_ref=False) + self.inputs.append(placeholder) + + def replace_capture(self, tensor, placeholder): + """Replace already existing capture.""" + self._function_captures.add_or_replace( + key=id(tensor), + external=tensor, + internal=placeholder, + is_by_ref=False) + + def replace_capture_with_deferred_capture(self, + tensor, + closure, + spec, + placeholder, + default_value=None): + """Replaces existing capture `tensor` with a deferred capture `closure`. + + Caution: It is the caller's responsibility to make sure that, after calling + this function, the TypeSpec of the `inputs` (i.e. internal placeholders) and + the `_captured_inputs` (i.e. external captures) of a concrete function that + wraps this function graph are still compatible. Thus user should pairing + usage of this function with `ConcreteFunction.set_external_captures` to make + sure the order still matches. For example, + ``` + # concrete_fn._captured_inputs == [tensor1, tensor2, tensor3] + # concrete_fn.inputs == [placeholder1, placeholder2, placeholder3] + # replace external capture `tensor2` with a deferred_capture, i.e., a + # closure, `closure2` + concrete_fn.graph.replace_capture_with_deferred_capture(tensor2, + closure2, + placeholder2, + some_spec, + some_default) + concrete_fn.set_external_captures([tensor1, closure2, tensor3]) + ``` + + Args: + tensor: Tensor already captured. + closure: function which takes no arguments, to be evaluated at function + call time, returning a nest of tensors compatible with `spec`. + spec: nest of TypeSpec for the value to capture. + placeholder: the internal placeholder corresponding to the captured + `tensor`. + default_value: optional value to use in environments that cannot safely + evaluate closure. + """ + self._function_captures.pop(id(tensor), is_by_ref=False) + self.capture_call_time_value( + closure, + spec, + key=id(tensor), + default_value=default_value, + placeholder=placeholder) + + @property + def external_captures(self): + """External tensors captured by this function.""" + return list(self._function_captures.by_val_external.values()) + + @property + def internal_captures(self): + """Placeholders in this function corresponding captured tensors.""" + return list(self._function_captures.by_val_internal.values()) + + @property + def deferred_external_captures(self): + """Ordered nest of tensors whose placeholders will be fed at call time.""" + return list(self._function_captures.by_ref_external.values()) + + @property + def deferred_internal_captures(self): + """List of nest of placeholders which at call time will be fed.""" + return list(self._function_captures.by_ref_internal.values()) + + @property + def variable_captures(self): + """Map of python object ids of variables to variables which are captured.""" + return self.variables + + @property + def function_captures(self): + return self._function_captures + + def mark_as_unsaveable(self, error_message): + """Marks this FuncGraph as unsaveable. + + Any attempts to export this FuncGraph will raise an error with the specified + message. + + Args: + error_message: List or string containing the error message to be raised + when saving this FuncGraph to SavedModel. + """ + self._saveable = False + if isinstance(error_message, str): + error_message = [error_message] + self._saving_errors.update(error_message) + + @property + def saveable(self): + """Returns whether this FuncGraph is saveable.""" + return self._saveable + + @property + def saving_errors(self): + """Returns set of errors preventing this FuncGraph from being saved.""" + return self._saving_errors + + def _add_scope_exit_callback(self, fn): + """Add a function to call when this graph exits the default scope.""" + if not callable(fn): + raise TypeError("fn is not callable: {}".format(fn)) + if self._scope_exit_callbacks is None: + raise RuntimeError( + "Attempting to add a scope exit callback, but the default graph is " + "not the context scope graph. Did you forget to call " + "'with graph.as_default(): ...'?") + self._scope_exit_callbacks.append(fn) + + +def func_graph_from_py_func(name, + python_func, + args, + kwargs, + signature=None, + func_graph=None, + add_control_dependencies=True, + arg_names=None, + op_return_value=None, + collections=None, + capture_by_value=None, + create_placeholders=True): + """Returns a `FuncGraph` generated from `python_func`. + + Args: + name: an identifier for the function. + python_func: the Python function to trace. + args: the positional args with which the Python function should be called; + ignored if a signature is provided. + kwargs: the keyword args with which the Python function should be called; + ignored if a signature is provided. + signature: a possibly nested sequence of `TensorSpecs` specifying the shapes + and dtypes of the arguments. When a signature is provided, `args` and + `kwargs` are ignored, and `python_func` is traced with Tensors conforming + to `signature`. If `None`, the shapes and dtypes are inferred from the + inputs. + func_graph: Optional. An instance of FuncGraph. If provided, we will use + this graph else a new one is built and returned. + add_control_dependencies: If True, automatically adds control dependencies + to ensure program order matches execution order and stateful ops always + execute. + arg_names: Optional list of argument names, used to give input placeholders + recognizable names. + op_return_value: Optional. A Tensor. If set and `python_func` returns + Operations, those return values will be replaced with this value. If not + set, returning an Operation triggers an error. + collections: a dictionary of collections this FuncGraph should start with. + If not specified (None), the FuncGraph will read (but not write to) the + outer graph's collections that are not allowlisted, and both read and + write to the outer graph's collections that are allowlisted. The current + allowlisted collections are the global variables, the local variables, and + the trainable variables. Defaults to None. + capture_by_value: An optional boolean. If True, the func graph will capture + Variables by value instead of reference. By default inherit from outer + graphs, and failing that will default to False. + create_placeholders: An optional boolean. If True, then func graph will + create placeholders for the inputs as graph ops. If False, the input args + and kwargs will be treated as the input placeholders. + + Returns: + A FuncGraph. + + Raises: + TypeError: If any of `python_func`'s return values is neither `None`, a + `Tensor` or a `tf.experimental.ExtensionType`. + """ + if op_return_value is not None: + assert isinstance(op_return_value, tensor_lib.Tensor), op_return_value + if func_graph is None: + func_graph = FuncGraph( + name, collections=collections, capture_by_value=capture_by_value) + assert isinstance(func_graph, FuncGraph) + if add_control_dependencies: + deps_control_manager = auto_control_deps.AutomaticControlDependencies() + else: + deps_control_manager = ops.NullContextmanager() + + with func_graph.as_default(), deps_control_manager as deps_ctx: + current_scope = variable_scope.get_variable_scope() + default_use_resource = current_scope.use_resource + current_scope.set_use_resource(True) + + if signature is not None: + args = signature + kwargs = {} + + if create_placeholders: + func_args, func_kwargs = _create_placeholders(args, kwargs, arg_names) + else: + func_args, func_kwargs = args, kwargs + + input_trace_types = trace_type.from_value([func_args, func_kwargs]) + func_graph.inputs = input_trace_types.to_tensors([func_args, func_kwargs]) # pylint: disable=protected-access + + # Reset variables watched while deconstructing inputs. + func_graph._watched_variables = object_identity.ObjectIdentityWeakSet() # pylint: disable=protected-access + + for arg in func_graph.inputs: + if arg.dtype == dtypes.resource: + func_graph._resource_tensor_inputs.add(arg) # pylint:disable=protected-access + + signature_context = trace_type.InternalTracingContext() + # Convert all Tensors into TensorSpecs before saving the structured inputs. + # If storing pure concrete functions that are not called through polymorphic + # functions, we don't have access to FunctionSpec, so we need to call the + # TensorSpecs by their `arg_names` for later binding. + func_graph.structured_input_signature = ( + convert_structure_to_signature( + func_args, arg_names, signature_context=signature_context), + convert_structure_to_signature( + func_kwargs, signature_context=signature_context)) + + # Note: `nest.flatten` sorts by keys, as does `_deterministic_dict_values`. + # Variables to help check whether mutation happens in calling the function + # Copy the recursive list, tuple and map structure, but not base objects + func_args_before = nest.pack_sequence_as( + func_args, + nest.flatten(func_args, expand_composites=True), + expand_composites=True) + func_kwargs_before = nest.pack_sequence_as( + func_kwargs, + nest.flatten(func_kwargs, expand_composites=True), + expand_composites=True) + + def convert(x): + """Converts a function output to a Tensor.""" + if x is None: + return None + if op_return_value is not None and isinstance(x, ops.Operation): + # TODO(b/79881896): we currently can't capture external control deps, so + # this won't work if x needs to be captured (i.e. if python_func returns + # captured Operations). + with ops.control_dependencies([x]): + x = array_ops.identity(op_return_value) + elif not isinstance(x, tensor_array_ops.TensorArray): + try: + x = ops.convert_to_tensor_or_composite(x) + except (ValueError, TypeError): + raise TypeError( + "To be compatible with tf.function, Python functions " + "must return zero or more Tensors or ExtensionTypes or None " + f"values; in compilation of {str(python_func)}, found return " + f"value of type {type(x).__name__}, which is not a Tensor or " + "ExtensionType.") + if add_control_dependencies: + x = deps_ctx.mark_as_return(x) + return x + + _, original_func = tf_decorator.unwrap(python_func) + func_outputs = python_func(*func_args, **func_kwargs) + + # invariant: `func_outputs` contains only Tensors, CompositeTensors, + # TensorArrays and `None`s. + func_outputs = variable_utils.convert_variables_to_tensors(func_outputs) + func_outputs = nest.map_structure( + convert, func_outputs, expand_composites=True) + + # flatten and unflatten func_args and func_kwargs to maintain parity + # from flattening which sorts by key + func_args = nest.pack_sequence_as( + func_args, + nest.flatten(func_args, expand_composites=True), + expand_composites=True) + func_kwargs = nest.pack_sequence_as( + func_kwargs, + nest.flatten(func_kwargs, expand_composites=True), + expand_composites=True) + check_func_mutation(func_args_before, func_kwargs_before, func_args, + func_kwargs, original_func) + current_scope.set_use_resource(default_use_resource) + + inputs = [] + for arg in composite_tensor_utils.flatten_with_variables([func_args, + func_kwargs]): + if isinstance(arg, resource_variable_ops.BaseResourceVariable): + # Even if an argument variable was not used in the function, we've + # already manually captured the resource Tensor when creating argument + # placeholders. + capture = func_graph._function_captures.pop(id(arg.handle), False) # pylint: disable=protected-access + assert len(capture) >= 2 + resource_placeholder = capture[1] + if resource_placeholder is None: + continue + inputs.append(resource_placeholder) + elif isinstance(arg, tensor_lib.Tensor): + inputs.append(arg) + func_graph.inputs = ( + inputs + func_graph.internal_captures + nest.flatten( + func_graph.deferred_internal_captures, expand_composites=True)) + func_graph.structured_outputs = func_outputs + # Returning a closed-over tensor does not trigger convert_to_tensor. + func_graph.outputs.extend( + func_graph.capture(x) + for x in flatten(func_graph.structured_outputs) + if x is not None) + + func_graph.variables = func_graph._watched_variables # pylint: disable=protected-access + + if add_control_dependencies: + func_graph.control_outputs.extend(deps_control_manager.ops_which_must_run) + func_graph.collective_manager_ids_used = ( + deps_control_manager.collective_manager_ids_used) + + return func_graph + + +def maybe_captured(tensor): + """If t is a captured value placeholder, returns the original captured value. + + Args: + tensor: Tensor. + + Returns: + A tensor, potentially from a different Graph/FuncGraph. + """ + if (not isinstance(tensor, ops.EagerTensor) and + tensor.op.graph.building_function and tensor.op.type == "Placeholder"): + for input_t, placeholder_t in tensor.op.graph.captures: + if tensor == placeholder_t: + return maybe_captured(input_t) + # pylint: enable=protected-access + return tensor + + +def device_stack_has_callable(device_stack): + """Checks whether a device stack contains a callable.""" + return any( + callable(spec._device_name_or_function) # pylint: disable=protected-access + for spec in device_stack.peek_objs()) + + +def has_mutation(n1, n2): + """Returns true if n1 and n2 are different (using `is` to compare leaves).""" + try: + nest.assert_same_structure(n1, n2, expand_composites=True) + except ValueError: + return True + + for arg1, arg2 in zip( + nest.flatten(n1, expand_composites=True), + nest.flatten(n2, expand_composites=True)): + if arg1 is not arg2: + return True + + return False + + +def check_func_mutation(old_args, old_kwargs, new_args, new_kwargs, func): + """Checks that the arguments to a function are not modified.""" + if not has_mutation((old_args, old_kwargs), (new_args, new_kwargs)): + return + + # Mutation detected; construct a useful error message. + func_name = getattr(func, "__qualname__", getattr(func, "__name__", func)) + signature = tf_inspect.signature(func) + try: + old_bound = signature.bind(*old_args, **old_kwargs).arguments + new_bound = signature.bind(*new_args, **new_kwargs).arguments + except TypeError as e: + # This occurs when the function is called with the (deprecated) + # "flat signature". See ConcreteFunction._call_with_flat_signature. In + # this case, we can't report which arguments were modified. + raise ValueError( + f"{func_name}{signature} should not modify its Python input " + f"arguments. Check if it modifies any lists or dicts passed as " + f"arguments. Modifying a copy is allowed.") from e + + assert set(old_bound) == set(new_bound) + modified_args = [ + arg_name for arg_name in new_bound + if has_mutation(old_bound[arg_name], new_bound[arg_name]) + ] + changes = ", ".join(modified_args) + raise ValueError(f"{func_name}{signature} should not modify its Python " + f"input arguments. Modifying a copy is allowed. The " + f"following parameter(s) were modified: {changes}") + + +# TODO(edloper): If TensorArray becomes a CompositeTensor, then delete this. +def flatten(sequence): + """Like nest.flatten w/ expand_composites, but returns flow for TensorArrays. + + Args: + sequence: A nested structure of Tensors, CompositeTensors, and TensorArrays. + + Returns: + A list of tensors. + """ + flat_sequence = nest.flatten(sequence, expand_composites=True) + return [ + item.flow if isinstance(item, tensor_array_ops.TensorArray) else item + for item in flat_sequence + ] + + +# TODO(edloper): If TensorArray becomes a CompositeTensor, then delete this. +def pack_sequence_as(structure, flat_sequence): + """Like `nest.pack_sequence_as` but also builds TensorArrays from flows. + + Args: + structure: The structure to pack into. May contain Tensors, + CompositeTensors, or TensorArrays. + flat_sequence: An iterable containing tensors. + + Returns: + A nested structure. + + Raises: + AssertionError if `structure` and `flat_sequence` are not compatible. + """ + flat_sequence = list(flat_sequence) + flattened_structure = nest.flatten(structure, expand_composites=True) + if len(flattened_structure) != len(flat_sequence): + raise ValueError("Mismatch in element count") + for i in range(len(flat_sequence)): + if isinstance(flattened_structure[i], tensor_array_ops.TensorArray): + flat_sequence[i] = tensor_array_ops.build_ta_with_new_flow( + old_ta=flattened_structure[i], flow=flat_sequence[i]) + return nest.pack_sequence_as(structure, flat_sequence, expand_composites=True) + + +def _create_placeholders(args, kwargs, arg_names=None): + """Create placeholders given positional args and keyword args.""" + signature_context = trace_type.InternalTracingContext( + is_legacy_signature=True) + arg_trace_types = trace_type.from_value(tuple(args), signature_context) + kwarg_trace_types = trace_type.from_value(kwargs, signature_context) + + placeholder_mapping = signature_context.get_placeholder_mapping() + placeholder_context = trace_type.InternalPlaceholderContext( + ops.get_default_graph(), placeholder_mapping) + + if arg_names is None: + arg_names = [None] * len(arg_trace_types.components) + + # Create placeholders for trace type args and trace type kwargs + func_args = [] + for name, trace_type_arg in zip(arg_names, arg_trace_types.components): + placeholder_context.update_naming_scope(name) + placeholder = trace_type_arg.placeholder_value(placeholder_context) + func_args.append(placeholder) + + func_kwargs = {} + for name, trace_type_kwarg in zip(*sorted(kwarg_trace_types.mapping.items())): + placeholder_context.update_naming_scope(name) + placeholder = trace_type_kwarg.placeholder_value(placeholder_context) + func_kwargs[name] = placeholder + + return tuple(func_args), func_kwargs + + +def dismantle_func_graph(func_graph): + """Removes reference cycles in `func_graph` FuncGraph. + + Helpful for making sure the garbage collector doesn't need to run when + the FuncGraph goes out of scope, e.g. in tests using defun with + @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True). + + Args: + func_graph: A `FuncGraph` object to destroy. `func_graph` is unusable after + this function. + """ + func_graph._function_captures.clear() # pylint: disable=protected-access + ops.dismantle_graph(func_graph) + + +def override_func_graph_name_scope(func_graph, name_scope): + func_graph._name_stack = name_scope # pylint: disable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/function.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/function.py new file mode 100644 index 0000000000000000000000000000000000000000..068a685184245add467759bfdef29a9d19556040 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/function.py @@ -0,0 +1,1385 @@ +# 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. +# ============================================================================= +"""Python front-end supports for functions. + +NOTE: At this time, functions are experimental and subject to change!. Proceed +with caution. +""" + +import collections +import hashlib + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import function_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.eager import context +from tensorflow.python.framework import c_api_util +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import graph_to_function_def +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variable_scope as vs +from tensorflow.python.util import compat +from tensorflow.python.util import function_utils +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_inspect + + +# TODO(b/136040013): Drop support for Defun. +class Defun(object): + """Obsolete. Slated for deletion. Please use tf.function instead. + + Known feature gaps while migrating to tf.function (could be outdated): + - tf.function doesn’t support Send/Recv capability since it doesn’t share + rendezvous with the main graph but always creates a new one. + - tf.function doesn’t support custom gradient function directly, instead you + need to define the function inside a tf.custom_gradient wrapper together + with the gradient function. + - Unlike Defun, Keras layers used inside a tf.function need to be created only + once to avoid variable recreation. + - Defun respects the device assignments and applies them to the function body + but tf.function needs it to be done manually. + - Defun might prune out unused ops automatically but tf.function doesn't. + + Limitations of Defun: + - Original source locations are not preserved so errors do not include + full/valid stack traces. + - Only supports linear sequence of arguments and return values, putting the + burden on the caller to pack/unpack everything across a Defun boundary into + tuples (as opposed to passing list and dict-like structures directly). + - Does not support overloading or late-bound specializations. + - Has its own way for defining gradient overrides which does not follow + current conventions. + - Cannot support imperative control flow or automatic control dependencies. + - Does not reflect statefulness in the graph and has a calling convention that + differs from how more modern tools interact. + - Is only compatible with graph building mode. + + Decorator used to define TensorFlow functions. + + Use this decorator to make a Python function usable directly as a TensorFlow + function. + + The decorated function must add ops to the default graph and return zero or + more `Tensor` objects. Call the decorator with named arguments, one for each + argument of the function to decorate, with the expected type of the argument + as value. + + For example if the function to decorate accepts two `tf.float32` arguments + named `x` and `y`, call the decorator with: + + @Defun(tf.float32, tf.float32) + def foo(x, y): + ... + + When you call the decorated function, it adds the `call` ops to the + default graph. In addition, it adds the definition of the function into the + default graph. Because the addition of the function into the graph + is deferred, the decorator can be used anywhere in the program. + + Any variables created inside of the function are hoisted into the outer graph. + Note that the variables are created in the variable scope that was active + during the first call to the function. Subsequent function calls will refer to + the same set of variables. + + Definitions of functions in a graph are frozen as soon as the graph is used to + create a session. However, new functions and new calls to existing functions + may be added to the graph, with the new functions themselves becoming + immediately frozen. + + Example, but also see the [How To on functions](link_needed). + + ```python + # Defining the function. + @tf.Defun(tf.float32, tf.float32) + def MyFunc(x, y): + return x + y, x - y + + # Building the graph. + a = tf.constant([1.0]) + b = tf.constant([2.0]) + c, d = MyFunc(a, b, name='mycall') + ``` + """ + + def __init__(self, *input_types, **kwargs): + """Create a `Defun` decorator. + + Args: + *input_types: A list of `tf.DType` + **kwargs: Optional keyword arguments, including + func_name - (optional). A python string, the name to use to + declare this `Function` in the graph. + + grad_func - (optional). A function implementing the gradient + of the function-to-register. This is must be a + `_DefinedFunction` object. The gradient + function must satisfy the criterion defined in + function.proto:GradientDef. + + python_grad_func - (optional). A function implementing the + gradient of the function python-side. This function must + take the current op and the gradients w.r.t. its outputs, + and return the gradients w.r.t. the inputs. That is it must + implement the interface expected by `tf.RegisterGradient`). + This will be called by tf.gradients to add the gradient ops + to the graph. At most one of grad_func and python_grad_func + can be specified. + + out_names = (optional). A list of strings, one per output + tensor. + + shape_func - (optional). A function taking the op and returning a list + of static shapes to set for the function's outputs. + """ + self._input_types = input_types + self._func_name = kwargs.pop("func_name", None) + self._grad_func = kwargs.pop("grad_func", None) + self._python_grad_func = kwargs.pop("python_grad_func", None) + self._out_names = kwargs.pop("out_names", None) + self._extra_kwargs = kwargs + + def __call__(self, func): + # Various sanity checks on the callable func. + if not callable(func): + raise ValueError(f"Function {func} must be a callable.") + + # Func should not use kwargs and defaults. + argspec = tf_inspect.getargspec(func) + if argspec.keywords or argspec.defaults: + raise ValueError( + "Functions with argument defaults or keywords arguments are not " + f"supported. {func} has defaults {argspec.defaults} and keywords " + f"{argspec.keywords}.") + + # Computes how many arguments 'func' has. + min_args = len(argspec.args) + max_args = min_args + if argspec.varargs: + max_args = 1000000 + argnames = argspec.args + if tf_inspect.ismethod(func): + # 1st argument is the "class" type. + min_args -= 1 + argnames = argnames[1:] + + if self._input_types: + # If Defun is given a list of types for the inputs, the number + # of input types should be compatible with 'func'. + num = len(self._input_types) + if num < min_args or num > max_args: + raise ValueError( + "The number of tf.function input types is not compatible with the " + f"allowed arguments of {func}. The tf.function have {num} input " + f"types, while the python function allows minimum {min_args} and " + f"maximum {max_args} arguments.") + return _DefinedFunction( + func, + argnames, + self._input_types, + self._func_name, + self._grad_func, + self._python_grad_func, + out_names=self._out_names, + **self._extra_kwargs) + + # 'func' expects no arguments and input types is an empty list. + if min_args == 0 and max_args == 0: + return _DefinedFunction( + func, [], [], + self._func_name, + self._grad_func, + self._python_grad_func, + out_names=self._out_names, + **self._extra_kwargs) + + # Input types are unknown. It's an overloaded function and hence + # its definition needs to be deferred until it's called. + return _OverloadedFunction( + func, + argnames, + self._func_name, + self._grad_func, + self._python_grad_func, + out_names=self._out_names, + **self._extra_kwargs) + + +class _DefinedFunctionDeleter(object): + """Unregister function from eager context.""" + + __slots__ = ["name"] + + def __init__(self, name): + self.name = name + + def __del__(self): + try: + context.remove_function(self.name) + except TypeError: + # Suppress some exceptions, mainly for the case when we're running on + # module deletion. Things that can go wrong include the context module + # already being unloaded, self._handle._handle_data no longer being + # valid, and so on. Printing warnings in these cases is silly + # (exceptions raised from __del__ are printed as warnings to stderr). + pass # 'NoneType' object is not callable when the handle has been + # partially unloaded. + except AttributeError: + pass # 'NoneType' object has no attribute 'eager_mode' when context has + # been unloaded. Will catch other module unloads as well. + + +class _DefinedFunction(object): + """_DefinedFunction encapsulates a function definition and its properties. + + Attributes: + name: The function name. + definition: The definition of this function. A FunctionDef proto. + cached_definition: Same as definition. Needed to match AtomicFunction API. + grad_func_name: If not None, the name of this function's gradient function. + python_grad_func: A python callable implementing the gradient of + the function python-side. + """ + + def __init__(self, + func, + argnames, + input_types, + func_name=None, + grad_func=None, + python_grad_func=None, + out_names=None, + shape_func=None, + capture_by_value=False, + allowlisted_stateful_ops=None, + capture_resource_var_by_value=True, + **kwargs): + """Creates _DefinedFunction. + + Args: + func: A python callable which constructs a tf function body. + argnames: A list of strings for function argument names. + input_types: The function's argument types. Can be a tuple, list of + tf data types. + func_name: The function name. Defaults to None, in which derives from + 'func'. + grad_func: This function's gradient function, if not None. Defaults + to None. + python_grad_func: A python callable implementing the gradient of + the function python-side. + out_names: An optional list of strings for the function return value + names. + shape_func: An optional function mapping an op to a list of static + output shapes. + capture_by_value: Boolean (defaults to False). If True, captured values + will be copied into the function body. + allowlisted_stateful_ops: A set of ops that if stateful we ignore and + copy into the function body, when `capture_by_value` is True. + capture_resource_var_by_value: Boolean (defaults to True). If False, + captured resource variable returns the handle instead of value. + **kwargs: The keyword arguments. **kwargs is passed to every call + site of this function. + + Raises: + ValueError: The function definition is invalid. + + """ + self._func = func + self._input_types = input_types + self._func_name = func_name + self._grad_func = grad_func + self._python_grad_func = python_grad_func + self._out_names = out_names + self._shape_func = shape_func + self._capture_by_value = capture_by_value + self._allowlisted_stateful_ops = allowlisted_stateful_ops + if self._allowlisted_stateful_ops is None: + self._allowlisted_stateful_ops = set() + self._capture_resource_var_by_value = capture_resource_var_by_value + self._extra_kwargs = kwargs + # Constructed only when C API is disabled, lazily + self._definition = None + # Constructed only when C API is enabled, lazily + self._c_func = None + self._function_deleter = None + self._sub_functions = {} # Constructed with _definition or _c_func + # pylint: disable=protected-access + device_funcs = ops.get_default_graph()._device_functions_outer_to_inner + # pylint: enable=protected-access + + # Get the innermost device if possible. + self._caller_device = device_funcs[-1] if device_funcs else None + + # Cached OpDef for this function. When C API is enabled, this is + # the only part of FunctionDef that we cache in Python. When C API + # is disabled the whole _definition is available and this is simply + # another reference to _definition.signature + self._op_def = None + + assert isinstance(input_types, (list, tuple)) + self._arg_types = input_types + self._arg_names = [argnames[i] if i < len(argnames) else ("arg%d" % i) + for i in range(len(input_types))] + + @property + def name(self): + """Function name.""" + self._create_definition_if_needed() + return self._func_name + + @property + def cached_definition(self): + return self.definition + + @property + def definition(self): + """Function definition proto.""" + self._create_definition_if_needed() + if self._c_func: + with c_api_util.tf_buffer() as buf: + with self._c_func.get() as func: + c_api.TF_FunctionToFunctionDef(func, buf) + fdef = function_pb2.FunctionDef() + proto_data = c_api.TF_GetBuffer(buf) + fdef.ParseFromString(compat.as_bytes(proto_data)) + with ops.init_scope(): + if context.executing_eagerly(): + context.add_c_function(func) + self._function_deleter = _DefinedFunctionDeleter( + fdef.signature.name) + return fdef + return self._definition + + @property + def _signature(self): + self._create_definition_if_needed() + return self._op_def + + def set_grad_func(self, grad_func): + """Specifies the gradient function of this function.""" + assert not self._grad_func + assert isinstance(grad_func, _DefinedFunction) + self._grad_func = grad_func + + @property + def grad_func_name(self): + """Returns the name of the gradient function.""" + return self._grad_func.name if self._grad_func else None + + @property + def python_grad_func(self): + """Python gradient function callable.""" + return self._python_grad_func + + @property + def declared_input_types(self): + """Returns the list of data types of explicit declared inputs.""" + return self._input_types + + @property + def captured_inputs(self): + """Returns the list of implicitly captured inputs.""" + self._create_definition_if_needed() + return self._extra_inputs + + @property + def stateful_ops(self): + """Returns the list of stateful ops in function definition. + + Returns: + A list of (op.name, op.type) pairs. + """ + self._create_definition_if_needed() + return self._stateful_ops + + def _create_definition_if_needed(self): + """Creates the function definition if it's not created yet.""" + with context.graph_mode(): + self._create_definition_if_needed_impl() + + def _create_definition_if_needed_impl(self): + """This is not what you want, see _create_definition_if_needed.""" + if self._definition is not None or self._c_func is not None: + return + + # Copy variable collections (by reference) from the parent graph such that + # name based variable sharing (e.g. via tf.make_template) works between the + # func graph and parent graph. + variable_keys = [] + variable_keys.extend(ops.GraphKeys._VARIABLE_COLLECTIONS) # pylint: disable=protected-access + variable_keys.append(vs._VARSTORE_KEY) # pylint: disable=protected-access + + parent_graph = ops.get_default_graph() + collections_ref = { + key: parent_graph.get_collection_ref(key) for key in variable_keys} + + temp_graph = func_graph_from_py_func( + self._func, + self._arg_names, + self._arg_types, + self._func_name, + self._capture_by_value, + self._caller_device, + collections_ref=collections_ref, + allowlisted_stateful_ops=self._allowlisted_stateful_ops, + capture_resource_var_by_value=self._capture_resource_var_by_value) + + self._extra_inputs = temp_graph.extra_inputs + # pylint: disable=protected-access + self._sub_functions = temp_graph._functions + # pylint: enable=protected-access + + # Extra kwargs are treated as attrs on the function def. + if self._func_name: + base_func_name = self._func_name + else: + base_func_name = function_utils.get_func_name(self._func) + if self._grad_func: + base_func_name += ("_%s" % self._grad_func.name) + kwargs_attr = _parse_kwargs_as_attrs(base_func_name, **self._extra_kwargs) + + # FIXME(feyu): C API is always enabled now. The if-true branch never runs. + if not temp_graph._c_graph: # pylint: disable=protected-access + # Build the FunctionDef + self._definition = graph_to_function_def.graph_to_function_def( + temp_graph, + temp_graph.get_operations(), + temp_graph.inputs, + temp_graph.outputs, + out_names=self._out_names) + + for k in kwargs_attr: + self._definition.attr[k].CopyFrom(kwargs_attr[k]) + + # Hash the definition and its dependencies. + self._hash_str = self._create_hash_str( + self._definition.signature.input_arg, + self._definition.signature.output_arg, self._definition.node_def) + + # Finally, we decide the function name to use. If not specified, + # make up something which is almost certainly unique (but deterministic). + if not self._func_name: + self._func_name = "_".join([base_func_name, self._hash_str]) + self._definition.signature.name = self._func_name + if self._func.__doc__: + self._definition.signature.description = self._func.__doc__ + + self._op_def = self._definition.signature + else: # C API is enabled + output_names = ([compat.as_bytes(x) for x in self._out_names] + if self._out_names else []) + description = self._func.__doc__ or None + # pylint: disable=protected-access + with temp_graph._c_graph.get() as c_graph: + c_func = c_api.TF_GraphToFunction_wrapper( + c_graph, + base_func_name, + self._func_name is None, # append_hash_to_fn_name + None, # opers + [t._as_tf_output() for t in temp_graph.inputs], + [t._as_tf_output() for t in temp_graph.outputs], + output_names, + [], # control_outputs + [], # control_output_names + None, # opts + description) + self._c_func = c_api_util.ScopedTFFunction(c_func, base_func_name) + # pylint: enable=protected-access + self._set_c_attrs(kwargs_attr) + + # Set cached fields: _op_def and _func_name (if not already set) + self._op_def = self.definition.signature + if self._func_name: + assert self._func_name == self._op_def.name + else: + self._func_name = compat.as_str(self._op_def.name) + + self._stateful_ops = [(op.name, op.type) + for op in temp_graph.get_operations() + if op._is_stateful] # pylint: disable=protected-access + + def _set_c_attrs(self, attrs): + """Sets `attrs` as attributes of self._c_func. + + Requires that self._c_func is not None. + + Args: + attrs: a dictionary from attribute name to attribute proto value + """ + for name, attr_value in attrs.items(): + serialized = attr_value.SerializeToString() + # TODO(skyewm): this creates and deletes a new TF_Status for every attr. + # It might be worth creating a convenient way to re-use the same status. + with self._c_func.get() as func: + c_api.TF_FunctionSetAttrValueProto(func, compat.as_str(name), + serialized) + + def _create_hash_str(self, input_arg, output_arg, node_def): + """Creates an 8-character string unique to this input. + + Args: + input_arg: the input_arg field of an OpDef + (e.g. self._definition.signature.input_arg) + output_arg: the output_arg field of an OpDef + (e.g. self._definition.signature.output_arg) + node_def: the node_def field of a FunctionDef + (e.g. self._definition.node_def) + + Returns: + The unique string for this input + """ + hasher = hashlib.sha1() + + def update_num(n): + hasher.update(compat.as_bytes("%x" % n)) + + def update_str(s): + update_num(len(s)) + hasher.update(compat.as_bytes(s)) + + def update_strs(slist): + update_num(len(slist)) + for s in slist: + update_str(s) + + for adef in input_arg: + update_str(adef.SerializeToString()) + + for adef in output_arg: + update_str(adef.SerializeToString()) + + for n in sorted(node_def, key=lambda n: n.name): + update_str(n.name) + update_str(n.op) + update_strs(n.input) + update_num(len(n.attr)) + # NOTE: protobuf map serialization does not guarantee ordering. + for k in sorted(n.attr): + update_str(k) + update_str(n.attr[k].SerializeToString()) + + return hasher.hexdigest()[:8] + + def add_to_graph(self, g): + """Adds this function into the graph g.""" + self._create_definition_if_needed() + + # Adds this function into 'g'. + # pylint: disable=protected-access + if context.executing_eagerly(): + context.context().add_function_def(self.definition) + else: + g._add_function(self) + # pylint: enable=protected-access + + # Ensures related sub-routines are defined in 'g', too. + for f in self._sub_functions.values(): + g._add_function_recursive(f) # pylint: disable=protected-access + + # Adds its gradient function, too. + if self._grad_func: + self._grad_func.add_to_graph(g) + + def __call__(self, *args, **kwargs): + self.add_to_graph(ops.get_default_graph()) + args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs + ret, op = _call(self._signature, *args, **kwargs) + + # Set a hidden attr in 'op' so that gradients_impl can refer back + # to this _DefinedFunction instance to access python_grad_func. + assert isinstance(op, ops.Operation) + setattr(op, "__defun", self) + + if self._shape_func is not None: + shapes = self._shape_func(op) + if len(shapes) != len(op.outputs): + raise ValueError(f"shape_func {self._shape_func} produced " + f"{len(shapes):d} shapes, which does not match " + f"{len(op.outputs)} outputs.") + for (t, shape) in zip(op.outputs, shapes): + t.set_shape(shape) + return ret + + +class _OverloadedFunction(object): + """_OverloadedFunction encapsulates an overloaded function. + + _OverloadedFunction maintains a mapping from input types to + instantiated _DefinedFunction in self._overload. + + """ + + def __init__(self, + func, + argnames, + func_name=None, + grad_func=None, + python_grad_func=None, + out_names=None, + **kwargs): + """Creates _DefinedFunction. + + Args: + func: A python callable which constructs a tf function body. + argnames: A list of strings for function argument names. + func_name: The function name. Defaults to None, in which derives from + 'func'. + grad_func: This function's gradient function, if not None. Defaults + to None. + python_grad_func: A python callable implementing the gradient of + the function python-side. + out_names: A list of strings for the function return value names. + **kwargs: The keyword arguments. **kwargs is passed to every call + site of this function. + + Raises: + ValueError: The function definition is invalid. + + """ + self._func = func + self._argnames = argnames + self._func_name = func_name + assert grad_func is None or isinstance(grad_func, _OverloadedFunction) + self._grad_func = grad_func + self._python_grad_func = python_grad_func + self._out_names = out_names + self._extra_kwargs = kwargs + self._overload = {} + + def instantiate(self, input_types): + """Instantiate this function given input argument types. + + Args: + input_types: A list of data types for the inputs. + + Returns: + _DefinedFunction for the given input types. + + """ + # Stringify the type list. + key = _type_list_to_str(input_types) + defined = self._overload.get(key) + if not defined: + # If not defined yet, define the function given the input types. + name = self._func_name + if name is not None: + name = "_".join([name, key]) + defined = _DefinedFunction( + self._func, + self._argnames, + input_types, + name, + None, + self._python_grad_func, + out_names=self._out_names, + **self._extra_kwargs) + _ = defined.name # Fully instantiate the function definition. + if self._grad_func: + # If _grad_func is given, it is another + # _OverloadedFunction. We need to instantiate it with the + # right input types. + output_types = [ + dtypes.DType(_.type) for _ in defined._signature.output_arg # pylint: disable=protected-access + ] + # pylint: disable=protected-access + defined._grad_func = self._grad_func.instantiate(input_types + + output_types) + # pylint: enable=protected-access + self._overload[key] = defined + return defined + + def __call__(self, *args, **kwargs): + input_types = [] + args = list(args) + for (i, x) in enumerate(args): + x = ops.convert_to_tensor(x) + if not isinstance(x, tensor_lib.Tensor): + raise ValueError(f"Expected a Tensor but got {x} with type {type(x)}.") + input_types.append(x.dtype) + args[i] = x + return self.instantiate(input_types)(*args, **kwargs) + + +class _FuncGraph(ops.Graph): + """A helper for constructing a function. + + _FuncGraph overrides ops.Graph's create_op() so that we can keep + track of all inputs into every op created inside the function. If + any input is from other graphs, we keep track of it in self.capture + and substitute the input with a place holder. + + Each captured input's corresponding place holder is converted into a + function argument and the caller passes in the captured tensor. + """ + + def __init__(self, name, capture_by_value, allowlisted_stateful_ops, + capture_resource_var_by_value, *args, **kwargs): + super(_FuncGraph, self).__init__(*args, **kwargs) + self._capture_by_value = capture_by_value + self._allowlisted_stateful_ops = allowlisted_stateful_ops + self._capture_resource_var_by_value = capture_resource_var_by_value + self._building_function = True + self._outer_graph = ops.get_default_graph() + self._vscope = vs.get_variable_scope() + self._old_custom_getter = self._vscope.custom_getter + + # The name of the function. + self.name = name + # Placeholder tensors representing the inputs to this function. The tensors + # are in this _FuncGraph. + self.inputs = [] + # Tensors that will be returned this function. The tensors are in this + # _FuncGraph. + self.outputs = [] + # Maps external tensor -> internal tensor (e.g. input placeholder). + self._captured = {} + # The external tensors that have been captured as inputs and must be passed + # to this function (empty if capturing by value, otherwise these are the + # keys of _captured). + self.extra_inputs = [] + # Input placeholders that been added for captured values (empty if capturing + # by value). + self.extra_args = [] + # Captured variables. + # TODO(skyewm): is this needed? + self.extra_vars = [] + + # pylint: disable=g-doc-return-or-yield + + @property + def outer_graph(self): + """The graph active when this _FuncGraph was created.""" + return self._outer_graph + + @tf_contextlib.contextmanager + def container(self, container_name): + """Returns a context manager that specifies the resource container to use. + + Overridden from `tf.Graph` to update both the init_scope container + and the present inner container. This is necessary to make sure setting + containers applies correctly both to created variables and to stateful + ops. + + Args: + container_name: container name string. + + Returns: + A context manager for defining resource containers for stateful ops, + yields the container name. + """ + original_container = self._container + # pylint: disable=protected-access + with ops.init_scope(): + original_init_container = ops.get_default_graph()._container + try: + self._container = container_name + with ops.init_scope(): + ops.get_default_graph()._container = container_name + yield self._container + finally: + self._container = original_container + with ops.init_scope(): + ops.get_default_graph()._container = original_init_container + # pylint: enable=protected-access + + # pylint: enable=g-doc-return-or-yield + + def getvar( + self, + getter, + name, + shape=None, + dtype=None, + initializer=None, + reuse=None, + trainable=True, + collections=None, # pylint: disable=redefined-outer-name + use_resource=None, + **kwargs): + """A custom variable getter.""" + # Here, we switch the default graph to the outer graph and ask the + # variable scope in which the function is defined to give us the + # variable. The variable is stashed in extra_vars and returned to + # the caller. + # + # We capture these variables so that the variable definition is + # hoisted upward to the outer most graph. + with self._outer_graph.as_default(): + # pylint: disable=protected-access + var = self._vscope.get_variable( + vs._get_default_variable_store(), + name, + shape=shape, + dtype=dtype, + initializer=initializer, + reuse=reuse, + trainable=trainable, + collections=collections, + use_resource=use_resource) + self.extra_vars.append(var) + if (isinstance(var, resource_variable_ops.BaseResourceVariable) and + self._capture_resource_var_by_value): + # For resource-based variables read the variable outside the function + # and pass in the value. This ensures that the function is pure and + # differentiable. TODO(apassos) this may have performance problems if + # the function will only do embedding lookups on the variable. + return var.value() + return var + + def _create_op_internal( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True): + for i, x in enumerate(inputs): + if isinstance(x, ops.EagerTensor) or x.graph is not self: + inputs[i] = self.capture(x) + return super(_FuncGraph, self)._create_op_internal( + op_type, + inputs, + dtypes=dtypes, + input_types=input_types, + name=name, + attrs=attrs, + op_def=op_def, + compute_device=compute_device) + + def capture(self, tensor, name=None): + """Adds the given tensor to this graph and returns the captured tensor.""" + if tensor.ref() in self._captured: + # Captured already. + return self._captured[tensor.ref()] + elif self._capture_by_value: + return self._add_tensor_and_parents(tensor) + else: + return self._capture_tensor_as_extra_input(tensor, name) + + @property + def captures(self): + """Pairs of tensors and captured tensor.""" + return [(k.deref(), v) for k, v in self._captured.items()] + + def _capture_tensor_as_extra_input(self, tensor, name=None): + # Substitute with a placeholder. + self.extra_inputs.append(tensor) + # Hoist the new input placeholder out of any control flow context + # we're currently in. + with ops.control_dependencies(None): + ph = array_ops.placeholder( + tensor.dtype, shape=tensor.get_shape(), name=name) + # pylint: disable=protected-access + if isinstance(tensor, ops.EagerTensor): + handle_data = tensor._handle_data + if handle_data: + handle_data = handle_data.SerializeToString() + else: + with tensor.graph._c_graph.get() as c_graph: + handle_data = c_api.GetHandleShapeAndType(c_graph, + tensor._as_tf_output()) + + if handle_data: + with ph.graph._c_graph.get() as c_graph: + c_api.SetHandleShapeAndType(c_graph, ph._as_tf_output(), + compat.as_bytes(handle_data)) + # pylint: enable=protected-access + self.inputs.append(ph) + self._captured[tensor.ref()] = ph + self.extra_args.append(ph) + if _is_guaranteed_const(tensor): + with ops.control_dependencies(None): + return array_ops.guarantee_const(ph) + else: + return ph + + def _add_tensor_and_parents(self, tensor): + op = self._add_op_and_parents(tensor.op) + return op.outputs[tensor.value_index] + + def _add_op_and_parents(self, op: ops.Operation): + # pylint: disable=protected-access + op_def = graph_to_function_def._get_op_def(op) + if op._is_stateful and op not in self._allowlisted_stateful_ops: + raise ValueError(f"Cannot capture a stateful node (name:{op.name}, " + f"type:{op.type}) by value.") + elif op.type in ("Placeholder", "PlaceholderV2"): + raise ValueError(f"Cannot capture a placeholder (name:{op.name}, " + f"type:{op.type}) by value.") + # pylint: enable=protected-access + + captured_inputs = [self._add_tensor_and_parents(x) for x in op.inputs] + + captured_op = self._create_op_internal( + op.type, + captured_inputs, [o.dtype for o in op.outputs], + name=op.name, + attrs=op.node_def.attr, + op_def=op_def) + + for t, captured_t in zip(op.outputs, captured_op.outputs): + self._captured[t.ref()] = captured_t + + return captured_op + + +def func_graph_from_py_func(func, + arg_names, + arg_types, + name=None, + capture_by_value=False, + device=None, + colocation_stack=None, + container=None, + collections_ref=None, + arg_shapes=None, + allowlisted_stateful_ops=None, + capture_resource_var_by_value=True): + """Returns a _FuncGraph generated from `func`. + + Args: + func: A Python callable which constructs a TF function body. The arguments + must correspond to `arg_types`. Returns a value or list/tuple of values. + No returned value can be None. + arg_names: A sequence of strings for the function argument names. + arg_types: A sequence of the function's argument types. + name: The function name. If None, the name is derived from `func`. + capture_by_value: boolean. If True, captured values will be copied into the + function body. + device: device name or function. + colocation_stack: A colocation stack (list) the _FuncGraph should use. + container: A container name the _FuncGraph should start with. + collections_ref: A reference to a collections dict the _FuncGraph should + use internally. + arg_shapes: A sequence of the function's argument shapes. + allowlisted_stateful_ops: A set of ops that if stateful we ignore and + re-create. + capture_resource_var_by_value: Boolean (defaults to True). If False, + captured resource variable returns the handle instead of value. + + Returns: + A _FuncGraph. + + Raises: + ValueError: if func returns None. + """ + if not name: + name = function_utils.get_func_name(func) + func_graph = _FuncGraph(name, capture_by_value, allowlisted_stateful_ops, + capture_resource_var_by_value) + + with func_graph.as_default(), ops.device(device): + # pylint: disable=protected-access + if collections_ref is not None: + func_graph._collections = collections_ref + if container is not None: + func_graph._container = container + if colocation_stack is not None: + func_graph._colocation_stack = colocation_stack + # pylint: enable=protected-access + + if arg_shapes is None: + arg_shapes = [None] * len(arg_types) + + # Create placeholders for the function arguments. + for (argname, argtype, argshape) in zip(arg_names, arg_types, arg_shapes): + argholder = array_ops.placeholder(argtype, shape=argshape, name=argname) + func_graph.inputs.append(argholder) + # Call func and gather the output tensors. + with vs.variable_scope("", custom_getter=func_graph.getvar): + outputs = func(*func_graph.inputs) + + # There is no way of distinguishing between a function not returning + # anything and a function returning None in Python. + # We need to allow the former and ideally want to forbid the latter as + # it is most likely user error. + # TODO(iga): Consider adding a @NoOutput decorator on top of @Defun to + # allow users to explicitly mark the function as not returning anything. + # For now, we allow a single None return and interpret it as a function + # with no output. + if outputs is None: + outputs = [] + else: + # If func only returned one value, make it a tuple. + if not isinstance(outputs, (list, tuple)): + outputs = (outputs,) + if any(_ is None for _ in outputs): + raise ValueError(f"Function {name} can not return None.") + # Ensures each output is a Tensor in the function graph. + outputs = [ops.convert_to_tensor(t) for t in outputs] + outputs = [func_graph.capture(t) if t.graph is not func_graph else t + for t in outputs] + func_graph.outputs = outputs + return func_graph + + +def _is_guaranteed_const(tensor): + """Determines whether `tensor` is guaranteed to be a constant. + + A tensor is guaranteed to be a constant if either it was produced by + a `GuaranteeConst` op or if all of its children are guaranteed to be + constants. + + Args: + tensor: The tensor for which to determine const-ness. + + Returns: + True if `tensor` is guaranteed to be a constant, False otherwise. + """ + + if isinstance(tensor, ops.EagerTensor): + return False + + class Work(object): + + def __init__(self, op: ops.Operation, leaving): + self.op = op + self.leaving = leaving + + is_guaranteed_const = lambda op: op.node_def.op == "GuaranteeConst" + constants = set([]) + def all_inputs_const(op: ops.Operation): + # If all inputs of an op are guaranteed constants, then we can infer that + # the op produces a constant as well. + return op.inputs and all(inp.op in constants for inp in op.inputs) + + visited = set([]) + stack = [Work(tensor.op, leaving=False)] + while stack: + work = stack.pop() + if work.leaving: + if all_inputs_const(work.op): + constants.add(work.op) + continue + visited.add(work.op) + if is_guaranteed_const(work.op): + constants.add(work.op) + continue + + # This op will be revisited after all its inputs are checked for const-ness. + stack.append(Work(work.op, leaving=True)) + for inp in work.op.inputs: + if inp.op not in visited: + stack.append(Work(inp.op, leaving=False)) + return tensor.op in constants + + +def _call(sig, *inputs, **kwargs): + """Adds a node calling a function. + + This adds a `call` op to the default graph that calls the function + of signature `sig`, passing the tensors in `inputs` as arguments. + It returns the outputs of the call, which are one or more tensors. + + `sig` is OpDefArg.a `_DefinedFunction` object. + + You can pass an optional keyword parameter `name=string` to name the + added operation. + + You can pass an optional keyword parameter `noinline=True|False` to + instruct the runtime not to inline the function body into the call + site. + + Args: + sig: OpDefArg. The signature of the function. + *inputs: arguments to the function. + **kwargs: Optional keyword arguments. Can only contain 'name' or + 'noinline'. + + Returns: + A 2-element tuple. First element: a Tensor if the function returns a single + value; a list of Tensors if the function returns multiple value; the + Operation if the function returns no values. Second element: the Operation. + + Raises: + ValueError: if the arguments are invalid. + """ + if len(inputs) != len(sig.input_arg): + raise ValueError(f"Expected {len(sig.input_arg):d} arguments, got " + f"{len(inputs):d}.") + name = kwargs.pop("name", None) + g = ops.get_default_graph() + func_name = sig.name + if name is None: + name = func_name + attrs = _parse_kwargs_as_attrs(func_name, **kwargs) + output_types = [dtypes.DType(x.type) for x in sig.output_arg] + op = g._create_op_internal( # pylint: disable=protected-access + func_name, list(inputs), output_types, name=name, attrs=attrs, op_def=sig) + if op.outputs: + if len(op.outputs) == 1: + ret = op.outputs[0] + else: + ret = tuple(op.outputs) + else: + ret = op + return ret, op + + +def _from_definition(fdef, grad_func=None): + """Creates a _DefinedFunction initialized from a FunctionDef proto. + + Args: + fdef: a FunctionDef + grad_func: a _DefinedFunction or None + + Returns: + A _DefinedFunction representing fdef + """ + # TODO(iga): This method does major surgery on _DefinedFunction. + # Make it a named constructor using @classmethod of _DefinedFunction. + + # The Python callable is only needed to create a FunctionDef. Since we have + # the FunctionDef here, we don't need to set _DefinedFunction._func (nor do we + # have access to such a callable here). + func = None + argnames = [arg.name for arg in fdef.signature.input_arg] + input_types = tuple( + dtypes.as_dtype(arg.type) for arg in fdef.signature.input_arg) + func_name = fdef.signature.name + # Note: FunctionDefs do not include python gradient functions, so if the + # original _DefinedFunction included one it will not be reflected here. + python_grad_func = None + out_names = [arg.name for arg in fdef.signature.output_arg] + result = _DefinedFunction(func, argnames, input_types, func_name, grad_func, + python_grad_func, out_names) + # pylint: disable=protected-access + serialized = fdef.SerializeToString() + c_func = c_api.TF_FunctionImportFunctionDef(serialized) + result._c_func = c_api_util.ScopedTFFunction(c_func, func_name) + result._extra_inputs = [] + result._op_def = fdef.signature + # pylint: enable=protected-access + + return result + + +def from_library(lib): + """Creates _DefinedFunctions initialized from a FunctionDefLibrary proto. + + This method handles assigning the correct gradient functions to each + function. + + Args: + lib: a FunctionDefLibrary + + Returns: + A list of _DefinedFunctions + + Raises: + ValueError: `lib` is invalid + """ + if not lib.function and not lib.gradient: + return [] + + # function name -> FunctionDef proto + funcs = {fdef.signature.name: fdef for fdef in lib.function} + + # Validate that all references function names have function defs + for g in lib.gradient: + if g.function_name not in funcs: + raise ValueError(f"FunctionDefLibrary missing '{g.function_name}' " + f"FunctionDef\n{lib}") + if g.gradient_func not in funcs: + raise ValueError(f"FunctionDefLibrary missing '{g.gradient_func}' " + f"FunctionDef\n{lib}") + + # function name -> gradient function name + func_to_grad = collections.defaultdict(lambda: None) + # gradient function name -> names of functions having that grad function + grad_to_funcs = collections.defaultdict(list) + + for gdef in lib.gradient: + func_to_grad[gdef.function_name] = gdef.gradient_func + grad_to_funcs[gdef.gradient_func].append(gdef.function_name) + + # Start with functions without gradients + ready = [ + fdef for fdef in lib.function if func_to_grad[fdef.signature.name] is None + ] + if not ready: + raise ValueError( + f"FunctionDefLibrary contains cyclic gradient functions!\n{lib}") + # function name -> _DefinedFunction + initialized = {} + + while ready: + fdef = ready.pop() + name = fdef.signature.name + + grad = initialized.get(func_to_grad[name]) + if func_to_grad[name]: + assert grad + defined_func = _from_definition(fdef, grad_func=grad) + initialized[name] = defined_func + + ready.extend(funcs[f] for f in grad_to_funcs[name]) + + return initialized.values() + + +def _get_experimental_kwarg_as_attr(attr_name, value): + """Creates an AttrValue for a python object.""" + if isinstance(value, bool): + return attr_value_pb2.AttrValue(b=value) + elif isinstance(value, int): + return attr_value_pb2.AttrValue(i=value) + elif isinstance(value, float): + return attr_value_pb2.AttrValue(f=value) + elif isinstance(value, str): + return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) + else: + raise ValueError(f"Attribute {attr_name} must be bool, int, float, or " + f"str. Got {type(value)}.") + + +def _get_kwarg_as_str_attr(attr_name, value): + """Creates an AttrValue for a python object.""" + if isinstance(value, str): + return attr_value_pb2.AttrValue(s=compat.as_bytes(value)) + else: + raise ValueError(f"Attribute {attr_name} must be str. Got {type(value)}.") + + +def _parse_kwargs_as_attrs(func_name, **kwargs): + """Parses **kwargs into a node's attributes.""" + attrs = {} + + noinline = kwargs.pop("noinline", None) + if noinline is not None: + attrs["_noinline"] = attr_value_pb2.AttrValue(b=bool(noinline)) + + # For compatibility with previous behavior, Defun does not perform shape + # inference through its function call operations. + attrs["_disable_call_shape_inference"] = attr_value_pb2.AttrValue(b=True) + + compiled = kwargs.pop("compiled", None) + separate_compiled_gradients = kwargs.pop("separate_compiled_gradients", None) + if compiled is not None: + attrs["_XlaCompile"] = attr_value_pb2.AttrValue(b=bool(compiled)) + attrs["_XlaSeparateCompiledGradients"] = attr_value_pb2.AttrValue( + b=bool(separate_compiled_gradients)) + # Forward _XlaScope from enclosing context (if set), otherwise create new. + # pylint: disable=protected-access + if "_XlaScope" in ops.get_default_graph()._attr_scope_map: + attrs["_XlaScope"] = ops.get_default_graph()._attr_scope_map["_XlaScope"] + else: + attrs["_XlaScope"] = attr_value_pb2.AttrValue( + s=("function_%s" % func_name).encode()) + # pylint: enable=protected-access + + kwargs_keys = list(kwargs.keys()) + for key in kwargs_keys: + if key.startswith("experimental_"): + attrs[key] = _get_experimental_kwarg_as_attr(key, kwargs[key]) + del kwargs[key] + # Support for https://github.com/tensorflow/community/pull/113/files. + elif key == "_implements" or key == "_reference": + attrs[key] = _get_kwarg_as_str_attr(key, kwargs[key]) + del kwargs[key] + if kwargs: + raise ValueError(f"Unknown keyword arguments: {kwargs.keys()}.") + return attrs + + +def get_extra_vars(): + """Returns the captured variables by the function. + + Returns: + If the default graph is being used to define a function, the + returned list of variables are those created inside the function + body so far. Otherwise, returns an empty list. + """ + g = ops.get_default_graph() + if isinstance(g, _FuncGraph): + return g.extra_vars + else: + return [] + + +def get_extra_inputs(): + """Returns the captured input tensors by the function. + + Returns: + If the default graph is being used to define a function, the + returned list of tensors are those accessed inside the function body + but defined outside the function body so far. Otherwise, returns an + empty list. + """ + g = ops.get_default_graph() + if isinstance(g, _FuncGraph): + return g.extra_inputs + else: + return [] + + +def get_extra_args(): + """Returns the corresponding function arguments for the captured inputs. + + Returns: + If the default graph is being used to define a function, the + returned list of place holders are those used inside the function + body corresponding those returned by get_extra_inputs(). Otherwise, + returns an empty list. + """ + g = ops.get_default_graph() + if isinstance(g, _FuncGraph): + return g.extra_args + else: + return [] + + +def _type_list_to_str(types): + if any(_ not in _DTYPE_TO_STR for _ in types): + unsupported_types = [type_ for type_ in types if type_ not in _DTYPE_TO_STR] + raise ValueError(f"Unsupported dtypes {unsupported_types} in " + "`types`. Supported dtypes are " + f"{_DTYPE_TO_STR.keys()}.") + return "".join(_DTYPE_TO_STR[_] for _ in types) + + +# NOTE: The list needs to be extended when more data types are added. +_DTYPE_TO_STR = { + dtypes.float16: "f16", + dtypes.float32: "f32", + dtypes.float64: "f64", + dtypes.int32: "i32", + dtypes.uint8: "i8", + dtypes.uint16: "u16", + dtypes.uint32: "u32", + dtypes.uint64: "u64", + dtypes.int16: "i16", + dtypes.int8: "i8", + dtypes.string: "s", + dtypes.complex64: "c64", + dtypes.complex128: "c128", + dtypes.int64: "i64", + dtypes.bool: "b", + dtypes.qint8: "qi8", + dtypes.quint8: "qu8", + dtypes.qint16: "qi16", + dtypes.quint16: "qu16", + dtypes.qint32: "qi32", + dtypes.bfloat16: "b16", + dtypes.float8_e5m2: "f8e5m2", + dtypes.float8_e4m3fn: "f8e4m3fn", + dtypes.int4: "i4", + dtypes.uint4: "u4", +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/function_def_to_graph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/function_def_to_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..61049e4d83a3e80a99f72ca697ea7067a1578cff --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/function_def_to_graph.py @@ -0,0 +1,409 @@ +# 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. +# ============================================================================= +"""Utility to convert FunctionDef to GraphDef and Graph.""" + +import itertools + + +from tensorflow.core.framework import function_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import tensor_shape_pb2 +from tensorflow.core.framework import types_pb2 +from tensorflow.core.framework import versions_pb2 +from tensorflow.python.eager import context +from tensorflow.python.framework import cpp_shape_inference_pb2 +from tensorflow.python.framework import importer +from tensorflow.python.framework import ops +from tensorflow.python.framework import versions +from tensorflow.python.framework.func_graph import FuncGraph +from tensorflow.python.ops import resource_variable_ops + + +def function_def_to_graph( + fdef, + structured_input_signature=None, + structured_outputs=None, + input_shapes=None, + propagate_device_spec=False, + include_library_functions=False, +): + """Converts a FunctionDef to a FuncGraph (sub-class Graph). + + The returned FuncGraph's `name`, `inputs` and `outputs` fields will be set. + The input tensors are represented as placeholders. + + Note: `FuncGraph.inputs` and `FuncGraph.captures` are not set and may be set + by the caller. + + Args: + fdef: FunctionDef. + structured_input_signature: Optional. The structured input signature to use + for initializing the FuncGraph. See the docstring for FuncGraph for more + information. + structured_outputs: Optional. The structured outputs to use for initializing + the FuncGraph. See the docstring for FuncGraph for more information. + input_shapes: Optional. A list of TensorShape objects of the shapes of + function inputs. Defaults to the function's "_input_shapes" attribute. If + specified, its length must match length of `fdef.signature.input_arg`. If + a shape is None, the corresponding input placeholder will have unknown + shape. + propagate_device_spec: Optional. Whether to propagate assigned device + information when constructing a new Graph from a FunctionDef. + include_library_functions: Optional. Whether to include library functions in + the output FuncGraph. In graph mode, the library functions will be found + from outer graph. In eager mode, the library functions will be found from + eager context. + + Returns: + A FuncGraph. + """ + func_graph = FuncGraph(fdef.signature.name, + structured_input_signature=structured_input_signature, + structured_outputs=structured_outputs) + if input_shapes is None: + input_shapes_attr = fdef.attr.get("_input_shapes", None) + if input_shapes_attr is not None: + raw_input_shapes = input_shapes_attr.list.shape + + # Replace resource handle shapes in the inputs to disable shape inference. + # Setting the shape to either the variable handle shape (which is always + # `[]`) or the variable shape can cause shape inference issues. + input_shapes = [] + for input_shape, arg_def in zip(raw_input_shapes, + fdef.signature.input_arg): + if arg_def.type == types_pb2.DT_RESOURCE and arg_def.handle_data: + input_shapes.append(None) + else: + input_shapes.append(input_shape) + + graph_def, nested_to_flat_tensor_name = function_def_to_graph_def( + fdef, input_shapes, include_library_functions=include_library_functions + ) + + with func_graph.as_default(): + # Add all function nodes to the graph. + importer.import_graph_def_for_function( + graph_def, name="", propagate_device_spec=propagate_device_spec) + + # Initialize fields specific to FuncGraph. + + # inputs + input_tensor_names = [ + nested_to_flat_tensor_name[arg.name] for arg in fdef.signature.input_arg + ] + func_graph.inputs = [ + func_graph.get_tensor_by_name(name) for name in input_tensor_names + ] + + # outputs + output_tensor_names = [ + nested_to_flat_tensor_name[fdef.ret[arg.name]] + for arg in fdef.signature.output_arg + ] + func_graph.outputs = [ + func_graph.get_tensor_by_name(name) for name in output_tensor_names + ] + func_graph.control_outputs = [ + func_graph.get_operation_by_name(fdef.control_ret[ret_name]) + for ret_name in fdef.signature.control_output + ] + + _set_handle_data(func_graph, fdef) + + for node in graph_def.node: + output_shapes = node.attr.get("_output_shapes", None) + if output_shapes is not None: + op = func_graph.get_operation_by_name(node.name) + # _output_shapes for functions can sometimes be too long because the + # output-intermediates-for-gradients version of the function was + # substituted before saving. We'll accept that here. (See b/133666530). + for output_index, shape in enumerate( + output_shapes.list.shape[:len(op.outputs)]): + op.outputs[output_index].set_shape(shape) + output_names = {} + for ret_arg_def, tensor_name in zip( + fdef.signature.output_arg, output_tensor_names): + output_names[ops.tensor_id( + func_graph.get_tensor_by_name(tensor_name))] = ( + ret_arg_def.name) + func_graph._output_names = output_names # pylint: disable=protected-access + return func_graph + + +def is_function(fname, graph): + """Checks for a function definition with `fname` in the current context.""" + if context.executing_eagerly(): + # Eager mode: use eager context as the single source of truth. + return context.context().has_function(fname) + else: + # Graph mode: use outer graphs as the single source of truth. + while graph is not None: + if graph._is_function(fname): # pylint: disable=protected-access + return True + if hasattr(graph, "outer_graph"): + graph = graph.outer_graph + else: + return False + + +def get_function_def(fname, graph): + """Gets a function definition with `fname` in the current context.""" + if context.executing_eagerly(): + # Eager mode: use eager context as the single source of truth. + if context.context().has_function(fname): + return context.context().get_function_def(fname) + else: + # Graph mode: use outer graphs as the single source of truth. + while graph is not None: + if graph._is_function(fname): # pylint: disable=protected-access + return graph._get_function(fname).cached_definition # pylint: disable=protected-access + graph = getattr(graph, "outer_graph", None) + + +def copy_function_def_to_graph_def_recursively( + func_name, graph_def, copied_functions, default_graph=None): + """Recursively copies `FunctionDef`s to `GraphDef`. + + It copies the outermost `FunctionDef` and all nested `FunctionDef`s to + `graph_def`. The `copied_function` enforces that every `FunctionDef` will be + copied at most once. The `FunctionDef`s will be found from `default_graph` if + this function was called in graph mode or from eager context if this function + was called in eager mode. + + Args: + func_name: The signature name of FunctionDef to be copied to `graph_def`. + graph_def: The GraphDef that will contain all `FunctionDef`s in its library. + copied_functions: A set contains all copied function names. + default_graph: The `tf.Graph` where all `FunctionDef`s will be found + in graph mode. Not used in eager mode. + """ + # Custom ops may contain a func attr with an empty fname. + if func_name and not is_function(func_name, default_graph): + raise ValueError(f"Function {func_name} was not found. Please make " + "sure the FunctionDef `fdef` is correct.") + + # If `copied_functions` contains `func_name`, the FunctionDef has already + # been added to GraphDef so we simply return here. + if func_name in copied_functions: + return + + copied_functions.add(func_name) + func_def = get_function_def(func_name, default_graph) + graph_def.library.function.add().CopyFrom(func_def) + + for node_def in func_def.node_def: + op_def = default_graph.op_def_for_type(node_def.op) + for attr in op_def.attr: + if attr.type == "func": + func_name = node_def.attr[attr.name].func.name + copy_function_def_to_graph_def_recursively( + func_name, graph_def, copied_functions, default_graph) + + elif attr.type == "list(func)": + for fn in node_def.attr[attr.name].list.func: + func_name = fn.name + copy_function_def_to_graph_def_recursively( + func_name, graph_def, copied_functions, default_graph) + + +def function_def_to_graph_def( + fdef, input_shapes=None, include_library_functions=False +): + """Convert a FunctionDef to a GraphDef. + + Steps: + 1. Creates placeholder nodes corresponding to inputs in + `FunctionDef.signature.input_arg`. + 2. Adds NodeDefs in `FunctionDef.node_def` to `GraphDef.node`. + 3. Renames inputs of all nodes to use the convention of GraphDef instead of + FunctionDef. See comment on `FunctionDef.node_def` on how the tensor naming + in FunctionDefs is different from GraphDefs. + + Args: + fdef: FunctionDef. + input_shapes: Optional. A list of TensorShape objects of the shapes of + function inputs. If specified, its length must match length of + `fdef.signature.input_arg`. If a shape is None, the corresponding input + placeholder will have unknown shape. + include_library_functions: Optional. If enabled, copy `fdef` and its + nested `FunctionDef`s to the library functions of the returned `GraphDef`. + In graph mode, the functions will be found from outer graph. In eager + mode, the functions will be found from eager context. + + Returns: + A tuple of (GraphDef, dict). The dict contains a mapping + from nested tensor names (in FunctionDef) to flattened names (in GraphDef). + + Raises: + ValueError: If the length of input_shapes does not match the number of + input_args or if the FunctionDef is invalid. + """ + graph_def = graph_pb2.GraphDef() + graph_def.versions.CopyFrom( + versions_pb2.VersionDef( + producer=versions.GRAPH_DEF_VERSION, + min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER)) + + default_graph = ops.get_default_graph() + + copied_functions = set() + + if input_shapes and len(input_shapes) != len(fdef.signature.input_arg): + raise ValueError("Length of `input_shapes` must match the number " + f"of `input_arg`s in `fdef`. Got " + f"{len(input_shapes)} `input_shapes` and " + f"{len(fdef.signature.input_arg)} `input_arg`s.") + + # 1. Create placeholders for input nodes. + for i, arg_def in enumerate(fdef.signature.input_arg): + node_def = graph_def.node.add() + node_def.name = arg_def.name + node_def.op = "Placeholder" + node_def.attr["dtype"].type = arg_def.type + if input_shapes and input_shapes[i] is not None: + input_shape = input_shapes[i] + if not isinstance(input_shape, tensor_shape_pb2.TensorShapeProto): + input_shape = input_shape.as_proto() + node_def.attr["shape"].shape.CopyFrom(input_shape) + arg_attrs = fdef.arg_attr[i].attr + for k in arg_attrs: + # Only copy internal attributes. Normal attributes for nodes cannot be + # applied to these Placeholder nodes. + if k == "_output_shapes": + if arg_attrs[k].WhichOneof("value") == "list": + node_def.attr["shape"].shape.CopyFrom(arg_attrs[k].list.shape[0]) + elif arg_attrs[k].WhichOneof("value") == "shape": + node_def.attr["shape"].shape.CopyFrom(arg_attrs[k].shape) + elif k.startswith("_"): + node_def.attr[k].CopyFrom(arg_attrs[k]) + + # 2. Copy all body NodeDefs to the GraphDef. + graph_def.node.extend(fdef.node_def) + + # 3. Perform the renaming. + + # Build the tensor name mapping then flatten the tensor names. + # See comment on `FunctionDef.node_def` on how the tensor naming in + # FunctionDefs is different from GraphDefs. + nested_to_flat_tensor_name = {} + + for arg_def in fdef.signature.input_arg: + nested_to_flat_tensor_name[arg_def.name] = "{}:0".format(arg_def.name) + control_name = "^" + arg_def.name + nested_to_flat_tensor_name[control_name] = control_name + + for node_def in fdef.node_def: + graph = default_graph + while True: + f = graph._functions.get(node_def.op, None) # pylint: disable=protected-access + if f is not None or not hasattr(graph, "outer_graph"): + break + graph = graph.outer_graph + + if f is not None: + fdef = f.cached_definition + op_def = fdef.signature + if node_def.op not in copied_functions: + # Since this function is referenced as an op type, we have no choice but + # to copy it into the GraphDef if we want downstream tools to process + # it. + graph_def.library.function.add().CopyFrom(fdef) + copied_functions.add(node_def.op) + if getattr(f, "grad_func_name", None): + grad_def = function_pb2.GradientDef() + grad_def.function_name = f.name + grad_def.gradient_func = f.grad_func_name + graph_def.library.gradient.extend([grad_def]) + else: + op_def = default_graph.op_def_for_type(node_def.op) # pylint: disable=protected-access + + for attr in op_def.attr: + if attr.type == "func": + fname = node_def.attr[attr.name].func.name + # Custom ops may contain a func attr with an empty fname. + if fname and not is_function(fname, default_graph): + raise ValueError(f"Function {fname} was not found. Please make sure " + "the FunctionDef `fdef` is correct.") + if include_library_functions: + copy_function_def_to_graph_def_recursively( + fname, graph_def, copied_functions, default_graph) + + elif attr.type == "list(func)": + for fn in node_def.attr[attr.name].list.func: + fname = fn.name + # Custom ops may contain a func attr with an empty fname. + if fname and not is_function(fname, default_graph): + raise ValueError(f"Function {fname} was not found. Please make " + "sure the FunctionDef `fdef` is correct.") + if include_library_functions: + copy_function_def_to_graph_def_recursively( + fname, graph_def, copied_functions, default_graph) + + # Iterate over output_args in op_def to build the map. + # Index of the output tensor in the flattened list of *all* output + # tensors of the op. + flattened_index = 0 + for arg_def in op_def.output_arg: + num_args = _get_num_args(arg_def, node_def) + for i in range(num_args): + # Map tensor names from "node_name:output_arg_name:index" to + # "node_name:flattened_index". + nested_name = "{}:{}:{}".format(node_def.name, arg_def.name, i) + flat_name = "{}:{}".format(node_def.name, flattened_index) + nested_to_flat_tensor_name[nested_name] = flat_name + flattened_index += 1 + control_name = "^" + node_def.name + nested_to_flat_tensor_name[control_name] = control_name + + # Update inputs of all nodes in graph. + for node_def in graph_def.node: + for i in range(len(node_def.input)): + node_def.input[i] = nested_to_flat_tensor_name[node_def.input[i]] + + return graph_def, nested_to_flat_tensor_name + + +# Based on implementation in core/framework/node_def_util.cc::ComputeArgRange. +def _get_num_args(arg_def, node_def): + if arg_def.number_attr: + return node_def.attr[arg_def.number_attr].i + elif arg_def.type_list_attr: + return len(node_def.attr[arg_def.type_list_attr].list.type) + elif arg_def.type_attr or arg_def.type != types_pb2.DT_INVALID: + return 1 + else: + raise ValueError(f"Invalid arg_def:\n\n{arg_def}. Please make sure the " + "FunctionDef `fdef` is correct.") + + +def _set_handle_data(func_graph, fdef): + """Adds handle data for resource type inputs and outputs.""" + # The shape of the handle itself is [], while the variable shape is + # saved in `handle_data`. Previously, the shape of the resource handle + # was set to `None`. Correct both shapes here. + for tensor, arg_def in itertools.chain( + zip(func_graph.inputs, fdef.signature.input_arg), + zip(func_graph.outputs, fdef.signature.output_arg)): + if arg_def.handle_data: + tensor.set_shape([]) + + shape_and_dtype = arg_def.handle_data[0] + handle_data = cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData() + handle_data.is_set = True + handle_data.shape_and_type.append( + cpp_shape_inference_pb2.CppShapeInferenceResult.HandleShapeAndType( + shape=shape_and_dtype.shape, dtype=shape_and_dtype.dtype)) + resource_variable_ops._set_handle_shapes_and_types( # pylint: disable=protected-access + tensor, handle_data, True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/gpu_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/gpu_util.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3707f16c482245c57674b065ae9d5146d34bdb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/gpu_util.py @@ -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. +# ============================================================================== +"""Contains GPU utility functions.""" + +import collections +import re + + +# Matches the DeviceAttributes.physical_device_desc field. +_PHYSICAL_DEVICE_DESCRIPTION_REGEX = re.compile( + r'name: ([^,]*), (?:.*compute capability: (\d+)\.(\d+))?') + + +# compute_capability is a (major version, minor version) pair, or None if this +# is not an Nvidia GPU. +GpuInfo = collections.namedtuple('gpu_info', ['name', 'compute_capability']) + + +def compute_capability_from_device_desc(device_attrs): + """Returns the GpuInfo given a DeviceAttributes proto. + + Args: + device_attrs: A DeviceAttributes proto. + + Returns + A gpu_info tuple. Both fields are None if `device_attrs` does not have a + valid physical_device_desc field. + """ + # TODO(jingyue): The device description generator has to be in sync with + # this file. Another option is to put compute capability in + # DeviceAttributes, but I avoided that to keep DeviceAttributes + # target-independent. Reconsider this option when we have more things like + # this to keep in sync. + # LINT.IfChange + match = _PHYSICAL_DEVICE_DESCRIPTION_REGEX.search( + device_attrs.physical_device_desc) + # LINT.ThenChange(//tensorflow/core/common_runtime/gpu/gpu_device.cc) + if not match: + return GpuInfo(None, None) + cc = (int(match.group(2)), int(match.group(3))) if match.group(2) else None + return GpuInfo(match.group(1), cc) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_io.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_io.py new file mode 100644 index 0000000000000000000000000000000000000000..05b764bb5eb77e06becd18ca9b0afc799c8b5c27 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_io.py @@ -0,0 +1,84 @@ +# 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. +# ============================================================================== + +"""Utility functions for reading/writing graphs.""" +import os +import os.path +import sys + +from google.protobuf import text_format +from tensorflow.python.framework import byte_swap_tensor +from tensorflow.python.framework import ops +from tensorflow.python.lib.io import file_io +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('io.write_graph', v1=['io.write_graph', 'train.write_graph']) +def write_graph(graph_or_graph_def, logdir, name, as_text=True): + """Writes a graph proto to a file. + + The graph is written as a text proto unless `as_text` is `False`. + + ```python + v = tf.Variable(0, name='my_variable') + sess = tf.compat.v1.Session() + tf.io.write_graph(sess.graph_def, '/tmp/my-model', 'train.pbtxt') + ``` + + or + + ```python + v = tf.Variable(0, name='my_variable') + sess = tf.compat.v1.Session() + tf.io.write_graph(sess.graph, '/tmp/my-model', 'train.pbtxt') + ``` + + Args: + graph_or_graph_def: A `Graph` or a `GraphDef` protocol buffer. + logdir: Directory where to write the graph. This can refer to remote + filesystems, such as Google Cloud Storage (GCS). + name: Filename for the graph. + as_text: If `True`, writes the graph as an ASCII proto. + + Returns: + The path of the output proto file. + """ + if isinstance(graph_or_graph_def, ops.Graph): + graph_def = graph_or_graph_def.as_graph_def() + else: + graph_def = graph_or_graph_def + + if sys.byteorder == 'big': + if hasattr(graph_def, 'node'): + byte_swap_tensor.swap_tensor_content_in_graph_node( + graph_def, 'big', 'little' + ) + else: + byte_swap_tensor.swap_tensor_content_in_graph_function( + graph_def, 'big', 'little' + ) + + # gcs does not have the concept of directory at the moment. + if not logdir.startswith('gs:'): + file_io.recursive_create_dir(logdir) + path = os.path.join(logdir, name) + if as_text: + file_io.atomic_write_string_to_file(path, + text_format.MessageToString( + graph_def, float_format='')) + else: + file_io.atomic_write_string_to_file( + path, graph_def.SerializeToString(deterministic=True)) + return path diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_to_function_def.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_to_function_def.py new file mode 100644 index 0000000000000000000000000000000000000000..9eac159ef156c98ee49ba5947f946317884db401 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_to_function_def.py @@ -0,0 +1,183 @@ +# 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. +# ============================================================================= +"""Utility to convert a Graph to a FunctionDef.""" + +import re + +from tensorflow.core.framework import function_pb2 +from tensorflow.core.framework import op_def_pb2 +from tensorflow.python.framework import op_def_registry + + +def _make_argname_from_tensor_name(name): + return re.sub(":0$", "", name).replace(":", "_o") + + +def _tensor_to_argdef(t, name=None, used_names=None): + """Convert tensor t to an argdef, with a specified name or a unique name.""" + arg = op_def_pb2.OpDef.ArgDef() + if name is None: + arg.name = _make_argname_from_tensor_name(t.name) + if used_names is not None: + if arg.name in used_names: + i = 0 + while True: + new_name = "%s_U%d" % (arg.name, i) + if new_name not in used_names: + arg.name = new_name + break + i += 1 + used_names.add(arg.name) + else: + arg.name = name + arg.type = t.dtype.as_datatype_enum + return arg + + +def _is_in_placeholders(op, func_arg_placeholders): + """Checks whether any output of this op is in func_arg_placeholders.""" + return op.values() and any(x.name in func_arg_placeholders + for x in op.values()) + + +def _get_node_def(op): + return op.node_def # pylint: disable=protected-access + + +def _get_op_def(op): + return op.op_def or op_def_registry.get(op.type) + + +def _create_input_dict(function_graph, + func_arg_placeholders, + initial_value=None): + """Create a mapping from graph tensor names to function tensor names.""" + if initial_value is None: + input_dict = {} + else: + input_dict = dict(initial_value) + for op in function_graph.get_operations(): + if _is_in_placeholders(op, func_arg_placeholders): + input_dict[op.name] = op.name + else: + op_def = _get_op_def(op) + attrs = _get_node_def(op).attr + o = 0 + for arg_def in op_def.output_arg: + if arg_def.number_attr: + num = attrs[arg_def.number_attr].i + elif arg_def.type_list_attr: + num = len(attrs[arg_def.type_list_attr].list.type) + else: + num = 1 + for i in range(num): + result = "%s:%s:%d" % (op.name, arg_def.name, i) + input_dict[op.values()[o].name] = result + if o == 0: + input_dict[op.name] = result + o += 1 + return input_dict + + +def _add_op_node(op, func, input_dict): + """Converts an op to a function def node and add it to `func`.""" + # Add an entry in func.node_def + + # Note that extend() makes a copy in this case, see: + # https://developers.google.com/protocol-buffers/docs/reference/python-generated#repeated-message-fields + func.node_def.extend([_get_node_def(op)]) + node_def = func.node_def[-1] + for i in range(len(node_def.input)): + if not node_def.input[i].startswith("^"): + assert node_def.input[i] in input_dict, ("%s missing from %s" % + (node_def.input[i], + input_dict.items())) + node_def.input[i] = input_dict[node_def.input[i]] + # The function is stateful if any of its operations are stateful. + # NOTE(mrry): The "Const" node typically does not have an `OpDef` associated + # with it, so we assume any nodes without an `OpDef` are stateless. + # TODO(skyewm): Remove the `is not None` test after we transition to the C + # API. + if op.op_def is not None and op.op_def.is_stateful: + func.signature.is_stateful = True + + +def graph_to_function_def(graph, operations, inputs, outputs, out_names=None): + """Returns `graph` as a `FunctionDef` protocol buffer. + + This method creates a [`FunctionDef`]( + https://www.tensorflow.org/code/tensorflow/core/framework/function.proto) + protocol buffer that contains all the ops in `operations`. The + operations become the body of the function. + + The arguments `inputs` and `outputs` will be listed as the inputs + and outputs tensors of the function. They must be lists of + tensors present in the graph. The lists can optionally be empty. + + Args: + graph: Graph. + operations: the operations to put in the function. Must be a subset of + the operations in the graph. + inputs: List of tensors. Inputs to the function. + outputs: List of tensors. Outputs of the function. + out_names: Optional list of string names for the outputs. + + Returns: + A FunctionDef protocol buffer. + + Raises: + ValueError: if out_names is specified and the wrong length. + """ + func = function_pb2.FunctionDef() + func.signature.name = "_" + used_names = set() + func.signature.input_arg.extend( + [_tensor_to_argdef(i, used_names=used_names) for i in inputs]) + # Initializes the input map with all placeholder input tensors. + initial_dict = {} + for o, m in zip(inputs, func.signature.input_arg): + initial_dict[o.name] = m.name + if out_names is None: + used_names = set() + func.signature.output_arg.extend( + [_tensor_to_argdef(o, used_names=used_names) for o in outputs]) + elif len(outputs) != len(out_names): + raise ValueError( + f"out_names must be either empty or equal in size to outputs. " + f"len(out_names) = {len(out_names)} len(outputs) = {len(outputs)}") + elif len(out_names) != len(set(out_names)): + raise ValueError( + f"Must not have duplicates in out_names. Received: {out_names}") + else: + func.signature.output_arg.extend( + [_tensor_to_argdef(o, name=n) for o, n in zip(outputs, out_names)]) + func_arg_placeholders = set(i.name for i in inputs) + input_dict = _create_input_dict(graph, func_arg_placeholders, + initial_value=initial_dict) + + for op in operations: + if _is_in_placeholders(op, func_arg_placeholders): + continue + _add_op_node(op, func, input_dict) + + if out_names is None: + for index, o in enumerate(outputs): + k = func.signature.output_arg[index].name + func.ret[k] = input_dict[o.name] + else: + for o, n in zip(outputs, out_names): + func.ret[n] = input_dict[o.name] + + return func diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_util.py new file mode 100644 index 0000000000000000000000000000000000000000..fe1abe3e9f98778b00920eb871e676395569528f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_util.py @@ -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. +# ============================================================================== + +"""Helpers to manipulate a tensor graph in python. + +API docstring: tensorflow.graph_util +""" + + +# pylint: disable=unused-import +from tensorflow.python.framework.graph_util_impl import extract_sub_graph +from tensorflow.python.framework.graph_util_impl import graph_defs_equal +from tensorflow.python.framework.graph_util_impl import must_run_on_cpu +from tensorflow.python.framework.graph_util_impl import remove_training_nodes +from tensorflow.python.framework.graph_util_impl import tensor_shape_from_node_def_name +# pylint: enable=unused-import diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_util_impl.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_util_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad402b978bd0275957a91fd6a7d88e23628a6c3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/graph_util_impl.py @@ -0,0 +1,432 @@ +# 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. +# ============================================================================== +"""Helpers to manipulate a tensor graph in python. +""" + +import copy +import re + +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import node_def_pb2 +from tensorflow.python.framework import _proto_comparators +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + +GraphDef = tf_export(v1=["GraphDef"])(graph_pb2.GraphDef) + +_VARIABLE_OPS = { + "Assign", + "AssignAdd", + "AssignSub", + "Queue", + "ScatterAdd", + "ScatterSub", + "ScatterUpdate", + "TruncatedNormal", + "Variable", + "VariableV2", +} + +_CONTROL_FLOW_OP_NAMES_OR_IDENTITY = [ + "Switch", + "Enter", + "Exit", + "Identity", + "Merge", + "NextIteration", +] + +_DEPRECATION_MSG = ( + "This API was designed for TensorFlow v1. See " + "https://www.tensorflow.org/guide/migrate for instructions on how to " + "migrate your code to TensorFlow v2.") + + +def _is_variable_op(op): + """Returns true if 'op' refers to a Variable node.""" + return op in _VARIABLE_OPS + +# GraphDef protobuf docstring. +graph_pb2.GraphDef.__doc__ = """\ +A protobuf containing the graph of operations. + +@compatibility(TF2) +This API is not available in TensorFlow 2.x. + +You should not need to use `GraphDef`s directly in TF2. To load `GraphDef`s in +TF2, use SavedModel. The SavedModel contains the `GraphDef`. + +Before: + +```python +with tf.io.gfile.GFile('/tmp/graph.pb', 'rb') as f: + graph_def = tf.compat.v1.GraphDef() + graph_def.ParseFromString(f.read()) +``` + +After: + +```python +tf.saved_model.load('/tmp/saved_model') +``` + +If you would like to create a `GraphDef` in TF2, use `tf.function` and +`get_concrete_function`. + +>>> @tf.function +>>> def f(x): +>>> return x +>>> +>>> graph_def = f.get_concrete_function(1.).graph.as_graph_def() +>>> print(graph_def) + +@end_compatibility + +""" + + +@deprecation.deprecated( + date=None, + instructions=_DEPRECATION_MSG) +@tf_export(v1=["graph_util.must_run_on_cpu"]) +def must_run_on_cpu(node, pin_variables_on_cpu=False): + """Returns True if the given node_def must run on CPU, otherwise False. + + Args: + node: The node to be assigned to a device. Could be either an ops.Operation + or NodeDef. + pin_variables_on_cpu: If True, this function will return False if node_def + represents a variable-related op. + + Returns: + True if the given node must run on CPU, otherwise False. + """ + + if isinstance(node, ops.Operation): + node_def = node.node_def + else: + assert isinstance(node, node_def_pb2.NodeDef) + node_def = node + + # If the op is a variable-related op, should we pin it on CPU? + if pin_variables_on_cpu and _is_variable_op(node_def.op): + return True + + # Constant operations producing a string or int32 must run on CPU. + if node_def.op == "Const": + # Get the value of the 'dtype' attr + dtype = node_def.attr["dtype"].type + if dtype == dtypes.string or dtype == dtypes.int32: + return True + + if node_def.op in ["DynamicStitch", "ParallelDynamicStitch"]: + dtype = node_def.attr["T"].type + if dtype == dtypes.int32: + # DynamicStitch on GPU only works for int32 values. + return True + + if node_def.op in ["Cast"]: + dtype = node_def.attr["SrcT"].type + if dtype == dtypes.int32: + # Cast on GPU does not works for int32 values. + return True + return False + + +################################################################################ +# +# device functions for use in with g.device(...) +# +################################################################################ + + +def _node_name(n): + if n.startswith("^"): + return n[1:] + else: + return n.split(":")[0] + + +def _get_colocated_node_name(colocated_node_name): + """Decodes colocated node name and returns it without loc:@ prepended.""" + colocated_node_decoded = colocated_node_name.decode("utf-8") + if colocated_node_decoded.startswith("loc:@"): + return colocated_node_decoded[5:] + return colocated_node_decoded + + +def _extract_graph_summary(graph_def): + """Extracts useful information from the graph and returns them.""" + name_to_input_name = {} # Keyed by the dest node name. + name_to_node = {} # Keyed by node name. + + # Keeps track of node sequences. It is important to still output the + # operations in the original order. + name_to_seq_num = {} # Keyed by node name. + seq = 0 + for node in graph_def.node: + n = _node_name(node.name) + name_to_node[n] = node + name_to_input_name[n] = [_node_name(x) for x in node.input] + # Prevent colocated nodes from being lost. + if "_class" in node.attr: + for colocated_node_name in node.attr["_class"].list.s: + name_to_input_name[n].append( + _get_colocated_node_name(colocated_node_name)) + name_to_seq_num[n] = seq + seq += 1 + return name_to_input_name, name_to_node, name_to_seq_num + + +def _assert_nodes_are_present(name_to_node, nodes): + """Assert that nodes are present in the graph.""" + for d in nodes: + assert d in name_to_node, "%s is not in graph" % d + + +def _bfs_for_reachable_nodes(target_nodes, name_to_input_name): + """Breadth first search for reachable nodes from target nodes.""" + nodes_to_keep = set() + # Breadth first search to find all the nodes that we should keep. + next_to_visit = list(target_nodes) + while next_to_visit: + node = next_to_visit[0] + del next_to_visit[0] + if node in nodes_to_keep: + # Already visited this node. + continue + nodes_to_keep.add(node) + if node in name_to_input_name: + next_to_visit += name_to_input_name[node] + return nodes_to_keep + + +@deprecation.deprecated( + date=None, + instructions=_DEPRECATION_MSG) +@tf_export(v1=["graph_util.extract_sub_graph"]) +def extract_sub_graph(graph_def, dest_nodes): + """Extract the subgraph that can reach any of the nodes in 'dest_nodes'. + + Args: + graph_def: A graph_pb2.GraphDef proto. + dest_nodes: An iterable of strings specifying the destination node names. + Returns: + The GraphDef of the sub-graph. + + Raises: + TypeError: If 'graph_def' is not a graph_pb2.GraphDef proto. + """ + + if not isinstance(graph_def, graph_pb2.GraphDef): + raise TypeError("graph_def must be a graph_pb2.GraphDef proto, but got " + f"type {type(graph_def)}.") + + if isinstance(dest_nodes, str): + raise TypeError("dest_nodes must be an iterable of strings, but got " + f"type {type(dest_nodes)}.") + + name_to_input_name, name_to_node, name_to_seq_num = _extract_graph_summary( + graph_def) + _assert_nodes_are_present(name_to_node, dest_nodes) + + nodes_to_keep = _bfs_for_reachable_nodes(dest_nodes, name_to_input_name) + + nodes_to_keep_list = sorted( + list(nodes_to_keep), key=lambda n: name_to_seq_num[n]) + # Now construct the output GraphDef + out = graph_pb2.GraphDef() + for n in nodes_to_keep_list: + out.node.extend([copy.deepcopy(name_to_node[n])]) + out.library.CopyFrom(graph_def.library) + out.versions.CopyFrom(graph_def.versions) + + return out + + +@deprecation.deprecated( + date=None, + instructions=_DEPRECATION_MSG) +@tf_export(v1=["graph_util.tensor_shape_from_node_def_name"]) +def tensor_shape_from_node_def_name(graph, input_name): + """Convenience function to get a shape from a NodeDef's input string.""" + # To get a tensor, the name must be in the form :, for example + # 'Mul:0'. The GraphDef input strings don't always have the port specified + # though, so if there isn't a colon we need to add a default ':0' to the end. + if ":" not in input_name: + canonical_name = input_name + ":0" + else: + canonical_name = input_name + tensor = graph.get_tensor_by_name(canonical_name) + shape = tensor.get_shape() + return shape + + +@deprecation.deprecated( + date=None, + instructions=_DEPRECATION_MSG) +@tf_export(v1=["graph_util.remove_training_nodes"]) +def remove_training_nodes(input_graph, protected_nodes=None): + """Prunes out nodes that aren't needed for inference. + + There are nodes like Identity and CheckNumerics that are only useful + during training, and can be removed in graphs that will be used for + nothing but inference. Here we identify and remove them, returning an + equivalent graph. To be specific, CheckNumerics nodes are always removed, and + Identity nodes that aren't involved in control edges are spliced out so that + their input and outputs are directly connected. + + Args: + input_graph: Model to analyze and prune. + protected_nodes: An optional list of names of nodes to be kept + unconditionally. This is for example useful to preserve Identity output + nodes. + + Returns: + A list of nodes with the unnecessary ones removed. + """ + if not protected_nodes: + protected_nodes = [] + + types_to_remove = {"CheckNumerics": True} + + input_nodes = input_graph.node + names_to_remove = {} + for node in input_nodes: + if node.op in types_to_remove and node.name not in protected_nodes: + names_to_remove[node.name] = True + + nodes_after_removal = [] + for node in input_nodes: + if node.name in names_to_remove: + continue + new_node = node_def_pb2.NodeDef() + new_node.CopyFrom(node) + input_before_removal = node.input + del new_node.input[:] + for full_input_name in input_before_removal: + input_name = re.sub(r"^\^", "", full_input_name) + if input_name in names_to_remove: + continue + new_node.input.append(full_input_name) + nodes_after_removal.append(new_node) + + types_to_splice = {"Identity": True} + control_input_names = set() + node_names_with_control_input = set() + node_in_colocated = set() + + for node in nodes_after_removal: + for node_input in node.input: + if "^" in node_input: + control_input_names.add(node_input.replace("^", "")) + node_names_with_control_input.add(node.name) + # Prevent colocated nodes from being lost. + if "_class" in node.attr: + for colocated_node_name in node.attr["_class"].list.s: + node_in_colocated.add(_get_colocated_node_name(colocated_node_name)) + + names_to_splice = {} + for node in nodes_after_removal: + if node.op in types_to_splice and node.name not in protected_nodes: + if node.name in node_in_colocated: + continue + # We don't want to remove nodes that have control edge inputs, because + # they might be involved in subtle dependency issues that removing them + # will jeopardize. + if node.name not in node_names_with_control_input: + names_to_splice[node.name] = node.input[0] + + # We also don't want to remove nodes which are used as control edge inputs. + names_to_splice = {name: value for name, value in names_to_splice.items() + if name not in control_input_names} + + nodes_after_splicing = [] + for node in nodes_after_removal: + if node.name in names_to_splice: + continue + new_node = node_def_pb2.NodeDef() + new_node.CopyFrom(node) + input_before_removal = node.input + del new_node.input[:] + for full_input_name in input_before_removal: + input_name = re.sub(r"^\^", "", full_input_name) + while input_name in names_to_splice: + full_input_name = names_to_splice[input_name] + input_name = re.sub(r"^\^", "", full_input_name) + new_node.input.append(full_input_name) + nodes_after_splicing.append(new_node) + + output_graph = graph_pb2.GraphDef() + output_graph.node.extend(nodes_after_splicing) + return output_graph + + +@tf_export("__internal__.graph_util.graph_defs_equal", v1=[]) +def graph_defs_equal(graph_def_1: graph_pb2.GraphDef, + graph_def_2: graph_pb2.GraphDef, + treat_nan_as_equal: bool = False) -> bool: + """Returns True iff the graph def arguments are structurally equivalent. + + The notion of equivalence encoded here checks that the set of NodeDefs in + the GraphDef's function library and main graph body are identical. + Additionally, it checks that the functions in the function library are equal + as sets. + + Example usage: + + ``` + with tf.Graph().as_default() as g1: + tf.constant(1) + + with tf.Graph().as_default() as g2: + tf.constant(2) + + with tf.Graph().as_default() as g3: + tf.constant(1) + + assert tf.__internal__.graph_util.graph_defs_equal(g1.as_graph_def(), + g3.as_graph_def()) + + assert not tf.__internal__.graph_util.graph_defs_equal(g1.as_graph_def(), + g2.as_graph_def()) + ``` + + Args: + graph_def_1: Instance of `graph_pb2.GraphDef` to compare. + graph_def_2: Instance of `graph_pb2.GraphDef` to compare. + treat_nan_as_equal: Boolean indicating whether or not to treat nan + floating-point values as equal. This is crucial for any equivalence + relation defined over GraphDefs, to ensure symmetry. + + Returns: + Boolean indicating structural equivalence as described above. + + Raises: + TypeError: If either of the GraphDefs are not instances of + `graph_pb2.GraphDef`. + """ + if not isinstance(graph_def_1, graph_pb2.GraphDef): + raise TypeError("graph_def_1 must be a graph_pb2.GraphDef proto, but got " + f"type {type(graph_def_1)}.") + if not isinstance(graph_def_2, graph_pb2.GraphDef): + raise TypeError("graph_def_2 must be a graph_pb2.GraphDef proto, but got " + f"type {type(graph_def_2)}.") + options = _proto_comparators.ProtoComparisonOptions(treat_nan_as_equal) + return _proto_comparators.EqualsGraphDef(graph_def_1.SerializeToString(), + graph_def_2.SerializeToString(), + options) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/immutable_dict.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/immutable_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..6c357a87ebcfe44d73c4cfdeba982a4e44ea0c01 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/immutable_dict.py @@ -0,0 +1,48 @@ +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Immutable mapping.""" + +import collections.abc + + +# WARNING: this class is used internally by extension types (tf.ExtensionType), +# and may be deleted if/when extension types transition to a different encoding +# in the future. +class ImmutableDict(collections.abc.Mapping): + """Immutable `Mapping`.""" + # Note: keys, items, values, get, __eq__, and __ne__ are implemented by + # the `Mapping` base class. + + def __init__(self, *args, **kwargs): + self._dict = dict(*args, **kwargs) + + def __getitem__(self, key): + return self._dict[key] + + def __contains__(self, key): + return key in self._dict + + def __iter__(self): + return iter(self._dict) + + def __len__(self): + return len(self._dict) + + def __repr__(self): + return f'ImmutableDict({self._dict})' + + # This supresses a warning that tf.nest woud otherwise generate. + __supported_by_tf_nest__ = True + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/importer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/importer.py new file mode 100644 index 0000000000000000000000000000000000000000..359e9f4f99af08c40608ea7b30f08f4375bdcda3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/importer.py @@ -0,0 +1,552 @@ +# 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 utility function for importing TensorFlow graphs.""" +import contextlib + +from tensorflow.core.framework import graph_pb2 +from tensorflow.python import tf2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.framework import c_api_util +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import errors +from tensorflow.python.framework import function +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.ops import control_flow_util +from tensorflow.python.util import compat +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.tf_export import tf_export + + +def _IsControlInput(input_name): + # Expected format: '^operation_name' (control input). + return input_name.startswith('^') + + +def _ParseTensorName(tensor_name): + """Parses a tensor name into an operation name and output index. + + This function will canonicalize tensor names as follows: + + * "foo:0" -> ("foo", 0) + * "foo:7" -> ("foo", 7) + * "foo" -> ("foo", 0) + * "foo:bar:baz" -> ValueError + + Args: + tensor_name: The name of a tensor. + + Returns: + A tuple containing the operation name, and the output index. + + Raises: + ValueError: If `tensor_name' cannot be interpreted as the name of a tensor. + """ + components = tensor_name.split(':') + if len(components) == 2: + # Expected format: 'operation_name:output_index'. + try: + output_index = int(components[1]) + except ValueError: + raise ValueError(f'Cannot convert {tensor_name!r} to a tensor name. ' + 'Second component of the name following the `:` should ' + f'be an int. Got {components[1]}.') + return components[0], output_index + elif len(components) == 1: + # Expected format: 'operation_name' (implicit 0th output). + return components[0], 0 + else: + raise ValueError(f"Cannot convert '{tensor_name}' to a tensor name. Tensor " + 'names should not contain more than 1 `:`. Obtained ' + f'{len(components) - 1}') + + +@contextlib.contextmanager +def _MaybeDevice(device): + """Applies the given device only if device is not None or empty.""" + if device: + with ops.device(device): + yield + else: + yield + + +def _ProcessGraphDefParam(graph_def): + """Type-checks and possibly canonicalizes `graph_def`.""" + if not isinstance(graph_def, graph_pb2.GraphDef): + # `graph_def` could be a dynamically-created message, so try a duck-typed + # approach + try: + old_graph_def = graph_def + graph_def = graph_pb2.GraphDef() + graph_def.MergeFrom(old_graph_def) + except TypeError: + raise TypeError('Argument `graph_def` must be a GraphDef proto.') + else: + # If we're using the graph_def provided by the caller, modify graph_def + # in-place to add attr defaults to the NodeDefs (this is visible to the + # caller). + # NOTE(skyewm): this is undocumented behavior that at least meta_graph.py + # depends on. It might make sense to move this to meta_graph.py and have + # import_graph_def not modify the graph_def argument (we'd have to make sure + # this doesn't break anything else.) + for node in graph_def.node: + op_def = op_def_registry.get(node.op) + if op_def is None: + # Assume unrecognized ops are functions for now. TF_ImportGraphDef will + # report an error if the op is actually missing. + continue + _SetDefaultAttrValues(node, op_def) + + return graph_def + + +def _ProcessInputMapParam(input_map): + """Type-checks and possibly canonicalizes `input_map`.""" + if input_map is None: + input_map = {} + else: + if not isinstance(input_map, dict): + raise TypeError('Argument `input_map` must be a dictionary. Obtained ' + f'{type(input_map).__name__}') + if not all( + isinstance(k, compat.bytes_or_text_types) for k in input_map.keys()): + raise TypeError('All keys for argument `input_map` must be strings. ' + f'Obtained keys: {list(input_map.keys())}') + return input_map + + +def _ProcessReturnElementsParam(return_elements): + """Type-checks and possibly canonicalizes `return_elements`.""" + if return_elements is None: + return None + if not all( + isinstance(x, compat.bytes_or_text_types) for x in return_elements): + raise TypeError('Argument `return_elements` must be a list of strings. ' + f'Obtained {return_elements}.') + return tuple(compat.as_str(x) for x in return_elements) + + +def _FindAttrInOpDef(attr_name, op_def): + for attr_def in op_def.attr: + if attr_name == attr_def.name: + return attr_def + return None + + +def _RemoveDefaultAttrs(producer_op_list, graph_def): + """Removes unknown default attrs according to `producer_op_list`. + + Removes any unknown attrs in `graph_def` (i.e. attrs that do not appear in + registered OpDefs) that have a default value in `producer_op_list`. + + Args: + producer_op_list: OpList proto. + graph_def: GraphDef proto + """ + producer_op_dict = {op.name: op for op in producer_op_list.op} + for node in graph_def.node: + # Remove any default attr values that aren't in op_def. + if node.op in producer_op_dict: + op_def = op_def_registry.get(node.op) + if op_def is None: + # Some custom op registrations won't show up here. That's OK, attribute + # stripping just won't be available. + continue + producer_op_def = producer_op_dict[node.op] + # We make a copy of node.attr to iterate through since we may modify + # node.attr inside the loop. + for key in list(node.attr): + if _FindAttrInOpDef(key, op_def) is None: + # No attr_def in consumer, look in producer. + attr_def = _FindAttrInOpDef(key, producer_op_def) + if (attr_def and attr_def.HasField('default_value') and + node.attr[key] == attr_def.default_value): + # Unknown attr had default value in producer, delete it so it can be + # understood by consumer. + del node.attr[key] + + +def _ConvertInputMapValues(name, input_map): + """Ensures all input map values are tensors. + + This should be called from inside the import name scope. + + Args: + name: the `name` argument passed to import_graph_def + input_map: the `input_map` argument passed to import_graph_def. + + Returns: + An possibly-updated version of `input_map`. + + Raises: + ValueError: if input map values cannot be converted due to empty name scope. + """ + if not all(isinstance(v, tensor.Tensor) for v in input_map.values()): + if name == '': # pylint: disable=g-explicit-bool-comparison + raise ValueError( + 'tf.import_graph_def() requires a non-empty `name` if `input_map` ' + 'contains non-Tensor values. Try calling tf.convert_to_tensor() on ' + '`input_map` values before calling tf.import_graph_def().') + with ops.name_scope('_inputs'): + input_map = {k: ops.convert_to_tensor(v) for k, v in input_map.items()} + return input_map + + +def _PopulateTFImportGraphDefOptions(options, prefix, input_map, + return_elements, + validate_colocation_constraints, + propagate_device_spec=False): + """Populates the TF_ImportGraphDefOptions `options`.""" + c_api.TF_ImportGraphDefOptionsSetPrefix(options, prefix) + c_api.TF_ImportGraphDefOptionsSetUniquifyNames(options, True) + c_api.TF_ImportGraphDefOptionsSetPropagateDeviceSpec(options, + propagate_device_spec) + + for input_src, input_dst in input_map.items(): + input_src = compat.as_str(input_src) + if input_src.startswith('^'): + src_name = compat.as_str(input_src[1:]) + dst_op = input_dst._as_tf_output().oper # pylint: disable=protected-access + c_api.TF_ImportGraphDefOptionsRemapControlDependency( + options, src_name, dst_op) + else: + src_name, src_idx = _ParseTensorName(input_src) + src_name = compat.as_str(src_name) + dst_output = input_dst._as_tf_output() # pylint: disable=protected-access + c_api.TF_ImportGraphDefOptionsAddInputMapping(options, src_name, src_idx, + dst_output) + for name in return_elements or []: + if ':' in name: + op_name, index = _ParseTensorName(name) + op_name = compat.as_str(op_name) + c_api.TF_ImportGraphDefOptionsAddReturnOutput(options, op_name, index) + else: + c_api.TF_ImportGraphDefOptionsAddReturnOperation(options, + compat.as_str(name)) + + c_api.TF_ImportGraphDefOptionsSetValidateColocationConstraints( + options, validate_colocation_constraints) + + +def _ProcessNewOps(graph): + """Processes the newly-added TF_Operations in `graph`.""" + # Maps from a node to the names of the ops it's colocated with, if colocation + # is specified in the attributes. + colocation_pairs = {} + + for new_op in graph._add_new_tf_operations(compute_devices=False): # pylint: disable=protected-access + original_device = new_op.device + new_op._set_device('') # pylint: disable=protected-access + colocation_names = _GetColocationNames(new_op) + if colocation_names: + colocation_pairs[new_op] = colocation_names + # Don't set a device for this op, since colocation constraints override + # device functions and the original device. Note that this op's device may + # still be set by the loop below. + # TODO(skyewm): why does it override the original device? + else: + with _MaybeDevice(original_device): + graph._apply_device_functions(new_op) # pylint: disable=protected-access + + # The following loop populates the device field of ops that are colocated + # with another op. This is implied by the colocation attribute, but we + # propagate the device field for completeness. + for op, coloc_op_list in colocation_pairs.items(): + coloc_device = None + # Find any device in the list of colocated ops that have a device, if it + # exists. We assume that if multiple ops have devices, they refer to the + # same device. Otherwise, a runtime error will occur since the colocation + # property cannot be guaranteed. Note in TF2 colocations have been removed + # from the public API and will be considered a hint, so there is no runtime + # error. + # + # One possible improvement is to try to check for compatibility of all + # devices in this list at import time here, which would require + # implementing a compatibility function for device specs in python. + for coloc_op_name in coloc_op_list: + try: + coloc_op = graph._get_operation_by_name(coloc_op_name) # pylint: disable=protected-access + except KeyError: + # Do not error in TF2 if the colocation cannot be guaranteed + if tf2.enabled() or control_flow_util.EnableControlFlowV2(graph): + continue + + raise ValueError(f'Specified colocation to an op: {coloc_op_name} that ' + f'does not exist during import for op: {op.name}') + if coloc_op.device: + coloc_device = pydev.DeviceSpec.from_string(coloc_op.device) + break + if coloc_device: + op._set_device(coloc_device) # pylint: disable=protected-access + + +def _GetColocationNames(op): + """Returns names of the ops that `op` should be colocated with.""" + colocation_names = [] + try: + class_values = op.get_attr('_class') + except ValueError: + # No _class attr + return + for val in class_values: + val = compat.as_str(val) + if val.startswith('loc:@'): + colocation_node_name = val[len('loc:@'):] + if colocation_node_name != op.name: + colocation_names.append(colocation_node_name) + return colocation_names + + +def _GatherReturnElements(requested_return_elements, graph, results): + """Returns the requested return elements from results. + + Args: + requested_return_elements: list of strings of operation and tensor names + graph: Graph + results: wrapped TF_ImportGraphDefResults + + Returns: + list of `Operation` and/or `Tensor` objects + """ + return_outputs = c_api.TF_ImportGraphDefResultsReturnOutputs(results) + return_opers = c_api.TF_ImportGraphDefResultsReturnOperations(results) + + combined_return_elements = [] + outputs_idx = 0 + opers_idx = 0 + for name in requested_return_elements: + if ':' in name: + combined_return_elements.append( + graph._get_tensor_by_tf_output(return_outputs[outputs_idx])) # pylint: disable=protected-access + outputs_idx += 1 + else: + combined_return_elements.append( + graph._get_operation_by_tf_operation(return_opers[opers_idx])) # pylint: disable=protected-access + opers_idx += 1 + return combined_return_elements + + +def _SetDefaultAttrValues(node_def, op_def): + """Set any default attr values in `node_def` that aren't present.""" + assert node_def.op == op_def.name + for attr_def in op_def.attr: + key = attr_def.name + if attr_def.HasField('default_value'): + value = node_def.attr[key] + if value is None or value.WhichOneof('value') is None: + node_def.attr[key].CopyFrom(attr_def.default_value) + + +@tf_export('graph_util.import_graph_def', 'import_graph_def') +@deprecated_args(None, 'Please file an issue at ' + 'https://github.com/tensorflow/tensorflow/issues if you depend' + ' on this feature.', 'op_dict') +def import_graph_def(graph_def, + input_map=None, + return_elements=None, + name=None, + op_dict=None, + producer_op_list=None): + """Imports the graph from `graph_def` into the current default `Graph`. + + This function provides a way to import a serialized TensorFlow + [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto) + protocol buffer, and extract individual objects in the `GraphDef` as + `tf.Tensor` and `tf.Operation` objects. Once extracted, + these objects are placed into the current default `Graph`. See + `tf.Graph.as_graph_def` for a way to create a `GraphDef` + proto. + + Args: + graph_def: A `GraphDef` proto containing operations to be imported into + the default graph. + input_map: A dictionary mapping input names (as strings) in `graph_def` + to `Tensor` objects. The values of the named input tensors in the + imported graph will be re-mapped to the respective `Tensor` values. + return_elements: A list of strings containing operation names in + `graph_def` that will be returned as `Operation` objects; and/or + tensor names in `graph_def` that will be returned as `Tensor` objects. + name: (Optional.) A prefix that will be prepended to the names in + `graph_def`. Note that this does not apply to imported function names. + Defaults to `"import"`. + op_dict: (Optional.) Deprecated, do not use. + producer_op_list: (Optional.) An `OpList` proto with the (possibly stripped) + list of `OpDef`s used by the producer of the graph. If provided, + unrecognized attrs for ops in `graph_def` that have their default value + according to `producer_op_list` will be removed. This will allow some more + `GraphDef`s produced by later binaries to be accepted by earlier binaries. + + Returns: + A list of `Operation` and/or `Tensor` objects from the imported graph, + corresponding to the names in `return_elements`, + and None if `returns_elements` is None. + + Raises: + TypeError: If `graph_def` is not a `GraphDef` proto, + `input_map` is not a dictionary mapping strings to `Tensor` objects, + or `return_elements` is not a list of strings. + ValueError: If `input_map`, or `return_elements` contains names that + do not appear in `graph_def`, or `graph_def` is not well-formed (e.g. + it refers to an unknown tensor). + """ + del op_dict + return _import_graph_def_internal( + graph_def, + input_map=input_map, + return_elements=return_elements, + name=name, + producer_op_list=producer_op_list) + + +def import_graph_def_for_function( # pylint: disable=invalid-name + graph_def, name=None, propagate_device_spec=False): + """Like import_graph_def but does not validate colocation constraints.""" + return _import_graph_def_internal( + graph_def, + validate_colocation_constraints=False, + name=name, + propagate_device_spec=propagate_device_spec) + + +def _import_graph_def_internal( # pylint: disable=invalid-name + graph_def, + input_map=None, + return_elements=None, + validate_colocation_constraints=True, + name=None, + producer_op_list=None, + propagate_device_spec=False): + """Imports the graph from `graph_def` into the current default `Graph`. + + This function provides a way to import a serialized TensorFlow + [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto) + protocol buffer, and extract individual objects in the `GraphDef` as + `tf.Tensor` and `tf.Operation` objects. Once extracted, + these objects are placed into the current default `Graph`. See + `tf.Graph.as_graph_def` for a way to create a `GraphDef` + proto. + + Args: + graph_def: A `GraphDef` proto containing operations to be imported into the + default graph. + input_map: A dictionary mapping input names (as strings) in `graph_def` to + `Tensor` objects. The values of the named input tensors in the imported + graph will be re-mapped to the respective `Tensor` values. + return_elements: A list of strings containing operation names in `graph_def` + that will be returned as `Operation` objects; and/or tensor names in + `graph_def` that will be returned as `Tensor` objects. + validate_colocation_constraints: Whether to validate colocation constraints. + name: (Optional.) A prefix that will be prepended to the names in + `graph_def`. Note that this does not apply to imported function names. + Defaults to `"import"`. + producer_op_list: (Optional.) An `OpList` proto with the (possibly stripped) + list of `OpDef`s used by the producer of the graph. If provided, + unrecognized attrs for ops in `graph_def` that have their default value + according to `producer_op_list` will be removed. This will allow some more + `GraphDef`s produced by later binaries to be accepted by earlier binaries. + propagate_device_spec: Whether to propagate assigned device information + when importing a graph from a GraphDef into the current default `Graph`. + + Returns: + A list of `Operation` and/or `Tensor` objects from the imported graph, + corresponding to the names in `return_elements`, + and None if `returns_elements` is None. + + Raises: + TypeError: If `graph_def` is not a `GraphDef` proto, + `input_map` is not a dictionary mapping strings to `Tensor` objects, + or `return_elements` is not a list of strings. + ValueError: If `input_map`, or `return_elements` contains names that + do not appear in `graph_def`, or `graph_def` is not well-formed (e.g. + it refers to an unknown tensor). + """ + graph_def = _ProcessGraphDefParam(graph_def) + input_map = _ProcessInputMapParam(input_map) + return_elements = _ProcessReturnElementsParam(return_elements) + + if producer_op_list is not None: + # TODO(skyewm): make a copy of graph_def so we're not mutating the argument? + _RemoveDefaultAttrs(producer_op_list, graph_def) + + graph = ops.get_default_graph() + with ops.name_scope(name, 'import', input_map.values()) as scope: + # Save unique prefix generated by name_scope + if scope: + assert scope.endswith('/') + prefix = scope[:-1] + else: + prefix = '' + + # Generate any input map tensors inside name scope + input_map = _ConvertInputMapValues(name, input_map) + + scoped_options = c_api_util.ScopedTFImportGraphDefOptions() + options = scoped_options.options + _PopulateTFImportGraphDefOptions(options, prefix, input_map, return_elements, + validate_colocation_constraints, + propagate_device_spec) + + # _ProcessNewOps mutates the new operations. _mutation_lock ensures a + # Session.run call cannot occur between creating the TF_Operations in the + # TF_GraphImportGraphDefWithResults call and mutating the them in + # _ProcessNewOps. + with graph._mutation_lock(): # pylint: disable=protected-access + with c_api_util.tf_buffer(graph_def.SerializeToString()) as serialized: + try: + with graph._c_graph.get() as c_graph: # pylint: disable=protected-access + results = c_api.TF_GraphImportGraphDefWithResults( + c_graph, serialized, options) + results = c_api_util.ScopedTFImportGraphDefResults(results) + except errors.InvalidArgumentError as e: + # Convert to ValueError for backwards compatibility. + raise ValueError(str(e)) + + # Create _DefinedFunctions for any imported functions. + # + # We do this by creating _DefinedFunctions directly from `graph_def`, and + # adding them to `graph`. Adding an existing function to a TF_Graph is a + # no-op, so this only has the effect of updating the Python state (usually + # _DefinedFunction.add_to_graph also adds the function to the TF_Graph). + # + # TODO(skyewm): fetch the TF_Functions directly from the TF_Graph + # TODO(skyewm): avoid sending serialized FunctionDefs back to the TF_Graph + + _ProcessNewOps(graph) + + if graph_def.library and graph_def.library.function: + functions = function.from_library(graph_def.library) + for f in functions: + f.add_to_graph(graph) + + # Treat input mappings that don't appear in the graph as an error, because + # they are likely to be due to a typo. + missing_unused_input_keys = ( + c_api.TF_ImportGraphDefResultsMissingUnusedInputMappings_wrapper( + results.results)) + if missing_unused_input_keys: + missing_unused_input_keys = [ + compat.as_str(s) for s in missing_unused_input_keys + ] + missing_keys = ', '.join(missing_unused_input_keys) + raise ValueError( + 'Attempted to map inputs that were not found in graph_def: ' + f'[{missing_keys}]') + + if return_elements is None: + return None + else: + return _GatherReturnElements(return_elements, graph, results.results) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/indexed_slices.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/indexed_slices.py new file mode 100644 index 0000000000000000000000000000000000000000..391a3587a9fb11b2d4dca40cbd2a8b2a7ffbd397 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/indexed_slices.py @@ -0,0 +1,455 @@ +# 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. +# ============================================================================== +"""Indexed slices.""" + +# pylint: disable=g-bad-name +import collections +import warnings + +import numpy as np + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python import tf2 +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import internal +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.tf_export import tf_export + + +class IndexedSlicesCompositeTensorGradient( + composite_tensor_gradient.CompositeTensorGradient): + """CompositeTensorGradient for IndexedSlices.""" + + def get_gradient_components(self, value): + return value + + def replace_gradient_components(self, value, component_grads): + return component_grads + + +# TODO(mdan): Should IndexedSlices be a "tensor"? +@tf_export("IndexedSlices") +class IndexedSlices( + internal.IndexedSlices, + internal.NativeObject, + composite_tensor.CompositeTensor): + """A sparse representation of a set of tensor slices at given indices. + + This class is a simple wrapper for a pair of `Tensor` objects: + + * `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`. + * `indices`: A 1-D integer `Tensor` with shape `[D0]`. + + An `IndexedSlices` is typically used to represent a subset of a larger + tensor `dense` of shape `[LARGE0, D1, .. , DN]` where `LARGE0 >> D0`. + The values in `indices` are the indices in the first dimension of + the slices that have been extracted from the larger tensor. + + The dense tensor `dense` represented by an `IndexedSlices` `slices` has + + ```python + dense[slices.indices[i], :, :, :, ...] = slices.values[i, :, :, :, ...] + ``` + + The `IndexedSlices` class is used principally in the definition of + gradients for operations that have sparse gradients + (e.g. `tf.gather`). + + >>> v = tf.Variable([[0.,1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8]]) + >>> with tf.GradientTape() as tape: + ... r = tf.gather(v, [1,3]) + >>> index_slices = tape.gradient(r,v) + >>> index_slices + <...IndexedSlices object ...> + >>> index_slices.indices.numpy() + array([1, 3], dtype=int32) + >>> index_slices.values.numpy() + array([[1., 1., 1.], + [1., 1., 1.]], dtype=float32) + + Contrast this representation with + `tf.sparse.SparseTensor`, + which uses multi-dimensional indices and scalar values. + """ + + def __init__(self, values, indices, dense_shape=None): + """Creates an `IndexedSlices`.""" + self._values = values + self._indices = indices + self._dense_shape = dense_shape + + @property + def values(self): + """A `Tensor` containing the values of the slices.""" + return self._values + + @property + def indices(self): + """A 1-D `Tensor` containing the indices of the slices.""" + return self._indices + + @property + def dense_shape(self): + """A 1-D `Tensor` containing the shape of the corresponding dense tensor.""" + return self._dense_shape + + @property + def shape(self): + """Gets the `tf.TensorShape` representing the shape of the dense tensor. + + Returns: + A `tf.TensorShape` object. + """ + if self._dense_shape is None: + return tensor_shape.TensorShape(None) + + return tensor_util.constant_value_as_shape(self._dense_shape) + + @property + def name(self): + """The name of this `IndexedSlices`.""" + return self.values.name + + @property + def device(self): + """The name of the device on which `values` will be produced, or `None`.""" + return self.values.device + + @property + def op(self) -> ops.Operation: + """The `Operation` that produces `values` as an output.""" + return self.values.op + + @property + def dtype(self): + """The `DType` of elements in this tensor.""" + return self.values.dtype + + @property + def graph(self) -> ops.Graph: + """The `Graph` that contains the values, indices, and shape tensors.""" + return self._values.graph + + def __str__(self): + return "IndexedSlices(indices=%s, values=%s%s)" % ( + self._indices, self._values, + (", dense_shape=%s" % + (self._dense_shape,)) if self._dense_shape is not None else "") + + def __neg__(self): + return IndexedSlices(-self.values, self.indices, self.dense_shape) + + __composite_gradient__ = IndexedSlicesCompositeTensorGradient() + + @property + def _type_spec(self): + indices_shape = self._indices.shape.merge_with(self._values.shape[:1]) + dense_shape = tensor_shape.TensorShape([None]).concatenate( + self._values.shape[1:]) + if self._dense_shape is not None: + dense_shape_dtype = self._dense_shape.dtype + dense_shape = dense_shape.merge_with( + tensor_util.constant_value_as_shape(self._dense_shape)) + else: + dense_shape_dtype = None + return IndexedSlicesSpec(dense_shape, self.dtype, self._indices.dtype, + dense_shape_dtype, indices_shape) + + def _shape_invariant_to_type_spec(self, shape): + # From tf.while_loop docs: "If a loop variable is an IndexedSlices, the + # shape invariant must be a shape invariant of the values tensor of the + # IndexedSlices. It means the shapes of the three tensors of the + # IndexedSlices are (shape, [shape[0]], [shape.ndims])." + indices_shape = shape[:1] + dense_shape = tensor_shape.TensorShape([None]).concatenate(shape[1:]) + if self._dense_shape is None: + dense_shape_dtype = None + else: + dense_shape_dtype = self._dense_shape.dtype + return IndexedSlicesSpec(dense_shape, self.dtype, self._indices.dtype, + dense_shape_dtype, indices_shape) + + def consumers(self): + return self._consumers() + + +IndexedSlicesValue = collections.namedtuple( + "IndexedSlicesValue", ["values", "indices", "dense_shape"]) + + +@tf_export("IndexedSlicesSpec") +class IndexedSlicesSpec(type_spec.TypeSpec): + """Type specification for a `tf.IndexedSlices`.""" + + __slots__ = ["_shape", "_values_dtype", "_indices_dtype", + "_dense_shape_dtype", "_indices_shape"] + + value_type = property(lambda self: IndexedSlices) + + def __init__(self, shape=None, dtype=dtypes.float32, + indices_dtype=dtypes.int64, dense_shape_dtype=None, + indices_shape=None): + """Constructs a type specification for a `tf.IndexedSlices`. + + Args: + shape: The dense shape of the `IndexedSlices`, or `None` to allow any + dense shape. + dtype: `tf.DType` of values in the `IndexedSlices`. + indices_dtype: `tf.DType` of the `indices` in the `IndexedSlices`. One + of `tf.int32` or `tf.int64`. + dense_shape_dtype: `tf.DType` of the `dense_shape` in the `IndexedSlices`. + One of `tf.int32`, `tf.int64`, or `None` (if the `IndexedSlices` has + no `dense_shape` tensor). + indices_shape: The shape of the `indices` component, which indicates + how many slices are in the `IndexedSlices`. + """ + self._shape = tensor_shape.as_shape(shape) + self._values_dtype = dtypes.as_dtype(dtype) + self._indices_dtype = dtypes.as_dtype(indices_dtype) + if dense_shape_dtype is None: + self._dense_shape_dtype = None + else: + self._dense_shape_dtype = dtypes.as_dtype(dense_shape_dtype) + self._indices_shape = tensor_shape.as_shape(indices_shape).with_rank(1) + + def _serialize(self): + return (self._shape, self._values_dtype, self._indices_dtype, + self._dense_shape_dtype, self._indices_shape) + + @property + def _component_specs(self): + value_shape = self._indices_shape.concatenate(self._shape[1:]) + specs = [ + tensor_spec.TensorSpec(value_shape, self._values_dtype), + tensor_spec.TensorSpec(self._indices_shape, self._indices_dtype)] + if self._dense_shape_dtype is not None: + specs.append( + tensor_spec.TensorSpec([self._shape.ndims], self._dense_shape_dtype)) + return tuple(specs) + + def _to_components(self, value): + if value.dense_shape is None: + return (value.values, value.indices) + else: + return (value.values, value.indices, value.dense_shape) + + def _from_components(self, tensor_list): + if (all(isinstance(t, np.ndarray) for t in tensor_list) and + not tf2.enabled()): + if len(tensor_list) == 2: + return IndexedSlicesValue(tensor_list[0], tensor_list[1], None) + else: + return IndexedSlicesValue(*tensor_list) + else: + return IndexedSlices(*tensor_list) + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + IndexedSlicesSpec, struct_pb2.TypeSpecProto.INDEXED_SLICES_SPEC + ) +) + + +@tf_export(v1=["convert_to_tensor_or_indexed_slices"]) +def convert_to_tensor_or_indexed_slices(value, dtype=None, name=None): + """Converts the given object to a `Tensor` or an `IndexedSlices`. + + If `value` is an `IndexedSlices` or `SparseTensor` it is returned + unmodified. Otherwise, it is converted to a `Tensor` using + `convert_to_tensor()`. + + Args: + value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed + by `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` or + `IndexedSlices`. + name: (Optional.) A name to use if a new `Tensor` is created. + + Returns: + A `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`. + + Raises: + ValueError: If `dtype` does not match the element type of `value`. + """ + return internal_convert_to_tensor_or_indexed_slices( + value=value, dtype=dtype, name=name, as_ref=False) + + +def internal_convert_to_tensor_or_indexed_slices(value, + dtype=None, + name=None, + as_ref=False): + """Converts the given object to a `Tensor` or an `IndexedSlices`. + + If `value` is an `IndexedSlices` or `SparseTensor` it is returned + unmodified. Otherwise, it is converted to a `Tensor` using + `convert_to_tensor()`. + + Args: + value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed + by `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` or + `IndexedSlices`. + name: (Optional.) A name to use if a new `Tensor` is created. + as_ref: True if the caller wants the results as ref tensors. + + Returns: + A `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`. + + Raises: + ValueError: If `dtype` does not match the element type of `value`. + """ + if isinstance(value, ops.EagerTensor) and not context.executing_eagerly(): + return ops.convert_to_tensor(value, dtype=dtype, name=name, as_ref=as_ref) + # TODO(mdan): Name says tensor_or_indexed_slices. So do explicitly just that? + elif isinstance(value, internal.NativeObject): + if dtype and not dtypes.as_dtype(dtype).is_compatible_with(value.dtype): + raise ValueError( + "Incompatible tensor conversion requested to `dtype` " + f"{dtypes.as_dtype(dtype).name} for `value` ({value}) with dtype" + f" {value.dtype.name}.") + return value + else: + return ops.convert_to_tensor(value, dtype=dtype, name=name, as_ref=as_ref) + + +def internal_convert_n_to_tensor_or_indexed_slices(values, + dtype=None, + name=None, + as_ref=False): + """Converts `values` to a list of `Tensor` or `IndexedSlices` objects. + + Any `IndexedSlices` or `SparseTensor` objects in `values` are returned + unmodified. + + Args: + values: An iterable of `None`, `IndexedSlices`, `SparseTensor`, or objects + that can be consumed by `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` or + `IndexedSlices`. + name: (Optional.) A name prefix to used when a new `Tensor` is created, in + which case element `i` will be given the name `name + '_' + i`. + as_ref: True if the caller wants the results as ref tensors. + + Returns: + A list of `Tensor`, `IndexedSlices`, `SparseTensor` and/or `None` objects. + + Raises: + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + if not isinstance(values, collections_abc.Iterable): + raise TypeError("Argument `values` must be iterable.") + ret = [] + for i, value in enumerate(values): + if value is None: + ret.append(value) + else: + n = None if name is None else "%s_%d" % (name, i) + ret.append( + internal_convert_to_tensor_or_indexed_slices( + value, dtype=dtype, name=n, as_ref=as_ref)) + return ret + + +def convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None): + """Converts `values` to a list of `Output` or `IndexedSlices` objects. + + Any `IndexedSlices` or `SparseTensor` objects in `values` are returned + unmodified. + + Args: + values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that + can be consumed by `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` + `IndexedSlices`. + name: (Optional.) A name prefix to used when a new `Tensor` is created, in + which case element `i` will be given the name `name + '_' + i`. + + Returns: + A list of `Tensor`, `IndexedSlices`, and/or `SparseTensor` objects. + + Raises: + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + return internal_convert_n_to_tensor_or_indexed_slices( + values=values, dtype=dtype, name=name, as_ref=False) + + +# Warn the user if we convert a sparse representation to dense with at +# least this number of elements. +_LARGE_SPARSE_NUM_ELEMENTS = 100000000 + + +def _indexed_slices_to_tensor(value, dtype=None, name=None, as_ref=False): + """Converts an IndexedSlices object `value` to a Tensor. + + NOTE(mrry): This function is potentially expensive. + + Args: + value: An ops.IndexedSlices object. + dtype: The dtype of the Tensor to be returned. + name: Optional name to use for the returned Tensor. + as_ref: True if a ref is requested. + + Returns: + A dense Tensor representing the values in the given IndexedSlices. + + Raises: + ValueError: If the IndexedSlices does not have the same dtype. + """ + _ = as_ref + if dtype and not dtype.is_compatible_with(value.dtype): + raise ValueError( + f"Incompatible tensor conversion requested to `dtype` {dtype.name} for " + f"IndexedSlices ({value}) with dtype {value.dtype.name}") + if value.dense_shape is None: + raise ValueError( + "Tensor conversion requested for IndexedSlices for argument `value` " + f"without dense_shape: {value!s}") + # TODO(mrry): Consider adding static shape information to + # IndexedSlices, to avoid using numpy here. + if not context.executing_eagerly(): + dense_shape_value = tensor_util.constant_value(value.dense_shape) + if dense_shape_value is not None: + num_elements = np.prod(dense_shape_value) + if num_elements >= _LARGE_SPARSE_NUM_ELEMENTS: + warnings.warn( + "Converting sparse IndexedSlices to a dense Tensor with %d " + "elements. This may consume a large amount of memory." % + num_elements) + return gen_math_ops.unsorted_segment_sum( + value.values, value.indices, value.dense_shape[0], name=name) + + +tensor_conversion_registry.register_tensor_conversion_function( + IndexedSlices, _indexed_slices_to_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/kernels.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..1a93b6d930387036949714a334d7e5014f57b81d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/kernels.py @@ -0,0 +1,42 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Functions for querying registered kernels.""" + +from tensorflow.core.framework import kernel_def_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.util import compat + + +def get_all_registered_kernels(): + """Returns a KernelList proto of all registered kernels. + """ + buf = c_api.TF_GetAllRegisteredKernels() + data = c_api.TF_GetBuffer(buf) + kernel_list = kernel_def_pb2.KernelList() + kernel_list.ParseFromString(compat.as_bytes(data)) + return kernel_list + + +def get_registered_kernels_for_op(name): + """Returns a KernelList proto of registered kernels for a given op. + + Args: + name: A string representing the name of the op whose kernels to retrieve. + """ + buf = c_api.TF_GetRegisteredKernelsForOp(name) + data = c_api.TF_GetBuffer(buf) + kernel_list = kernel_def_pb2.KernelList() + kernel_list.ParseFromString(compat.as_bytes(data)) + return kernel_list diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/load_library.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/load_library.py new file mode 100644 index 0000000000000000000000000000000000000000..4adcedcee995c0cc5e8645abacb0c95efc12081d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/load_library.py @@ -0,0 +1,220 @@ +# 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. +# ============================================================================== + +"""Function for loading TensorFlow plugins.""" +import errno +import hashlib +import importlib +import os +import platform +import sys + +from tensorflow.python.client import pywrap_tf_session as py_tf +from tensorflow.python.eager import context +from tensorflow.python.framework import _pywrap_python_op_gen +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +@tf_export('load_op_library') +def load_op_library(library_filename): + """Loads a TensorFlow plugin, containing custom ops and kernels. + + Pass "library_filename" to a platform-specific mechanism for dynamically + loading a library. The rules for determining the exact location of the + library are platform-specific and are not documented here. When the + library is loaded, ops and kernels registered in the library via the + `REGISTER_*` macros are made available in the TensorFlow process. Note + that ops with the same name as an existing op are rejected and not + registered with the process. + + Args: + library_filename: Path to the plugin. + Relative or absolute filesystem path to a dynamic library file. + + Returns: + A python module containing the Python wrappers for Ops defined in + the plugin. + + Raises: + RuntimeError: when unable to load the library or get the python wrappers. + """ + lib_handle = py_tf.TF_LoadLibrary(library_filename) + try: + wrappers = _pywrap_python_op_gen.GetPythonWrappers( + py_tf.TF_GetOpList(lib_handle)) + finally: + # Delete the library handle to release any memory held in C + # that are no longer needed. + py_tf.TF_DeleteLibraryHandle(lib_handle) + + # Get a unique name for the module. + module_name = hashlib.sha1(wrappers).hexdigest() + if module_name in sys.modules: + return sys.modules[module_name] + module_spec = importlib.machinery.ModuleSpec(module_name, None) + module = importlib.util.module_from_spec(module_spec) + # pylint: disable=exec-used + exec(wrappers, module.__dict__) + # Allow this to be recognized by AutoGraph. + setattr(module, '_IS_TENSORFLOW_PLUGIN', True) + sys.modules[module_name] = module + return module + + +@deprecation.deprecated(date=None, + instructions='Use `tf.load_library` instead.') +@tf_export(v1=['load_file_system_library']) +def load_file_system_library(library_filename): + """Loads a TensorFlow plugin, containing file system implementation. + + Pass `library_filename` to a platform-specific mechanism for dynamically + loading a library. The rules for determining the exact location of the + library are platform-specific and are not documented here. + + Args: + library_filename: Path to the plugin. + Relative or absolute filesystem path to a dynamic library file. + + Returns: + None. + + Raises: + RuntimeError: when unable to load the library. + """ + py_tf.TF_LoadLibrary(library_filename) + + +def _is_shared_object(filename): + """Check the file to see if it is a shared object, only using extension.""" + if platform.system() == 'Linux': + if filename.endswith('.so'): + return True + else: + index = filename.rfind('.so.') + if index == -1: + return False + else: + # A shared object with the API version in filename + return filename[index + 4].isdecimal() + elif platform.system() == 'Darwin': + return filename.endswith('.dylib') + elif platform.system() == 'Windows': + return filename.endswith('.dll') + else: + return False + + +@tf_export('load_library') +def load_library(library_location): + """Loads a TensorFlow plugin. + + "library_location" can be a path to a specific shared object, or a folder. + If it is a folder, all shared objects that are named "libtfkernel*" will be + loaded. When the library is loaded, kernels registered in the library via the + `REGISTER_*` macros are made available in the TensorFlow process. + + Args: + library_location: Path to the plugin or the folder of plugins. + Relative or absolute filesystem path to a dynamic library file or folder. + + Returns: + None + + Raises: + OSError: When the file to be loaded is not found. + RuntimeError: when unable to load the library. + """ + if os.path.exists(library_location): + if os.path.isdir(library_location): + directory_contents = os.listdir(library_location) + + kernel_libraries = [ + os.path.join(library_location, f) for f in directory_contents + if _is_shared_object(f)] + else: + kernel_libraries = [library_location] + + for lib in kernel_libraries: + py_tf.TF_LoadLibrary(lib) + + else: + raise OSError( + errno.ENOENT, + 'The file or folder to load kernel libraries from does not exist.', + library_location) + + +def load_pluggable_device_library(library_location): + """Loads a TensorFlow PluggableDevice plugin. + + "library_location" can be a path to a specific shared object, or a folder. + If it is a folder, all shared objects will be loaded. when the library is + loaded, devices/kernels registered in the library via StreamExecutor C API + and Kernel/Op Registration C API are made available in TensorFlow process. + + Args: + library_location: Path to the plugin or folder of plugins. Relative or + absolute filesystem path to a dynamic library file or folder. + + Raises: + OSError: When the file to be loaded is not found. + RuntimeError: when unable to load the library. + """ + if os.path.exists(library_location): + if os.path.isdir(library_location): + directory_contents = os.listdir(library_location) + + pluggable_device_libraries = [ + os.path.join(library_location, f) + for f in directory_contents + if _is_shared_object(f) + ] + else: + pluggable_device_libraries = [library_location] + + for lib in pluggable_device_libraries: + py_tf.TF_LoadPluggableDeviceLibrary(lib) + # Reinitialized physical devices list after plugin registration. + context.context().reinitialize_physical_devices() + else: + raise OSError( + errno.ENOENT, + 'The file or folder to load pluggable device libraries from does not ' + 'exist.', library_location) + + +@tf_export('experimental.register_filesystem_plugin') +def register_filesystem_plugin(plugin_location): + """Loads a TensorFlow FileSystem plugin. + + Args: + plugin_location: Path to the plugin. Relative or absolute filesystem plugin + path to a dynamic library file. + + Returns: + None + + Raises: + OSError: When the file to be loaded is not found. + RuntimeError: when unable to load the library. + """ + if os.path.exists(plugin_location): + py_tf.TF_RegisterFilesystemPlugin(plugin_location) + + else: + raise OSError(errno.ENOENT, + 'The file to load file system plugin from does not exist.', + plugin_location) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/memory_checker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/memory_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..88ef3cb2a06e9b9d768d7000e82d15b7d00741f9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/memory_checker.py @@ -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. +# ============================================================================== +"""Memory leak detection utility.""" + +from tensorflow.python.framework.python_memory_checker import _PythonMemoryChecker +from tensorflow.python.profiler import trace +from tensorflow.python.util import tf_inspect + +try: + from tensorflow.python.platform.cpp_memory_checker import _CppMemoryChecker as CppMemoryChecker # pylint:disable=g-import-not-at-top +except ImportError: + CppMemoryChecker = None + + +def _get_test_name_best_effort(): + """If available, return the current test name. Otherwise, `None`.""" + for stack in tf_inspect.stack(): + function_name = stack[3] + if function_name.startswith('test'): + try: + class_name = stack[0].f_locals['self'].__class__.__name__ + return class_name + '.' + function_name + except: # pylint:disable=bare-except + pass + + return None + + +# TODO(kkb): Also create decorator versions for convenience. +class MemoryChecker(object): + """Memory leak detection class. + + This is a utility class to detect Python and C++ memory leaks. It's intended + for both testing and debugging. Basic usage: + + >>> # MemoryChecker() context manager tracks memory status inside its scope. + >>> with MemoryChecker() as memory_checker: + >>> tensors = [] + >>> for _ in range(10): + >>> # Simulating `tf.constant(1)` object leak every iteration. + >>> tensors.append(tf.constant(1)) + >>> + >>> # Take a memory snapshot for later analysis. + >>> memory_checker.record_snapshot() + >>> + >>> # `report()` generates a html graph file showing allocations over + >>> # snapshots per every stack trace. + >>> memory_checker.report() + >>> + >>> # This assertion will detect `tf.constant(1)` object leak. + >>> memory_checker.assert_no_leak_if_all_possibly_except_one() + + `record_snapshot()` must be called once every iteration at the same location. + This is because the detection algorithm relies on the assumption that if there + is a leak, it's happening similarly on every snapshot. + """ + + @trace.trace_wrapper + def __enter__(self): + self._python_memory_checker = _PythonMemoryChecker() + if CppMemoryChecker: + self._cpp_memory_checker = CppMemoryChecker(_get_test_name_best_effort()) + return self + + @trace.trace_wrapper + def __exit__(self, exc_type, exc_value, traceback): + if CppMemoryChecker: + self._cpp_memory_checker.stop() + + # We do not enable trace_wrapper on this function to avoid contaminating + # the snapshot. + def record_snapshot(self): + """Take a memory snapshot for later analysis. + + `record_snapshot()` must be called once every iteration at the same + location. This is because the detection algorithm relies on the assumption + that if there is a leak, it's happening similarly on every snapshot. + + The recommended number of `record_snapshot()` call depends on the testing + code complexity and the allcoation pattern. + """ + self._python_memory_checker.record_snapshot() + if CppMemoryChecker: + self._cpp_memory_checker.record_snapshot() + + @trace.trace_wrapper + def report(self): + """Generates a html graph file showing allocations over snapshots. + + It create a temporary directory and put all the output files there. + If this is running under Google internal testing infra, it will use the + directory provided the infra instead. + """ + self._python_memory_checker.report() + if CppMemoryChecker: + self._cpp_memory_checker.report() + + @trace.trace_wrapper + def assert_no_leak_if_all_possibly_except_one(self): + """Raises an exception if a leak is detected. + + This algorithm classifies a series of allocations as a leak if it's the same + type(Python) or it happens at the same stack trace(C++) at every snapshot, + but possibly except one snapshot. + """ + + self._python_memory_checker.assert_no_leak_if_all_possibly_except_one() + if CppMemoryChecker: + self._cpp_memory_checker.assert_no_leak_if_all_possibly_except_one() + + @trace.trace_wrapper + def assert_no_new_python_objects(self, threshold=None): + """Raises an exception if there are new Python objects created. + + It computes the number of new Python objects per type using the first and + the last snapshots. + + Args: + threshold: A dictionary of [Type name string], [count] pair. It won't + raise an exception if the new Python objects are under this threshold. + """ + self._python_memory_checker.assert_no_new_objects(threshold=threshold) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/meta_graph.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/meta_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..f621119ab976cbc455389c9158a7ba524f58348f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/meta_graph.py @@ -0,0 +1,1094 @@ +# 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. +# ============================================================================== + +"""MetaGraph and related functions.""" +import copy +from packaging import version as packaging_version # pylint: disable=g-bad-import-order +import os.path +import re +import sys + +from google.protobuf.any_pb2 import Any +from google.protobuf import text_format + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import op_def_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.protobuf import saver_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.eager import context +from tensorflow.python.framework import byte_swap_tensor as bst +from tensorflow.python.framework import error_interpolation +from tensorflow.python.framework import graph_io +from tensorflow.python.framework import importer +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import versions +from tensorflow.python.lib.io import file_io +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat + + +# Prefix to be added to unbound input names so they are easily identifiable. +_UNBOUND_INPUT_PREFIX = "$unbound_inputs_" + +# List of collections that didn't register proto functions, as a result in +# a previously exported meta_graph the items are of a different data type. +_COMPAT_COLLECTION_LIST = [ops.GraphKeys.LOCAL_VARIABLES, + ops.GraphKeys.MODEL_VARIABLES, + ops.GraphKeys.METRIC_VARIABLES] + + +def _node_def(from_node_def, export_scope, unbound_inputs, clear_devices=False): + """Create a `NodeDef` proto with export_scope stripped. + + Args: + from_node_def: A `node_def_pb2.NodeDef` protocol buffer. + export_scope: A `string` representing the name scope to remove. + unbound_inputs: An array of unbound input names if they exist. + clear_devices: Boolean which controls whether to clear device information + from node_def. Default false. + + Returns: + A `node_def_pb2.NodeDef` protocol buffer. + """ + node_def = copy.deepcopy(from_node_def) + for i, v in enumerate(node_def.input): + if (export_scope and + not node_def.input[i].lstrip("^").startswith(export_scope)): + # Adds "$unbound_inputs_" prefix to the unbound name so they are easily + # identifiable. + node_def.input[i] = re.sub(r"([\^]|^)(.*)", + r"\1" + _UNBOUND_INPUT_PREFIX + r"\2", + compat.as_str(v)) + unbound_inputs.append(node_def.input[i]) + else: + node_def.input[i] = ops.strip_name_scope(v, export_scope) + node_def.name = compat.as_bytes( + ops.strip_name_scope(from_node_def.name, export_scope)) + for k, v in from_node_def.attr.items(): + if k == "_class": + new_s = [compat.as_bytes( + ops.strip_name_scope(s, export_scope)) for s in v.list.s + if not export_scope or + compat.as_str(s).split("@")[1].startswith(export_scope)] + node_def.attr[k].CopyFrom(attr_value_pb2.AttrValue( + list=attr_value_pb2.AttrValue.ListValue(s=new_s))) + elif node_def.op in ("Enter", "RefEnter") and k == "frame_name": + if not export_scope or compat.as_str(v.s).startswith(export_scope): + new_s = compat.as_bytes(ops.strip_name_scope(v.s, export_scope)) + node_def.attr[k].CopyFrom(attr_value_pb2.AttrValue(s=new_s)) + else: + node_def.attr[k].CopyFrom(v) + + if clear_devices: + node_def.device = "" + + return node_def + + +def _read_file(filename): + """Reads a file containing `GraphDef` and returns the protocol buffer. + + Args: + filename: `graph_def` filename including the path. + + Returns: + A `GraphDef` protocol buffer. + + Raises: + IOError: If the file doesn't exist, or cannot be successfully parsed. + """ + graph_def = graph_pb2.GraphDef() + if not file_io.file_exists(filename): + raise IOError(f"File {filename} does not exist.") + # First try to read it as a binary file. + with file_io.FileIO(filename, "rb") as f: + file_content = f.read() + try: + graph_def.ParseFromString(file_content) + return graph_def + except Exception: # pylint: disable=broad-except + pass + + # Next try to read it as a text file. + try: + text_format.Merge(file_content, graph_def) + except text_format.ParseError as e: + raise IOError(f"Cannot parse file {filename}: {str(e)}.") + + return graph_def + + +def ops_used_by_graph_def(graph_def): + """Collect the list of ops used by a graph. + + Does not validate that the ops are all registered. + + Args: + graph_def: A `GraphDef` proto, as from `graph.as_graph_def()`. + + Returns: + A list of strings, each naming an op used by the graph. + """ + # Map function names to definitions + name_to_function = {} + for fun in graph_def.library.function: + name_to_function[fun.signature.name] = fun + + # Collect the list of op names. Since functions can reference functions, we + # need a recursive traversal. + used_ops = set() # Includes both primitive ops and functions + functions_to_process = [] # A subset of used_ops + + def mark_op_as_used(op): + if op not in used_ops and op in name_to_function: + functions_to_process.append(name_to_function[op]) + used_ops.add(op) + + def process_node(node): + mark_op_as_used(node.op) + if node.op in ["PartitionedCall", "StatefulPartitionedCall"]: + mark_op_as_used(node.attr["f"].func.name) + + for node in graph_def.node: + process_node(node) + while functions_to_process: + fun = functions_to_process.pop() + for node in fun.node_def: + process_node(node) + + return [op for op in used_ops if op not in name_to_function] + + +def stripped_op_list_for_graph(graph_def): + """Collect the stripped OpDefs for ops used by a graph. + + This function computes the `stripped_op_list` field of `MetaGraphDef` and + similar protos. The result can be communicated from the producer to the + consumer, which can then use the C++ function + `RemoveNewDefaultAttrsFromGraphDef` to improve forwards compatibility. + + Args: + graph_def: A `GraphDef` proto, as from `graph.as_graph_def()`. + + Returns: + An `OpList` of ops used by the graph. + """ + # This is similar to StrippedOpListForGraph in C++, but unlike its + # C++ counterpart, this version does not require all ops to be registered. + # This is done to support Prelu fusion in tfjs. + used_ops = ops_used_by_graph_def(graph_def) + op_defs = [] + for op in sorted(used_ops): + op_def = op_def_registry.get(op) + if op_def is not None: + op_defs.append(op_def) + return op_def_pb2.OpList(op=op_defs) + + +def _get_kind_name(item): + """Returns the kind name in CollectionDef. + + Args: + item: A data item. + + Returns: + The string representation of the kind in CollectionDef. + """ + if isinstance(item, (str, bytes)): + kind = "bytes_list" + elif isinstance(item, int): + kind = "int64_list" + elif isinstance(item, float): + kind = "float_list" + elif isinstance(item, Any): + kind = "any_list" + else: + kind = "node_list" + return kind + + +SAVE_AND_RESTORE_OPS = ["SaveV2", + "Save", "SaveSlice", + "LegacySave", "LegacySaveSlice", + "RestoreV2", + "Restore", "RestoreSlice", + "LegacyRestore", "LegacyRestoreSlice"] + + +def _get_scope(node_name): + """Extract the scope name from a node name. + + The scope name is everything before the final slash, + not including any ^ prefix denoting a control dependency. + + Args: + node_name: the full name of an Op or a Tensor in the graph. + Returns: + The deepest named scope containing the node. + Raises: + ValueError: if tensor_name is None or empty + """ + if not node_name: + raise ValueError( + f"Node name cannot be empty or None. Received: {node_name}.") + + # Control dependency inputs start with ^. + if node_name.startswith("^"): + node_name = node_name[1:] + if "/" in node_name: + scope, _ = node_name.rsplit("/", 1) + return scope + + return "" + + +def _find_extraneous_saver_nodes(graph_def, saver_def): + """Identifies any nodes in the graph_def related to unused Savers. + + This approach assumes that each Saver is cleanly isolated in its own name + scope, so we need only identify the scopes associated with extraneous Savers + and return all the nodes in those scopes. + + Args: + graph_def: a GraphDef proto to evaluate. + saver_def: a SaverDef proto referencing Save/Restore ops to be retained. + Returns: + An iterable of node names that may be safely omitted. + """ + # TODO(soergel): confirm that the assumption of scope isolation is valid. + # If not, we need to walk up the graph from any restore_all nodes, and walk + # down the graph from any Save/Restore nodes. I drafted that approach too, + # but it seems unnecessarily complex given the name scope solution. + + # load the graph DAG in minimal form, without initializing a full Graph object + nodes = { + node_def.name: ( + set(tensor.get_op_name(x) for x in node_def.input), node_def.op) + for node_def in graph_def.node + } + + retain_scope_save = None + retain_scope_restore = None + # It's possible to have no saver if the graph has no Variables + if saver_def is not None: + save_op_name = tensor.get_op_name(saver_def.save_tensor_name) + restore_op_name = tensor.get_op_name(saver_def.restore_op_name) + + # The save and restore scopes should always be the same, but if they differ + # for some reason, we retain them both to be safe. + retain_scope_restore = _get_scope(restore_op_name) + "/" + retain_scope_save = _get_scope(save_op_name) + "/" + + all_saver_node_names = set( + name for name, (_, op) in nodes.items() if op in SAVE_AND_RESTORE_OPS) + + all_saver_scopes = ( + set(_get_scope(x) for x in all_saver_node_names) - all_saver_node_names) + all_saver_scopes = set(x + "/" for x in all_saver_scopes) + + extraneous_scopes = all_saver_scopes - set([retain_scope_save, + retain_scope_restore]) + + extraneous_node_names = set() + for name, _ in nodes.items(): + for extraneous_scope in extraneous_scopes: + if name.startswith(extraneous_scope): + extraneous_node_names.add(name) + break + + return extraneous_node_names + + +def _should_include_node(node_or_node_name, export_scope, exclude_nodes): + """Returns `True` if a node should be included. + + Args: + node_or_node_name: A node or `string` node name. + export_scope: `string`. Name scope under which to extract the subgraph. The + scope name will be stripped from the node definitions for easy import + later into new name scopes. + exclude_nodes: An iterable of nodes or `string` node names to omit from the + export, or None. Note no sanity-checking is done, so this list must be + carefully constructed to avoid producing an invalid graph. + + Returns: + `True` if the node should be included. + """ + if not isinstance(node_or_node_name, str): + try: + node_name = node_or_node_name.name + except AttributeError: + # Keep the object that we don't know how to process. + return True + else: + node_name = node_or_node_name + + if exclude_nodes and (node_or_node_name in exclude_nodes + or node_name in exclude_nodes): + return False + + return (node_name.startswith(_UNBOUND_INPUT_PREFIX) or + (not export_scope or node_name.startswith(export_scope))) + + +def add_collection_def(meta_graph_def, key, graph=None, + export_scope=None, exclude_nodes=None, + override_contents=None): + """Adds a collection to MetaGraphDef protocol buffer. + + Args: + meta_graph_def: MetaGraphDef protocol buffer. + key: One of the GraphKeys or user-defined string. + graph: The `Graph` from which to get collections. + export_scope: Optional `string`. Name scope to remove. + exclude_nodes: An iterable of nodes or `string` node names to omit from the + collection, or None. + override_contents: An iterable of values to place in the collection, + ignoring the current values (if set). + """ + if graph and not isinstance(graph, ops.Graph): + raise TypeError( + f"graph must be of type Graph. Received type: {type(graph)}.") + + if not isinstance(key, str) and not isinstance(key, bytes): + logging.warning("Only collections with string type keys will be " + "serialized. This key has %s", type(key)) + return + + # Sets graph to default graph if it's not passed in. + graph = graph or ops.get_default_graph() + + if override_contents: + collection_list = override_contents + else: + collection_list = graph.get_collection(key) + + # Remove nodes that should not be exported from the collection list. + collection_list = [x for x in collection_list if + _should_include_node(x, export_scope, exclude_nodes)] + if not collection_list: + return + + try: + col_def = meta_graph_def.collection_def[key] + to_proto = ops.get_to_proto_function(key) + proto_type = ops.get_collection_proto_type(key) + if to_proto: + kind = "bytes_list" + for x in collection_list: + # Additional type check to make sure the returned proto is indeed + # what we expect. + proto = to_proto(x, export_scope=export_scope) + if proto: + assert isinstance(proto, proto_type) + getattr(col_def, kind).value.append(proto.SerializeToString()) + else: + kind = _get_kind_name(collection_list[0]) + if kind == "node_list": + for x in collection_list: + if not export_scope or x.name.startswith(export_scope): + getattr(col_def, kind).value.append( + ops.strip_name_scope(x.name, export_scope)) + elif kind == "bytes_list": + # NOTE(opensource): This force conversion is to work around the fact + # that Python3 distinguishes between bytes and strings. + getattr(col_def, kind).value.extend( + [compat.as_bytes(x) for x in collection_list]) + else: + getattr(col_def, kind).value.extend([x for x in collection_list]) + except Exception as e: # pylint: disable=broad-except + logging.warning("Issue encountered when serializing %s.\n" + "Type is unsupported, or the types of the items don't " + "match field type in CollectionDef. Note this is a warning " + "and probably safe to ignore.\n%s", key, str(e)) + if key in meta_graph_def.collection_def: + del meta_graph_def.collection_def[key] + return + + +def _is_default_attr_value(op_def, attr_name, attr_value): + """Checks if given attribute matches the default value in the op def.""" + for attr_def in op_def.attr: + if attr_def.name == attr_name: + if not attr_def.HasField("default_value"): + return False + # c_api.EqualAttrValueWrapper returns an empty string + # if both arguments represent an equivalent AttrValue instance. + return not c_api.EqualAttrValueWrapper( + attr_value.SerializeToString(), + attr_def.default_value.SerializeToString()) + return False + + +def strip_graph_default_valued_attrs(meta_graph_def): + """Strips default valued attributes for node defs in given MetaGraphDef. + + This method also sets `meta_info_def.stripped_default_attrs` in the given + `MetaGraphDef` proto to True. + + Args: + meta_graph_def: `MetaGraphDef` protocol buffer + + Returns: + None. + """ + # Map function op names to their function definitions. + op_name_to_function = {} + for function_def in meta_graph_def.graph_def.library.function: + op_name_to_function[function_def.signature.name] = function_def + + def _strip_node_default_valued_attrs(node_def): + """Removes default valued attributes from a single node def.""" + if node_def.op in op_name_to_function: + return + + op_def = op_def_registry.get(node_def.op) + if op_def is None: + return + + attrs_to_strip = set() + for attr_name, attr_value in node_def.attr.items(): + if _is_default_attr_value(op_def, attr_name, attr_value): + attrs_to_strip.add(attr_name) + + for attr in attrs_to_strip: + del node_def.attr[attr] + + # Process all NodeDef instances in graph_def. + for node_def in meta_graph_def.graph_def.node: + _strip_node_default_valued_attrs(node_def) + + # Process all NodeDef instances in graph_def.library.function. + for function_def in meta_graph_def.graph_def.library.function: + for function_node_def in function_def.node_def: + _strip_node_default_valued_attrs(function_node_def) + + # Tell consumers of this graph that default valued attrs have been stripped. + meta_graph_def.meta_info_def.stripped_default_attrs = True + + +def create_meta_graph_def(meta_info_def=None, + graph_def=None, + saver_def=None, + collection_list=None, + graph=None, + export_scope=None, + exclude_nodes=None, + clear_extraneous_savers=False, + strip_default_attrs=False): + # pylint: disable=line-too-long + """Construct and returns a `MetaGraphDef` protocol buffer. + + Args: + meta_info_def: `MetaInfoDef` protocol buffer. + graph_def: `GraphDef` protocol buffer. + saver_def: `SaverDef` protocol buffer. + collection_list: List of string keys to collect. + graph: The `Graph` to create `MetaGraphDef` out of. + export_scope: Optional `string`. Name scope to remove. + exclude_nodes: An iterable of nodes or `string` node names to omit from all + collection, or None. + clear_extraneous_savers: Remove any preexisting SaverDefs from the SAVERS + collection. Note this method does not alter the graph, so any + extraneous Save/Restore ops should have been removed already, as needed. + strip_default_attrs: Boolean. If `True`, default-valued attributes will be + removed from the NodeDefs. For a detailed guide, see + [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). + + Returns: + MetaGraphDef protocol buffer. + + Raises: + TypeError: If the arguments are not of the correct proto buffer type. + """ + # pylint: enable=line-too-long + # Type check. + if graph and not isinstance(graph, ops.Graph): + raise TypeError( + f"graph must be of type Graph. Received type: {type(graph)}.") + if meta_info_def and not isinstance(meta_info_def, + meta_graph_pb2.MetaGraphDef.MetaInfoDef): + raise TypeError( + "meta_info_def must be of type MetaInfoDef. " + f"Received type: {type(meta_info_def)}.") + if graph_def and not isinstance(graph_def, graph_pb2.GraphDef): + raise TypeError( + "graph_def must be of type GraphDef. " + f"Received type: {type(graph_def)}.") + if saver_def and not isinstance(saver_def, saver_pb2.SaverDef): + raise TypeError( + f"saver_def must be of type SaverDef. " + f"Received type: {type(saver_def)}.") + + # Sets graph to default graph if it's not passed in. + graph = graph or ops.get_default_graph() + + # Creates a MetaGraphDef proto. + meta_graph_def = meta_graph_pb2.MetaGraphDef() + # Adds meta_info_def. + if not meta_info_def: + meta_info_def = meta_graph_pb2.MetaGraphDef.MetaInfoDef() + + # Set the tf version strings to the current tf build. + meta_info_def.tensorflow_version = versions.__version__ + meta_info_def.tensorflow_git_version = versions.__git_version__ + meta_graph_def.meta_info_def.MergeFrom(meta_info_def) + + # Adds graph_def or the default. + if not graph_def: + meta_graph_def.graph_def.MergeFrom(graph.as_graph_def(add_shapes=True)) + else: + meta_graph_def.graph_def.MergeFrom(graph_def) + + # Fills in meta_info_def.stripped_op_list using the ops from graph_def. + # pylint: disable=g-explicit-length-test + if len(meta_graph_def.meta_info_def.stripped_op_list.op) == 0: + meta_graph_def.meta_info_def.stripped_op_list.MergeFrom( + stripped_op_list_for_graph(meta_graph_def.graph_def)) + # pylint: enable=g-explicit-length-test + + # Strip default valued attributes in graph_def. + if strip_default_attrs: + strip_graph_default_valued_attrs(meta_graph_def) + + # Adds saver_def. + if saver_def: + meta_graph_def.saver_def.MergeFrom(saver_def) + + # Adds collection_list. + if collection_list is not None: + clist = collection_list + else: + clist = graph.get_all_collection_keys() + + for ctype in clist: + if clear_extraneous_savers and ctype == ops.GraphKeys.SAVERS: + # Avoid importing Saver here + from_proto = ops.get_from_proto_function(ctype) + add_collection_def(meta_graph_def, ctype, + graph=graph, + export_scope=export_scope, + exclude_nodes=exclude_nodes, + override_contents=[from_proto(saver_def)]) + else: + add_collection_def(meta_graph_def, ctype, + graph=graph, + export_scope=export_scope, + exclude_nodes=exclude_nodes) + return meta_graph_def + + +def read_meta_graph_file(filename): + """Reads a file containing `MetaGraphDef` and returns the protocol buffer. + + Args: + filename: `meta_graph_def` filename including the path. + + Returns: + A `MetaGraphDef` protocol buffer. + + Raises: + IOError: If the file doesn't exist, or cannot be successfully parsed. + """ + meta_graph_def = meta_graph_pb2.MetaGraphDef() + if not file_io.file_exists(filename): + raise IOError(f"File does not exist. Received: {filename}.") + # First try to read it as a binary file. + with file_io.FileIO(filename, "rb") as f: + file_content = f.read() + try: + meta_graph_def.ParseFromString(file_content) + if sys.byteorder == "big": + bst.swap_tensor_content_in_graph_function(meta_graph_def, "little", "big") + return meta_graph_def + except Exception: # pylint: disable=broad-except + pass + + # Next try to read it as a text file. + try: + text_format.Merge(file_content.decode("utf-8"), meta_graph_def) + if sys.byteorder == "big": + bst.swap_tensor_content_in_graph_function(meta_graph_def, "little", "big") + except text_format.ParseError as e: + raise IOError(f"Cannot parse file {filename}: {str(e)}.") + + return meta_graph_def + + +def import_scoped_meta_graph(meta_graph_or_file, + clear_devices=False, + graph=None, + import_scope=None, + input_map=None, + unbound_inputs_col_name="unbound_inputs", + restore_collections_predicate=(lambda key: True)): + """Recreates a `Graph` saved in a `MetaGraphDef` proto. + + This function takes a `MetaGraphDef` protocol buffer as input. If + the argument is a file containing a `MetaGraphDef` protocol buffer , + it constructs a protocol buffer from the file content. The function + then adds all the nodes from the `graph_def` field to the + current graph, recreates the desired collections, and returns a dictionary of + all the Variables imported into the name scope. + + In combination with `export_scoped_meta_graph()`, this function can be used to + + * Serialize a graph along with other Python objects such as `QueueRunner`, + `Variable` into a `MetaGraphDef`. + + * Restart training from a saved graph and checkpoints. + + * Run inference from a saved graph and checkpoints. + + Args: + meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including + the path) containing a `MetaGraphDef`. + clear_devices: Boolean which controls whether to clear device information + from graph_def. Default false. + graph: The `Graph` to import into. If `None`, use the default graph. + import_scope: Optional `string`. Name scope into which to import the + subgraph. If `None`, the graph is imported to the root name scope. + input_map: A dictionary mapping input names (as strings) in `graph_def` to + `Tensor` objects. The values of the named input tensors in the imported + graph will be re-mapped to the respective `Tensor` values. + unbound_inputs_col_name: Collection name for looking up unbound inputs. + restore_collections_predicate: a predicate on collection names. A collection + named c (i.e whose key is c) will be restored iff + 1) `restore_collections_predicate(c)` is True, and + 2) `c != unbound_inputs_col_name`. + + Returns: + A dictionary of all the `Variables` imported into the name scope. + + Raises: + ValueError: If the graph_def contains unbound inputs. + """ + return import_scoped_meta_graph_with_return_elements( + meta_graph_or_file, clear_devices, graph, import_scope, input_map, + unbound_inputs_col_name, restore_collections_predicate)[0] + + +def import_scoped_meta_graph_with_return_elements( + meta_graph_or_file, + clear_devices=False, + graph=None, + import_scope=None, + input_map=None, + unbound_inputs_col_name="unbound_inputs", + restore_collections_predicate=(lambda key: True), + return_elements=None): + """Imports graph from `MetaGraphDef` and returns vars and return elements. + + This function takes a `MetaGraphDef` protocol buffer as input. If + the argument is a file containing a `MetaGraphDef` protocol buffer , + it constructs a protocol buffer from the file content. The function + then adds all the nodes from the `graph_def` field to the + current graph, recreates the desired collections, and returns a dictionary of + all the Variables imported into the name scope. + + In combination with `export_scoped_meta_graph()`, this function can be used to + + * Serialize a graph along with other Python objects such as `QueueRunner`, + `Variable` into a `MetaGraphDef`. + + * Restart training from a saved graph and checkpoints. + + * Run inference from a saved graph and checkpoints. + + Args: + meta_graph_or_file: `MetaGraphDef` protocol buffer or filename (including + the path) containing a `MetaGraphDef`. + clear_devices: Boolean which controls whether to clear device information + from graph_def. Default false. + graph: The `Graph` to import into. If `None`, use the default graph. + import_scope: Optional `string`. Name scope into which to import the + subgraph. If `None`, the graph is imported to the root name scope. + input_map: A dictionary mapping input names (as strings) in `graph_def` to + `Tensor` objects. The values of the named input tensors in the imported + graph will be re-mapped to the respective `Tensor` values. + unbound_inputs_col_name: Collection name for looking up unbound inputs. + restore_collections_predicate: a predicate on collection names. A collection + named c (i.e whose key is c) will be restored iff + 1) `restore_collections_predicate(c)` is True, and + 2) `c != unbound_inputs_col_name`. + return_elements: A list of strings containing operation names in the + `MetaGraphDef` that will be returned as `Operation` objects; and/or + tensor names in `MetaGraphDef` that will be returned as `Tensor` objects. + + Returns: + A tuple of ( + dictionary of all the `Variables` imported into the name scope, + list of `Operation` or `Tensor` objects from the `return_elements` list). + + Raises: + ValueError: If the graph_def contains unbound inputs. + + """ + if context.executing_eagerly(): + raise ValueError("Exporting/importing meta graphs is not supported when " + "eager execution is enabled.") + if isinstance(meta_graph_or_file, meta_graph_pb2.MetaGraphDef): + meta_graph_def = meta_graph_or_file + else: + meta_graph_def = read_meta_graph_file(meta_graph_or_file) + + if unbound_inputs_col_name: + for key, col_def in meta_graph_def.collection_def.items(): + if key == unbound_inputs_col_name: + kind = col_def.WhichOneof("kind") + field = getattr(col_def, kind) + if field.value and ( + not input_map or + sorted([compat.as_str(v) for v in field.value]) != + sorted(input_map)): + raise ValueError("Graph contains unbound inputs: %s. Must " + "provide these inputs through input_map." % ",".join( + compat.as_str(v) + for v in field.value + if not input_map or v not in input_map)) + break + + # Sets graph to default graph if it's not passed in. + graph = graph or ops.get_default_graph() + + # Gathers the list of nodes we are interested in. + with graph.as_default(): + producer_op_list = None + if meta_graph_def.meta_info_def.HasField("stripped_op_list"): + producer_op_list = meta_graph_def.meta_info_def.stripped_op_list + input_graph_def = meta_graph_def.graph_def + # Remove all the explicit device specifications for this node. This helps to + # make the graph more portable. + if clear_devices: + for node in input_graph_def.node: + node.device = "" + + scope_to_prepend_to_names = graph.unique_name( + import_scope or "", mark_as_used=False) + + imported_return_elements = importer.import_graph_def( + input_graph_def, + name=(import_scope or scope_to_prepend_to_names), + input_map=input_map, + producer_op_list=producer_op_list, + return_elements=return_elements) + + # TensorFlow versions before 1.9 (not inclusive) exported SavedModels + # without a VariableDef.trainable field set. + tf_version = meta_graph_def.meta_info_def.tensorflow_version + if not tf_version: + variables_have_trainable = True + else: + variables_have_trainable = ( + packaging_version.parse(tf_version) >= packaging_version.parse("1.9")) + + # Sort collections so we see TRAINABLE_VARIABLES first and can default these + # variables to trainable if the value is not set in their VariableDef. + sorted_collections = [] + if ops.GraphKeys.TRAINABLE_VARIABLES in meta_graph_def.collection_def: + sorted_collections.append( + (ops.GraphKeys.TRAINABLE_VARIABLES, + meta_graph_def.collection_def[ops.GraphKeys.TRAINABLE_VARIABLES])) + for key, value in sorted(meta_graph_def.collection_def.items()): + if key != ops.GraphKeys.TRAINABLE_VARIABLES: + sorted_collections.append((key, value)) + + # Restores all the other collections. + variable_objects = {} + for key, col_def in sorted_collections: + # Don't add unbound_inputs to the new graph. + if key == unbound_inputs_col_name: + continue + if not restore_collections_predicate(key): + continue + + kind = col_def.WhichOneof("kind") + if kind is None: + logging.error("Cannot identify data type for collection %s. Skipping.", + key) + continue + from_proto = ops.get_from_proto_function(key) + + # Temporary change to allow the TFMA evaluator to read metric variables + # saved as a bytes list. + # TODO(kathywu): Remove this hack once cl/248406059 has been submitted. + if key == ops.GraphKeys.METRIC_VARIABLES: + # Metric variables will use the same proto functions as GLOBAL_VARIABLES + from_proto = ops.get_from_proto_function(ops.GraphKeys.GLOBAL_VARIABLES) + if from_proto and kind == "bytes_list": + proto_type = ops.get_collection_proto_type(key) + if key in ops.GraphKeys._VARIABLE_COLLECTIONS: # pylint: disable=protected-access + for value in col_def.bytes_list.value: + variable = variable_objects.get(value, None) + if variable is None: + proto = proto_type() + proto.ParseFromString(value) + if not variables_have_trainable: + # If the VariableDef proto does not contain a "trainable" + # property because it was exported before that property was + # added, we default it to whether the variable is in the + # TRAINABLE_VARIABLES collection. We've sorted + # TRAINABLE_VARIABLES to be first, so trainable variables will + # be created from that collection. + proto.trainable = (key == ops.GraphKeys.TRAINABLE_VARIABLES) + variable = from_proto( + proto, import_scope=scope_to_prepend_to_names) + variable_objects[value] = variable + graph.add_to_collection(key, variable) + else: + for value in col_def.bytes_list.value: + proto = proto_type() + proto.ParseFromString(value) + graph.add_to_collection( + key, from_proto( + proto, import_scope=scope_to_prepend_to_names)) + else: + field = getattr(col_def, kind) + if key in _COMPAT_COLLECTION_LIST: + logging.warning( + "The saved meta_graph is possibly from an older release:\n" + "'%s' collection should be of type 'byte_list', but instead " + "is of type '%s'.", key, kind) + if kind == "node_list": + for value in field.value: + col_op = graph.as_graph_element( + ops.prepend_name_scope(value, scope_to_prepend_to_names)) + graph.add_to_collection(key, col_op) + elif kind == "int64_list": + # NOTE(opensource): This force conversion is to work around the fact + # that Python2 distinguishes between int and long, while Python3 has + # only int. + for value in field.value: + graph.add_to_collection(key, int(value)) + else: + for value in field.value: + graph.add_to_collection( + key, ops.prepend_name_scope(value, scope_to_prepend_to_names)) + + var_list = {} + variables = graph.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, + scope=scope_to_prepend_to_names) + for v in variables: + var_list[ops.strip_name_scope(v.name, scope_to_prepend_to_names)] = v + + return var_list, imported_return_elements + + +def export_scoped_meta_graph(filename=None, + graph_def=None, + graph=None, + export_scope=None, + as_text=False, + unbound_inputs_col_name="unbound_inputs", + clear_devices=False, + saver_def=None, + clear_extraneous_savers=False, + strip_default_attrs=False, + save_debug_info=False, + **kwargs): + """Returns `MetaGraphDef` proto. Optionally writes it to filename. + + This function exports the graph, saver, and collection objects into + `MetaGraphDef` protocol buffer with the intention of it being imported + at a later time or location to restart training, run inference, or be + a subgraph. + + Args: + filename: Optional filename including the path for writing the + generated `MetaGraphDef` protocol buffer. + graph_def: `GraphDef` protocol buffer. + graph: The `Graph` to export. If `None`, use the default graph. + export_scope: Optional `string`. Name scope under which to extract + the subgraph. The scope name will be stripped from the node definitions + for easy import later into new name scopes. If `None`, the whole graph + is exported. + as_text: If `True`, writes the `MetaGraphDef` as an ASCII proto. + unbound_inputs_col_name: Optional `string`. If provided, a string collection + with the given name will be added to the returned `MetaGraphDef`, + containing the names of tensors that must be remapped when importing the + `MetaGraphDef`. + clear_devices: Boolean which controls whether to clear device information + before exporting the graph. + saver_def: `SaverDef` protocol buffer. + clear_extraneous_savers: Remove any Saver-related information from the + graph (both Save/Restore ops and SaverDefs) that are not associated + with the provided SaverDef. + strip_default_attrs: Set to true if default valued attributes must be + removed while exporting the GraphDef. + save_debug_info: If `True`, save the GraphDebugInfo to a separate file, + which in the same directory of filename and with `_debug` added before the + file extension. + **kwargs: Optional keyed arguments, including meta_info_def and + collection_list. + + Returns: + A `MetaGraphDef` proto and dictionary of `Variables` in the exported + name scope. + + Raises: + ValueError: When the `GraphDef` is larger than 2GB. + ValueError: When executing in Eager mode and either `graph_def` or `graph` + is undefined. + """ + if context.executing_eagerly() and not (graph_def is not None and + graph is not None): + raise ValueError("Exporting/importing meta graphs is not supported when " + "Eager Execution is enabled.") + graph = graph or ops.get_default_graph() + + exclude_nodes = None + unbound_inputs = [] + if export_scope or clear_extraneous_savers or clear_devices: + if graph_def: + new_graph_def = graph_pb2.GraphDef() + new_graph_def.versions.CopyFrom(graph_def.versions) + new_graph_def.library.CopyFrom(graph_def.library) + + if clear_extraneous_savers: + exclude_nodes = _find_extraneous_saver_nodes(graph_def, saver_def) + + for node_def in graph_def.node: + if _should_include_node(node_def.name, export_scope, exclude_nodes): + new_node_def = _node_def(node_def, export_scope, unbound_inputs, + clear_devices=clear_devices) + new_graph_def.node.extend([new_node_def]) + graph_def = new_graph_def + else: + # Only do this complicated work if we want to remove a name scope. + graph_def = graph_pb2.GraphDef() + # pylint: disable=protected-access + graph_def.versions.CopyFrom(graph.graph_def_versions) + bytesize = 0 + + if clear_extraneous_savers: + exclude_nodes = _find_extraneous_saver_nodes(graph.as_graph_def(), + saver_def) + + for key in sorted(graph._nodes_by_id): + if _should_include_node(graph._nodes_by_id[key].name, + export_scope, + exclude_nodes): + value = graph._nodes_by_id[key] + # pylint: enable=protected-access + node_def = _node_def(value.node_def, export_scope, unbound_inputs, + clear_devices=clear_devices) + graph_def.node.extend([node_def]) + if value.outputs: + assert "_output_shapes" not in graph_def.node[-1].attr + graph_def.node[-1].attr["_output_shapes"].list.shape.extend([ + output.get_shape().as_proto() for output in value.outputs]) + bytesize += value.node_def.ByteSize() + if bytesize >= (1 << 31) or bytesize < 0: + raise ValueError( + "GraphDef cannot be larger than 2GB. " + f"Received size: {bytesize}.") + + graph._copy_functions_to_graph_def(graph_def, bytesize) # pylint: disable=protected-access + + # It's possible that not all the inputs are in the export_scope. + # If we would like such information included in the exported meta_graph, + # add them to a special unbound_inputs collection. + if unbound_inputs_col_name: + # Clears the unbound_inputs collections. + graph.clear_collection(unbound_inputs_col_name) + for k in unbound_inputs: + graph.add_to_collection(unbound_inputs_col_name, k) + + var_list = {} + variables = graph.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, + scope=export_scope) + for v in variables: + if _should_include_node(v, export_scope, exclude_nodes): + var_list[ops.strip_name_scope(v.name, export_scope)] = v + + scoped_meta_graph_def = create_meta_graph_def( + graph_def=graph_def, + graph=graph, + export_scope=export_scope, + exclude_nodes=exclude_nodes, + clear_extraneous_savers=clear_extraneous_savers, + saver_def=saver_def, + strip_default_attrs=strip_default_attrs, + **kwargs) + + if filename: + graph_io.write_graph( + scoped_meta_graph_def, + os.path.dirname(filename), + os.path.basename(filename), + as_text=as_text) + if save_debug_info: + name, _ = os.path.splitext(filename) + debug_filename = "{name}{ext}".format(name=name, ext=".debug") + + # Gets the operation from the graph by the name. Excludes variable nodes, + # so only the nodes in the frozen models are included. + # TODO(liufengdb): fix this for functions. + ops_to_export = [] + for node in scoped_meta_graph_def.graph_def.node: + scoped_op_name = ops.prepend_name_scope(node.name, export_scope) + ops_to_export.append(("", graph.get_operation_by_name(scoped_op_name))) + + graph_debug_info = error_interpolation.create_graph_debug_info_def( + ops_to_export) + + graph_io.write_graph( + graph_debug_info, + os.path.dirname(debug_filename), + os.path.basename(debug_filename), + as_text=as_text) + + return scoped_meta_graph_def, var_list + + +def copy_scoped_meta_graph(from_scope, to_scope, + from_graph=None, to_graph=None): + """Copies a sub-meta_graph from one scope to another. + + Args: + from_scope: `String` name scope containing the subgraph to be copied. + to_scope: `String` name scope under which the copied subgraph will reside. + from_graph: Optional `Graph` from which to copy the subgraph. If `None`, the + default graph is use. + to_graph: Optional `Graph` to which to copy the subgraph. If `None`, the + default graph is used. + + Returns: + A dictionary of `Variables` that has been copied into `to_scope`. + + Raises: + ValueError: If `from_scope` and `to_scope` are the same while + `from_graph` and `to_graph` are also the same. + """ + from_graph = from_graph or ops.get_default_graph() + to_graph = to_graph or ops.get_default_graph() + + if from_graph == to_graph and from_scope == to_scope: + raise ValueError("'from_scope' and 'to_scope' need to be different " + "when performing copy in the same graph. " + f"Received: 'from_graph': {from_graph}, " + f"'to_graph': {to_graph}, " + f"'from_scope': {from_scope}, 'to_scope': {to_scope}.") + + orig_meta_graph, var_list = export_scoped_meta_graph( + export_scope=from_scope, graph=from_graph) + var_list = import_scoped_meta_graph(orig_meta_graph, + graph=to_graph, + import_scope=to_scope) + return var_list diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/none_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/none_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..2cfb8aae1c503545b6530c0d30ffc555a1ccce29 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/none_tensor.py @@ -0,0 +1,86 @@ +# 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. +# ============================================================================== +"""NoneTensor and NoneTensorSpec classes.""" + +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry + + +# TODO(b/149584798): add tests for non-tf.data functionality. +class NoneTensor(composite_tensor.CompositeTensor): + """Composite tensor representation for `None` value.""" + + @property + def _type_spec(self): + return NoneTensorSpec() + + +# TODO(b/149584798): add tests for non-tf.data functionality. +@type_spec_registry.register("tf.NoneTensorSpec") +class NoneTensorSpec(type_spec.BatchableTypeSpec): + """Type specification for `None` value.""" + + @property + def value_type(self): + return NoneTensor + + def _serialize(self): + return () + + @property + def _component_specs(self): + return [] + + def _to_components(self, value): + return [] + + def _from_components(self, components): + return + + def _to_tensor_list(self, value): + return [] + + @staticmethod + def from_value(value): + return NoneTensorSpec() + + def _batch(self, batch_size): + return NoneTensorSpec() + + def _unbatch(self): + return NoneTensorSpec() + + def _to_batched_tensor_list(self, value): + return [] + + def _to_legacy_output_types(self): + return self + + def _to_legacy_output_shapes(self): + return self + + def _to_legacy_output_classes(self): + return self + + def most_specific_compatible_shape(self, other): + if type(self) is not type(other): + raise ValueError("No `TypeSpec` is compatible with both {} and {}".format( + self, other)) + return self + + +type_spec.register_type_spec_from_value_converter(type(None), + NoneTensorSpec.from_value) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_callbacks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..16298e45ac34df22e501f8f73aa488380e5c8c45 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_callbacks.py @@ -0,0 +1,214 @@ +# 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. +# ============================================================================== +"""Unified callbacks op execution and creation under eager and graph modes.""" + +from tensorflow.python.eager import context +from tensorflow.python.eager import execute + + +def add_op_callback(callback_fn): + r"""Add a thread-local callback that intercepts op execution and op creation. + + The `callback_fn` will be invoked immediately after any of the three types + of events: + - The execution of an TensorFlow operation ("op" for short hereafter) + under eager mode, + - The execution of a FuncGraph under eager mode, + - The creation of an op during graph construction (e.g., in + @tf.function-decorated Python functions). + + Known limitations: + 1. Under graph mode, overriding the output tensors of control-flow ops, + including "If", "StatelessIf" and "While", may cause errors + (b/139668453). Overriding other tensors in a graph consisting of such + control-flow ops is okay. + 2. Under eager mode, calling eager ops from the callback function itself + may lead to recursion stack overflow. This can be prevented by + returning from the callback function immediately on encountering the + op type involved (b/140334369). + + Args: + callback_fn: A callback_fn that has the following signature: + def callback_fn(op_type, + inputs, + attrs, + outputs, + op_name=None, + graph=None): + # op_type: The type of the op, as a string. E.g., "MatMul". + # For the special case of FuncGraph execution, op_type + # takes the name of the graph name, e.g., + # "__inference_my_func_24". + # inputs: (`tuple` of `Tensor`s) Input tensors to the op or the + # FuncGraph. + # - In eager execution, these are `EagerTensor`s. + # - In graph construction, these are non-eager `Tensor`s + # that form the inputs to the just-created op. + # attrs: The attributes of the op or FuncGraph of which the execution + # or creation caused the current invocation of the callback. + # This is applicable to both eager- and graph-based execution, + # as well as graph construction. + # This is a tuple of alternating attribute keys and attribute + # values. E.g., `('adjoint_a', False, 'adjoint_b', False)`. + # outputs: (`tuple of `Tensor`s) Output tensors from the op or + # FuncGraph. + # In eager execution, these are `EagerTensor`s. + # In graph construction, these are non-eager `Tensor`s that + # are the outputs of the just-created op. + # op_name: Name of the op. + # - If the current invocation of the callback is due to the + # eager execution of an op or FuncGraph, this will be + # `None`, as op names are meaningless in eager execution. + # - In graph construction, this is the name of the op, e.g., + # "MatMul_2". + # graph: The graph that the op belongs to (if any). + # - In eager execution of an op or FuncGraph, this is `None`. + # - In graph construction, this is the op's enclosing graph + # as a `tf.Graph` object. + # + # Return values: + # This callback function is expected to return `None` or + # a `list` or `tuple` of `Tensor`s with its length matching + # `len(outputs)`, in the order that corresponds to that of the + # `outputs` argument. + # If the return value is `None`, downstream execution or graph + # construction will be unaffected. + # However, if the return value is a `list` or `tuple` of `Tensor`s, + # - In eager execution, these returned `Tensor`s should be + # `EagerTensor`s. Their values will replace the original values of + # `outputs` for downstream eager execution. (*Not implemented yet*). + # - In graph construction, these returned `Tensor`s should be + # non-eager `Tensor`s. Their values will replace the original + # `outputs` for downstream graph construction. + + Raises: + ValueEror: If `callback_fn` is `None` or not callable. + """ + # TODO(b/139668041): Implement support for overriding `EagerTensor`s from + # callback. + if callback_fn is None: + raise ValueError("Passed callback function cannot be None.") + if not callable(callback_fn): + raise ValueError( + "Callback function passed to op_callback() is expected to be callable, " + f"but got {callback_fn} of type {type(callback_fn)}.") + ctx = context.context() + ctx.add_op_callback(callback_fn) + if ctx.executing_eagerly(): + # Monkey-patch `execute.execute()`. + execute.execute = execute.execute_with_callbacks + + +def should_invoke_op_callbacks(): + """Determine if op callbacks are present and should be invoked. + + Returns: + A thread-local result (boolean) indicating whether any op callback(s) exist + and should be invoked. + """ + ctx = context.context() + return ctx.op_callbacks and not ctx.invoking_op_callbacks + + +def remove_op_callback(op_callback): + """Remove an already-added op callback. + + Args: + op_callback: The op callback to be removed. + + Raises: + KeyError: If `op_callback` has not been registered using `add_op_callback()` + before. + """ + ctx = context.context() + ctx.remove_op_callback(op_callback) + if ctx.executing_eagerly() and not ctx.op_callbacks: + # Undo monkey-patch of execute.execute if there are no more callbacks. + execute.execute = execute.quick_execute + + +def clear_op_callbacks(): + """Clear all op callbacks registered in the current thread.""" + for callback in context.context().op_callbacks: + remove_op_callback(callback) + + +def invoke_op_callbacks(op_type, + inputs, + attrs, + outputs, + op_name=None, + graph=None): + r"""Invoke the callbacks that exist in the current scope (if any). + + If no callbacks are present in the current scope, this method returns + immediately. + + Args: + op_type: Type of the operation (e.g., "MatMul"). + inputs: Input tensors to the op. These are `EagerTensor`s in the case of + eager execution of ops or `FuncGraph`s, and are non-eager `Tensor`s in the + case of graph construction. + attrs: Attributes of the op, as `tuple` of alternating keys and values. + outputs: Output tensors from the op. These are `EagerTensor`s in the case of + eager execution and are non-eager `Tensor`s in the case of graph + construction. + op_name: Name of the op. Applicable if and only if this method is invoked + due to the graph construction of an op or the eager execution of a + `FuncGraph`. + graph: The graph involved (if any). + - In the case if the eager execution of an op or FuncGraph, this is + `None`. + - In the case of the graph construction of an op, this is the `tf.Graph` + object being built. + + Returns: + `None`, or a `list` or `tuple` of output tenors that will override the + original (input) `outputs`. + """ + ctx = context.context() + if ctx.op_callbacks: + # Guards against stack overflow that can result from recursive invocation + # due to op constructions inside client-supplied op callbacks. + ctx.invoking_op_callbacks = True + try: + if isinstance(attrs, dict): + attrs_list = [] + for key in attrs: + attrs_list.append(key) + attrs_list.append(attrs[key]) + attrs_tuple = tuple(attrs_list) + else: + attrs_tuple = attrs + + new_outputs = outputs + for callback in ctx.op_callbacks: + new_outputs = callback( + op_type, + inputs, + attrs_tuple, + new_outputs, + op_name=op_name, + graph=graph) + if new_outputs is not None and len(new_outputs) != len(outputs): + raise ValueError( + f"The op callback returned {len(new_outputs)} tensors, which " + f"does not match the original number of outputs of op {op_name} " + f"({len(outputs)}).") + return new_outputs + finally: + ctx.invoking_op_callbacks = False + else: + return outputs diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_library.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_library.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac4f9b73460da0374c44c85d0c5c8f214c4c1d8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_library.py @@ -0,0 +1,880 @@ +# 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. +# ============================================================================== + +"""Class to hold a library of OpDefs and use it to create Brain operations.""" + +from google.protobuf import text_format +from tensorflow.core.config import flags +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import tensor_pb2 +from tensorflow.core.framework import tensor_shape_pb2 +from tensorflow.core.framework import types_pb2 +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import op_def_library_pybind +from tensorflow.python.framework import op_def_registry +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import compat +from tensorflow.python.util import tf_contextlib + + +def _Attr(op_def, name): + for attr in op_def.attr: + if attr.name == name: + return attr + raise TypeError(f"Inconsistent OpDef for '{op_def.name}', missing attr " + f"'{name}'") + + +def _AttrValue(attr_protos, name, op_type_name): + if name in attr_protos: + return attr_protos[name] + raise TypeError(f"Inconsistent OpDef for '{op_type_name}', missing attr " + f"'{name}' from '{attr_protos}'.") + + +def _SatisfiesTypeConstraint(dtype, attr_def, param_name): + if attr_def.HasField("allowed_values"): + allowed_list = attr_def.allowed_values.list.type + allowed_values = ", ".join(dtypes.as_dtype(x).name for x in allowed_list) + if dtype not in allowed_list: + raise TypeError( + f"Value passed to parameter '{param_name}' has DataType " + f"{dtypes.as_dtype(dtype).name} not in list of allowed values: " + f"{allowed_values}") + + +def _SatisfiesLengthConstraint(length, attr_def, param_name, op_type_name): + if attr_def.has_minimum and length < attr_def.minimum: + raise ValueError(f"Attr '{param_name}' of '{op_type_name}' Op passed list " + f"of length {length} less than minimum " + f"{attr_def.minimum}.") + + +def _SatisfiesAllowedStringsConstraint(value, attr_def, arg_name, op_type_name): + if value not in attr_def.allowed_values.list.s: + allowed_values = '", "'.join( + map(compat.as_text, attr_def.allowed_values.list.s)) + raise ValueError(f"Attr '{arg_name}' of '{op_type_name}' Op passed string " + f"'{compat.as_text(value)}' not in: \"{allowed_values}\".") + + +def _SatisfiesIntMinimumConstraint(value, attr_def, arg_name, op_type_name): + if value < attr_def.minimum: + raise ValueError(f"Attr '{arg_name}' of '{op_type_name}' Op passed {value} " + f"less than minimum {attr_def.minimum}.") + + +def _IsListParameter(arg): + if arg.number_attr: + return True + elif arg.type_list_attr: + return True + return False + + +def _NumTypeFields(arg): + num = 0 + if arg.type != types_pb2.DT_INVALID: num += 1 + if arg.type_attr: num += 1 + if arg.type_list_attr: num += 1 + return num + + +def _IsListValue(v): + return isinstance(v, (list, tuple)) + + +def _Flatten(l): + """Converts [1, 2, [3, 4], [5]] to [1, 2, 3, 4, 5].""" + # [1, 2, [3, 4], [5]] -> [[1], [2], [3, 4], [5]] + l_of_l = [x if _IsListValue(x) else [x] for x in l] + # [[1], [2], [3, 4], [5]] -> [1, 2, 3, 4, 5] + return [item for sublist in l_of_l for item in sublist] + + +def _Restructure(l, structure): + """Returns the elements of list l structured according to the given structure. + + A structure is represented by a list whose elements are either + `None` or a non-negative integer. `None` corresponds to a single + element in the output list, and an integer N corresponds to a nested + list of length N. + + The function returns a data structure whose shape is given by + `structure`, and whose elements are taken from `l`. If `structure` + is a singleton, the function returns the single data structure + implied by the 0th element of `structure`. For example: + + _Restructure(["foo", "bar", "baz", "qux"], [None, 2, None]) + -> ["foo", ["bar", "baz"], "qux"] + + _Restructure(["foo"], [None]) -> "foo" + + _Restructure(["foo"], [1]) -> ["foo"] + + _Restructure([], [0]) -> [] + + Args: + l: A list. + structure: A list whose elements are either `None` or a non-negative + integer. + + Returns: + The elements of `l`, restructured according to `structure`. If + `structure` is a list of length 1, this function returns the + single data structure implied by `structure[0]`. + + """ + result = [] + current_index = 0 + for element in structure: + if element is None: + result.append(l[current_index]) + current_index += 1 + else: + result.append(l[current_index:current_index+element]) + current_index += element + + if len(result) == 1: + return result[0] + else: + return tuple(result) + + +def _MakeFloat(v, arg_name): + if not isinstance(v, compat.real_types): + raise TypeError(f"Expected float for argument '{arg_name}' not {repr(v)}.") + return float(v) + + +def _MakeInt(v, arg_name): + if isinstance(v, str): + raise TypeError(f"Expected int for argument '{arg_name}' not {repr(v)}.") + try: + return int(v) + except (ValueError, TypeError): + raise TypeError(f"Expected int for argument '{arg_name}' not {repr(v)}.") + + +def _MakeStr(v, arg_name): + if not isinstance(v, compat.bytes_or_text_types): + raise TypeError(f"Expected string for argument '{arg_name}' not {repr(v)}.") + return compat.as_bytes(v) # Convert unicode strings to bytes. + + +def _MakeBool(v, arg_name): + if not isinstance(v, bool): + raise TypeError(f"Expected bool for argument '{arg_name}' not {repr(v)}.") + return v + + +def _MakeType(v, arg_name): + try: + v = dtypes.as_dtype(v).base_dtype + except TypeError: + raise TypeError(f"Expected DataType for argument '{arg_name}' not " + f"{repr(v)}.") + return v.as_datatype_enum + + +def _MakeShape(v, arg_name): + """Convert v into a TensorShapeProto.""" + # Args: + # v: A TensorShapeProto, a list of ints, or a tensor_shape.TensorShape. + # arg_name: String, for error messages. + + # Returns: + # A TensorShapeProto. + if isinstance(v, tensor_shape_pb2.TensorShapeProto): + for d in v.dim: + if d.name: + logging.warning("Warning: TensorShapeProto with a named dimension: %s", + str(v)) + break + return v + try: + return tensor_shape.as_shape(v).as_proto() + except TypeError as e: + raise TypeError(f"Error converting {repr(v)} (arg name = {arg_name}) to a " + f"TensorShape: {e}") + except ValueError as e: + raise TypeError(f"Error converting {repr(v)} (arg name = {arg_name}) to a " + f"TensorShape: {e}") + + +def _MakeTensor(v, arg_name): + """Ensure v is a TensorProto.""" + if isinstance(v, tensor_pb2.TensorProto): + return v + raise TypeError( + f"Don't know how to convert {repr(v)} to a TensorProto for argument " + f"'{arg_name}'") + + +def _MakeFunc(v, arg_name): + """Ensure v is a func.""" + if isinstance(v, attr_value_pb2.NameAttrList): + return v + if isinstance(v, compat.bytes_or_text_types): + fn_attr = attr_value_pb2.NameAttrList(name=v) + elif hasattr(v, "add_to_graph"): + v.add_to_graph(ops.get_default_graph()) + if hasattr(v, "_as_name_attr_list"): + fn_attr = v._as_name_attr_list # pylint: disable=protected-access + else: + fn_attr = attr_value_pb2.NameAttrList(name=v.name) + else: + raise TypeError(f"Don't know how to convert {repr(v)} to a func for " + f"argument {arg_name}") + return fn_attr + + +# pylint: disable=g-doc-return-or-yield +@tf_contextlib.contextmanager +def _MaybeColocateWith(inputs): + """A context manager for (maybe) colocating with a list of input tensors. + + Args: + inputs: A list of `Tensor` or `Operation` objects. + + Returns: + A context manager. + """ + if not inputs: + yield + else: + # NOTE(mrry): The `ops.colocate_with()` function accepts only a single + # op or tensor, so we create one context manager per element in the list. + with ops.colocate_with(inputs[0]), _MaybeColocateWith(inputs[1:]): + yield +# pylint: enable=g-doc-return-or-yield + + +def apply_op(op_type_name, name=None, **keywords): # pylint: disable=invalid-name + """Add a node invoking a registered Op to a graph. + + Example usage: + # input1 and input2 can be Tensors or anything ops.convert_to_tensor() + # will convert to a Tensor. + op_def_library.apply_op("op", input1=input1, input2=input2) + # Can specify a node name. + op_def_library.apply_op("op", input1=input1, name="node_name") + # Must use keyword arguments, with the names specified in the OpDef. + op_def_library.apply_op("op", input_name=input, attr_name=attr) + + All attrs must either be inferred from an input or specified. + (If inferred, the attr must not be specified.) If an attr has a default + value specified in the Op's OpDef, then you may pass None as the value + of that attr to get the default. + + Args: + op_type_name: string. Must match the name field of a registered Op. + name: string. Optional name of the created op. + **keywords: input Tensor and attr arguments specified by name, and optional + parameters to pass when constructing the Operation. + + Returns: + The Tensor(s) representing the output of the operation, or the Operation + itself if there are no outputs. + + Raises: + RuntimeError: On some errors. + TypeError: On some errors. + ValueError: On some errors. + """ + output_structure, is_stateful, op, outputs = _apply_op_helper( + op_type_name, name, **keywords) + if output_structure: + res = _Restructure(ops.convert_n_to_tensor(outputs), output_structure) + if isinstance(res, list) and not res and is_stateful: + return op + else: + return res + else: + return op + + +# This is temporary Python/C++ code duplication until all of it can be ported +# over to C++. +# LINT.IfChange +def _ExtractAttrProto(op_type_name, op_def, attrs, attr_protos): + """Extracts `attr_protos`. For use in _apply_op_helper.""" + for attr_def in op_def.attr: + key = attr_def.name + value = attrs[key] + + if attr_def.HasField("default_value") and value is None: + attr_value = attr_value_pb2.AttrValue() + attr_value.CopyFrom(attr_def.default_value) + attr_protos[key] = attr_value + continue + + attr_value = value_to_attr_value(value, attr_def.type, key) + if attr_def.type.startswith("list("): + _SatisfiesLengthConstraint(len(value), attr_def, key, op_type_name) + if attr_def.HasField("allowed_values"): + if attr_def.type == "string": + _SatisfiesAllowedStringsConstraint(attr_value.s, attr_def, key, + op_type_name) + elif attr_def.type == "list(string)": + for value in attr_value.list.s: + _SatisfiesAllowedStringsConstraint(value, attr_def, key, op_type_name) + if attr_def.has_minimum and attr_def.type == "int": + _SatisfiesIntMinimumConstraint(attr_value.i, attr_def, key, op_type_name) + if attr_def.type == "type": + _SatisfiesTypeConstraint(attr_value.type, attr_def, key) + if attr_def.type == "list(type)": + for value in attr_value.list.type: + _SatisfiesTypeConstraint(value, attr_def, key) + + attr_protos[key] = attr_value + + +def _ExtractOutputStructure(op_type_name, op_def, attr_protos, + output_structure): + """Extracts `output_structure`. For use in _apply_op_helper.""" + for arg in op_def.output_arg: + if arg.number_attr: + n = _AttrValue(attr_protos, arg.number_attr, op_type_name).i + output_structure.append(n) + elif arg.type_attr: + t = _AttrValue(attr_protos, arg.type_attr, op_type_name) + output_structure.append(None) + elif arg.type_list_attr: + t = _AttrValue(attr_protos, arg.type_list_attr, op_type_name) + output_structure.append(len(t.list.type)) + else: + output_structure.append(None) + + +def _CanExtractAttrsFastPath(op_def, keywords): + """Check if the fast path for _apply_op_helper is applicable.""" + # Check if all inputs are already tf.Tensor + for input_arg in op_def.input_arg: + value = keywords.get(input_arg.name, None) + if not isinstance(value, tensor.Tensor): + return False + + # Check that attrs are not `func` or `list(func)` type. + for attr_def in op_def.attr: + if attr_def.type == "func" or attr_def.type == "list(func)": + return False + + return True + + +def _CheckOpDeprecation(op_type_name, op_def, producer): + """Checks if the op is deprecated.""" + deprecation_version = op_def.deprecation.version + if deprecation_version and producer >= deprecation_version: + raise NotImplementedError( + f"Op {op_type_name} is not available in GraphDef version {producer}. " + f"It has been removed in version {deprecation_version}. " + f"{op_def.deprecation.explanation}.") + + +def _ExtractDefaultTypesAndAllowedTypes(op_def, default_type_attr_map, + allowed_list_attr_map): + """Extracts the `default_type_attr_map` and `allowed_list_attr_map`.""" + # TODO(b/31302892): Currently the defaults don't work in the right + # way if you have two inputs, one of whose type resolution depends + # on the other. Handling this will require restructuring this code + # significantly. + for attr_def in op_def.attr: + if attr_def.type != "type": + continue + key = attr_def.name + if attr_def.HasField("default_value"): + default_type_attr_map[key] = dtypes.as_dtype( + attr_def.default_value.type) + if attr_def.HasField("allowed_values"): + allowed_list_attr_map[key] = attr_def.allowed_values.list.type + + +def _ExtractInputsAndAttrs(op_type_name, op_def, allowed_list_attr_map, + keywords, default_type_attr_map, attrs, inputs, + input_types): + """Extracts `attrs`, `inputs`, and `input_types` in _apply_op_helper.""" + inferred_from = {} + for input_arg in op_def.input_arg: + input_name = input_arg.name + if input_name in keywords: + values = keywords.pop(input_name) + elif input_name + "_" in keywords: + # Handle the case where the name is a keyword or built-in + # for Python so we use the name + _ instead. + input_name += "_" + values = keywords.pop(input_name) + else: + raise TypeError(f"No argument for input {input_name} found in {op_def}") + + # Goals: + # * Convert values to Tensors if it contains constants. + # * Verify that values is a list if that matches the input_arg's + # type. + # * If the input_arg's type is determined by attrs, either set + # those attrs and validate those attr values are legal (if + # they have not yet been set) or validate the input matches + # the type indicated by the attrs (if they have already been + # inferred via an earlier input). + # * If the input_arg has an explicit type, make sure the input + # conforms. + + if _IsListParameter(input_arg): + if not _IsListValue(values): + raise TypeError( + f"Expected list for '{input_name}' argument to '{op_type_name}' " + f"Op, not {values}.") + # In cases where we expect all elements of the list to have the + # same dtype, try to cast non-Tensor elements to that type. + dtype = None + default_dtype = None + if input_arg.type != types_pb2.DT_INVALID: + dtype = input_arg.type + elif input_arg.number_attr: + if input_arg.type_attr in attrs: + dtype = attrs[input_arg.type_attr] + else: + for t in values: + if isinstance(t, tensor.Tensor): + dtype = t.dtype + break + + # dtype still not found, prefer using the default dtype + # from the attr. + if dtype is None and input_arg.type_attr in default_type_attr_map: + default_dtype = default_type_attr_map[input_arg.type_attr] + + try: + if not input_arg.is_ref and dtype: + dtype = dtypes.as_dtype(dtype).base_dtype + values = ops.internal_convert_n_to_tensor( + values, + name=input_arg.name, + dtype=dtype if dtype else None, + preferred_dtype=default_dtype, + as_ref=input_arg.is_ref) + all_types = set(v.dtype.base_dtype for v in values) + if input_arg.number_attr and len(all_types) > 1: + # All types should match. + raise TypeError(f"Not all types matched for {input_arg.name} for " + f"{op_type_name}. Got {all_types}") + except (TypeError, ValueError): + # What types does the conversion function think values have? + observed_types = [] + for value in values: + try: + converted_value = ops.convert_to_tensor( + value, as_ref=input_arg.is_ref) + observed_types.append(converted_value.dtype.base_dtype.name) + except (TypeError, ValueError): + observed_types.append("") + observed = ", ".join(observed_types) + + prefix = ("Tensors in list passed to '%s' of '%s' Op have types [%s]" % + (input_name, op_type_name, observed)) + if input_arg.number_attr: + if input_arg.type != types_pb2.DT_INVALID: + raise TypeError(f"{prefix} that do not match expected type " + f"{dtype.name}.") + elif input_arg.type_attr in attrs: + raise TypeError(f"{prefix} that do not match type {dtype.name} " + "inferred from earlier arguments.") + else: + raise TypeError(f"{prefix} that don't all match.") + else: + raise TypeError(f"{prefix} that are invalid. Tensors: {values}") + + types = [x.dtype for x in values] + inputs.extend(values) + else: + # In cases where we have an expected type, try to convert non-Tensor + # arguments to that type. + dtype = None + default_dtype = None + allowed_list = None + if input_arg.type != types_pb2.DT_INVALID: + dtype = input_arg.type + elif input_arg.type_attr in attrs: + dtype = attrs[input_arg.type_attr] + elif input_arg.type_attr in default_type_attr_map: + # The dtype could not be inferred solely from the inputs, + # so we prefer the attr's default, so code that adds a new attr + # with a default is backwards compatible. + default_dtype = default_type_attr_map[input_arg.type_attr] + allowed_list = allowed_list_attr_map.get(input_arg.type_attr) + + try: + # First see if we can get a valid dtype with the default conversion + # and see if it matches an allowed dtypes. Some ops like ConcatV2 may + # not list allowed dtypes, in which case we should skip this. + if dtype is None and allowed_list: + inferred = None + try: + inferred = ops.convert_to_tensor( + values, name=input_arg.name, as_ref=input_arg.is_ref) + except TypeError as err: + # When converting a python object such as a list of Dimensions, we + # need a dtype to be specified, thus tensor conversion may throw + # an exception which we will ignore and try again below. + pass + + # If we did not match an allowed dtype, try again with the default + # dtype. This could be because we have an empty tensor and thus we + # picked the wrong type. + if inferred is not None and inferred.dtype in allowed_list: + values = inferred + else: + values = ops.convert_to_tensor( + values, + name=input_arg.name, + as_ref=input_arg.is_ref, + preferred_dtype=default_dtype) + else: + values = ops.convert_to_tensor( + values, + name=input_arg.name, + dtype=dtype, + as_ref=input_arg.is_ref, + preferred_dtype=default_dtype) + except TypeError as err: + if dtype is None: + raise err + else: + raise TypeError( + f"Expected {dtypes.as_dtype(dtype).name} passed to parameter " + f"'{input_arg.name}' of op '{op_type_name}', got " + f"{repr(values)} of type '{type(values).__name__}' instead. " + f"Error: {err}") + except ValueError: + # What type does convert_to_tensor think it has? + try: + observed = ops.convert_to_tensor( + values, as_ref=input_arg.is_ref).dtype.name + except ValueError as err: + raise ValueError( + f"Tried to convert '{input_name}' to a tensor and failed. " + f"Error: {err}") + prefix = ("Input '%s' of '%s' Op has type %s that does not match" % + (input_name, op_type_name, observed)) + if input_arg.type != types_pb2.DT_INVALID: + raise TypeError(f"{prefix} expected type of " + f"{dtypes.as_dtype(input_arg.type).name}.") + else: + # Update the maps with the default, if needed. + k = input_arg.type_attr + if k in default_type_attr_map: + if k not in attrs: + attrs[k] = default_type_attr_map[k] + if k not in inferred_from: + inferred_from[k] = "Default in OpDef" + + raise TypeError( + f"{prefix} type " + f"{dtypes.as_dtype(attrs[input_arg.type_attr]).name} of " + f"argument '{inferred_from[input_arg.type_attr]}'.") + + types = [values.dtype] + inputs.append(values) + base_types = [x.base_dtype for x in types] + + if input_arg.number_attr: + # * or * + if input_arg.number_attr in attrs: + if len(values) != attrs[input_arg.number_attr]: + raise ValueError( + f"List argument '{input_name}' to '{op_type_name}' Op with " + f"length {len(values)} must match length " + f"{attrs[input_arg.number_attr]} of argument " + f"'{inferred_from[input_arg.number_attr]}'.") + else: + attrs[input_arg.number_attr] = len(values) + inferred_from[input_arg.number_attr] = input_name + num_attr = _Attr(op_def, input_arg.number_attr) + if num_attr.has_minimum and len(values) < num_attr.minimum: + raise ValueError( + f"List argument '{input_name}' to '{op_type_name}' Op with " + f"length {len(values)} shorter than minimum length " + f"{num_attr.minimum}.") + # All tensors must have the same base type. + if any(bt != base_types[0] for bt in base_types): + raise TypeError( + f"All tensors passed to '{input_name}' of '{op_type_name}' Op " + f"must have the same type. Got {base_types} instead.") + if input_arg.type != types_pb2.DT_INVALID: + # * case + if base_types and base_types[0] != input_arg.type: + assert False, "Unreachable" + elif input_arg.type_attr in attrs: + # * case, where already + # has an inferred value. + if base_types and base_types[0] != attrs[input_arg.type_attr]: + assert False, "Unreachable" + else: + # * case, where we are now setting + # the based on this input + if not base_types: + # If it's in default_type_attr_map, then wait to set it + # (in "process remaining attrs", below). + if input_arg.type_attr not in default_type_attr_map: + raise TypeError( + "Don't know how to infer type variable from empty input " + f"list passed to input '{input_name}' of '{op_type_name}' " + "Op.") + else: + attrs[input_arg.type_attr] = base_types[0] + inferred_from[input_arg.type_attr] = input_name + type_attr = _Attr(op_def, input_arg.type_attr) + _SatisfiesTypeConstraint( + base_types[0], type_attr, param_name=input_name) + elif input_arg.type_attr: + # + attr_value = base_types[0] + if input_arg.type_attr in attrs: + if attrs[input_arg.type_attr] != attr_value: + raise TypeError( + f"Input '{input_name}' of '{op_type_name}' Op has type " + f"{dtypes.as_dtype(attr_value).name} that does not match type " + f"{dtypes.as_dtype(attrs[input_arg.type_attr]).name} of " + f"argument '{inferred_from[input_arg.type_attr]}'.") + else: + for base_type in base_types: + _SatisfiesTypeConstraint( + base_type, + _Attr(op_def, input_arg.type_attr), + param_name=input_name) + attrs[input_arg.type_attr] = attr_value + inferred_from[input_arg.type_attr] = input_name + elif input_arg.type_list_attr: + # + attr_value = base_types + if input_arg.type_list_attr in attrs: + if attrs[input_arg.type_list_attr] != attr_value: + actual_types = ", ".join(dtypes.as_dtype(x).name for x in attr_value) + expected_types = ", ".join( + dtypes.as_dtype(x).name for x in attrs[input_arg.type_list_attr]) + raise TypeError( + f"Input '{input_name}' of '{op_type_name}' Op has type list of " + f"{actual_types} that does not match type list {expected_types}" + f" of argument '{inferred_from[input_arg.type_list_attr]}'.") + else: + for base_type in base_types: + _SatisfiesTypeConstraint( + base_type, + _Attr(op_def, input_arg.type_list_attr), + param_name=input_name) + attrs[input_arg.type_list_attr] = attr_value + inferred_from[input_arg.type_list_attr] = input_name + else: + # single Tensor with specified type + if base_types[0] != input_arg.type: + assert False, "Unreachable" + + if input_arg.is_ref: + if not all(x._is_ref_dtype for x in types): # pylint: disable=protected-access + raise TypeError( + f"'{op_type_name}' Op requires that input '{input_name}' be a " + "mutable tensor (e.g.: a tf.Variable)") + input_types.extend(types) + else: + input_types.extend(base_types) + + +def _ExtractRemainingAttrs(op_type_name, op_def, keywords, + default_type_attr_map, attrs): + """Extracts the remaining attributes into `attrs` in _apply_op_helper.""" + for attr in op_def.attr: + # Skip attrs that have already had their values inferred + if attr.name in attrs: + if attr.name in keywords: + raise TypeError( + f"Should not specify value for inferred attr '{attr.name}' for " + f"{op_type_name}.") + continue + if attr.name in keywords: + attrs[attr.name] = keywords.pop(attr.name) + elif attr.name + "_" in keywords: + # Attrs whose names match Python keywords have an extra '_' + # appended, so we must check for that as well. + attrs[attr.name] = keywords.pop(attr.name + "_") + elif attr.name in default_type_attr_map: + attrs[attr.name] = default_type_attr_map[attr.name] + else: + raise TypeError(f"No argument found for attr {attr.name} for " + f"{op_type_name}") + + +def _GetOpDef(op_type_name, keywords): + """Returns the OpDef, Graph and Producer. For use in _apply_op_helper.""" + op_def = op_def_registry.get(op_type_name) + if op_def is None: + raise RuntimeError(f"Unrecognized Op name {op_type_name}") + + # Determine the graph context. + try: + # Need to flatten all the arguments into a list. + # pylint: disable=protected-access + g = ops._get_graph_from_inputs(_Flatten(keywords.values())) + producer = g.graph_def_versions.producer + # pylint: enable=protected-access + except AssertionError as e: + raise RuntimeError( + f"Cannot determine graph for Op '{op_type_name}' due to: {e.message}") + + return op_def, g, producer + + +def _CheckAllInputsUsed(op_type_name, keywords): + """Ensures all inputs passed into _apply_op_helper were used.""" + if keywords: + all_keywords = ", ".join(sorted(keywords.keys())) + raise TypeError(f"{op_type_name} got unexpected keyword arguments: " + f"{all_keywords}.") + + +def _apply_op_helper(op_type_name, name=None, **keywords): # pylint: disable=invalid-name + """Implementation of apply_op that returns output_structure, op.""" + + op_def, g, producer = _GetOpDef(op_type_name, keywords) + name = name if name else op_type_name + + attrs, attr_protos = {}, {} + default_type_attr_map, allowed_list_attr_map = {}, {} + inputs, input_types, output_structure = [], [], [] + fallback = True + + if (_CanExtractAttrsFastPath(op_def, keywords) and + flags.config().graph_building_optimization.value()): + fallback = False + attr_protos, inputs, input_types, output_structure = ( + op_def_library_pybind.process_inputs(op_type_name, producer, keywords)) + + if fallback: + _CheckOpDeprecation(op_type_name, op_def, producer) + _ExtractDefaultTypesAndAllowedTypes(op_def, default_type_attr_map, + allowed_list_attr_map) + + # Requires that op_def has passed validation (using the C++ + # ValidateOpDef() from ../framework/op_def_util.h). + with g.as_default(), ops.name_scope(name) as scope: + if fallback: + _ExtractInputsAndAttrs(op_type_name, op_def, allowed_list_attr_map, + keywords, default_type_attr_map, attrs, inputs, + input_types) + _ExtractRemainingAttrs(op_type_name, op_def, keywords, + default_type_attr_map, attrs) + _ExtractAttrProto(op_type_name, op_def, attrs, attr_protos) + del attrs # attrs is no longer authoritative, use attr_protos instead + _ExtractOutputStructure(op_type_name, op_def, attr_protos, + output_structure) + _CheckAllInputsUsed(op_type_name, keywords) + + # NOTE(mrry): We add an explicit colocation constraint between + # the newly created op and any of its reference-typed inputs. + must_colocate_inputs = [val for arg, val in zip(op_def.input_arg, inputs) + if arg.is_ref] + with _MaybeColocateWith(must_colocate_inputs): + # Add Op to graph + # pylint: disable=protected-access + op = g._create_op_internal(op_type_name, inputs, dtypes=None, + name=scope, input_types=input_types, + attrs=attr_protos, op_def=op_def) + + # `outputs` is returned as a separate return value so that the output + # tensors can the `op` per se can be decoupled so that the + # `op_callbacks` can function properly. See framework/op_callbacks.py + # for more details. + outputs = op.outputs + # Conditionally invoke tfdbg v2's op callback(s). + if op_callbacks.should_invoke_op_callbacks(): + callback_outputs = op_callbacks.invoke_op_callbacks( + op.node_def.op, tuple(op.inputs), attr_protos, tuple(outputs), + op_name=op.name, graph=g) + if callback_outputs is not None: + outputs = callback_outputs + + return output_structure, op_def.is_stateful, op, outputs + + +def value_to_attr_value(value, attr_type, arg_name): # pylint: disable=invalid-name + """Encodes a Python value as an `AttrValue` proto message. + + Args: + value: The value to convert. + attr_type: The value type (string) -- see the AttrValue proto definition for + valid strings. + arg_name: Argument name (for error messages). + + Returns: + An AttrValue proto message that encodes `value`. + """ + attr_value = attr_value_pb2.AttrValue() + + if attr_type.startswith("list("): + if not _IsListValue(value): + raise TypeError(f"Expected list for attr {arg_name}, obtained " + f"{type(value).__name__} instead.") + + if attr_type == "string": + attr_value.s = _MakeStr(value, arg_name) + elif attr_type == "list(string)": + attr_value.list.s.extend([_MakeStr(x, arg_name) for x in value]) + elif attr_type == "int": + attr_value.i = _MakeInt(value, arg_name) + elif attr_type == "list(int)": + attr_value.list.i.extend([_MakeInt(x, arg_name) for x in value]) + elif attr_type == "float": + attr_value.f = _MakeFloat(value, arg_name) + elif attr_type == "list(float)": + attr_value.list.f.extend([_MakeFloat(x, arg_name) for x in value]) + elif attr_type == "bool": + attr_value.b = _MakeBool(value, arg_name) + elif attr_type == "list(bool)": + attr_value.list.b.extend([_MakeBool(x, arg_name) for x in value]) + elif attr_type == "type": + attr_value.type = _MakeType(value, arg_name) + elif attr_type == "list(type)": + attr_value.list.type.extend([_MakeType(x, arg_name) for x in value]) + elif attr_type == "shape": + attr_value.shape.CopyFrom(_MakeShape(value, arg_name)) + elif attr_type == "list(shape)": + attr_value.list.shape.extend([_MakeShape(x, arg_name) for x in value]) + elif attr_type == "tensor": + attr_value.tensor.CopyFrom(_MakeTensor(value, arg_name)) + elif attr_type == "list(tensor)": + attr_value.list.tensor.extend([_MakeTensor(x, arg_name) for x in value]) + elif attr_type == "func": + attr_value.func.CopyFrom(_MakeFunc(value, arg_name)) + elif attr_type == "list(func)": + attr_value.list.func.extend([_MakeFunc(x, arg_name) for x in value]) + else: + raise TypeError(f"Unrecognized Attr type {attr_type} for {arg_name}.") + return attr_value +# LINT.ThenChange(//tensorflow/python/framework/op_def_library_pybind.cc) + + +# The following symbols are used by op_def_util.cc. +_pywrap_utils.RegisterPyObject("tf.dtypes.DType", dtypes.DType) +_pywrap_utils.RegisterPyObject("tf.dtypes.as_dtype", dtypes.as_dtype) +_pywrap_utils.RegisterPyObject("tf.TensorShape", tensor_shape.TensorShape) +_pywrap_utils.RegisterPyObject("tf.as_shape", tensor_shape.as_shape) +_pywrap_utils.RegisterPyObject("tf.TensorProto", tensor_pb2.TensorProto) +_pywrap_utils.RegisterPyObject("text_format.Parse", text_format.Parse) +_pywrap_utils.RegisterPyObject("tf.convert_to_tensor", ops.convert_to_tensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_library_pybind.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_library_pybind.py new file mode 100644 index 0000000000000000000000000000000000000000..e05c3f54cd3ff35df7723a5c6f1fffb88520cf9d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_library_pybind.py @@ -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. +# ============================================================================== +"""Code to assist with the op_def_library.""" + +# pylint: disable=invalid-import-order, g-bad-import-order, unused-import +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.framework import _op_def_library_pybind + +from tensorflow.core.framework import attr_value_pb2 + + +def process_inputs(op_name, producer_version, keywords): + """Helper method to speed up `_apply_op_helper` in op_def_library.""" + attr_protos, inputs, input_types, output_structure = ( + _op_def_library_pybind.process_inputs(op_name, producer_version, + keywords)) + for k, attr in attr_protos.items(): + attr_protos[k] = attr_value_pb2.AttrValue.FromString(attr) + return attr_protos, inputs, input_types, output_structure diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_registry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..29c11a1342efd207ef99edcc7d38ea42669a3aed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/op_def_registry.py @@ -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. +# ============================================================================== + +"""Global registry for OpDefs.""" + +import threading + +from tensorflow.core.framework import op_def_pb2 +# pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.framework import _op_def_registry + +# The cache amortizes ProtoBuf serialization/deserialization overhead +# on the language boundary. If an OpDef has been looked up, its Python +# representation is cached. +_cache = {} +_cache_lock = threading.Lock() + + +def get(name): + """Returns an OpDef for a given `name` or None if the lookup fails.""" + try: + return _cache[name] + except KeyError: + pass + + with _cache_lock: + try: + # Return if another thread has already populated the cache. + return _cache[name] + except KeyError: + pass + + serialized_op_def = _op_def_registry.get(name) + if serialized_op_def is None: + return None + + op_def = op_def_pb2.OpDef() + op_def.ParseFromString(serialized_op_def) + _cache[name] = op_def + return op_def + + +# TODO(b/141354889): Remove once there are no callers. +def sync(): + """No-op. Used to synchronize the contents of the Python registry with C++.""" diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..622208c996fa7144b0b0cb697f833436a89972ab --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/ops.py @@ -0,0 +1,6086 @@ +# 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. +# ============================================================================== +"""Classes and functions used to construct graphs.""" +# pylint: disable=g-bad-name +import collections +import copy +import enum +import re +import sys +import threading +import types +from typing import Any, AnyStr, Callable, List, NoReturn, Optional, Pattern, Sequence, Tuple, Union + +from absl import app +import numpy as np + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import full_type_pb2 +from tensorflow.core.framework import function_pb2 +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.framework import node_def_pb2 +from tensorflow.core.framework import op_def_pb2 +from tensorflow.core.framework import versions_pb2 +from tensorflow.core.protobuf import config_pb2 +# pywrap_tensorflow must be imported first to avoid protobuf issues. +# (b/143110113) +# pylint: disable=invalid-import-order,g-bad-import-order,unused-import +from tensorflow.python import pywrap_tensorflow +from tensorflow.python import pywrap_tfe +# pylint: enable=invalid-import-order,g-bad-import-order,unused-import +from tensorflow.python import tf2 +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.eager import context +from tensorflow.python.eager import core +from tensorflow.python.eager import monitoring +from tensorflow.python.eager import record +from tensorflow.python.framework import c_api_util +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import registry +from tensorflow.python.framework import stack +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import traceable_stack +from tensorflow.python.framework import versions +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import handle_data_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace as profiler_trace +from tensorflow.python.types import core as core_tf_types +from tensorflow.python.types import internal +from tensorflow.python.util import compat +from tensorflow.python.util import decorator_utils +from tensorflow.python.util import deprecation +from tensorflow.python.util import function_utils +from tensorflow.python.util import lock_util +from tensorflow.python.util import object_identity +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util import tf_stack +from tensorflow.python.util import traceback_utils +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.deprecation import deprecated_args +from tensorflow.python.util.tf_export import kwarg_only +from tensorflow.python.util.tf_export import tf_export + + +# Temporary global switches determining if we should enable the work-in-progress +# calls to the C API. These will be removed once all functionality is supported. +_USE_C_API: bool = True +_USE_C_SHAPES: bool = True + + +_api_usage_gauge = monitoring.BoolGauge( + "/tensorflow/api/ops_eager_execution", + "Whether ops.enable_eager_execution() is called.") + +_control_flow_api_gauge = monitoring.BoolGauge( + "/tensorflow/api/enable_control_flow_v2", + "Whether enable_control_flow_v2() is called.") + +_tf_function_api_gauge = monitoring.BoolGauge( + "/tensorflow/api/tf_function", + "Whether tf.function() is used.") + +# pylint: disable=protected-access +_DTYPES_INTERN_TABLE = dtypes._INTERN_TABLE +# pylint: enable=protected-access + + +def tensor_id(tensor): + """Returns a unique identifier for this Tensor.""" + return tensor._id # pylint: disable=protected-access + + +class _UserDeviceSpec(object): + """Store user-specified device and provide computation of merged device.""" + + def __init__(self, device_name_or_function) -> None: + self._device_name_or_function = device_name_or_function + self.display_name = str(self._device_name_or_function) + self.function = device_name_or_function + self.raw_string = None + + if isinstance(device_name_or_function, pydev.MergeDevice): + self.is_null_merge = device_name_or_function.is_null_merge + + elif callable(device_name_or_function): + self.is_null_merge = False + dev_func = self._device_name_or_function + func_name = function_utils.get_func_name(dev_func) + func_code = function_utils.get_func_code(dev_func) + if func_code: + fname = func_code.co_filename + lineno = func_code.co_firstlineno + else: + fname = "unknown" + lineno = -1 + self.display_name = "%s<%s, %d>" % (func_name, fname, lineno) + + elif device_name_or_function is None: + # NOTE(taylorrobie): This MUST be False. None signals a break in the + # device stack, so `is_null_merge` must be False for such a case to + # allow callers to safely skip over null merges without missing a None. + self.is_null_merge = False + + else: + self.raw_string = device_name_or_function + self.function = pydev.merge_device(device_name_or_function) + self.is_null_merge = self.function.is_null_merge + + # We perform this check in __init__ because it is of non-trivial cost, + # and self.string_merge is typically called many times. + self.fast_string_merge = isinstance(self.function, pydev.MergeDevice) + + def string_merge(self, node_def) -> str: + if self.fast_string_merge: + return self.function.shortcut_string_merge(node_def) + + return compat.as_str(_device_string(self.function(node_def))) + + +class NullContextmanager(object): + + def __init__(self, *args, **kwargs) -> None: + pass + + def __enter__(self) -> None: + pass + + def __exit__(self, type_arg, value_arg, traceback_arg) -> bool: + return False # False values do not suppress exceptions + + +def _as_graph_element(obj): + """Convert `obj` to a graph element if possible, otherwise return `None`. + + Args: + obj: Object to convert. + + Returns: + The result of `obj._as_graph_element()` if that method is available; + otherwise `None`. + """ + conv_fn = getattr(obj, "_as_graph_element", None) + if conv_fn and callable(conv_fn): + return conv_fn() + return None + + +# Deprecated - do not use. +# This API to avoid breaking estimator and tensorflow-mesh which depend on this +# internal API. The stub should be safe to use after TF 2.3 is released. +def is_dense_tensor_like(t) -> bool: + return isinstance(t, core_tf_types.Tensor) + + +def uid() -> int: + """A unique (within this program execution) integer.""" + return pywrap_tfe.TFE_Py_UID() + + +def numpy_text(tensor, is_repr=False) -> str: + """Human readable representation of a tensor's numpy value.""" + if tensor.dtype.is_numpy_compatible: + # pylint: disable=protected-access + text = repr(tensor._numpy()) if is_repr else str(tensor._numpy()) + # pylint: enable=protected-access + else: + text = "" + if "\n" in text: + text = "\n" + text + return text + + +def value_text(tensor, is_repr=False) -> AnyStr: + """Either the NumPy value or a custom TensorFlow formatting of `tensor`. + + Custom formatting is used for custom device tensors, e.g. parallel tensors + with multiple components on different devices. + + Args: + tensor: The tensor to format. + is_repr: Controls the style/verbosity of formatting. + + Returns: + The formatted tensor. + """ + # pylint: disable=protected-access # friend access + if tensor._prefer_custom_summarizer(): + text = tensor._summarize_value() + # pylint: enable=protected-access + if is_repr: + text = "value=" + text + else: + text = numpy_text(tensor, is_repr=is_repr) + if is_repr: + text = "numpy=" + text + return text + + +@tf_export("__internal__.SymbolicTensor") +class SymbolicTensor(pywrap_tf_session.PyTensor, tensor_lib.Tensor): + """A symbolic tensor from a graph or tf.function.""" + + def __new__(cls, op, value_index, dtype, unique_id=None): + if unique_id is None: + unique_id = uid() + return pywrap_tf_session.PyTensor.__new__( + SymbolicTensor, op, value_index, dtypes.as_dtype(dtype), unique_id + ) + + def __copy__(self): + cls = self.__class__ + result = cls.__new__(cls, self.op, self.value_index, self.dtype, self._id) + result.__dict__.update(self.__dict__) + return result + + +def _create_graph_constant( + value, dtype, shape, name, verify_shape, allow_broadcast +) -> "Operation": + """Create a graph constant and invoke constant callbacks.""" + g = get_default_graph() + tensor_value = attr_value_pb2.AttrValue() + tensor_value.tensor.CopyFrom( + tensor_util.make_tensor_proto( + value, dtype=dtype, shape=shape, verify_shape=verify_shape, + allow_broadcast=allow_broadcast)) + dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) + attrs = {"value": tensor_value, "dtype": dtype_value} + const_tensor = g._create_op_internal( # pylint: disable=protected-access + "Const", [], [dtype_value.type], attrs=attrs, name=name).outputs[0] + + if op_callbacks.should_invoke_op_callbacks(): + # TODO(b/147670703): Once the special-op creation code paths + # are unified. Remove this `if` block. + callback_outputs = op_callbacks.invoke_op_callbacks( + "Const", tuple(), attrs, (const_tensor,), op_name=name, graph=g) + if callback_outputs is not None: + [const_tensor] = callback_outputs + return const_tensor + + +class _EagerTensorBase( + tensor_lib.Tensor, internal.NativeObject, core_tf_types.Value): + """Base class for EagerTensor.""" + + # __complex__, __int__, __float__ and __index__ may copy the tensor to CPU and + # only work for scalars; values are cast as per numpy. + def __complex__(self) -> complex: + return complex(self._numpy()) + + def __int__(self) -> int: + return int(self._numpy()) + + def __float__(self) -> float: + return float(self._numpy()) + + def __index__(self): + return self._numpy().__index__() + + def __bool__(self) -> bool: + return bool(self._numpy()) + + __nonzero__ = __bool__ + + def __format__(self, format_spec): + if self._prefer_custom_summarizer(): + return self._summarize_value().__format__(format_spec) + elif self.dtype.is_numpy_compatible: + # Not numpy_text here, otherwise the __format__ behaves differently. + return self._numpy().__format__(format_spec) + else: + return "".__format__(format_spec) # pytype: disable=attribute-error + + def __reduce__(self): + return convert_to_tensor, (self._numpy(),) + + def __copy__(self): + # Eager Tensors are immutable so it's safe to return themselves as a copy. + return self + + def __deepcopy__(self, memo): + # Eager Tensors are immutable so it's safe to return themselves as a copy. + del memo + return self + + def __str__(self) -> str: + return "tf.Tensor(%s, shape=%s, dtype=%s)" % ( + value_text(self, is_repr=False), self.shape, self.dtype.name) + + def __repr__(self) -> str: + return "" % ( + self.shape, self.dtype.name, value_text(self, is_repr=True)) + + def __len__(self): + """Returns the length of the first dimension in the Tensor.""" + if not self.shape.ndims: + raise TypeError("Scalar tensor has no `len()`") + # pylint: disable=protected-access + try: + return self._shape_tuple()[0] + except core._NotOkStatusException as e: + raise core._status_to_exception(e) from None + + def __array__(self, dtype=None): + a = self._numpy() + if not dtype: + return a + + return np.array(a, dtype=dtype) + + def __hash__(self) -> int: + # EagerTensors are never hashable. + raise TypeError("Tensor is unhashable. " + "Instead, use tensor.ref() as the key.") + + def _numpy_internal(self) -> NoReturn: + raise NotImplementedError() + + def _numpy(self): + try: + return self._numpy_internal() + except core._NotOkStatusException as e: # pylint: disable=protected-access + raise core._status_to_exception(e) from None # pylint: disable=protected-access + + @property + def dtype(self): + # Note: using the intern table directly here as this is + # performance-sensitive in some models. + return dtypes._INTERN_TABLE[self._datatype_enum()] # pylint: disable=protected-access + + def numpy(self): + """Copy of the contents of this Tensor into a NumPy array or scalar. + + Unlike NumPy arrays, Tensors are immutable, so this method has to copy + the contents to ensure safety. Use `memoryview` to get a readonly + view of the contents without doing a copy: + + >>> t = tf.constant([42]) + >>> np.array(memoryview(t)) + array([42], dtype=int32) + + Note that `memoryview` is only zero-copy for Tensors on CPU. If a Tensor + is on GPU, it will have to be transferred to CPU first in order for + `memoryview` to work. + + Returns: + A NumPy array of the same shape and dtype or a NumPy scalar, if this + Tensor has rank 0. + + Raises: + ValueError: If the dtype of this Tensor does not have a compatible + NumPy dtype. + """ + # TODO(slebedev): Consider avoiding a copy for non-CPU or remote tensors. + maybe_arr = self._numpy() # pylint: disable=protected-access + return maybe_arr.copy() if isinstance(maybe_arr, np.ndarray) else maybe_arr + + @property + def backing_device(self): + """Returns the name of the device holding this tensor's memory. + + `.backing_device` is usually the same as `.device`, which returns + the device on which the kernel of the operation that produced this tensor + ran. However, some operations can produce tensors on a different device + (e.g., an operation that executes on the GPU but produces output tensors + in host memory). + """ + raise NotImplementedError() + + def _datatype_enum(self) -> NoReturn: + raise NotImplementedError() + + def _shape_tuple(self) -> NoReturn: + """The shape of this Tensor, as a tuple. + + This is more performant than tuple(shape().as_list()) as it avoids + two list and one object creation. Marked private for now as from an API + perspective, it would be better to have a single performant way of + getting a shape rather than exposing shape() and shape_tuple() + (and heaven forbid, shape_list() etc. as well!). Punting on that for now, + but ideally one would work things out and remove the need for this method. + + Returns: + tuple with the shape. + """ + raise NotImplementedError() + + def _rank(self) -> NoReturn: + """Integer rank of this Tensor. + + Unlike regular Tensors, the rank is always known for EagerTensors. + + This is more performant than len(self._shape_tuple()) + + Returns: + Integer rank + """ + raise NotImplementedError() + + def _num_elements(self) -> NoReturn: + """Number of elements of this Tensor. + + Unlike regular Tensors, the number of elements is always known for + EagerTensors. + + This is more performant than tensor.shape.num_elements + + Returns: + Long - num elements in the tensor + """ + raise NotImplementedError() + + def _copy_to_device(self, device_name) -> NoReturn: # pylint: disable=redefined-outer-name + raise NotImplementedError() + + @staticmethod + def _override_operator(name, func) -> None: + setattr(_EagerTensorBase, name, func) + + def _copy_nograd(self, ctx=None, device_name=None): + """Copies tensor to dest device, but doesn't record the operation.""" + # Creates a new tensor on the dest device. + if ctx is None: + ctx = context.context() + if device_name is None: + device_name = ctx.device_name + # pylint: disable=protected-access + try: + ctx.ensure_initialized() + new_tensor = self._copy_to_device(device_name) + except core._NotOkStatusException as e: + raise core._status_to_exception(e) from None + return new_tensor + + def _copy(self, ctx=None, device_name=None): + """Copies tensor to dest device.""" + new_tensor = self._copy_nograd(ctx, device_name) + # Record the copy on tape and define backprop copy as well. + if context.executing_eagerly(): + self_device = self.device + + def grad_fun(dresult): + return [ + dresult._copy(device_name=self_device) + if hasattr(dresult, "_copy") else dresult + ] + + record.record_operation("_copy", [new_tensor], [self], grad_fun) + return new_tensor + # pylint: enable=protected-access + + @property + def shape(self) -> tensor_shape.TensorShape: + if self._tensor_shape is None: # pylint: disable=access-member-before-definition + # pylint: disable=protected-access + try: + # `_tensor_shape` is declared and defined in the definition of + # `EagerTensor`, in C. + self._tensor_shape = tensor_shape.TensorShape(self._shape_tuple()) + except core._NotOkStatusException as e: + raise core._status_to_exception(e) from None + + return self._tensor_shape + + def get_shape(self) -> tensor_shape.TensorShape: + """Alias of Tensor.shape.""" + return self.shape + + def _shape_as_list(self) -> List[Tuple[int, ...]]: + """The shape of the tensor as a list.""" + return list(self._shape_tuple()) + + @deprecation.deprecated( + None, "Use tf.identity with explicit device placement instead.") + def cpu(self): + """A copy of this Tensor with contents backed by host memory.""" + return self._copy(context.context(), "CPU:0") + + @deprecation.deprecated(None, "Use tf.identity instead.") + def gpu(self, gpu_index=0): + """A copy of this Tensor with contents backed by memory on the GPU. + + Args: + gpu_index: Identifies which GPU to place the contents on the returned + Tensor in. + + Returns: + A GPU-memory backed Tensor object initialized with the same contents + as this Tensor. + """ + return self._copy(context.context(), "GPU:" + str(gpu_index)) + + def set_shape(self, shape) -> None: + if not self.shape.is_compatible_with(shape): + raise ValueError(f"Tensor's shape {self.shape} is not compatible " + f"with supplied shape {shape}.") + + # Methods not supported / implemented for Eager Tensors. + @property + def op(self): + raise AttributeError( + "Tensor.op is undefined when eager execution is enabled.") + + @property + def graph(self): + raise AttributeError( + "Tensor.graph is undefined when eager execution is enabled.") + + @property + def name(self): + raise AttributeError( + "Tensor.name is undefined when eager execution is enabled.") + + @property + def value_index(self): + raise AttributeError( + "Tensor.value_index is undefined when eager execution is enabled.") + + def consumers(self) -> NoReturn: + raise NotImplementedError( + "Tensor.consumers is undefined when eager execution is enabled.") + + def _add_consumer(self, consumer) -> NoReturn: + raise NotImplementedError( + "_add_consumer not supported when eager execution is enabled.") + + def _as_node_def_input(self) -> NoReturn: + raise NotImplementedError( + "_as_node_def_input not supported when eager execution is enabled.") + + def _as_tf_output(self) -> NoReturn: + raise NotImplementedError( + "_as_tf_output not supported when eager execution is enabled.") + + def eval(self, feed_dict=None, session=None) -> NoReturn: + raise NotImplementedError( + "eval is not supported when eager execution is enabled, " + "is .numpy() what you're looking for?") + + def __tf_tensor__( + self, dtype: Optional[dtypes.DType] = None, name: Optional[str] = None + ) -> tensor_lib.Tensor: + if not context.executing_eagerly(): + graph = get_default_graph() + if not graph.building_function: + raise RuntimeError( + _add_error_prefix( + "Attempting to capture an EagerTensor without " + "building a function.", + name=name)) + return graph.capture(self, name=name) + return super().__tf_tensor__(dtype, name) + + def _capture_as_const(self, name): + """Capture the EagerTensor to a graph constant tensor.""" + with control_dependencies(None): + constant_value = tensor_util.constant_value(self) + if constant_value is None: + # Some eager tensors, e.g. parallel tensors, are not convertible to + # a single constant. Return None in this case and the caller graph + # would create a placeholder instead. + return None + + const_tensor = _create_graph_constant( + constant_value, dtype=self.dtype, shape=self.shape, name=name, + verify_shape=False, allow_broadcast=True) + return const_tensor + + +# This call creates an EagerTensor class, as a subclass of _EagerTensorBase, and +# registers it with the current module. +# It is exposed as an __internal__ api for now (b/171081052), though we +# expect it to be eventually covered by tf Tensor types and typing. +EagerTensor = tf_export("__internal__.EagerTensor", v1=[])( + pywrap_tfe.TFE_Py_InitEagerTensor(_EagerTensorBase)) + + +def _add_error_prefix(msg: str, *, name: Optional[str] = None) -> str: + return msg if name is None else f"{name}: {msg}" + + +def pack_eager_tensors(tensors, ctx=None): + """Pack multiple `EagerTensor`s of the same dtype and shape. + + Args: + tensors: a list of EagerTensors to pack. + ctx: context.context(). + + Returns: + A packed EagerTensor. + """ + if not isinstance(tensors, list): + raise TypeError(f"tensors must be a list, but got a {type(tensors)}") + + if not tensors: + raise ValueError("Cannot pack an empty list of tensors.") + + dtype = tensors[0].dtype + shape = tensors[0].shape + handle_data = tensors[0]._handle_data # pylint: disable=protected-access + is_resource = dtype == dtypes.resource + for i in range(len(tensors)): + t = tensors[i] + if not isinstance(t, EagerTensor): + raise TypeError(f"All tensors being packed must be EagerTensor. " + f"Found an item of type {type(t)}.") + + if t.dtype != dtype: + raise ValueError( + f"All tensors being packed should have the same dtype {dtype}, " + f"but the {i}-th tensor is of dtype {t.dtype}") + if t.shape != shape: + raise ValueError( + f"All tensors being packed should have the same shape {shape}, " + f"but the {i}-th tensor is of shape {t.shape}") + # pylint: disable=protected-access + if is_resource and t._handle_data != handle_data: + raise ValueError( + f"All tensors being packed should have the same handle data " + f"{handle_data}, " + f"but the {i}-th tensor is of handle data {t._handle_data}") + # pylint: enable=protected-access + + if ctx is None: + ctx = context.context() + + # Propagate handle data for resource variables + packed_tensor = ctx.pack_eager_tensors(tensors) + if handle_data is not None: + packed_tensor._handle_data = handle_data # pylint: disable=protected-access + + def grad_fun(_): + raise ValueError( + "Computing gradients through pack_eager_tensors is not supported.") + + record.record_operation("pack_eager_tensors", [packed_tensor], tensors, + grad_fun) + + return packed_tensor + + +@profiler_trace.trace_wrapper("convert_to_tensor") +def convert_to_tensor( + value, + dtype=None, + name=None, + as_ref=False, + preferred_dtype=None, + dtype_hint=None, + # TODO(b/268347915): Remove argument. + ctx=None, # pylint: disable=unused-argument + accepted_result_types=(tensor_lib.Tensor,), +) -> Union[EagerTensor, SymbolicTensor]: + """Implementation of the public convert_to_tensor.""" + # TODO(b/142518781): Fix all call-sites and remove redundant arg + preferred_dtype = preferred_dtype or dtype_hint + return tensor_conversion_registry.convert( + value, dtype, name, as_ref, preferred_dtype, accepted_result_types + ) + + +internal_convert_to_tensor: Callable[ + ..., Union[EagerTensor, SymbolicTensor]] = convert_to_tensor + + +def internal_convert_n_to_tensor( + values, + dtype=None, + name=None, + as_ref=False, + preferred_dtype=None, + # TODO(b/268347915): Remove argument. + ctx=None) -> List[Union[EagerTensor, SymbolicTensor]]: # pylint: disable=unused-argument + """Converts `values` to a list of `Tensor` objects. + + Args: + values: A list of objects that can be consumed by `tf.convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` objects. + name: (Optional.) A name prefix to used when a new `Tensor` is created, in + which case element `i` will be given the name `name + '_' + i`. + as_ref: True if the caller wants the results as ref tensors. + preferred_dtype: Optional element type for the returned tensors, used when + dtype is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so preferred_dtype can be used as a soft + preference. If the conversion to `preferred_dtype` is not possible, this + argument has no effect. + ctx: Unused. Present for API backwards compatibility. + + Returns: + A list of `Tensor` and/or `IndexedSlices` objects. + + Raises: + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + if not isinstance(values, collections_abc.Sequence): + raise TypeError("values must be a sequence.") + ret = [] + for i, value in enumerate(values): + n = None if name is None else "%s_%d" % (name, i) + ret.append( + convert_to_tensor( + value, + dtype=dtype, + name=n, + as_ref=as_ref, + preferred_dtype=preferred_dtype)) + return ret + + +def convert_n_to_tensor( + values, dtype=None, name=None, preferred_dtype=None +) -> List[Union[EagerTensor, SymbolicTensor]]: + """Converts `values` to a list of `Tensor` objects. + + Args: + values: A list of objects that can be consumed by `tf.convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` objects. + name: (Optional.) A name prefix to used when a new `Tensor` is created, in + which case element `i` will be given the name `name + '_' + i`. + preferred_dtype: Optional element type for the returned tensors, used when + dtype is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so preferred_dtype can be used as a soft + preference. If the conversion to `preferred_dtype` is not possible, this + argument has no effect. + + Returns: + A list of `Tensor` and/or `IndexedSlices` objects. + + Raises: + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + return internal_convert_n_to_tensor( + values=values, + dtype=dtype, + name=name, + preferred_dtype=preferred_dtype, + as_ref=False) + + +def convert_to_tensor_or_composite( + value, dtype=None, name=None +) -> Union[EagerTensor, SymbolicTensor, composite_tensor.CompositeTensor]: + """Converts the given object to a `Tensor` or `CompositeTensor`. + + If `value` is a `CompositeTensor` it is returned unmodified. Otherwise, it + is converted to a `Tensor` using `convert_to_tensor()`. + + Args: + value: A `CompositeTensor` or an object that can be consumed by + `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` or + `CompositeTensor`. + name: (Optional.) A name to use if a new `Tensor` is created. + + Returns: + A `Tensor` or `CompositeTensor`, based on `value`. + + Raises: + ValueError: If `dtype` does not match the element type of `value`. + """ + return internal_convert_to_tensor_or_composite( + value=value, dtype=dtype, name=name, as_ref=False) + + +def internal_convert_to_tensor_or_composite( + value, dtype=None, + name=None, + as_ref=False +) -> Union[EagerTensor, SymbolicTensor, composite_tensor.CompositeTensor]: + """Converts the given object to a `Tensor` or `CompositeTensor`. + + If `value` is a `CompositeTensor` it is returned unmodified. Otherwise, it + is converted to a `Tensor` using `convert_to_tensor()`. + + Args: + value: A `CompositeTensor`, or an object that can be consumed by + `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor` or + `CompositeTensor`. + name: (Optional.) A name to use if a new `Tensor` is created. + as_ref: True if the caller wants the results as ref tensors. + + Returns: + A `Tensor` or `CompositeTensor`, based on `value`. + + Raises: + ValueError: If `dtype` does not match the element type of `value`. + """ + if isinstance(value, composite_tensor.CompositeTensor): + value_dtype = getattr(value, "dtype", None) + if dtype and not dtypes.as_dtype(dtype).is_compatible_with(value_dtype): + raise ValueError(f"Tensor conversion dtype mismatch. " + f"Requested dtype is {dtypes.as_dtype(dtype).name}, " + f"Tensor has dtype {value.dtype.name}: {value!r}") + return value + else: + return convert_to_tensor( + value, + dtype=dtype, + name=name, + as_ref=as_ref, + accepted_result_types=( + tensor_lib.Tensor, composite_tensor.CompositeTensor)) + + +def internal_convert_n_to_tensor_or_composite( + values, + dtype=None, + name=None, + as_ref=False +) -> List[Union[ + EagerTensor, SymbolicTensor, composite_tensor.CompositeTensor, type(None)]]: + """Converts `values` to a list of `Tensor` or `CompositeTensor` objects. + + Any `CompositeTensor` objects in `values` are returned unmodified. + + Args: + values: A list of `None`, `CompositeTensor`, or objects that can be consumed + by `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor`s or + `CompositeTensor`s. + name: (Optional.) A name prefix to used when a new `Tensor` is created, in + which case element `i` will be given the name `name + '_' + i`. + as_ref: True if the caller wants the results as ref tensors. + + Returns: + A list of `Tensor`, `CompositeTensor`, and/or `None` objects. + + Raises: + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + if not isinstance(values, collections_abc.Sequence): + raise TypeError("values must be a sequence.") + ret = [] + for i, value in enumerate(values): + if value is None: + ret.append(value) + else: + n = None if name is None else "%s_%d" % (name, i) + ret.append( + internal_convert_to_tensor_or_composite( + value, dtype=dtype, name=n, as_ref=as_ref)) + return ret + + +def convert_n_to_tensor_or_composite( + values, dtype=None, name=None +) -> List[Union[ + EagerTensor, SymbolicTensor, composite_tensor.CompositeTensor, type(None)]]: + """Converts `values` to a list of `Output` or `CompositeTensor` objects. + + Any `CompositeTensor` objects in `values` are returned unmodified. + + Args: + values: A list of `None`, `CompositeTensor``, or objects that can be + consumed by `convert_to_tensor()`. + dtype: (Optional.) The required `DType` of the returned `Tensor`s or + `CompositeTensor`s. + name: (Optional.) A name prefix to used when a new `Tensor` is created, in + which case element `i` will be given the name `name + '_' + i`. + + Returns: + A list of `Tensor` and/or `CompositeTensor` objects. + + Raises: + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + return internal_convert_n_to_tensor_or_composite( + values=values, dtype=dtype, name=name, as_ref=False) + + +def _device_string(dev_spec): + if pydev.is_device_spec(dev_spec): + return dev_spec.to_string() + else: + return dev_spec + + +def _NodeDef(op_type, name, attrs=None) -> node_def_pb2.NodeDef: + """Create a NodeDef proto. + + Args: + op_type: Value for the "op" attribute of the NodeDef proto. + name: Value for the "name" attribute of the NodeDef proto. + attrs: Dictionary where the key is the attribute name (a string) + and the value is the respective "attr" attribute of the NodeDef proto (an + AttrValue). + + Returns: + A node_def_pb2.NodeDef protocol buffer. + """ + node_def = node_def_pb2.NodeDef(op=compat.as_bytes(op_type), + name=compat.as_bytes(name)) + if attrs: + for k, v in attrs.items(): + node_def.attr[k].CopyFrom(v) + return node_def + + +# Copied from core/framework/node_def_util.cc +# TODO(mrry,josh11b): Consolidate this validation in C++ code. +_VALID_OP_NAME_REGEX: Pattern[str] = re.compile( + r"^[A-Za-z0-9.][A-Za-z0-9_.\\/>-]*$") +_VALID_SCOPE_NAME_REGEX: Pattern[str] = re.compile( + r"^[A-Za-z0-9_.\\/>-]*$") + + +@tf_export("__internal__.create_c_op", v1=[]) +@traceback_utils.filter_traceback +def _create_c_op(graph, + node_def, + inputs, + control_inputs, + op_def=None, + extract_traceback=True): + """Creates a TF_Operation. + + Args: + graph: a `Graph`. + node_def: `node_def_pb2.NodeDef` for the operation to create. + inputs: A flattened list of `Tensor`s. This function handles grouping + tensors into lists as per attributes in the `node_def`. + control_inputs: A list of `Operation`s to set as control dependencies. + op_def: Optional. `op_def_pb2.OpDef` for the operation to create. If not + specified, is looked up from the `graph` using `node_def.op`. + extract_traceback: if True, extract the current Python traceback to the + TF_Operation. + + Returns: + A wrapped TF_Operation*. + """ + if op_def is None: + op_def = graph.op_def_for_type(node_def.op) # pylint: disable=protected-access + # TODO(skyewm): op_def_library.apply_op() flattens the incoming inputs. + # Refactor so we don't have to do this here. + inputs = _reconstruct_sequence_inputs(op_def, inputs, node_def.attr) + # pylint: disable=protected-access + with graph._c_graph.get() as c_graph: + op_desc = pywrap_tf_session.TF_NewOperation(c_graph, + compat.as_str(node_def.op), + compat.as_str(node_def.name)) + if node_def.device: + pywrap_tf_session.TF_SetDevice(op_desc, compat.as_str(node_def.device)) + # Add inputs + for op_input in inputs: + if isinstance(op_input, (list, tuple)): + pywrap_tf_session.TF_AddInputList(op_desc, + [t._as_tf_output() for t in op_input]) + else: + pywrap_tf_session.TF_AddInput(op_desc, op_input._as_tf_output()) + + # Add control inputs + for control_input in control_inputs: + pywrap_tf_session.TF_AddControlInput(op_desc, control_input._c_op) + # pylint: enable=protected-access + + # Add attrs + for name, attr_value in node_def.attr.items(): + serialized = attr_value.SerializeToString() + # TODO(skyewm): this creates and deletes a new TF_Status for every attr. + # It might be worth creating a convenient way to re-use the same status. + pywrap_tf_session.TF_SetAttrValueProto(op_desc, compat.as_str(name), + serialized) + + try: + c_op = pywrap_tf_session.TF_FinishOperation(op_desc) + except errors.InvalidArgumentError as e: + # Convert to ValueError for backwards compatibility. + raise ValueError(e.message) + + # Record the current Python stack trace as the creating stacktrace of this + # TF_Operation. + if extract_traceback: + pywrap_tf_session.TF_SetOpStackTrace( + c_op, tf_stack.extract_stack(stacklevel=3) + ) + + return c_op + + +@tf_export("Operation") +class Operation(pywrap_tf_session.PyOperation): + """Represents a graph node that performs computation on tensors. + + An `Operation` is a node in a `tf.Graph` that takes zero or more `Tensor` + objects as input, and produces zero or more `Tensor` objects as output. + Objects of type `Operation` are created by calling a Python op constructor + (such as `tf.matmul`) within a `tf.function` or under a `tf.Graph.as_default` + context manager. + + For example, within a `tf.function`, `c = tf.matmul(a, b)` creates an + `Operation` of type "MatMul" that takes tensors `a` and `b` as input, and + produces `c` as output. + + If a `tf.compat.v1.Session` is used, an `Operation` of a `tf.Graph` can be + executed by passing it to `tf.Session.run`. `op.run()` is a shortcut for + calling `tf.compat.v1.get_default_session().run(op)`. + """ + + @classmethod + def from_node_def( + cls, + node_def, + g, + inputs=None, + output_types=None, + control_inputs=None, + input_types=None, + original_op=None, + op_def=None, + ): + r"""Creates an `Operation`. + + NOTE: This constructor validates the name of the `Operation` (passed + as `node_def.name`). Valid `Operation` names match the following + regular expression: + + [A-Za-z0-9.][A-Za-z0-9_.\\-/]* + + Args: + node_def: `node_def_pb2.NodeDef`. `NodeDef` for the `Operation`. Used for + attributes of `node_def_pb2.NodeDef`, typically `name`, `op`, and + `device`. The `input` attribute is irrelevant here as it will be + computed when generating the model. + g: `Graph`. The parent graph. + inputs: list of `Tensor` objects. The inputs to this `Operation`. + output_types: list of `DType` objects. List of the types of the `Tensors` + computed by this operation. The length of this list indicates the + number of output endpoints of the `Operation`. + control_inputs: list of operations or tensors from which to have a control + dependency. + input_types: List of `DType` objects representing the types of the tensors + accepted by the `Operation`. By default uses `[x.dtype.base_dtype for x + in inputs]`. Operations that expect reference-typed inputs must specify + these explicitly. + original_op: Optional. Used to associate the new `Operation` with an + existing `Operation` (for example, a replica with the op that was + replicated). + op_def: Optional. The `op_def_pb2.OpDef` proto that describes the op type + that this `Operation` represents. + + Raises: + TypeError: if control inputs are not Operations or Tensors, + or if `node_def` is not a `NodeDef`, + or if `g` is not a `Graph`, + or if `inputs` are not tensors, + or if `inputs` and `input_types` are incompatible. + ValueError: if the `node_def` name is not valid. + + Returns: + Operation object. + """ + if not isinstance(g, Graph): + raise TypeError(f"Argument g must be a Graph. " + f"Received an instance of type {type(g)}") + + if not isinstance(node_def, node_def_pb2.NodeDef): + raise TypeError(f"Argument node_def must be a NodeDef. " + f"Received an instance of type: {type(node_def)}.") + if node_def.ByteSize() >= (1 << 31) or node_def.ByteSize() < 0: + raise ValueError( + f"Cannot create a tensor proto whose content is larger than 2GB. " + f"Size of tensor is {node_def.ByteSize()} bytes.") + + # TODO(mdan): This does not belong here. Graph::AddNode should handle it. + if not _VALID_OP_NAME_REGEX.match(node_def.name): + raise ValueError( + f"`{node_def.name}` is not a valid node name. " + f"Accepted names conform to Regex /{_VALID_OP_NAME_REGEX}/") + + # FIXME(b/225400189): output_types is unused. Consider remove it from + # the argument list. + del output_types + + if inputs is None: + inputs = [] + elif not isinstance(inputs, list): + raise TypeError(f"Argument inputs shall be a list of Tensors. " + f"Received an instance of type {type(inputs)}") + for a in inputs: + if not isinstance(a, tensor_lib.Tensor): + raise TypeError(f"Items of argument inputs shall be Tensor. " + f"Received an instance of type {type(a)}.") + if input_types is None: + input_types = [i.dtype.base_dtype for i in inputs] + else: + if not all( + x.is_compatible_with(i.dtype) for i, x in zip(inputs, input_types)): + raise TypeError("In op '%s', input types (%s) are not compatible " + "with expected types (%s)" % + (node_def.name, [i.dtype for i in inputs], input_types)) + + # Build the list of control inputs. + control_input_ops = [] + if control_inputs: + for c in control_inputs: + control_op = None + if isinstance(c, Operation): + control_op = c + elif isinstance(c, (tensor_lib.Tensor, internal.IndexedSlices)): + control_op = c.op + else: + raise TypeError(f"Control input must be an Operation, " + f"a Tensor, or IndexedSlices. " + f"Received an instance of type {type(c)}.") + control_input_ops.append(control_op) + + # Initialize c_op from node_def and other inputs + c_op = _create_c_op(g, node_def, inputs, control_input_ops, op_def=op_def) + self = Operation(c_op, SymbolicTensor) + self._init(g) + + self._original_op = original_op + + # Post process for control flows. + self._control_flow_post_processing(input_tensors=inputs) + + return self + + @classmethod + def _from_c_op(cls, c_op, g): + """Create an Operation from a TF_Operation. + + For internal use only: This is useful for creating Operation for ops + indirectly created by C API methods, e.g. the ops created by + TF_ImportGraphDef. + + Args: + c_op: a TF_Operation. + g: A Graph. + + Returns: + an Operation object. + """ + self = Operation(c_op, SymbolicTensor) + self._init(g) + return self + + def _init(self, graph: "Graph"): + """Initializes Operation from a TF_Operation.""" + self.graph = graph + self._original_op = None + + # This will be set by self.inputs. + self._inputs_val = None + + # List of _UserDevSpecs holding code location of device context manager + # invocations and the users original argument to them. + self._device_code_locations = None + # Dict mapping op name to file and line information for op colocation + # context managers. + self._colocation_code_locations = None + self._control_flow_context = self.graph._get_control_flow_context() # pylint: disable=protected-access + + # Gradient function for this op. There are three ways to specify gradient + # function, and first available gradient gets used, in the following order. + # 1. self._gradient_function + # 2. Gradient name registered by "_gradient_op_type" attribute. + # 3. Gradient name registered by op.type. + self._gradient_function = None + + self._init_outputs() + self._id_value = self.graph._add_op(self) # pylint: disable=protected-access + + def _control_flow_post_processing(self, input_tensors=None): + """Add this op to its control flow context. + + This may add new ops and change this op's inputs. self.inputs must be + available before calling this method. + + Args: + input_tensors: (Optional.) A list of `Tensors` corresponding to the inputs + of this op, which should be equivalent to `self.inputs`. Pass this + argument to avoid evaluating `self.inputs` unnecessarily. + """ + if input_tensors is None: + input_tensors = self.inputs + for input_tensor in input_tensors: + control_flow_util.CheckInputFromValidContext(self, input_tensor.op) + if self._control_flow_context is not None: + self._control_flow_context.AddOp(self) + + def colocation_groups(self): + """Returns the list of colocation groups of the op.""" + default_colocation_group = [compat.as_bytes("loc:@%s" % self.name)] + try: + class_attr = self.get_attr("_class") + except ValueError: + # This op has no explicit colocation group, so it is itself its + # own root of a colocation group. + return default_colocation_group + + attr_groups = [ + class_name for class_name in class_attr + if class_name.startswith(b"loc:@") + ] + + # If there are no colocation groups in the explicit _class field, + # return the default colocation group. + return attr_groups if attr_groups else default_colocation_group + + def values(self): + """DEPRECATED: Use outputs.""" + return tuple(self.outputs) + + def _get_control_flow_context(self): + """Returns the control flow context of this op. + + Returns: + A context object. + """ + return self._control_flow_context + + def _set_control_flow_context(self, ctx): + """Sets the current control flow context of this op. + + Args: + ctx: a context object. + """ + self._control_flow_context = ctx + + @property + def _id(self): + """The unique integer id of this operation.""" + return self._id_value + + @property + def device(self): + """The name of the device to which this op has been assigned, if any. + + Returns: + The string name of the device to which this op has been + assigned, or an empty string if it has not been assigned to a + device. + """ + return pywrap_tf_session.TF_OperationDevice(self._c_op) + + @property + def _device_assignments(self): + """Code locations for device context managers active at op creation. + + This property will return a list of traceable_stack.TraceableObject + instances where .obj is a string representing the assigned device + (or information about the function that would be applied to this op + to compute the desired device) and the filename and lineno members + record the location of the relevant device context manager. + + For example, suppose file_a contained these lines: + + file_a.py: + 15: with tf.device('/gpu:0'): + 16: node_b = tf.constant(4, name='NODE_B') + + Then a TraceableObject t_obj representing the device context manager + would have these member values: + + t_obj.obj -> '/gpu:0' + t_obj.filename = 'file_a.py' + t_obj.lineno = 15 + + and node_b.op._device_assignments would return the list [t_obj]. + + Returns: + [str: traceable_stack.TraceableObject, ...] as per this method's + description, above. + """ + return self._device_code_locations or [] + + @property + def _colocation_dict(self): + """Code locations for colocation context managers active at op creation. + + This property will return a dictionary for which the keys are nodes with + which this Operation is colocated, and for which the values are + traceable_stack.TraceableObject instances. The TraceableObject instances + record the location of the relevant colocation context manager but have the + "obj" field set to None to prevent leaking private data. + + For example, suppose file_a contained these lines: + + file_a.py: + 14: node_a = tf.constant(3, name='NODE_A') + 15: with tf.compat.v1.colocate_with(node_a): + 16: node_b = tf.constant(4, name='NODE_B') + + Then a TraceableObject t_obj representing the colocation context manager + would have these member values: + + t_obj.obj -> None + t_obj.filename = 'file_a.py' + t_obj.lineno = 15 + + and node_b.op._colocation_dict would return the dictionary + + { 'NODE_A': t_obj } + + Returns: + {str: traceable_stack.TraceableObject} as per this method's description, + above. + """ + locations_dict = self._colocation_code_locations or {} + return locations_dict.copy() + + @property + def _output_types(self): + """List this operation's output types. + + Returns: + List of the types of the Tensors computed by this operation. + Each element in the list is an integer whose value is one of + the TF_DataType enums defined in pywrap_tf_session.h + The length of this list indicates the number of output endpoints + of the operation. + """ + num_outputs = pywrap_tf_session.TF_OperationNumOutputs(self._c_op) + output_types = [ + int(pywrap_tf_session.TF_OperationOutputType(self._tf_output(i))) + for i in range(num_outputs) + ] + + return output_types + + def _set_device(self, device): # pylint: disable=redefined-outer-name + """Set the device of this operation. + + Args: + device: string or device.. The device to set. + """ + self._set_device_from_string(compat.as_str(_device_string(device))) + + def _update_input(self, index, tensor): + """Update the input to this operation at the given index. + + NOTE: This is for TF internal use only. Please don't use it. + + Args: + index: the index of the input to update. + tensor: the Tensor to be used as the input at the given index. + + Raises: + TypeError: if tensor is not a Tensor, + or if input tensor type is not convertible to dtype. + ValueError: if the Tensor is from a different graph. + """ + if not isinstance(tensor, tensor_lib.Tensor): + raise TypeError("tensor must be a Tensor: %s" % tensor) + + _assert_same_graph(self, tensor) + + # Reset cached inputs. + self._inputs_val = None + with self.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + pywrap_tf_session.UpdateEdge( + c_graph, + tensor._as_tf_output(), # pylint: disable=protected-access + self._tf_input(index)) + + def _add_while_inputs(self, tensors): + """See AddWhileInputHack in python_api.h. + + NOTE: This is for TF internal use only. Please don't use it. + + Args: + tensors: list of Tensors + + Raises: + TypeError: if tensor is not a Tensor, + or if input tensor type is not convertible to dtype. + ValueError: if the Tensor is from a different graph. + """ + with self.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + for tensor in tensors: + if not isinstance(tensor, tensor_lib.Tensor): + raise TypeError("tensor must be a Tensor: %s" % tensor) + _assert_same_graph(self, tensor) + + # Reset cached inputs. + self._inputs_val = None + pywrap_tf_session.AddWhileInputHack( + c_graph, # pylint: disable=protected-access + tensor._as_tf_output(), # pylint: disable=protected-access + self._c_op) + + def __str__(self): + return str(self.node_def) + + def __repr__(self): + return "" % (self.name, self.type) + + def __tf_tensor__(self, dtype=None, name=None): + """Raises a helpful error.""" + raise TypeError("can't convert Operation '{}' to Tensor".format(self.name)) + + @property + def inputs(self) -> Sequence[tensor_lib.Tensor]: + """The sequence of `Tensor` objects representing the data inputs of this op.""" + if self._inputs_val is None: + # pylint: disable=protected-access + self._inputs_val = tuple( + self.graph._get_tensor_by_tf_output(i) + for i in pywrap_tf_session.GetOperationInputs(self._c_op)) + # pylint: enable=protected-access + return self._inputs_val + + @property + def _input_types(self): + num_inputs = pywrap_tf_session.TF_OperationNumInputs(self._c_op) + input_types = [ + dtypes.as_dtype( + pywrap_tf_session.TF_OperationInputType(self._tf_input(i))) + for i in range(num_inputs) + ] + return input_types + + @property + def traceback(self): + """Returns the call stack from when this operation was constructed.""" + # FIXME(b/225423591): This object contains a dangling reference if _c_op + # goes out of scope. + return pywrap_tf_session.TF_OperationGetStackTrace(self._c_op) + + @property + def node_def(self): + return node_def_pb2.NodeDef.FromString(self._node_def) + + @property + def op_def(self): + return op_def_pb2.OpDef.FromString(self._op_def) + + def _set_attr(self, attr_name, attr_value): + """Private method used to set an attribute in the node_def.""" + buf = pywrap_tf_session.TF_NewBufferFromString( + compat.as_bytes(attr_value.SerializeToString())) + try: + self._set_attr_with_buf(attr_name, buf) + finally: + pywrap_tf_session.TF_DeleteBuffer(buf) + + def _set_attr_with_buf(self, attr_name, attr_buf): + """Set an attr in the node_def with a pre-allocated buffer.""" + with self.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + # pylint: disable=protected-access + pywrap_tf_session.SetAttr(c_graph, self._c_op, attr_name, attr_buf) + # pylint: enable=protected-access + + def _set_func_attr(self, attr_name, func_name): + """Private method used to set a function attribute in the node_def.""" + func = attr_value_pb2.NameAttrList(name=func_name) + self._set_attr(attr_name, attr_value_pb2.AttrValue(func=func)) + + def _set_func_list_attr(self, attr_name, func_names): + """Private method used to set a list(function) attribute in the node_def.""" + funcs = [attr_value_pb2.NameAttrList(name=func_name) + for func_name in func_names] + funcs_list = attr_value_pb2.AttrValue.ListValue(func=funcs) + self._set_attr(attr_name, attr_value_pb2.AttrValue(list=funcs_list)) + + def _set_type_list_attr(self, attr_name, types): + """Private method used to set a list(type) attribute in the node_def.""" + if not types: + return + if isinstance(types[0], dtypes.DType): + types = [dt.as_datatype_enum for dt in types] + types_list = attr_value_pb2.AttrValue.ListValue(type=types) + self._set_attr(attr_name, attr_value_pb2.AttrValue(list=types_list)) + + def _set_shape_list_attr(self, attr_name, shapes): + """Private method used to set a list(shape) attribute in the node_def.""" + shapes = [s.as_proto() for s in shapes] + shapes_list = attr_value_pb2.AttrValue.ListValue(shape=shapes) + self._set_attr(attr_name, attr_value_pb2.AttrValue(list=shapes_list)) + + def _clear_attr(self, attr_name): + """Private method used to clear an attribute in the node_def.""" + with self.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + # pylint: disable=protected-access + pywrap_tf_session.ClearAttr(c_graph, self._c_op, attr_name) + # pylint: enable=protected-access + + def get_attr(self, name): + """Returns the value of the attr of this op with the given `name`. + + Args: + name: The name of the attr to fetch. + + Returns: + The value of the attr, as a Python object. + + Raises: + ValueError: If this op does not have an attr with the given `name`. + """ + fields = ("s", "i", "f", "b", "type", "shape", "tensor", "func") + try: + with c_api_util.tf_buffer() as buf: # pytype: disable=wrong-arg-count + pywrap_tf_session.TF_OperationGetAttrValueProto(self._c_op, name, buf) + data = pywrap_tf_session.TF_GetBuffer(buf) + except errors.InvalidArgumentError as e: + # Convert to ValueError for backwards compatibility. + raise ValueError(e.message) + x = attr_value_pb2.AttrValue() + x.ParseFromString(data) + + oneof_value = x.WhichOneof("value") + if oneof_value is None: + return [] + if oneof_value == "list": + for f in fields: + if getattr(x.list, f): + if f == "type": + return [dtypes.as_dtype(t) for t in x.list.type] + else: + return list(getattr(x.list, f)) + return [] + if oneof_value == "type": + return dtypes.as_dtype(x.type) + assert oneof_value in fields, "Unsupported field type in " + str(x) + return getattr(x, oneof_value) + + def _get_attr_type(self, name): + """Returns the `DType` value of the attr of this op with the given `name`.""" + try: + dtype_enum = pywrap_tf_session.TF_OperationGetAttrType(self._c_op, name) + return _DTYPES_INTERN_TABLE[dtype_enum] + except errors.InvalidArgumentError as e: + # Convert to ValueError for backwards compatibility. + raise ValueError(e.message) + + def _get_attr_bool(self, name): + """Returns the `bool` value of the attr of this op with the given `name`.""" + try: + return pywrap_tf_session.TF_OperationGetAttrBool(self._c_op, name) + except errors.InvalidArgumentError as e: + # Convert to ValueError for backwards compatibility. + raise ValueError(e.message) + + def _get_attr_int(self, name): + """Returns the `int` value of the attr of this op with the given `name`.""" + try: + return pywrap_tf_session.TF_OperationGetAttrInt(self._c_op, name) + except errors.InvalidArgumentError as e: + # Convert to ValueError for backwards compatibility. + raise ValueError(e.message) + + def experimental_set_type(self, type_proto): + """Sets the corresponding node's `experimental_type` field. + + See the description of `NodeDef.experimental_type` for more info. + + Args: + type_proto: A FullTypeDef proto message. The root type_if of this object + must be `TFT_PRODUCT`, even for ops which only have a singlre return + value. + """ + with self.graph._c_graph.get() as c_graph: # pylint: disable=protected-access + if (type_proto.type_id + not in (full_type_pb2.TFT_UNSET, full_type_pb2.TFT_PRODUCT)): + raise ValueError("error setting the type of ", self.name, + ": expected TFT_UNSET or TFT_PRODUCT, got ", + type_proto.type_id) + with c_api_util.tf_buffer(type_proto.SerializeToString()) as serialized: + pywrap_tf_session.SetFullType(c_graph, self._c_op, serialized) # pylint:disable=protected-access + + def run(self, feed_dict=None, session=None): + """Runs this operation in a `Session`. + + Calling this method will execute all preceding operations that + produce the inputs needed for this operation. + + *N.B.* Before invoking `Operation.run()`, its graph must have been + launched in a session, and either a default session must be + available, or `session` must be specified explicitly. + + Args: + feed_dict: A dictionary that maps `Tensor` objects to feed values. See + `tf.Session.run` for a description of the valid feed values. + session: (Optional.) The `Session` to be used to run to this operation. If + none, the default session will be used. + """ + _run_using_default_session(self, feed_dict, self.graph, session) + +gradient_registry: registry.Registry +_gradient_registry: registry.Registry +# TODO(b/185395742): Clean up usages of _gradient_registry +gradient_registry = _gradient_registry = registry.Registry("gradient") + + +@tf_export("RegisterGradient") +class RegisterGradient(object): + """A decorator for registering the gradient function for an op type. + + This decorator is only used when defining a new op type. For an op + with `m` inputs and `n` outputs, the gradient function is a function + that takes the original `Operation` and `n` `Tensor` objects + (representing the gradients with respect to each output of the op), + and returns `m` `Tensor` objects (representing the partial gradients + with respect to each input of the op). + + For example, assuming that operations of type `"Sub"` take two + inputs `x` and `y`, and return a single output `x - y`, the + following gradient function would be registered: + + ```python + @tf.RegisterGradient("Sub") + def _sub_grad(unused_op, grad): + return grad, tf.negative(grad) + ``` + + The decorator argument `op_type` is the string type of an + operation. This corresponds to the `OpDef.name` field for the proto + that defines the operation. + """ + + __slots__ = ["_op_type"] + + def __init__(self, op_type): + """Creates a new decorator with `op_type` as the Operation type. + + Args: + op_type: The string type of an operation. This corresponds to the + `OpDef.name` field for the proto that defines the operation. + + Raises: + TypeError: If `op_type` is not string. + """ + if not isinstance(op_type, str): + raise TypeError("op_type must be a string") + self._op_type = op_type + + def __call__(self, f): + """Registers the function `f` as gradient function for `op_type`.""" + gradient_registry.register(f, self._op_type) + return f + + +@deprecation.deprecated_endpoints("NotDifferentiable", "NoGradient") +@tf_export("no_gradient", v1=["no_gradient", "NotDifferentiable", "NoGradient"]) +def no_gradient(op_type: str): + """Specifies that ops of type `op_type` is not differentiable. + + This function should *not* be used for operations that have a + well-defined gradient that is not yet implemented. + + This function is only used when defining a new op type. It may be + used for ops such as `tf.size()` that are not differentiable. For + example: + + ```python + tf.no_gradient("Size") + ``` + + The gradient computed for 'op_type' will then propagate zeros. + + For ops that have a well-defined gradient but are not yet implemented, + no declaration should be made, and an error *must* be thrown if + an attempt to request its gradient is made. + + Args: + op_type: The string type of an operation. This corresponds to the + `OpDef.name` field for the proto that defines the operation. + + Raises: + TypeError: If `op_type` is not a string. + + """ + if not isinstance(op_type, str): + raise TypeError("op_type must be a string") + gradient_registry.register(None, op_type) + + +# Aliases for the old names, will be eventually removed. +NoGradient: Callable[[str], None] = no_gradient +NotDifferentiable: Callable[[str], None] = no_gradient + + +def get_gradient_function(op): + """Returns the function that computes gradients for "op".""" + if not op.inputs: + return None + + gradient_function = op._gradient_function # pylint: disable=protected-access + if gradient_function: + return gradient_function + + try: + op_type = op.get_attr("_gradient_op_type") + except ValueError: + op_type = op.type + return gradient_registry.lookup(op_type) + + +def set_shape_and_handle_data_for_outputs(_) -> None: + """No op. TODO(b/74620627): Remove this.""" + pass + + +class OpStats(object): + """A holder for statistics about an operator. + + This class holds information about the resource requirements for an op, + including the size of its weight parameters on-disk and how many FLOPS it + requires to execute forward inference. + + If you define a new operation, you can create a function that will return a + set of information about its usage of the CPU and disk space when serialized. + The function itself takes a Graph object that's been set up so you can call + methods like get_tensor_by_name to help calculate the results, and a NodeDef + argument. + + """ + + __slots__ = ["_statistic_type", "_value"] + + def __init__(self, statistic_type, value=None) -> None: + """Sets up the initial placeholders for the statistics.""" + self.statistic_type = statistic_type + self.value = value + + @property + def statistic_type(self): + return self._statistic_type + + @statistic_type.setter + def statistic_type(self, statistic_type): + self._statistic_type = statistic_type + + @property + def value(self): + return self._value + + @value.setter + def value(self, value): + self._value = value + + def __iadd__(self, other): + if other.statistic_type != self.statistic_type: + raise ValueError("Can't add an OpStat of type %s to one of %s." % + (self.statistic_type, other.statistic_type)) + if self.value is None: + self.value = other.value + elif other.value is not None: + self._value += other.value # pytype: disable=attribute-error + return self + + +_stats_registry: registry.Registry = registry.Registry("statistical functions") + + +class RegisterStatistics(object): + """A decorator for registering the statistics function for an op type. + + This decorator can be defined for an op type so that it gives a + report on the resources used by an instance of an operator, in the + form of an OpStats object. + + Well-known types of statistics include these so far: + + - flops: When running a graph, the bulk of the computation happens doing + numerical calculations like matrix multiplications. This type allows a node + to return how many floating-point operations it takes to complete. The + total number of FLOPs for a graph is a good guide to its expected latency. + + You can add your own statistics just by picking a new type string, registering + functions for the ops you care about, and then calling get_stats_for_node_def. + + If a statistic for an op is registered multiple times, a KeyError will be + raised. + + Since the statistics is counted on a per-op basis. It is not suitable for + model parameters (capacity), which is expected to be counted only once, even + if it is shared by multiple ops. (e.g. RNN) + + For example, you can define a new metric called doohickey for a Foo operation + by placing this in your code: + + ```python + @ops.RegisterStatistics("Foo", "doohickey") + def _calc_foo_bojangles(unused_graph, unused_node_def): + return ops.OpStats("doohickey", 20) + ``` + + Then in client code you can retrieve the value by making this call: + + ```python + doohickey = ops.get_stats_for_node_def(graph, node_def, "doohickey") + ``` + + If the NodeDef is for an op with a registered doohickey function, you'll get + back the calculated amount in doohickey.value, or None if it's not defined. + + """ + + __slots__ = ["_op_type", "_statistic_type"] + + def __init__(self, op_type, statistic_type) -> None: + """Saves the `op_type` as the `Operation` type.""" + if not isinstance(op_type, str): + raise TypeError("op_type must be a string.") + if "," in op_type: + raise TypeError("op_type must not contain a comma.") + self._op_type = op_type + if not isinstance(statistic_type, str): + raise TypeError("statistic_type must be a string.") + if "," in statistic_type: + raise TypeError("statistic_type must not contain a comma.") + self._statistic_type = statistic_type + + def __call__(self, f): + """Registers "f" as the statistics function for "op_type".""" + _stats_registry.register(f, self._op_type + "," + self._statistic_type) + return f + + +def get_stats_for_node_def(graph, node, statistic_type) -> Any: + """Looks up the node's statistics function in the registry and calls it. + + This function takes a Graph object and a NodeDef from a GraphDef, and if + there's an associated statistics method, calls it and returns a result. If no + function has been registered for the particular node type, it returns an empty + statistics object. + + Args: + graph: A Graph object that's been set up with the node's graph. + node: A NodeDef describing the operator. + statistic_type: A string identifying the statistic we're interested in. + + Returns: + An OpStats object containing information about resource usage. + """ + + try: + stats_func = _stats_registry.lookup(node.op + "," + statistic_type) + result = stats_func(graph, node) + except LookupError: + result = OpStats(statistic_type) + return result + + +def name_from_scope_name(name) -> str: + """Returns the name of an op given the name of its scope. + + Args: + name: the name of the scope. + + Returns: + the name of the op (equal to scope name minus any trailing slash). + """ + return name[:-1] if (name and name[-1] == "/") else name + + +_MUTATION_LOCK_GROUP: int = 0 +_SESSION_RUN_LOCK_GROUP: int = 1 + + +@tf_contextlib.contextmanager +def resource_creator_scope(resource_type, resource_creator): + with get_default_graph()._resource_creator_scope(resource_type, # pylint: disable=protected-access + resource_creator): + yield + + +@tf_export("Graph") +class Graph(pywrap_tf_session.PyGraph): + """A TensorFlow computation, represented as a dataflow graph. + + Graphs are used by `tf.function`s to represent the function's computations. + Each graph contains a set of `tf.Operation` objects, which represent units of + computation; and `tf.Tensor` objects, which represent the units of data that + flow between operations. + + ### Using graphs directly (deprecated) + + A `tf.Graph` can be constructed and used directly without a `tf.function`, as + was required in TensorFlow 1, but this is deprecated and it is recommended to + use a `tf.function` instead. If a graph is directly used, other deprecated + TensorFlow 1 classes are also required to execute the graph, such as a + `tf.compat.v1.Session`. + + A default graph can be registered with the `tf.Graph.as_default` context + manager. Then, operations will be added to the graph instead of being executed + eagerly. For example: + + ```python + g = tf.Graph() + with g.as_default(): + # Define operations and tensors in `g`. + c = tf.constant(30.0) + assert c.graph is g + ``` + + `tf.compat.v1.get_default_graph()` can be used to obtain the default graph. + + Important note: This class *is not* thread-safe for graph construction. All + operations should be created from a single thread, or external + synchronization must be provided. Unless otherwise specified, all methods + are not thread-safe. + + A `Graph` instance supports an arbitrary number of "collections" + that are identified by name. For convenience when building a large + graph, collections can store groups of related objects: for + example, the `tf.Variable` uses a collection (named + `tf.GraphKeys.GLOBAL_VARIABLES`) for + all variables that are created during the construction of a graph. The caller + may define additional collections by specifying a new name. + """ + + def __init__(self): + """Creates a new, empty Graph.""" + super().__init__() + # Protects core state that can be returned via public accessors. + # Thread-safety is provided on a best-effort basis to support buggy + # programs, and is not guaranteed by the public `tf.Graph` API. + # + # NOTE(mrry): This does not protect the various stacks. A warning will + # be reported if these are used from multiple threads + self._lock = threading.RLock() + # The group lock synchronizes Session.run calls with methods that create + # and mutate ops (e.g. Graph.create_op()). This synchronization is + # necessary because it's illegal to modify an operation after it's been run. + # The group lock allows any number of threads to mutate ops at the same time + # but if any modification is going on, all Session.run calls have to wait. + # Similarly, if one or more Session.run calls are going on, all mutate ops + # have to wait until all Session.run calls have finished. + self._group_lock = lock_util.GroupLock(num_groups=2) + # Maps a name used in the graph to the next id to use for that name. + self._names_in_use = {} + self._stack_state_is_thread_local = False + self._thread_local = threading.local() + # Functions that will be applied to choose a device if none is specified. + # In TF2.x or after switch_to_thread_local(), + # self._thread_local._device_function_stack is used instead. + self._graph_device_function_stack = traceable_stack.TraceableStack() + # Default original_op applied to new ops. + self._default_original_op = None + # Current control flow context. It could be either CondContext or + # WhileContext defined in ops/control_flow_ops.py + self._control_flow_context = None + # A new node will depend of the union of all of the nodes in the stack. + # In TF2.x or after switch_to_thread_local(), + # self._thread_local._control_dependencies_stack is used instead. + self._graph_control_dependencies_stack = [] + # Arbitrary collections of objects. + self._collections = {} + # The graph-level random seed + self._seed = None + # A dictionary of attributes that should be applied to all ops. + self._attr_scope_map = {} + # A map from op type to the kernel label that should be used. + self._op_to_kernel_label_map = {} + # A map from op type to an alternative op type that should be used when + # computing gradients. + self._gradient_override_map = {} + # A map from op type to a gradient function that should be used instead. + self._gradient_function_map = {} + # True if the graph is considered "finalized". In that case no + # new operations can be added. + self._finalized = False + # Functions defined in the graph + self._functions = collections.OrderedDict() + # Default GraphDef versions + self._graph_def_versions = versions_pb2.VersionDef( + producer=versions.GRAPH_DEF_VERSION, + min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER) + self._building_function = False + # Stack of colocate_with ops. In TF2.x or after switch_to_thread_local(), + # self._thread_local._colocation_stack is used instead. + self._graph_colocation_stack = traceable_stack.TraceableStack() + # Set of tensors that are dangerous to feed! + self._unfeedable_tensors = object_identity.ObjectIdentitySet() + # Set of operations that are dangerous to fetch! + self._unfetchable_ops = set() + # A map of tensor handle placeholder to tensor dtype. + self._handle_feeders = {} + # A map from tensor handle to its read op. + self._handle_readers = {} + # A map from tensor handle to its move op. + self._handle_movers = {} + # A map from tensor handle to its delete op. + self._handle_deleters = {} + # Allow optimizers and other objects to pseudo-uniquely key graphs (this key + # will be shared when defining function graphs, for example, so optimizers + # being called inside function definitions behave as if they were seeing the + # actual outside graph). + self._graph_key = "graph-key-%d/" % (uid(),) + # A string with the last reduction method passed to + # losses.compute_weighted_loss(), or None. This is required only for + # backward compatibility with Estimator and optimizer V1 use cases. + self._last_loss_reduction = None + # Flag that is used to indicate whether loss has been scaled by optimizer. + # If this flag has been set, then estimator uses it to scale losss back + # before reporting. This is required only for backward compatibility with + # Estimator and optimizer V1 use cases. + self._is_loss_scaled_by_optimizer = False + self._container = "" + + # The current AutomaticControlDependencies context manager. + self.experimental_acd_manager = None + # Set to True if this graph is being built in an + # AutomaticControlDependencies context. + # Deprecated: use acd_manager instead. + self._add_control_dependencies = False + + # Cache for OpDef protobufs retrieved via the C API. + self._op_def_cache = {} + # Cache for constant results of `reduced_shape()`. The keys are pairs of + # tuples: (input_shape_tuple, reduction_indices_tuple), and the values + # are pairs of tuples: (output_shape_kept_dims, tile_scaling). + self._reduced_shape_cache = {} + + if tf2.enabled(): + self.switch_to_thread_local() + + # `Graph` now _is_ the C graph, but we have many places that manually attempt + # to manipulate the _c_graph object. Leave these accessors here until these + # are cleaned up. + @property + def _c_graph(self): + return self + + def __enter__(self): + return self + + def __exit__(self, *args): + return + + def get(self): + return self + + # Note: this method is private because the API of tf.Graph() is public and + # frozen, and this functionality is still not ready for public visibility. + @tf_contextlib.contextmanager + def _variable_creator_scope(self, creator, priority=100): + """Scope which defines a variable creation function. + + Args: + creator: A callable taking `next_creator` and `kwargs`. See the + `tf.variable_creator_scope` docstring. + priority: Creators with a higher `priority` are called first. Within the + same priority, creators are called inner-to-outer. + + Yields: + `_variable_creator_scope` is a context manager with a side effect, but + doesn't return a value. + + Raises: + RuntimeError: If variable creator scopes are not properly nested. + """ + # This step keeps a reference to the existing stack, and it also initializes + # self._thread_local._variable_creator_stack if it doesn't exist yet. + old = self._variable_creator_stack + new = list(old) + new.append((priority, creator)) + # Sorting is stable, so we'll put higher-priority creators later in the list + # but otherwise maintain registration order. + new.sort(key=lambda item: item[0]) + self._thread_local._variable_creator_stack = new # pylint: disable=protected-access + try: + yield + finally: + if self._thread_local._variable_creator_stack is not new: # pylint: disable=protected-access + raise RuntimeError( + "Exiting variable_creator_scope without proper nesting.") + self._thread_local._variable_creator_stack = old # pylint: disable=protected-access + + # TODO(b/192405401): unify resource_creator_scope with variable_creator_scope. + # pylint: disable=protected-access + @tf_contextlib.contextmanager + def _resource_creator_scope(self, resource_type, creator): + """Scope which defines a resource creation function used by some resource. + + The resource should be a subclass of CapturableResource with a class method + `cls._resource_type`, the output of which is what the `resource_type` + argument should be. By default, `cls._resource_type` returns the class name, + `cls.__name__`. Given a scope, creators being added with the same + `resource_type` argument will be composed together to apply to all classes + with this `_resource_type`. + + + `creator` is expected to be a function with the following signature: + + ``` + def resource_creator(next_creator, *a, **kwargs) + ``` + + The creator is supposed to eventually call the next_creator to create an + instance if it does want to create an instance and not call + the class initialization method directly. This helps make creators + composable. A creator may choose to create multiple instances, return + already existing instances, or simply register that an instance was created + and defer to the next creator in line. Creators can also modify keyword + arguments seen by the next creators. + + Valid keyword arguments in `kwargs` depends on the specific resource + class. For StaticHashTable, this may be: + * initializer: The table initializer to use. + * default_value: The value to use if a key is missing in the table. + * name: Optional name for the table, default to None. + + + Args: + resource_type: the output of the resource class's `_resource_type` method. + creator: the passed creator for the resource. + + Yields: + A scope in which the creator is active + + Raises: + RuntimeError: If resource_creator_scope is existed without proper nesting. + """ + # This step keeps a reference to the existing stack, and it also initializes + # self._thread_local._variable_creator_stack if it doesn't exist yet. + old = self._resource_creator_stack + new = copy.deepcopy(old) + if isinstance(resource_type, (list, tuple)): + for r in resource_type: + new[r].append(creator) + else: + new[resource_type].append(creator) + self._thread_local._resource_creator_stack = new + try: + yield + finally: + if self._thread_local._resource_creator_stack is not new: + raise RuntimeError( + "Exiting resource_creator_scope without proper nesting.") + self._thread_local._resource_creator_stack = old + + @property + def _resource_creator_stack(self): + if not hasattr(self._thread_local, "_resource_creator_stack"): + self._thread_local._resource_creator_stack = collections.defaultdict(list) + return self._thread_local._resource_creator_stack + + @_resource_creator_stack.setter + def _resource_creator_stack(self, resource_creator_stack): + self._thread_local._resource_creator_stack = resource_creator_stack + # pylint: enable=protected-access + + # Note: this method is private because the API of tf.Graph() is public and + # frozen, and this functionality is still not ready for public visibility. + @property + def _variable_creator_stack(self): + if not hasattr(self._thread_local, "_variable_creator_stack"): + self._thread_local._variable_creator_stack = [] # pylint: disable=protected-access + + # This previously returned a copy of the stack instead of the stack itself, + # to guard against accidental mutation. Consider, however, code that wants + # to save and restore the variable creator stack: + # def f(): + # original_stack = graph._variable_creator_stack + # graph._variable_creator_stack = new_stack + # ... # Some code + # graph._variable_creator_stack = original_stack + # + # And lets say you have some code that calls this function with some + # variable_creator: + # def g(): + # with variable_scope.variable_creator_scope(creator): + # f() + # When exiting the variable creator scope, it would see a different stack + # object than it expected leading to a "Exiting variable_creator_scope + # without proper nesting" error. + return self._thread_local._variable_creator_stack # pylint: disable=protected-access + + @_variable_creator_stack.setter + def _variable_creator_stack(self, variable_creator_stack): + self._thread_local._variable_creator_stack = variable_creator_stack # pylint: disable=protected-access + + def _check_not_finalized(self): + """Check if the graph is finalized. + + Raises: + RuntimeError: If the graph finalized. + """ + if self._finalized: + raise RuntimeError("Graph is finalized and cannot be modified.") + + @property + def graph_def_versions(self): + # pylint: disable=line-too-long + """The GraphDef version information of this graph. + + For details on the meaning of each version, see + [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto). + + Returns: + A `VersionDef`. + """ + return versions_pb2.VersionDef.FromString(self._version_def) + + @property + def seed(self): + """The graph-level random seed of this graph.""" + return self._seed + + @seed.setter + def seed(self, seed): + self._seed = seed + + @property + def finalized(self): + """True if this graph has been finalized.""" + return self._finalized + + def finalize(self): + """Finalizes this graph, making it read-only. + + After calling `g.finalize()`, no new operations can be added to + `g`. This method is used to ensure that no operations are added + to a graph when it is shared between multiple threads, for example + when using a `tf.compat.v1.train.QueueRunner`. + """ + self._finalized = True + + def _unsafe_unfinalize(self): + """Opposite of `finalize`. + + Internal interface. + + NOTE: Unfinalizing a graph could have negative impact on performance, + especially in a multi-threaded environment. Unfinalizing a graph + when it is in use by a Session may lead to undefined behavior. Ensure + that all sessions using a graph are closed before calling this method. + """ + self._finalized = False + + def _get_control_flow_context(self): + """Returns the current control flow context. + + Returns: + A context object. + """ + return self._control_flow_context + + def _set_control_flow_context(self, ctx): + """Sets the current control flow context. + + Args: + ctx: a context object. + """ + self._control_flow_context = ctx + + def _copy_functions_to_graph_def(self, graph_def, starting_bytesize): + """If this graph contains functions, copy them to `graph_def`.""" + bytesize = starting_bytesize + for f in self._functions.values(): + bytesize += f.cached_definition.ByteSize() + if bytesize >= (1 << 31) or bytesize < 0: + raise ValueError("GraphDef cannot be larger than 2GB.") + graph_def.library.function.extend([f.cached_definition]) + if getattr(f, "grad_func_name", None): + grad_def = function_pb2.GradientDef() + grad_def.function_name = f.name + grad_def.gradient_func = f.grad_func_name + graph_def.library.gradient.extend([grad_def]) + + def _as_graph_def( + self, from_version=None, add_shapes=False, use_pybind11_proto=False): + # pylint: disable=line-too-long + """Returns a serialized `GraphDef` representation of this graph. + + The serialized `GraphDef` can be imported into another `Graph` + (using `tf.import_graph_def`) or used with the + [C++ Session API](https://chromium.googlesource.com/external/github.com/tensorflow/tensorflow/+/r0.10/tensorflow/g3doc/api_docs/cc/index.md). + + This method is thread-safe. + + Args: + from_version: Optional. If this is set, returns a `GraphDef` containing + only the nodes that were added to this graph since its `version` + property had the given value. + add_shapes: If true, adds an "_output_shapes" list attr to each node with + the inferred shapes of each of its outputs. + use_pybind11_proto: If true, uses the c++ pybind11_proto api to get the + GraphDef proto directly from c++, instead of through a TF buffer. + + Returns: + A tuple containing a + [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto) + protocol buffer, and the version of the graph to which that + `GraphDef` corresponds. + + Raises: + ValueError: If the `graph_def` would be too large. + + """ + # pylint: enable=line-too-long + with self._lock: + if use_pybind11_proto: + with self._c_graph.get() as c_graph: + graph = graph_pb2.GraphDef() + graph.CopyFrom(pywrap_tf_session.TF_GraphToGraphDefPybind(c_graph)) + else: + with c_api_util.tf_buffer() as buf: # pytype: disable=wrong-arg-count + with self._c_graph.get() as c_graph: + pywrap_tf_session.TF_GraphToGraphDef(c_graph, buf) + data = pywrap_tf_session.TF_GetBuffer(buf) + graph = graph_pb2.GraphDef() + graph.ParseFromString(compat.as_bytes(data)) + # Strip the experimental library field iff it's empty. + if not graph.library.function: + graph.ClearField("library") + + if add_shapes: + for node in graph.node: + op = self._get_operation_by_name(node.name) + if op.outputs: + node.attr["_output_shapes"].list.shape.extend( + [output.get_shape().as_proto() for output in op.outputs]) + for function_def in graph.library.function: + defined_function = self._functions[function_def.signature.name] + try: + func_graph = defined_function.graph + except AttributeError: + # _DefinedFunction doesn't have a graph, _EagerDefinedFunction + # does. Both rely on ops.py, so we can't really isinstance check + # them. + continue + input_shapes = function_def.attr["_input_shapes"] + try: + func_graph_inputs = func_graph.inputs + except AttributeError: + continue + # TODO(b/141471245): Fix the inconsistency when inputs of func graph + # are appended during gradient computation of while/cond. + assert len(input_shapes.list.shape) in [0, len(func_graph_inputs)] + # If the function_def has inputs already filled out, skip this step. + if not input_shapes.list.shape: + for input_tensor, arg_def in zip(func_graph_inputs, + function_def.signature.input_arg): + input_shapes.list.shape.add().CopyFrom( + input_tensor.get_shape().as_proto()) + if input_tensor.dtype == dtypes.resource: + _copy_handle_data_to_arg_def(input_tensor, arg_def) + + for output_tensor, arg_def in zip(func_graph.outputs, + function_def.signature.output_arg): + if output_tensor.dtype == dtypes.resource: + _copy_handle_data_to_arg_def(output_tensor, arg_def) + + for node in function_def.node_def: + try: + op = func_graph.get_operation_by_name(node.name) + except KeyError: + continue + outputs = op.outputs + + if op.type == "StatefulPartitionedCall": + # Filter out any extra outputs (possibly added by function + # backpropagation rewriting). + num_outputs = len(node.attr["Tout"].list.type) + outputs = outputs[:num_outputs] + + node.attr["_output_shapes"].list.shape.extend( + [output.get_shape().as_proto() for output in outputs]) + + return graph, self.version + + def as_graph_def(self, from_version=None, add_shapes=False): + # pylint: disable=line-too-long + """Returns a serialized `GraphDef` representation of this graph. + + The serialized `GraphDef` can be imported into another `Graph` + (using `tf.import_graph_def`) or used with the + [C++ Session API](../../api_docs/cc/index.md). + + This method is thread-safe. + + Args: + from_version: Optional. If this is set, returns a `GraphDef` containing + only the nodes that were added to this graph since its `version` + property had the given value. + add_shapes: If true, adds an "_output_shapes" list attr to each node with + the inferred shapes of each of its outputs. + + Returns: + A + [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto) + protocol buffer. + + Raises: + ValueError: If the `graph_def` would be too large. + """ + # pylint: enable=line-too-long + result, _ = self._as_graph_def(from_version, add_shapes) + return result + + def _is_function(self, name): + """Tests whether 'name' is registered in this graph's function library. + + Args: + name: string op name. + + Returns: + bool indicating whether or not 'name' is registered in function library. + """ + return compat.as_str(name) in self._functions + + def _get_function(self, name): + """Returns the function definition for 'name'. + + Args: + name: string function name. + + Returns: + The function def proto. + """ + return self._functions.get(compat.as_str(name), None) + + def _add_function_recursive(self, function, overwrite=False): + """Adds function to the graph including other functions in its graph.""" + + if self._is_function(function.name): + if overwrite: + self._remove_function(function.name) + self._add_function(function) + else: + self._add_function(function) + + if hasattr(function, "children"): + for f in function.children: # pylint: disable=protected-access + if self._is_function(f.name): + if overwrite: + self._remove_function(f.name) + self._add_function(f) + else: + self._add_function(f) + + def _add_function(self, function): + """Adds a function to the graph. + + After the function has been added, you can call to the function by + passing the function name in place of an op name to + `Graph.create_op()`. + + Args: + function: A `_DefinedFunction` object. + + Raises: + ValueError: if another function is defined with the same name. + """ + self._check_not_finalized() + + name = function.name + # Sanity checks on gradient definition for deprecated _DefinedFunction. + if getattr(function, "grad_func_name", None) and getattr( + function, "python_grad_func", None + ): + raise ValueError("Gradient defined twice for function %s" % name) + + # Add function to graph + # pylint: disable=protected-access + with self._c_graph.get() as c_graph: + with function._c_func.get() as func: + if getattr(function, "_grad_func", None): + # For deprecated _DefinedFunction. + with function._grad_func._c_func.get() as gradient: + pywrap_tf_session.TF_GraphCopyFunction(c_graph, func, gradient) + else: + pywrap_tf_session.TF_GraphCopyFunction(c_graph, func, None) + # pylint: enable=protected-access + + self._functions[compat.as_str(name)] = function + + # Need a new-enough consumer to support the functions we add to the graph. + if self._graph_def_versions.min_consumer < 12: + self._graph_def_versions.min_consumer = 12 + + def _remove_function(self, name): + self._check_not_finalized() + if not self._is_function(name): + raise ValueError(f"Function {name!r} is not found in {self!r}.") + + with self._c_graph.get() as c_graph: + pywrap_tf_session.TF_GraphRemoveFunction(c_graph, compat.as_bytes(name)) + del self._functions[compat.as_str(name)] + + @property + def building_function(self): + """Returns True iff this graph represents a function.""" + return self._building_function + + # Helper functions to create operations. + @deprecated_args(None, + "Shapes are always computed; don't use the compute_shapes " + "as it has no effect.", "compute_shapes") + @traceback_utils.filter_traceback + def create_op( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_shapes=True, + compute_device=True): + """Creates an `Operation` in this graph. + + This is a low-level interface for creating an `Operation`. Most + programs will not call this method directly, and instead use the + Python op constructors, such as `tf.constant()`, which add ops to + the default graph. + + Args: + op_type: The `Operation` type to create. This corresponds to the + `OpDef.name` field for the proto that defines the operation. + inputs: A list of `Tensor` objects that will be inputs to the `Operation`. + dtypes: (Optional) A list of `DType` objects that will be the types of the + tensors that the operation produces. + input_types: (Optional.) A list of `DType`s that will be the types of the + tensors that the operation consumes. By default, uses the base `DType` + of each input in `inputs`. Operations that expect reference-typed inputs + must specify `input_types` explicitly. + name: (Optional.) A string name for the operation. If not specified, a + name is generated based on `op_type`. + attrs: (Optional.) A dictionary where the key is the attribute name (a + string) and the value is the respective `attr` attribute of the + `NodeDef` proto that will represent the operation (an `AttrValue` + proto). + op_def: (Optional.) The `OpDef` proto that describes the `op_type` that + the operation will have. + compute_shapes: (Optional.) Deprecated. Has no effect (shapes are always + computed). + compute_device: (Optional.) If True, device functions will be executed to + compute the device property of the Operation. + + Raises: + TypeError: if any of the inputs is not a `Tensor`. + ValueError: if colocation conflicts with existing device assignment. + + Returns: + An `Operation` object. + """ + del compute_shapes + for idx, a in enumerate(inputs): + if not isinstance(a, tensor_lib.Tensor): + raise TypeError("Input #%d is not a tensor: %s" % (idx, a)) + return self._create_op_internal(op_type, inputs, dtypes, input_types, name, + attrs, op_def, compute_device) + + def _create_op_internal( + self, + op_type, + inputs, + dtypes=None, # pylint: disable=redefined-outer-name + input_types=None, + name=None, + attrs=None, + op_def=None, + compute_device=True) -> "Operation": + """Creates an `Operation` in this graph. + + Implements `Graph.create_op()` without the overhead of the deprecation + wrapper. + + Args: + op_type: The `Operation` type to create. This corresponds to the + `OpDef.name` field for the proto that defines the operation. + inputs: A list of `Tensor` objects that will be inputs to the `Operation`. + dtypes: (Optional) A list of `DType` objects that will be the types of the + tensors that the operation produces. + input_types: (Optional.) A list of `DType`s that will be the types of the + tensors that the operation consumes. By default, uses the base `DType` + of each input in `inputs`. Operations that expect reference-typed inputs + must specify `input_types` explicitly. + name: (Optional.) A string name for the operation. If not specified, a + name is generated based on `op_type`. + attrs: (Optional.) A dictionary where the key is the attribute name (a + string) and the value is the respective `attr` attribute of the + `NodeDef` proto that will represent the operation (an `AttrValue` + proto). + op_def: (Optional.) The `OpDef` proto that describes the `op_type` that + the operation will have. + compute_device: (Optional.) If True, device functions will be executed to + compute the device property of the Operation. + + Raises: + ValueError: if colocation conflicts with existing device assignment. + + Returns: + An `Operation` object. + """ + self._check_not_finalized() + if name is None: + name = op_type + # If a names ends with a '/' it is a "name scope" and we use it as-is, + # after removing the trailing '/'. + if name and name[-1] == "/": + name = name_from_scope_name(name) + else: + name = self.unique_name(name) + + node_def = _NodeDef(op_type, name, attrs) + + input_ops = set(t.op for t in inputs) + control_inputs = self._control_dependencies_for_inputs(input_ops) + # _create_op_helper mutates the new Operation. `_mutation_lock` ensures a + # Session.run call cannot occur between creating and mutating the op. + with self._mutation_lock(): + ret = Operation.from_node_def( + node_def, + self, + inputs=inputs, + output_types=dtypes, + control_inputs=control_inputs, + input_types=input_types, + original_op=self._default_original_op, + op_def=op_def, + ) + self._create_op_helper(ret, compute_device=compute_device) + return ret + + def _create_op_from_tf_operation(self, c_op, compute_device=True): + """Creates an `Operation` in this graph from the supplied TF_Operation. + + This method is like create_op() except the new Operation is constructed + using `c_op`. The returned Operation will have `c_op` as its _c_op + field. This is used to create Operation objects around TF_Operations created + indirectly by the C API (e.g. by TF_ImportGraphDef, TF_FinishWhile). + + This function does not call Operation._control_flow_post_processing or + Graph._control_dependencies_for_inputs (since the inputs may not be + available yet). The caller is responsible for calling these methods. + + Args: + c_op: a wrapped TF_Operation + compute_device: (Optional.) If True, device functions will be executed to + compute the device property of the Operation. + + Returns: + An `Operation` object. + """ + self._check_not_finalized() + ret = Operation._from_c_op(c_op=c_op, g=self) # pylint: disable=protected-access + # If a name_scope was created with ret.name but no nodes were created in it, + # the name will still appear in _names_in_use even though the name hasn't + # been used. This is ok, just leave _names_in_use as-is in this case. + # TODO(skyewm): make the C API guarantee no name conflicts. + name_key = ret.name.lower() + if name_key not in self._names_in_use: + self._names_in_use[name_key] = 1 + self._create_op_helper(ret, compute_device=compute_device) + return ret + + def _create_op_helper(self, op, compute_device=True): + """Common logic for creating an op in this graph.""" + # Apply any additional attributes requested. Do not overwrite any existing + # attributes. + for key, value in self._attr_scope_map.items(): + try: + op.get_attr(key) + except ValueError: + if callable(value): + value = value(op.node_def) + if not isinstance(value, (type(None), attr_value_pb2.AttrValue)): + raise TypeError( + "Callable for scope map key '%s' must return either None or " + "an AttrValue protocol buffer; but it returned: %s" % + (key, value)) + if value: + op._set_attr(key, value) # pylint: disable=protected-access + + # Apply a kernel label if one has been specified for this op type. + try: + kernel_label = self._op_to_kernel_label_map[op.type] + op._set_attr("_kernel", # pylint: disable=protected-access + attr_value_pb2.AttrValue(s=compat.as_bytes(kernel_label))) + except KeyError: + pass + + op._gradient_function = self._gradient_function_map.get(op.type) # pylint: disable=protected-access + + # Apply the overriding op type for gradients if one has been specified for + # this op type. + try: + mapped_op_type = self._gradient_override_map[op.type] + op._set_attr("_gradient_op_type", # pylint: disable=protected-access + attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type))) + except KeyError: + pass + + self._record_op_seen_by_control_dependencies(op) + + if compute_device: + self._apply_device_functions(op) + + # Snapshot the colocation stack metadata before we might generate error + # messages using it. Note that this snapshot depends on the actual stack + # and is independent of the op's _class attribute. + # pylint: disable=protected-access + op._colocation_code_locations = self._snapshot_colocation_stack_metadata() + # pylint: enable=protected-access + + if self._colocation_stack: + all_colocation_groups = [] + is_device_set = False + for colocation_op in self._colocation_stack.peek_objs(): + try: + all_colocation_groups.extend(colocation_op.colocation_groups()) + except AttributeError: + pass + if colocation_op.device and not is_device_set: + # pylint: disable=protected-access + op._set_device(colocation_op.device) + # pylint: enable=protected-access + is_device_set = True + + all_colocation_groups = sorted(set(all_colocation_groups)) + # pylint: disable=protected-access + op._set_attr( + "_class", + attr_value_pb2.AttrValue( + list=attr_value_pb2.AttrValue.ListValue(s=all_colocation_groups))) + # pylint: enable=protected-access + + # Sets "container" attribute if + # (1) self._container is not None + # (2) "is_stateful" is set in OpDef + # (3) "container" attribute is in OpDef + # (4) "container" attribute is None + if self._container and op._is_stateful: # pylint: disable=protected-access + try: + container_attr = op.get_attr("container") + except ValueError: + # "container" attribute is not in OpDef + pass + else: + if not container_attr: + op._set_attr("container", attr_value_pb2.AttrValue( # pylint: disable=protected-access + s=compat.as_bytes(self._container))) + + def _add_new_tf_operations(self, compute_devices=True): + """Creates `Operations` in this graph for any new TF_Operations. + + This is useful for when TF_Operations are indirectly created by the C API + outside of the Operation constructor (e.g. by TF_ImportGraphDef, + TF_FinishWhile). This ensures there are corresponding Operations for all + TF_Operations in the underlying TF_Graph. + + Args: + compute_devices: (Optional.) If True, device functions will be executed to + compute the device properties of each new Operation. + + Returns: + A list of the new `Operation` objects. + """ + self._check_not_finalized() + + # Create all Operation objects before accessing their inputs since an op may + # be created before its inputs. + new_ops = [ + self._create_op_from_tf_operation(c_op, compute_device=compute_devices) + for c_op in self.new_operations() + ] + + # pylint: disable=protected-access + for op in new_ops: + new_control_inputs = self._control_dependencies_for_inputs(op.inputs) + op._add_control_inputs(new_control_inputs) + op._control_flow_post_processing() + # pylint: enable=protected-access + + return new_ops + + def as_graph_element(self, obj, allow_tensor=True, allow_operation=True): + """Returns the object referred to by `obj`, as an `Operation` or `Tensor`. + + This function validates that `obj` represents an element of this + graph, and gives an informative error message if it is not. + + This function is the canonical way to get/validate an object of + one of the allowed types from an external argument reference in the + Session API. + + This method may be called concurrently from multiple threads. + + Args: + obj: A `Tensor`, an `Operation`, or the name of a tensor or operation. Can + also be any object with an `_as_graph_element()` method that returns a + value of one of these types. Note: `_as_graph_element` will be called + inside the graph's lock and so may not modify the graph. + allow_tensor: If true, `obj` may refer to a `Tensor`. + allow_operation: If true, `obj` may refer to an `Operation`. + + Returns: + The `Tensor` or `Operation` in the Graph corresponding to `obj`. + + Raises: + TypeError: If `obj` is not a type we support attempting to convert + to types. + ValueError: If `obj` is of an appropriate type but invalid. For + example, an invalid string. + KeyError: If `obj` is not an object in the graph. + """ + if self._finalized: + return self._as_graph_element_locked(obj, allow_tensor, allow_operation) + + with self._lock: + return self._as_graph_element_locked(obj, allow_tensor, allow_operation) + + def _as_graph_element_locked(self, obj, allow_tensor, allow_operation): + """See `Graph.as_graph_element()` for details.""" + # The vast majority of this function is figuring + # out what an API user might be doing wrong, so + # that we can give helpful error messages. + # + # Ideally, it would be nice to split it up, but we + # need context to generate nice error messages. + + if allow_tensor and allow_operation: + types_str = "Tensor or Operation" + elif allow_tensor: + types_str = "Tensor" + elif allow_operation: + types_str = "Operation" + else: + raise ValueError("allow_tensor and allow_operation can't both be False.") + + temp_obj = _as_graph_element(obj) + if temp_obj is not None: + obj = temp_obj + + # If obj appears to be a name... + if isinstance(obj, compat.bytes_or_text_types): + name = compat.as_str(obj) + + if ":" in name and allow_tensor: + # Looks like a Tensor name and can be a Tensor. + try: + op_name, out_n = name.split(":") + out_n = int(out_n) + except: + raise ValueError("The name %s looks a like a Tensor name, but is " + "not a valid one. Tensor names must be of the " + "form \":\"." % repr(name)) + try: + op = self._get_operation_by_name(op_name) + except KeyError as exc: + raise KeyError( + "The name %s refers to a Tensor which does not " + "exist. The operation, %s, does not exist in the " + "graph." % (repr(name), repr(op_name)) + ) from exc + + try: + return op.outputs[out_n] + except: + raise KeyError("The name %s refers to a Tensor which does not " + "exist. The operation, %s, exists but only has " + "%s outputs." % + (repr(name), repr(op_name), len(op.outputs))) + + elif ":" in name and not allow_tensor: + # Looks like a Tensor name but can't be a Tensor. + raise ValueError("Name %s appears to refer to a Tensor, not a %s." % + (repr(name), types_str)) + + elif ":" not in name and allow_operation: + # Looks like an Operation name and can be an Operation. + try: + op = self._get_operation_by_name(name) + except KeyError as exc: + raise KeyError( + "The name %s refers to an Operation not in the graph." + % repr(name) + ) from exc + return op + + elif ":" not in name and not allow_operation: + # Looks like an Operation name but can't be an Operation. + try: + op = self._get_operation_by_name(name) + # Yep, it's an Operation name + err_msg = ("The name %s refers to an Operation, not a %s." % + (repr(name), types_str)) + except KeyError: + err_msg = ("The name %s looks like an (invalid) Operation name, " + "not a %s." % (repr(name), types_str)) + err_msg += (" Tensor names must be of the form " + "\":\".") + raise ValueError(err_msg) + + elif isinstance(obj, tensor_lib.Tensor) and allow_tensor: + # Actually obj is just the object it's referring to. + if obj.graph is not self: + raise ValueError("Tensor %s is not an element of this graph." % obj) + return obj + elif isinstance(obj, Operation) and allow_operation: + # Actually obj is just the object it's referring to. + if obj.graph is not self: + raise ValueError("Operation %s is not an element of this graph." % obj) + return obj + else: + # We give up! + raise TypeError("Can not convert a %s into a %s." % + (type(obj).__name__, types_str)) + + def get_operation_by_name(self, name): + """Returns the `Operation` with the given `name`. + + This method may be called concurrently from multiple threads. + + Args: + name: The name of the `Operation` to return. + + Returns: + The `Operation` with the given `name`. + + Raises: + TypeError: If `name` is not a string. + KeyError: If `name` does not correspond to an operation in this graph. + """ + + if not isinstance(name, str): + raise TypeError("Operation names are strings (or similar), not %s." % + type(name).__name__) + return self.as_graph_element(name, allow_tensor=False, allow_operation=True) + + def _get_operation_by_tf_operation(self, tf_oper): + op_name = pywrap_tf_session.TF_OperationName(tf_oper) + return self._get_operation_by_name(op_name) + + def get_tensor_by_name(self, name): + """Returns the `Tensor` with the given `name`. + + This method may be called concurrently from multiple threads. + + Args: + name: The name of the `Tensor` to return. + + Returns: + The `Tensor` with the given `name`. + + Raises: + TypeError: If `name` is not a string. + KeyError: If `name` does not correspond to a tensor in this graph. + """ + # Names should be strings. + if not isinstance(name, str): + raise TypeError("Tensor names are strings (or similar), not %s." % + type(name).__name__) + return self.as_graph_element(name, allow_tensor=True, allow_operation=False) + + def _get_tensor_by_tf_output(self, tf_output): + """Returns the `Tensor` representing `tf_output`. + + Note that there is only one such `Tensor`, i.e. multiple calls to this + function with the same TF_Output value will always return the same `Tensor` + object. + + Args: + tf_output: A wrapped `TF_Output` (the C API equivalent of `Tensor`). + + Returns: + The `Tensor` that represents `tf_output`. + """ + op = self._get_operation_by_tf_operation(tf_output.oper) + return op.outputs[tf_output.index] + + def op_def_for_type(self, type): # pylint: disable=redefined-builtin + """Returns the `OpDef` proto for `type`. `type` is a string.""" + # NOTE: No locking is required because the lookup and insertion operations + # on Python dictionaries are atomic. + try: + return self._op_def_cache[type] + except KeyError: + self._op_def_cache[type] = op_def_pb2.OpDef.FromString( + self._op_def_for_type(type) + ) + return self._op_def_cache[type] + + def as_default(self): + """Returns a context manager that makes this `Graph` the default graph. + + This method should be used if you want to create multiple graphs + in the same process. For convenience, a global default graph is + provided, and all ops will be added to this graph if you do not + create a new graph explicitly. + + Use this method with the `with` keyword to specify that ops created within + the scope of a block should be added to this graph. In this case, once + the scope of the `with` is exited, the previous default graph is set again + as default. There is a stack, so it's ok to have multiple nested levels + of `as_default` calls. + + The default graph is a property of the current thread. If you + create a new thread, and wish to use the default graph in that + thread, you must explicitly add a `with g.as_default():` in that + thread's function. + + The following code examples are equivalent: + + ```python + # 1. Using Graph.as_default(): + g = tf.Graph() + with g.as_default(): + c = tf.constant(5.0) + assert c.graph is g + + # 2. Constructing and making default: + with tf.Graph().as_default() as g: + c = tf.constant(5.0) + assert c.graph is g + ``` + + If eager execution is enabled ops created under this context manager will be + added to the graph instead of executed eagerly. + + Returns: + A context manager for using this graph as the default graph. + """ + return _default_graph_stack.get_controller(self) + + @property + def collections(self): + """Returns the names of the collections known to this graph.""" + return list(self._collections) + + def add_to_collection(self, name, value): + """Stores `value` in the collection with the given `name`. + + Note that collections are not sets, so it is possible to add a value to + a collection several times. + + Args: + name: The key for the collection. The `GraphKeys` class contains many + standard names for collections. + value: The value to add to the collection. + """ # pylint: disable=g-doc-exception + self._check_not_finalized() + with self._lock: + if name not in self._collections: + self._collections[name] = [value] + else: + self._collections[name].append(value) + + def add_to_collections(self, names, value): + """Stores `value` in the collections given by `names`. + + Note that collections are not sets, so it is possible to add a value to + a collection several times. This function makes sure that duplicates in + `names` are ignored, but it will not check for pre-existing membership of + `value` in any of the collections in `names`. + + `names` can be any iterable, but if `names` is a string, it is treated as a + single collection name. + + Args: + names: The keys for the collections to add to. The `GraphKeys` class + contains many standard names for collections. + value: The value to add to the collections. + """ + # Make sure names are unique, but treat strings as a single collection name + names = (names,) if isinstance(names, str) else set(names) + for name in names: + self.add_to_collection(name, value) + + def get_collection_ref(self, name): + """Returns a list of values in the collection with the given `name`. + + If the collection exists, this returns the list itself, which can + be modified in place to change the collection. If the collection does + not exist, it is created as an empty list and the list is returned. + + This is different from `get_collection()` which always returns a copy of + the collection list if it exists and never creates an empty collection. + + Args: + name: The key for the collection. For example, the `GraphKeys` class + contains many standard names for collections. + + Returns: + The list of values in the collection with the given `name`, or an empty + list if no value has been added to that collection. + """ # pylint: disable=g-doc-exception + with self._lock: + coll_list = self._collections.get(name, None) + if coll_list is None: + coll_list = [] + self._collections[name] = coll_list + return coll_list + + def get_collection(self, name, scope=None): + """Returns a list of values in the collection with the given `name`. + + This is different from `get_collection_ref()` which always returns the + actual collection list if it exists in that it returns a new list each time + it is called. + + Args: + name: The key for the collection. For example, the `GraphKeys` class + contains many standard names for collections. + scope: (Optional.) A string. If supplied, the resulting list is filtered + to include only items whose `name` attribute matches `scope` using + `re.match`. Items without a `name` attribute are never returned if a + scope is supplied. The choice of `re.match` means that a `scope` without + special tokens filters by prefix. + + Returns: + The list of values in the collection with the given `name`, or + an empty list if no value has been added to that collection. The + list contains the values in the order under which they were + collected. + """ # pylint: disable=g-doc-exception + with self._lock: + collection = self._collections.get(name, None) + if collection is None: + return [] + if scope is None: + return list(collection) + else: + c = [] + regex = re.compile(scope) + for item in collection: + try: + if regex.match(item.name): + c.append(item) + except AttributeError: + # Collection items with no name are ignored. + pass + return c + + def get_all_collection_keys(self): + """Returns a list of collections used in this graph.""" + with self._lock: + return [x for x in self._collections if isinstance(x, str)] + + def clear_collection(self, name): + """Clears all values in a collection. + + Args: + name: The key for the collection. The `GraphKeys` class contains many + standard names for collections. + """ + self._check_not_finalized() + with self._lock: + if name in self._collections: + del self._collections[name] + + @tf_contextlib.contextmanager + def _original_op(self, op): + """Python 'with' handler to help annotate ops with their originator. + + An op may have an 'original_op' property that indicates the op on which + it was based. For example a replica op is based on the op that was + replicated and a gradient op is based on the op that was differentiated. + + All ops created in the scope of this 'with' handler will have + the given 'op' as their original op. + + Args: + op: The Operation that all ops created in this scope will have as their + original op. + + Yields: + Nothing. + """ + old_original_op = self._default_original_op + self._default_original_op = op + try: + yield + finally: + self._default_original_op = old_original_op + + @property + def _name_stack(self): + # This may be called from a thread where name_stack doesn't yet exist. + if not hasattr(self._thread_local, "_name_stack"): + self._thread_local._name_stack = "" + return self._thread_local._name_stack + + @_name_stack.setter + def _name_stack(self, name_stack): + self._thread_local._name_stack = name_stack + + # pylint: disable=g-doc-return-or-yield,line-too-long + @tf_contextlib.contextmanager + def name_scope(self, name): + """Returns a context manager that creates hierarchical names for operations. + + A graph maintains a stack of name scopes. A `with name_scope(...):` + statement pushes a new name onto the stack for the lifetime of the context. + + The `name` argument will be interpreted as follows: + + * A string (not ending with '/') will create a new name scope, in which + `name` is appended to the prefix of all operations created in the + context. If `name` has been used before, it will be made unique by + calling `self.unique_name(name)`. + * A scope previously captured from a `with g.name_scope(...) as + scope:` statement will be treated as an "absolute" name scope, which + makes it possible to re-enter existing scopes. + * A value of `None` or the empty string will reset the current name scope + to the top-level (empty) name scope. + + For example: + + ```python + with tf.Graph().as_default() as g: + c = tf.constant(5.0, name="c") + assert c.op.name == "c" + c_1 = tf.constant(6.0, name="c") + assert c_1.op.name == "c_1" + + # Creates a scope called "nested" + with g.name_scope("nested") as scope: + nested_c = tf.constant(10.0, name="c") + assert nested_c.op.name == "nested/c" + + # Creates a nested scope called "inner". + with g.name_scope("inner"): + nested_inner_c = tf.constant(20.0, name="c") + assert nested_inner_c.op.name == "nested/inner/c" + + # Create a nested scope called "inner_1". + with g.name_scope("inner"): + nested_inner_1_c = tf.constant(30.0, name="c") + assert nested_inner_1_c.op.name == "nested/inner_1/c" + + # Treats `scope` as an absolute name scope, and + # switches to the "nested/" scope. + with g.name_scope(scope): + nested_d = tf.constant(40.0, name="d") + assert nested_d.op.name == "nested/d" + + with g.name_scope(""): + e = tf.constant(50.0, name="e") + assert e.op.name == "e" + ``` + + The name of the scope itself can be captured by `with + g.name_scope(...) as scope:`, which stores the name of the scope + in the variable `scope`. This value can be used to name an + operation that represents the overall result of executing the ops + in a scope. For example: + + ```python + inputs = tf.constant(...) + with g.name_scope('my_layer') as scope: + weights = tf.Variable(..., name="weights") + biases = tf.Variable(..., name="biases") + affine = tf.matmul(inputs, weights) + biases + output = tf.nn.relu(affine, name=scope) + ``` + + NOTE: This constructor validates the given `name`. Valid scope + names match one of the following regular expressions: + + [A-Za-z0-9.][A-Za-z0-9_.\\-/]* (for scopes at the root) + [A-Za-z0-9_.\\-/]* (for other scopes) + + Args: + name: A name for the scope. + + Returns: + A context manager that installs `name` as a new name scope. + + Raises: + ValueError: If `name` is not a valid scope name, according to the rules + above. + """ + if name: + if isinstance(name, compat.bytes_or_text_types): + name = compat.as_str(name) + + if self._name_stack: + # Scopes created in a nested scope may have initial characters + # that are illegal as the initial character of an op name + # (viz. '-', '\', '/', and '_'). + if not _VALID_SCOPE_NAME_REGEX.match(name): + raise ValueError( + f"'{name}' is not a valid scope name. A scope name has to match " + f"the following pattern: {_VALID_SCOPE_NAME_REGEX.pattern}") + else: + # Scopes created in the root must match the more restrictive + # op name regex, which constrains the initial character. + if not _VALID_OP_NAME_REGEX.match(name): + raise ValueError( + f"'{name}' is not a valid root scope name. A root scope name has " + f"to match the following pattern: {_VALID_OP_NAME_REGEX.pattern}") + old_stack = self._name_stack + if not name: # Both for name=None and name="" we re-set to empty scope. + new_stack = "" + returned_scope = "" + elif name[-1] == "/": + new_stack = name_from_scope_name(name) + returned_scope = name + else: + new_stack = self.unique_name(name) + returned_scope = new_stack + "/" + self._name_stack = new_stack + try: + yield returned_scope + finally: + self._name_stack = old_stack + + # pylint: enable=g-doc-return-or-yield,line-too-long + + def unique_name(self, name, mark_as_used=True): + """Return a unique operation name for `name`. + + Note: You rarely need to call `unique_name()` directly. Most of + the time you just need to create `with g.name_scope()` blocks to + generate structured names. + + `unique_name` is used to generate structured names, separated by + `"/"`, to help identify operations when debugging a graph. + Operation names are displayed in error messages reported by the + TensorFlow runtime, and in various visualization tools such as + TensorBoard. + + If `mark_as_used` is set to `True`, which is the default, a new + unique name is created and marked as in use. If it's set to `False`, + the unique name is returned without actually being marked as used. + This is useful when the caller simply wants to know what the name + to be created will be. + + Args: + name: The name for an operation. + mark_as_used: Whether to mark this name as being used. + + Returns: + A string to be passed to `create_op()` that will be used + to name the operation being created. + """ + if self._name_stack: + name = self._name_stack + "/" + name + + # For the sake of checking for names in use, we treat names as case + # insensitive (e.g. foo = Foo). + name_key = name.lower() + i = self._names_in_use.get(name_key, 0) + # Increment the number for "name_key". + if mark_as_used: + self._names_in_use[name_key] = i + 1 + if i > 0: + base_name_key = name_key + # Make sure the composed name key is not already used. + while name_key in self._names_in_use: + name_key = "%s_%d" % (base_name_key, i) + i += 1 + # Mark the composed name_key as used in case someone wants + # to call unique_name("name_1"). + if mark_as_used: + self._names_in_use[name_key] = 1 + + # Return the new name with the original capitalization of the given name. + name = "%s_%d" % (name, i - 1) + return name + + def get_name_scope(self): + """Returns the current name scope. + + For example: + + ```python + with tf.name_scope('scope1'): + with tf.name_scope('scope2'): + print(tf.compat.v1.get_default_graph().get_name_scope()) + ``` + would print the string `scope1/scope2`. + + Returns: + A string representing the current name scope. + """ + return self._name_stack + + @tf_contextlib.contextmanager + def _colocate_with_for_gradient(self, op, gradient_uid, + ignore_existing=False): + with self.colocate_with(op, ignore_existing): + if gradient_uid is not None: + ctx = _get_enclosing_context(self) + if ctx is not None: + ctx.EnterGradientColocation(op, gradient_uid) + try: + yield + finally: + ctx.ExitGradientColocation(op, gradient_uid) + else: + yield + else: + yield + + @tf_contextlib.contextmanager + def colocate_with(self, op, ignore_existing=False): + """Returns a context manager that specifies an op to colocate with. + + Note: this function is not for public use, only for internal libraries. + + For example: + + ```python + a = tf.Variable([1.0]) + with g.colocate_with(a): + b = tf.constant(1.0) + c = tf.add(a, b) + ``` + + `b` and `c` will always be colocated with `a`, no matter where `a` + is eventually placed. + + **NOTE** Using a colocation scope resets any existing device constraints. + + If `op` is `None` then `ignore_existing` must be `True` and the new + scope resets all colocation and device constraints. + + Args: + op: The op to colocate all created ops with, or `None`. + ignore_existing: If true, only applies colocation of this op within the + context, rather than applying all colocation properties on the stack. + If `op` is `None`, this value must be `True`. + + Raises: + ValueError: if op is None but ignore_existing is False. + + Yields: + A context manager that specifies the op with which to colocate + newly created ops. + """ + if op is None and not ignore_existing: + raise ValueError("Trying to reset colocation (op is None) but " + "ignore_existing is not True") + op, device_only_candidate = _op_to_colocate_with(op, self) + + # By default, colocate_with resets the device function stack, + # since colocate_with is typically used in specific internal + # library functions where colocation is intended to be "stronger" + # than device functions. + # + # In the future, a caller may specify that device_functions win + # over colocation, in which case we can add support. + device_fn_tmp = self._device_function_stack + self._device_function_stack = traceable_stack.TraceableStack() + + if ignore_existing: + current_stack = self._colocation_stack + self._colocation_stack = traceable_stack.TraceableStack() + + if op is not None: + # offset refers to the stack frame used for storing code location. + # We use 4, the sum of 1 to use our caller's stack frame and 3 + # to jump over layers of context managers above us. + self._colocation_stack.push_obj(op, offset=4) + if device_only_candidate is not None: + self._colocation_stack.push_obj(device_only_candidate, offset=4) + elif not ignore_existing: + raise ValueError("Trying to reset colocation (op is None) but " + "ignore_existing is not True") + try: + yield + finally: + # Restore device function stack + self._device_function_stack = device_fn_tmp + if op is not None: + self._colocation_stack.pop_obj() + if device_only_candidate is not None: + self._colocation_stack.pop_obj() + + # Reset the colocation stack if requested. + if ignore_existing: + self._colocation_stack = current_stack + + def _add_device_to_stack(self, device_name_or_function, offset=0): + """Add device to stack manually, separate from a context manager.""" + total_offset = 1 + offset + spec = _UserDeviceSpec(device_name_or_function) + self._device_function_stack.push_obj(spec, offset=total_offset) + return spec + + @tf_contextlib.contextmanager + def device(self, device_name_or_function): + # pylint: disable=line-too-long + """Returns a context manager that specifies the default device to use. + + The `device_name_or_function` argument may either be a device name + string, a device function, or None: + + * If it is a device name string, all operations constructed in + this context will be assigned to the device with that name, unless + overridden by a nested `device()` context. + * If it is a function, it will be treated as a function from + Operation objects to device name strings, and invoked each time + a new Operation is created. The Operation will be assigned to + the device with the returned name. + * If it is None, all `device()` invocations from the enclosing context + will be ignored. + + For information about the valid syntax of device name strings, see + the documentation in + [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h). + + For example: + + ```python + with g.device('/device:GPU:0'): + # All operations constructed in this context will be placed + # on GPU 0. + with g.device(None): + # All operations constructed in this context will have no + # assigned device. + + # Defines a function from `Operation` to device string. + def matmul_on_gpu(n): + if n.type == "MatMul": + return "/device:GPU:0" + else: + return "/cpu:0" + + with g.device(matmul_on_gpu): + # All operations of type "MatMul" constructed in this context + # will be placed on GPU 0; all other operations will be placed + # on CPU 0. + ``` + + **N.B.** The device scope may be overridden by op wrappers or + other library code. For example, a variable assignment op + `v.assign()` must be colocated with the `tf.Variable` `v`, and + incompatible device scopes will be ignored. + + Args: + device_name_or_function: The device name or function to use in the + context. + + Yields: + A context manager that specifies the default device to use for newly + created ops. + + Raises: + RuntimeError: If device scopes are not properly nested. + """ + self._add_device_to_stack(device_name_or_function, offset=2) + old_top_of_stack = self._device_function_stack.peek_top_obj() + try: + yield + finally: + new_top_of_stack = self._device_function_stack.peek_top_obj() + if old_top_of_stack is not new_top_of_stack: + raise RuntimeError("Exiting device scope without proper scope nesting.") + self._device_function_stack.pop_obj() + + def _apply_device_functions(self, op): + """Applies the current device function stack to the given operation.""" + # Apply any device functions in LIFO order, so that the most recently + # pushed function has the first chance to apply a device to the op. + # We apply here because the result can depend on the Operation's + # signature, which is computed in the Operation constructor. + # pylint: disable=protected-access + prior_device_string = None + for device_spec in self._device_function_stack.peek_objs(): + if device_spec.is_null_merge: + continue + + if device_spec.function is None: + break + + device_string = device_spec.string_merge(op) + + # Take advantage of the fact that None is a singleton and Python interns + # strings, since identity checks are faster than equality checks. + if device_string is not prior_device_string: + op._set_device_from_string(device_string) + prior_device_string = device_string + op._device_code_locations = self._snapshot_device_function_stack_metadata() + # pylint: enable=protected-access + + # pylint: disable=g-doc-return-or-yield + @tf_contextlib.contextmanager + def container(self, container_name): + """Returns a context manager that specifies the resource container to use. + + Stateful operations, such as variables and queues, can maintain their + states on devices so that they can be shared by multiple processes. + A resource container is a string name under which these stateful + operations are tracked. These resources can be released or cleared + with `tf.Session.reset()`. + + For example: + + ```python + with g.container('experiment0'): + # All stateful Operations constructed in this context will be placed + # in resource container "experiment0". + v1 = tf.Variable([1.0]) + v2 = tf.Variable([2.0]) + with g.container("experiment1"): + # All stateful Operations constructed in this context will be + # placed in resource container "experiment1". + v3 = tf.Variable([3.0]) + q1 = tf.queue.FIFOQueue(10, tf.float32) + # All stateful Operations constructed in this context will be + # be created in the "experiment0". + v4 = tf.Variable([4.0]) + q1 = tf.queue.FIFOQueue(20, tf.float32) + with g.container(""): + # All stateful Operations constructed in this context will be + # be placed in the default resource container. + v5 = tf.Variable([5.0]) + q3 = tf.queue.FIFOQueue(30, tf.float32) + + # Resets container "experiment0", after which the state of v1, v2, v4, q1 + # will become undefined (such as uninitialized). + tf.Session.reset(target, ["experiment0"]) + ``` + + Args: + container_name: container name string. + + Returns: + A context manager for defining resource containers for stateful ops, + yields the container name. + """ + original_container = self._container + self._container = container_name + try: + yield self._container + finally: + self._container = original_container + + # pylint: enable=g-doc-return-or-yield + + class _ControlDependenciesController(object): + """Context manager for `control_dependencies()`.""" + + def __init__(self, graph, control_inputs): + """Create a new `_ControlDependenciesController`. + + A `_ControlDependenciesController` is the context manager for + `with tf.control_dependencies()` blocks. These normally nest, + as described in the documentation for `control_dependencies()`. + + The `control_inputs` argument list control dependencies that must be + added to the current set of control dependencies. Because of + uniquification the set can be empty even if the caller passed a list of + ops. The special value `None` indicates that we want to start a new + empty set of control dependencies instead of extending the current set. + + In that case we also clear the current control flow context, which is an + additional mechanism to add control dependencies. + + Args: + graph: The graph that this controller is managing. + control_inputs: List of ops to use as control inputs in addition to the + current control dependencies. None to indicate that the dependencies + should be cleared. + """ + self._graph = graph + if control_inputs is None: + self._control_inputs_val = [] + self._new_stack = True + else: + self._control_inputs_val = control_inputs + self._new_stack = False + self._seen_nodes = set() + self._old_stack = None + self._old_control_flow_context = None + + # pylint: disable=protected-access + + def __enter__(self): + if self._new_stack: + # Clear the control_dependencies graph. + self._old_stack = self._graph._control_dependencies_stack + self._graph._control_dependencies_stack = [] + # Clear the control_flow_context too. + self._old_control_flow_context = self._graph._get_control_flow_context() + self._graph._set_control_flow_context(None) + self._graph._push_control_dependencies_controller(self) + + def __exit__(self, unused_type, unused_value, unused_traceback): + self._graph._pop_control_dependencies_controller(self) + if self._new_stack: + self._graph._control_dependencies_stack = self._old_stack + self._graph._set_control_flow_context(self._old_control_flow_context) + + # pylint: enable=protected-access + + @property + def control_inputs(self): + return self._control_inputs_val + + def add_op(self, op): + if isinstance(op, tensor_lib.Tensor): + op = op.ref() + self._seen_nodes.add(op) + + def op_in_group(self, op): + if isinstance(op, tensor_lib.Tensor): + op = op.ref() + return op in self._seen_nodes + + def _push_control_dependencies_controller(self, controller): + self._control_dependencies_stack.append(controller) + + def _pop_control_dependencies_controller(self, controller): + assert self._control_dependencies_stack[-1] is controller + self._control_dependencies_stack.pop() + + def _current_control_dependencies(self): + ret = set() + for controller in self._control_dependencies_stack: + for op in controller.control_inputs: + ret.add(op) + return ret + + def _control_dependencies_for_inputs(self, input_ops): + """For an op that takes `input_ops` as inputs, compute control inputs. + + The returned control dependencies should yield an execution that + is equivalent to adding all control inputs in + self._control_dependencies_stack to a newly created op. However, + this function attempts to prune the returned control dependencies + by observing that nodes created within the same `with + control_dependencies(...):` block may have data dependencies that make + the explicit approach redundant. + + Args: + input_ops: The data input ops for an op to be created. + + Returns: + A list of control inputs for the op to be created. + """ + ret = [] + for controller in self._control_dependencies_stack: + # If any of the input_ops already depends on the inputs from controller, + # we say that the new op is dominated (by that input), and we therefore + # do not need to add control dependencies for this controller's inputs. + dominated = False + for op in input_ops: + if controller.op_in_group(op): + dominated = True + break + if not dominated: + # Don't add a control input if we already have a data dependency on i. + # NOTE(mrry): We do not currently track transitive data dependencies, + # so we may add redundant control inputs. + ret.extend(c for c in controller.control_inputs if c not in input_ops) + return ret + + def _record_op_seen_by_control_dependencies(self, op): + """Record that the given op depends on all registered control dependencies. + + Args: + op: An Operation. + """ + for controller in self._control_dependencies_stack: + controller.add_op(op) + + def control_dependencies(self, control_inputs): + """Returns a context manager that specifies control dependencies. + + Use with the `with` keyword to specify that all operations constructed + within the context should have control dependencies on + `control_inputs`. For example: + + ```python + with g.control_dependencies([a, b, c]): + # `d` and `e` will only run after `a`, `b`, and `c` have executed. + d = ... + e = ... + ``` + + Multiple calls to `control_dependencies()` can be nested, and in + that case a new `Operation` will have control dependencies on the union + of `control_inputs` from all active contexts. + + ```python + with g.control_dependencies([a, b]): + # Ops constructed here run after `a` and `b`. + with g.control_dependencies([c, d]): + # Ops constructed here run after `a`, `b`, `c`, and `d`. + ``` + + You can pass None to clear the control dependencies: + + ```python + with g.control_dependencies([a, b]): + # Ops constructed here run after `a` and `b`. + with g.control_dependencies(None): + # Ops constructed here run normally, not waiting for either `a` or `b`. + with g.control_dependencies([c, d]): + # Ops constructed here run after `c` and `d`, also not waiting + # for either `a` or `b`. + ``` + + *N.B.* The control dependencies context applies *only* to ops that + are constructed within the context. Merely using an op or tensor + in the context does not add a control dependency. The following + example illustrates this point: + + ```python + # WRONG + def my_func(pred, tensor): + t = tf.matmul(tensor, tensor) + with tf.control_dependencies([pred]): + # The matmul op is created outside the context, so no control + # dependency will be added. + return t + + # RIGHT + def my_func(pred, tensor): + with tf.control_dependencies([pred]): + # The matmul op is created in the context, so a control dependency + # will be added. + return tf.matmul(tensor, tensor) + ``` + + Also note that though execution of ops created under this scope will trigger + execution of the dependencies, the ops created under this scope might still + be pruned from a normal tensorflow graph. For example, in the following + snippet of code the dependencies are never executed: + + ```python + loss = model.loss() + with tf.control_dependencies(dependencies): + loss = loss + tf.constant(1) # note: dependencies ignored in the + # backward pass + return tf.gradients(loss, model.variables) + ``` + + This is because evaluating the gradient graph does not require evaluating + the constant(1) op created in the forward pass. + + Args: + control_inputs: A list of `Operation` or `Tensor` objects which must be + executed or computed before running the operations defined in the + context. Can also be `None` to clear the control dependencies. + + Returns: + A context manager that specifies control dependencies for all + operations constructed within the context. + + Raises: + TypeError: If `control_inputs` is not a list of `Operation` or + `Tensor` objects. + """ + if control_inputs is None: + return self._ControlDependenciesController(self, None) + # First convert the inputs to ops, and deduplicate them. + # NOTE(mrry): Other than deduplication, we do not currently track direct + # or indirect dependencies between control_inputs, which may result in + # redundant control inputs. + control_ops = [] + current = self._current_control_dependencies() + for c in control_inputs: + # The hasattr(handle) is designed to match ResourceVariables. This is so + # control dependencies on a variable or on an unread variable don't + # trigger reads. + if (isinstance(c, internal.IndexedSlices) or + (hasattr(c, "_handle") and hasattr(c, "op"))): + c = c.op + c = self.as_graph_element(c) + if isinstance(c, tensor_lib.Tensor): + c = c.op # pytype: disable=attribute-error + elif not isinstance(c, Operation): + raise TypeError("Control input must be Operation or Tensor: %s" % c) + if c not in current: + control_ops.append(c) + current.add(c) + # Mark this op with an attribute indicating that it is used as a manual + # control dep in order to allow tracking how common utilization of + # manual control deps in graphs run through the MLIR Bridge are. See + # go/manual-control-dependencies-bridge for details. + # pylint: disable=protected-access + c._set_attr("_has_manual_control_dependencies", # pytype: disable=attribute-error + attr_value_pb2.AttrValue(b=True)) + # pylint: enable=protected-access + return self._ControlDependenciesController(self, control_ops) + + # pylint: disable=g-doc-return-or-yield + @tf_contextlib.contextmanager + def _attr_scope(self, attr_map): + """EXPERIMENTAL: A context manager for setting attributes on operators. + + This context manager can be used to add additional + attributes to operators within the scope of the context. + + For example: + + with ops.Graph().as_default() as g: + f_1 = Foo() # No extra attributes + with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=False)}): + f_2 = Foo() # Additional attribute _a=False + with g._attr_scope({"_a": tf.attr_value_pb2.AttrValue(b=True)}): + f_3 = Foo() # Additional attribute _a=False + with g._attr_scope({"_a": None}): + f_4 = Foo() # No additional attributes. + + Args: + attr_map: A dictionary mapping attr name strings to AttrValue protocol + buffers or None. + + Returns: + A context manager that sets the kernel label to be used for one or more + ops created in that context. + + Raises: + TypeError: If attr_map is not a dictionary mapping + strings to AttrValue protobufs. + """ + if not isinstance(attr_map, dict): + raise TypeError("attr_map must be a dictionary mapping " + "strings to AttrValue protocol buffers") + # The saved_attrs dictionary stores any currently-set labels that + # will be overridden by this context manager. + saved_attrs = {} + # Install the given attribute + for name, attr in attr_map.items(): + if not (isinstance(name, str) and + (isinstance(attr, (type(None), attr_value_pb2.AttrValue)) or + callable(attr))): + raise TypeError("attr_map must be a dictionary mapping " + "strings to AttrValue protocol buffers or " + "callables that emit AttrValue protocol buffers") + try: + saved_attrs[name] = self._attr_scope_map[name] + except KeyError: + pass + if attr is None: + del self._attr_scope_map[name] + else: + self._attr_scope_map[name] = attr + try: + yield # The code within the context runs here. + finally: + # Remove the attributes set for this context, and restore any saved + # attributes. + for name, attr in attr_map.items(): + try: + self._attr_scope_map[name] = saved_attrs[name] + except KeyError: + del self._attr_scope_map[name] + + # pylint: enable=g-doc-return-or-yield + + # pylint: disable=g-doc-return-or-yield + @tf_contextlib.contextmanager + def _kernel_label_map(self, op_to_kernel_label_map): + """EXPERIMENTAL: A context manager for setting kernel labels. + + This context manager can be used to select particular + implementations of kernels within the scope of the context. + + For example: + + with ops.Graph().as_default() as g: + f_1 = Foo() # Uses the default registered kernel for the Foo op. + with g.kernel_label_map({"Foo": "v_2"}): + f_2 = Foo() # Uses the registered kernel with label "v_2" + # for the Foo op. + with g.kernel_label_map({"Foo": "v_3"}): + f_3 = Foo() # Uses the registered kernel with label "v_3" + # for the Foo op. + with g.kernel_label_map({"Foo": ""}): + f_4 = Foo() # Uses the default registered kernel + # for the Foo op. + + Args: + op_to_kernel_label_map: A dictionary mapping op type strings to kernel + label strings. + + Returns: + A context manager that sets the kernel label to be used for one or more + ops created in that context. + + Raises: + TypeError: If op_to_kernel_label_map is not a dictionary mapping + strings to strings. + """ + if not isinstance(op_to_kernel_label_map, dict): + raise TypeError("op_to_kernel_label_map must be a dictionary mapping " + "strings to strings") + # The saved_labels dictionary stores any currently-set labels that + # will be overridden by this context manager. + saved_labels = {} + # Install the given label + for op_type, label in op_to_kernel_label_map.items(): + if not (isinstance(op_type, str) and + isinstance(label, str)): + raise TypeError("op_to_kernel_label_map must be a dictionary mapping " + "strings to strings") + try: + saved_labels[op_type] = self._op_to_kernel_label_map[op_type] + except KeyError: + pass + self._op_to_kernel_label_map[op_type] = label + try: + yield # The code within the context runs here. + finally: + # Remove the labels set for this context, and restore any saved labels. + for op_type, label in op_to_kernel_label_map.items(): + try: + self._op_to_kernel_label_map[op_type] = saved_labels[op_type] + except KeyError: + del self._op_to_kernel_label_map[op_type] + + # pylint: enable=g-doc-return-or-yield + + @tf_contextlib.contextmanager + def _override_gradient_function(self, gradient_function_map): + """Specify gradient function for the given op type.""" + + # This is an internal API and we don't need nested context for this. + # TODO(mdan): make it a proper context manager. + assert not self._gradient_function_map + self._gradient_function_map = gradient_function_map + try: + yield + finally: + self._gradient_function_map = {} + + # pylint: disable=g-doc-return-or-yield + @tf_contextlib.contextmanager + def gradient_override_map(self, op_type_map): + """EXPERIMENTAL: A context manager for overriding gradient functions. + + This context manager can be used to override the gradient function + that will be used for ops within the scope of the context. + + For example: + + ```python + @tf.RegisterGradient("CustomSquare") + def _custom_square_grad(op, grad): + # ... + + with tf.Graph().as_default() as g: + c = tf.constant(5.0) + s_1 = tf.square(c) # Uses the default gradient for tf.square. + with g.gradient_override_map({"Square": "CustomSquare"}): + s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the + # gradient of s_2. + ``` + + Args: + op_type_map: A dictionary mapping op type strings to alternative op type + strings. + + Returns: + A context manager that sets the alternative op type to be used for one + or more ops created in that context. + + Raises: + TypeError: If `op_type_map` is not a dictionary mapping strings to + strings. + """ + if not isinstance(op_type_map, dict): + raise TypeError("op_type_map must be a dictionary mapping " + "strings to strings") + # The saved_mappings dictionary stores any currently-set mappings that + # will be overridden by this context manager. + saved_mappings = {} + # Install the given label + for op_type, mapped_op_type in op_type_map.items(): + if not (isinstance(op_type, str) and + isinstance(mapped_op_type, str)): + raise TypeError("op_type_map must be a dictionary mapping " + "strings to strings") + try: + saved_mappings[op_type] = self._gradient_override_map[op_type] + except KeyError: + pass + self._gradient_override_map[op_type] = mapped_op_type + try: + yield # The code within the context runs here. + finally: + # Remove the labels set for this context, and restore any saved labels. + for op_type, mapped_op_type in op_type_map.items(): + try: + self._gradient_override_map[op_type] = saved_mappings[op_type] + except KeyError: + del self._gradient_override_map[op_type] + + # pylint: enable=g-doc-return-or-yield + + def prevent_feeding(self, tensor): + """Marks the given `tensor` as unfeedable in this graph.""" + self._unfeedable_tensors.add(tensor) + + def is_feedable(self, tensor): + """Returns `True` if and only if `tensor` is feedable.""" + return tensor not in self._unfeedable_tensors + + def prevent_fetching(self, op): + """Marks the given `op` as unfetchable in this graph.""" + self._unfetchable_ops.add(op) + + def is_fetchable(self, tensor_or_op): + """Returns `True` if and only if `tensor_or_op` is fetchable.""" + if isinstance(tensor_or_op, tensor_lib.Tensor): + return tensor_or_op.op not in self._unfetchable_ops + else: + return tensor_or_op not in self._unfetchable_ops + + def switch_to_thread_local(self): + """Make device, colocation and dependencies stacks thread-local. + + Device, colocation and dependencies stacks are not thread-local be default. + If multiple threads access them, then the state is shared. This means that + one thread may affect the behavior of another thread. + + After this method is called, the stacks become thread-local. If multiple + threads access them, then the state is not shared. Each thread uses its own + value; a thread doesn't affect other threads by mutating such a stack. + + The initial value for every thread's stack is set to the current value + of the stack when `switch_to_thread_local()` was first called. + """ + if not self._stack_state_is_thread_local: + self._stack_state_is_thread_local = True + + @property + def _device_function_stack(self): + if self._stack_state_is_thread_local: + # This may be called from a thread where device_function_stack doesn't yet + # exist. + # pylint: disable=protected-access + if not hasattr(self._thread_local, "_device_function_stack"): + stack_copy_for_this_thread = self._graph_device_function_stack.copy() + self._thread_local._device_function_stack = stack_copy_for_this_thread + return self._thread_local._device_function_stack + # pylint: enable=protected-access + else: + return self._graph_device_function_stack + + @property + def _device_functions_outer_to_inner(self): + user_device_specs = self._device_function_stack.peek_objs() + device_functions = [spec.function for spec in user_device_specs] + device_functions_outer_to_inner = list(reversed(device_functions)) + return device_functions_outer_to_inner + + def _snapshot_device_function_stack_metadata(self): + """Return device function stack as a list of TraceableObjects. + + Returns: + [traceable_stack.TraceableObject, ...] where each TraceableObject's .obj + member is a displayable name for the user's argument to Graph.device, and + the filename and lineno members point to the code location where + Graph.device was called directly or indirectly by the user. + """ + snapshot = [] + for obj in self._device_function_stack.peek_traceable_objs(): + obj_copy = obj.copy_metadata() + obj_copy.obj = obj.obj.display_name + snapshot.append(obj_copy) + return snapshot + + @_device_function_stack.setter + def _device_function_stack(self, device_function_stack): + if self._stack_state_is_thread_local: + # pylint: disable=protected-access + self._thread_local._device_function_stack = device_function_stack + # pylint: enable=protected-access + else: + self._graph_device_function_stack = device_function_stack + + @property + def _colocation_stack(self): + """Return thread-local copy of colocation stack.""" + if self._stack_state_is_thread_local: + # This may be called from a thread where colocation_stack doesn't yet + # exist. + # pylint: disable=protected-access + if not hasattr(self._thread_local, "_colocation_stack"): + stack_copy_for_this_thread = self._graph_colocation_stack.copy() + self._thread_local._colocation_stack = stack_copy_for_this_thread + return self._thread_local._colocation_stack + # pylint: enable=protected-access + else: + return self._graph_colocation_stack + + def _snapshot_colocation_stack_metadata(self): + """Return colocation stack metadata as a dictionary.""" + return { + traceable_obj.obj.name: traceable_obj.copy_metadata() + for traceable_obj in self._colocation_stack.peek_traceable_objs() + } + + @_colocation_stack.setter + def _colocation_stack(self, colocation_stack): + if self._stack_state_is_thread_local: + # pylint: disable=protected-access + self._thread_local._colocation_stack = colocation_stack + # pylint: enable=protected-access + else: + self._graph_colocation_stack = colocation_stack + + @property + def _control_dependencies_stack(self): + if self._stack_state_is_thread_local: + # This may be called from a thread where control_dependencies_stack + # doesn't yet exist. + if not hasattr(self._thread_local, "_control_dependencies_stack"): + self._thread_local._control_dependencies_stack = ( + self._graph_control_dependencies_stack[:]) + return self._thread_local._control_dependencies_stack + else: + return self._graph_control_dependencies_stack + + @_control_dependencies_stack.setter + def _control_dependencies_stack(self, control_dependencies): + if self._stack_state_is_thread_local: + self._thread_local._control_dependencies_stack = control_dependencies + else: + self._graph_control_dependencies_stack = control_dependencies + + @property + def _distribution_strategy_stack(self): + """A stack to maintain distribution strategy context for each thread.""" + if not hasattr(self._thread_local, "_distribution_strategy_stack"): + self._thread_local._distribution_strategy_stack = [] # pylint: disable=protected-access + return self._thread_local._distribution_strategy_stack # pylint: disable=protected-access + + @_distribution_strategy_stack.setter + def _distribution_strategy_stack(self, _distribution_strategy_stack): + self._thread_local._distribution_strategy_stack = ( # pylint: disable=protected-access + _distribution_strategy_stack) + + @property + def _global_distribute_strategy_scope(self): + """For implementing `tf.distribute.set_strategy()`.""" + if not hasattr(self._thread_local, "distribute_strategy_scope"): + self._thread_local.distribute_strategy_scope = None + return self._thread_local.distribute_strategy_scope + + @_global_distribute_strategy_scope.setter + def _global_distribute_strategy_scope(self, distribute_strategy_scope): + self._thread_local.distribute_strategy_scope = (distribute_strategy_scope) + + def _mutation_lock(self): + """Returns a lock to guard code that creates & mutates ops. + + See the comment for self._group_lock for more info. + """ + return self._group_lock.group(_MUTATION_LOCK_GROUP) + + def _session_run_lock(self): + """Returns a lock to guard code for Session.run. + + See the comment for self._group_lock for more info. + """ + return self._group_lock.group(_SESSION_RUN_LOCK_GROUP) + + +# TODO(agarwal): currently device directives in an outer eager scope will not +# apply to inner graph mode code. Fix that. + + +@tf_export(v1=["device"]) +def device(device_name_or_function): + """Wrapper for `Graph.device()` using the default graph. + + See `tf.Graph.device` for more details. + + Args: + device_name_or_function: The device name or function to use in the context. + + Returns: + A context manager that specifies the default device to use for newly + created ops. + + Raises: + RuntimeError: If eager execution is enabled and a function is passed in. + """ + if context.executing_eagerly(): + if callable(device_name_or_function): + raise RuntimeError( + "tf.device does not support functions when eager execution " + "is enabled.") + return context.device(device_name_or_function) + elif executing_eagerly_outside_functions(): + @tf_contextlib.contextmanager + def combined(device_name_or_function): + with get_default_graph().device(device_name_or_function): + if not callable(device_name_or_function): + with context.device(device_name_or_function): + yield + else: + yield + return combined(device_name_or_function) + else: + return get_default_graph().device(device_name_or_function) + + +@tf_export("device", v1=[]) +def device_v2(device_name): + """Specifies the device for ops created/executed in this context. + + This function specifies the device to be used for ops created/executed in a + particular context. Nested contexts will inherit and also create/execute + their ops on the specified device. If a specific device is not required, + consider not using this function so that a device can be automatically + assigned. In general the use of this function is optional. `device_name` can + be fully specified, as in "/job:worker/task:1/device:cpu:0", or partially + specified, containing only a subset of the "/"-separated fields. Any fields + which are specified will override device annotations from outer scopes. + + For example: + + ```python + with tf.device('/job:foo'): + # ops created here have devices with /job:foo + with tf.device('/job:bar/task:0/device:gpu:2'): + # ops created here have the fully specified device above + with tf.device('/device:gpu:1'): + # ops created here have the device '/job:foo/device:gpu:1' + ``` + + Args: + device_name: The device name to use in the context. + + Returns: + A context manager that specifies the default device to use for newly + created ops. + + Raises: + RuntimeError: If a function is passed in. + """ + if callable(device_name): + raise RuntimeError("tf.device does not support functions.") + return device(device_name) + + +@tf_export(v1=["container"]) +def container(container_name): + """Wrapper for `Graph.container()` using the default graph. + + Args: + container_name: The container string to use in the context. + + Returns: + A context manager that specifies the default container to use for newly + created stateful ops. + """ + return get_default_graph().container(container_name) + + +def _colocate_with_for_gradient(op, gradient_uid, ignore_existing=False): + if context.executing_eagerly(): + if op is not None: + if not hasattr(op, "device"): + op = convert_to_tensor(op) + return device(op.device) + else: + return NullContextmanager() + else: + default_graph = get_default_graph() + if isinstance(op, EagerTensor): + if default_graph.building_function: + return default_graph.device(op.device) + else: + raise ValueError("Encountered an Eager-defined Tensor during graph " + "construction, but a function was not being built.") + return default_graph._colocate_with_for_gradient( + op, gradient_uid=gradient_uid, ignore_existing=ignore_existing) + + +# Internal interface to colocate_with. colocate_with has been deprecated from +# public API. There are still a few internal uses of colocate_with. Add internal +# only API for those uses to avoid deprecation warning. +def colocate_with(op, ignore_existing=False): + return _colocate_with_for_gradient(op, None, ignore_existing=ignore_existing) + + +@deprecation.deprecated( + date=None, instructions="Colocations handled automatically by placer.") +@tf_export(v1=["colocate_with"]) +def _colocate_with(op, ignore_existing=False): + return colocate_with(op, ignore_existing) + + +@tf_export("control_dependencies") +def control_dependencies(control_inputs): + """Wrapper for `Graph.control_dependencies()` using the default graph. + + See `tf.Graph.control_dependencies` for more details. + + In TensorFlow 2 with eager and/or Autograph, you should not need this method + most of the times, as ops execute in the expected order thanks to automatic + control dependencies. Only use it to manually control ordering, for example as + a workaround to known issues such as `tf.function` with `tf.debugging.assert*` + and `tf.py_function`. + For example: + + >>> @tf.function( + ... input_signature=[tf.TensorSpec([None, None], tf.float32), + ... tf.TensorSpec([None, None], tf.float32)]) + ... def my_assert_func_1(x, bias): + ... # `tf.function` attempts to execute `tf.math.add` in parallel to + ... # `assert_equal`. As a result an error can get raised from `tf.math.add` + ... # without triggering the assertion error. + ... tf.assert_equal(tf.shape(x)[1], + ... tf.shape(bias)[1], + ... message='bad shape') + ... return x + bias + + >>> # Error raised in either `add` or `assert` + >>> my_assert_func_1(tf.ones((2, 5)), tf.ones((2, 7))) + Traceback (most recent call last): + ... + InvalidArgumentError: ... + + + >>> @tf.function( + ... input_signature=[tf.TensorSpec([None, None], tf.float32), + ... tf.TensorSpec([None, None], tf.float32)]) + ... def my_assert_func_2(x, bias): + ... with tf.control_dependencies( + ... [tf.assert_equal(tf.shape(x)[1], + ... tf.shape(bias)[1], + ... message='bad shape')]): + ... return x + bias + + >>> # Error raised in `assert` + >>> my_assert_func_2(tf.ones((2, 5)), tf.ones((2, 7))) + Traceback (most recent call last): + ... + InvalidArgumentError: ... + + When eager execution is enabled, any callable object in the `control_inputs` + list will be called. + + Args: + control_inputs: A list of `Operation` or `Tensor` objects which must be + executed or computed before running the operations defined in the context. + Can also be `None` to clear the control dependencies. If eager execution + is enabled, any callable object in the `control_inputs` list will be + called. + + Returns: + A context manager that specifies control dependencies for all + operations constructed within the context. + """ + if context.executing_eagerly(): + if control_inputs: + # Execute any pending callables. + for control in control_inputs: + if callable(control): + control() + return NullContextmanager() + else: + return get_default_graph().control_dependencies(control_inputs) + +# TODO(b/271463878): Remove in favor of direct references to `stack`. +get_default_session = stack.get_default_session + + +def _run_using_default_session( + operation, feed_dict, graph, session=None) -> None: + """Uses the default session to run "operation". + + Args: + operation: The Operation to be run. + feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists, + numpy ndarrays, TensorProtos, or strings. + graph: The graph in which "operation" is defined. + session: (Optional) A different session to use to run "operation". + + Raises: + ValueError: If no default session is available; the default session + does not have "graph" as its graph; or if "session" is specified, + and it does not have "graph" as its graph. + """ + if session is None: + session = stack.get_default_session() + if session is None: + raise ValueError("Cannot execute operation using `run()`: No default " + "session is registered. Use `with " + "sess.as_default():` or pass an explicit session to " + "`run(session=sess)`") + if session.graph is not graph: + raise ValueError("Cannot use the default session to execute operation: " + "the operation's graph is different from the " + "session's graph. Pass an explicit session to " + "run(session=sess).") + else: + if session.graph is not graph: + raise ValueError("Cannot use the given session to execute operation: " + "the operation's graph is different from the session's " + "graph.") + session.run(operation, feed_dict) + + +class _DefaultGraphStack(stack.DefaultStack): # pylint: disable=protected-access + """A thread-local stack of objects for providing an implicit default graph.""" + + def __init__(self) -> None: + super(_DefaultGraphStack, self).__init__() + self._global_default_graph = None + + def get_default(self): + """Override that returns a global default if the stack is empty.""" + if self.stack: + return self.stack[-1] + elif self._global_default_graph: + return self._global_default_graph + else: + self._global_default_graph = Graph() + return self._global_default_graph + + def _GetGlobalDefaultGraph(self): + if self._global_default_graph is None: + # TODO(mrry): Perhaps log that the default graph is being used, or set + # provide some other feedback to prevent confusion when a mixture of + # the global default graph and an explicit graph are combined in the + # same process. + self._global_default_graph = Graph() + return self._global_default_graph + + def reset(self) -> None: + super(_DefaultGraphStack, self).reset() + self._global_default_graph = None + + @tf_contextlib.contextmanager + def get_controller(self, default): + context.context().context_switches.push(default.building_function, + default.as_default, + default._device_function_stack) + try: + with super(_DefaultGraphStack, + self).get_controller(default) as g, context.graph_mode(): # pytype: disable=wrong-arg-count + yield g + finally: + # If an exception is raised here it may be hiding a related exception in + # the try-block (just above). + context.context().context_switches.pop() + + +_default_graph_stack: _DefaultGraphStack = _DefaultGraphStack() + + +# Shared helper used in init_scope and executing_eagerly_outside_functions +# to obtain the outermost context that is not building a function, and the +# innermost non empty device stack. +def _get_outer_context_and_inner_device_stack(): + """Get the outermost context not building a function.""" + default_graph = get_default_graph() + outer_context = None + innermost_nonempty_device_stack = default_graph._device_function_stack # pylint: disable=protected-access + + if not _default_graph_stack.stack: + # If the default graph stack is empty, then we cannot be building a + # function. Install the global graph (which, in this case, is also the + # default graph) as the outer context. + if default_graph.building_function: + raise RuntimeError("The global graph is building a function.") + outer_context = default_graph.as_default + else: + # Find a context that is not building a function. + for stack_entry in reversed(context.context().context_switches.stack): + if not innermost_nonempty_device_stack: + innermost_nonempty_device_stack = stack_entry.device_stack + if not stack_entry.is_building_function: + outer_context = stack_entry.enter_context_fn + break + + if outer_context is None: + # As a last resort, obtain the global default graph; this graph doesn't + # necessarily live on the graph stack (and hence it doesn't necessarily + # live on the context stack), but it is stored in the graph stack's + # encapsulating object. + outer_context = _default_graph_stack._GetGlobalDefaultGraph().as_default # pylint: disable=protected-access + + if outer_context is None: + # Sanity check; this shouldn't be triggered. + raise RuntimeError("All graphs are building functions, and no " + "eager context was previously active.") + + return outer_context, innermost_nonempty_device_stack + + +# pylint: disable=g-doc-return-or-yield,line-too-long +@tf_export("init_scope") +@tf_contextlib.contextmanager +def init_scope(): + """A context manager that lifts ops out of control-flow scopes and function-building graphs. + + There is often a need to lift variable initialization ops out of control-flow + scopes, function-building graphs, and gradient tapes. Entering an + `init_scope` is a mechanism for satisfying these desiderata. In particular, + entering an `init_scope` has three effects: + + (1) All control dependencies are cleared the moment the scope is entered; + this is equivalent to entering the context manager returned from + `control_dependencies(None)`, which has the side-effect of exiting + control-flow scopes like `tf.cond` and `tf.while_loop`. + + (2) All operations that are created while the scope is active are lifted + into the lowest context on the `context_stack` that is not building a + graph function. Here, a context is defined as either a graph or an eager + context. Every context switch, i.e., every installation of a graph as + the default graph and every switch into eager mode, is logged in a + thread-local stack called `context_switches`; the log entry for a + context switch is popped from the stack when the context is exited. + Entering an `init_scope` is equivalent to crawling up + `context_switches`, finding the first context that is not building a + graph function, and entering it. A caveat is that if graph mode is + enabled but the default graph stack is empty, then entering an + `init_scope` will simply install a fresh graph as the default one. + + (3) The gradient tape is paused while the scope is active. + + When eager execution is enabled, code inside an init_scope block runs with + eager execution enabled even when tracing a `tf.function`. For example: + + ```python + tf.compat.v1.enable_eager_execution() + + @tf.function + def func(): + # A function constructs TensorFlow graphs, + # it does not execute eagerly. + assert not tf.executing_eagerly() + with tf.init_scope(): + # Initialization runs with eager execution enabled + assert tf.executing_eagerly() + ``` + + Raises: + RuntimeError: if graph state is incompatible with this initialization. + """ + # pylint: enable=g-doc-return-or-yield,line-too-long + + if context.executing_eagerly(): + # Fastpath. + with record.stop_recording(): + yield + else: + # Retrieve the active name scope: entering an `init_scope` preserves + # the name scope of the current context. + scope = get_default_graph().get_name_scope() + if scope and scope[-1] != "/": + # Names that end with trailing slashes are treated by `name_scope` as + # absolute. + scope = scope + "/" + + outer_context, innermost_nonempty_device_stack = ( + _get_outer_context_and_inner_device_stack()) + + outer_graph = None + outer_device_stack = None + try: + with outer_context(), name_scope( + scope, skip_on_eager=False), control_dependencies( + None), record.stop_recording(): + context_manager = NullContextmanager + context_manager_input = None + if not context.executing_eagerly(): + # The device stack is preserved when lifting into a graph. Eager + # execution doesn't implement device stacks and in particular it + # doesn't support device functions, so in general it's not possible + # to do the same when lifting into the eager context. + outer_graph = get_default_graph() + outer_device_stack = outer_graph._device_function_stack # pylint: disable=protected-access + outer_graph._device_function_stack = innermost_nonempty_device_stack # pylint: disable=protected-access + elif innermost_nonempty_device_stack is not None: + for device_spec in innermost_nonempty_device_stack.peek_objs(): + if device_spec.function is None: + break + if device_spec.raw_string: + context_manager = context.device + context_manager_input = device_spec.raw_string + break + # It is currently not possible to have a device function in V2, + # but in V1 we are unable to apply device functions in eager mode. + # This means that we will silently skip some of the entries on the + # device stack in V1 + eager mode. + + with context_manager(context_manager_input): + yield + finally: + # If an exception is raised here it may be hiding a related exception in + # try-block (just above). + if outer_graph is not None: + outer_graph._device_function_stack = outer_device_stack # pylint: disable=protected-access + + +@tf_export(v1=["executing_eagerly_outside_functions"]) +def executing_eagerly_outside_functions(): + """Returns True if executing eagerly, even if inside a graph function. + + This function will check the outermost context for the program and see if + it is in eager mode. It is useful comparing to `tf.executing_eagerly()`, + which checks the current context and will return `False` within a + `tf.function` body. It can be used to build library that behave differently + in eager runtime and v1 session runtime (deprecated). + + Example: + + >>> tf.compat.v1.enable_eager_execution() + >>> @tf.function + ... def func(): + ... # A function constructs TensorFlow graphs, it does not execute eagerly, + ... # but the outer most context is still eager. + ... assert not tf.executing_eagerly() + ... return tf.compat.v1.executing_eagerly_outside_functions() + >>> func() + + + Returns: + boolean, whether the outermost context is in eager mode. + """ + if context.executing_eagerly(): + return True + else: + outer_context, _ = _get_outer_context_and_inner_device_stack() + with outer_context(): + return context.executing_eagerly() + + +@tf_export("inside_function", v1=[]) +def inside_function(): + """Indicates whether the caller code is executing inside a `tf.function`. + + Returns: + Boolean, True if the caller code is executing inside a `tf.function` + rather than eagerly. + + Example: + + >>> tf.inside_function() + False + >>> @tf.function + ... def f(): + ... print(tf.inside_function()) + >>> f() + True + """ + return get_default_graph().building_function + + +@tf_export(v1=["enable_eager_execution"]) +def enable_eager_execution(config=None, device_policy=None, + execution_mode=None): + """Enables eager execution for the lifetime of this program. + + Eager execution provides an imperative interface to TensorFlow. With eager + execution enabled, TensorFlow functions execute operations immediately (as + opposed to adding to a graph to be executed later in a `tf.compat.v1.Session`) + and + return concrete values (as opposed to symbolic references to a node in a + computational graph). + + For example: + + ```python + tf.compat.v1.enable_eager_execution() + + # After eager execution is enabled, operations are executed as they are + # defined and Tensor objects hold concrete values, which can be accessed as + # numpy.ndarray`s through the numpy() method. + assert tf.multiply(6, 7).numpy() == 42 + ``` + + Eager execution cannot be enabled after TensorFlow APIs have been used to + create or execute graphs. It is typically recommended to invoke this function + at program startup and not in a library (as most libraries should be usable + both with and without eager execution). + + @compatibility(TF2) + This function is not necessary if you are using TF2. Eager execution is + enabled by default. + @end_compatibility + + Args: + config: (Optional.) A `tf.compat.v1.ConfigProto` to use to configure the + environment in which operations are executed. Note that + `tf.compat.v1.ConfigProto` is also used to configure graph execution (via + `tf.compat.v1.Session`) and many options within `tf.compat.v1.ConfigProto` + are not implemented (or are irrelevant) when eager execution is enabled. + device_policy: (Optional.) Policy controlling how operations requiring + inputs on a specific device (e.g., a GPU 0) handle inputs on a different + device (e.g. GPU 1 or CPU). When set to None, an appropriate value will + be picked automatically. The value picked may change between TensorFlow + releases. + Valid values: + - DEVICE_PLACEMENT_EXPLICIT: raises an error if the + placement is not correct. + - DEVICE_PLACEMENT_WARN: copies the tensors which are not + on the right device but logs a warning. + - DEVICE_PLACEMENT_SILENT: silently copies the tensors. + Note that this may hide performance problems as there is no notification + provided when operations are blocked on the tensor being copied between + devices. + - DEVICE_PLACEMENT_SILENT_FOR_INT32: silently copies + int32 tensors, raising errors on the other ones. + execution_mode: (Optional.) Policy controlling how operations dispatched are + actually executed. When set to None, an appropriate value will be picked + automatically. The value picked may change between TensorFlow releases. + Valid values: + - SYNC: executes each operation synchronously. + - ASYNC: executes each operation asynchronously. These + operations may return "non-ready" handles. + + Raises: + ValueError: If eager execution is enabled after creating/executing a + TensorFlow graph, or if options provided conflict with a previous call + to this function. + """ + _api_usage_gauge.get_cell().set(True) + logging.vlog(1, "Enabling eager execution") + if context.default_execution_mode != context.EAGER_MODE: + return enable_eager_execution_internal( + config=config, + device_policy=device_policy, + execution_mode=execution_mode, + server_def=None) + + +@tf_export(v1=["disable_eager_execution"]) +def disable_eager_execution(): + """Disables eager execution. + + This function can only be called before any Graphs, Ops, or Tensors have been + created. + + @compatibility(TF2) + This function is not necessary if you are using TF2. Eager execution is + enabled by default. If you want to use Graph mode please consider + [tf.function](https://www.tensorflow.org/api_docs/python/tf/function). + @end_compatibility + """ + _api_usage_gauge.get_cell().set(False) + logging.vlog(1, "Disabling eager execution") + context.default_execution_mode = context.GRAPH_MODE + c = context.context_safe() + if c is not None: + c._thread_local_data.is_eager = False # pylint: disable=protected-access + + +def enable_eager_execution_internal(config=None, + device_policy=None, + execution_mode=None, + server_def=None) -> None: + """Enables eager execution for the lifetime of this program. + + Most of the doc string for enable_eager_execution is relevant here as well. + + Args: + config: See enable_eager_execution doc string + device_policy: See enable_eager_execution doc string + execution_mode: See enable_eager_execution doc string + server_def: (Optional.) A tensorflow::ServerDef proto. Enables execution on + remote devices. GrpcServers need to be started by creating an identical + server_def to this, and setting the appropriate task_indexes, so that the + servers can communicate. It will then be possible to execute operations on + remote devices. + + Raises: + ValueError + + """ + if config is not None and not isinstance(config, config_pb2.ConfigProto): + raise TypeError("config must be a tf.ConfigProto, but got %s" % + type(config)) + if device_policy not in (None, context.DEVICE_PLACEMENT_EXPLICIT, + context.DEVICE_PLACEMENT_WARN, + context.DEVICE_PLACEMENT_SILENT, + context.DEVICE_PLACEMENT_SILENT_FOR_INT32): + raise ValueError("device_policy must be one of None, DEVICE_PLACEMENT_*") + if execution_mode not in (None, context.SYNC, context.ASYNC): + raise ValueError("execution_mode must be one of None, SYNC, " "ASYNC") + if context.default_execution_mode == context.GRAPH_MODE: + graph_mode_has_been_used = ( + _default_graph_stack._global_default_graph is not None) # pylint: disable=protected-access + if graph_mode_has_been_used: + raise ValueError( + "tf.enable_eager_execution must be called at program startup.") + context.default_execution_mode = context.EAGER_MODE + # pylint: disable=protected-access + with context._context_lock: + if context._context is None: + context._set_context_locked(context.Context( + config=config, + device_policy=device_policy, + execution_mode=execution_mode, + server_def=server_def)) + elif ((config is not None and config is not context._context._config) or + (device_policy is not None and + device_policy is not context._context._device_policy) or + (execution_mode is not None and + execution_mode is not context._context._execution_mode)): + raise ValueError( + "Trying to change the options of an active eager" + " execution. Context config: %s, specified config:" + " %s. Context device policy: %s, specified device" + " policy: %s. Context execution mode: %s, " + " specified execution mode %s." % + (context._context._config, config, context._context._device_policy, + device_policy, context._context._execution_mode, execution_mode)) + else: + # We already created everything, so update the thread local data. + context._context._thread_local_data.is_eager = True + + # Monkey patch to get rid of an unnecessary conditional since the context is + # now initialized. + context.context = context.context_safe + + +def eager_run(main=None, argv=None) -> NoReturn: + """Runs the program with an optional main function and argv list. + + The program will run with eager execution enabled. + + Example: + ```python + import tensorflow as tf + # Import subject to future changes: + + def main(_): + u = tf.constant(6.0) + v = tf.constant(7.0) + print(u * v) + + if __name__ == "__main__": + tfe.run() + ``` + + Args: + main: the main function to run. + argv: the arguments to pass to it. + """ + enable_eager_execution() + app.run(main, argv) + + +@tf_export(v1=["reset_default_graph"]) +def reset_default_graph(): + """Clears the default graph stack and resets the global default graph. + + NOTE: The default graph is a property of the current thread. This + function applies only to the current thread. Calling this function while + a `tf.compat.v1.Session` or `tf.compat.v1.InteractiveSession` is active will + result in undefined + behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects + after calling this function will result in undefined behavior. + + @compatibility(TF2) + `reset_default_graph` does not work with either eager execution or + `tf.function`, and you should not invoke it directly. To migrate code that + uses Graph-related functions to TF2, rewrite the code without them. See the + [migration guide](https://www.tensorflow.org/guide/migrate) for more + description about the behavior and semantic changes between Tensorflow 1 and + Tensorflow 2. + @end_compatibility + + Raises: + AssertionError: If this function is called within a nested graph. + """ + if not _default_graph_stack.is_cleared(): + raise AssertionError("Do not use tf.reset_default_graph() to clear " + "nested graphs. If you need a cleared graph, " + "exit the nesting and create a new graph.") + _default_graph_stack.reset() + + +@tf_export(v1=["get_default_graph"]) +def get_default_graph() -> Graph: + """Returns the default graph for the current thread. + + The returned graph will be the innermost graph on which a + `Graph.as_default()` context has been entered, or a global default + graph if none has been explicitly created. + + NOTE: The default graph is a property of the current thread. If you + create a new thread, and wish to use the default graph in that + thread, you must explicitly add a `with g.as_default():` in that + thread's function. + + @compatibility(TF2) + `get_default_graph` does not work with either eager execution or + `tf.function`, and you should not invoke it directly. To migrate code that + uses Graph-related functions to TF2, rewrite the code without them. See the + [migration guide](https://www.tensorflow.org/guide/migrate) for more + description about the behavior and semantic changes between Tensorflow 1 and + Tensorflow 2. + @end_compatibility + + Returns: + The default `Graph` being used in the current thread. + """ + return _default_graph_stack.get_default() + + +def has_default_graph() -> bool: + """Returns True if there is a default graph.""" + return len(_default_graph_stack.stack) >= 1 + + +# Exported due to b/171079555 +@tf_export("__internal__.get_name_scope", v1=[]) +def get_name_scope(): + """Returns the current name scope in the default_graph. + + For example: + + ```python + with tf.name_scope('scope1'): + with tf.name_scope('scope2'): + print(tf.get_name_scope()) + ``` + would print the string `scope1/scope2`. + + Returns: + A string representing the current name scope. + """ + if context.executing_eagerly(): + return context.context().scope_name.rstrip("/") + return get_default_graph().get_name_scope() + + +def _assert_same_graph(original_item, item) -> None: + """Fail if the 2 items are from different graphs. + + Args: + original_item: Original item to check against. + item: Item to check. + + Raises: + ValueError: if graphs do not match. + """ + original_graph = getattr(original_item, "graph", None) + graph = getattr(item, "graph", None) + if original_graph and graph and original_graph is not graph: + raise ValueError( + "%s must be from the same graph as %s (graphs are %s and %s)." % + (item, original_item, graph, original_graph)) + + +def _get_graph_from_inputs(op_input_list, graph=None): + """Returns the appropriate graph to use for the given inputs. + + This library method provides a consistent algorithm for choosing the graph + in which an Operation should be constructed: + + 1. If the default graph is being used to construct a function, we + use the default graph. + 2. If the "graph" is specified explicitly, we validate that all of the inputs + in "op_input_list" are compatible with that graph. + 3. Otherwise, we attempt to select a graph from the first Operation- + or Tensor-valued input in "op_input_list", and validate that all other + such inputs are in the same graph. + 4. If the graph was not specified and it could not be inferred from + "op_input_list", we attempt to use the default graph. + + Args: + op_input_list: A list of inputs to an operation, which may include `Tensor`, + `Operation`, and other objects that may be converted to a graph element. + graph: (Optional) The explicit graph to use. + + Raises: + TypeError: If op_input_list is not a list or tuple, or if graph is not a + Graph. + ValueError: If a graph is explicitly passed and not all inputs are from it, + or if the inputs are from multiple graphs, or we could not find a graph + and there was no default graph. + + Returns: + The appropriate graph to use for the given inputs. + + """ + current_default_graph = get_default_graph() + if current_default_graph.building_function: + return current_default_graph + + op_input_list = tuple(op_input_list) # Handle generators correctly + if graph and not isinstance(graph, Graph): + raise TypeError("Input graph needs to be a Graph: %s" % (graph,)) + + # 1. We validate that all of the inputs are from the same graph. This is + # either the supplied graph parameter, or the first one selected from one + # the graph-element-valued inputs. In the latter case, we hold onto + # that input in original_graph_element so we can provide a more + # informative error if a mismatch is found. + original_graph_element = None + for op_input in op_input_list: + graph_element = None + if isinstance(op_input, (Operation, SymbolicTensor)): + graph_element = op_input + else: + graph_element = _as_graph_element(op_input) + + if graph_element is not None: + if not graph: + original_graph_element = graph_element + graph = getattr(graph_element, "graph", None) + elif original_graph_element is not None: + _assert_same_graph(original_graph_element, graph_element) + elif graph_element.graph is not graph: + raise ValueError("%s is not from the passed-in graph." % graph_element) + + # 2. If all else fails, we use the default graph, which is always there. + return graph or current_default_graph + + +@tf_export(v1=["GraphKeys"]) +class GraphKeys(object): + """Standard names to use for graph collections. + + The standard library uses various well-known names to collect and + retrieve values associated with a graph. For example, the + `tf.Optimizer` subclasses default to optimizing the variables + collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is + specified, but it is also possible to pass an explicit list of + variables. + + The following standard keys are defined: + + * `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared + across distributed environment (model variables are subset of these). See + `tf.compat.v1.global_variables` + for more details. + Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`, + and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`. + * `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each + machine. Usually used for temporarily variables, like counters. + * `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the + model for inference (feed forward). + * `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will + be trained by an optimizer. See + `tf.compat.v1.trainable_variables` + for more details. + * `SUMMARIES`: the summary `Tensor` objects that have been created in the + graph. See + `tf.compat.v1.summary.merge_all` + for more details. + * `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to + produce input for a computation. See + `tf.compat.v1.train.start_queue_runners` + for more details. + * `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also + keep moving averages. See + `tf.compat.v1.moving_average_variables` + for more details. + * `REGULARIZATION_LOSSES`: regularization losses collected during graph + construction. + + The following standard keys are _defined_, but their collections are **not** + automatically populated as many of the others are: + + * `WEIGHTS` + * `BIASES` + * `ACTIVATIONS` + """ + + # Key to collect Variable objects that are global (shared across machines). + # Default collection for all variables, except local ones. + GLOBAL_VARIABLES = "variables" + # Key to collect local variables that are local to the machine and are not + # saved/restored. + LOCAL_VARIABLES = "local_variables" + # Key to collect local variables which are used to accumulate internal state + # to be used in tf.metrics.*. + METRIC_VARIABLES = "metric_variables" + # Key to collect model variables defined by layers. + MODEL_VARIABLES = "model_variables" + # Key to collect Variable objects that will be trained by the + # optimizers. + TRAINABLE_VARIABLES = "trainable_variables" + # Key to collect summaries. + SUMMARIES = "summaries" + # Key to collect QueueRunners. + QUEUE_RUNNERS = "queue_runners" + # Key to collect table initializers. + TABLE_INITIALIZERS = "table_initializer" + # Key to collect asset filepaths. An asset represents an external resource + # like a vocabulary file. + ASSET_FILEPATHS = "asset_filepaths" + # Key to collect Variable objects that keep moving averages. + MOVING_AVERAGE_VARIABLES = "moving_average_variables" + # Key to collect regularization losses at graph construction. + REGULARIZATION_LOSSES = "regularization_losses" + # Key to collect concatenated sharded variables. + CONCATENATED_VARIABLES = "concatenated_variables" + # Key to collect savers. + SAVERS = "savers" + # Key to collect weights + WEIGHTS = "weights" + # Key to collect biases + BIASES = "biases" + # Key to collect activations + ACTIVATIONS = "activations" + # Key to collect update_ops + UPDATE_OPS = "update_ops" + # Key to collect losses + LOSSES = "losses" + # Key to collect BaseSaverBuilder.SaveableObject instances for checkpointing. + SAVEABLE_OBJECTS = "saveable_objects" + # Key to collect all shared resources used by the graph which need to be + # initialized once per cluster. + RESOURCES = "resources" + # Key to collect all shared resources used in this graph which need to be + # initialized once per session. + LOCAL_RESOURCES = "local_resources" + # Trainable resource-style variables. + TRAINABLE_RESOURCE_VARIABLES = "trainable_resource_variables" + + # Key to indicate various ops. + INIT_OP = "init_op" + LOCAL_INIT_OP = "local_init_op" + READY_OP = "ready_op" + READY_FOR_LOCAL_INIT_OP = "ready_for_local_init_op" + SUMMARY_OP = "summary_op" + GLOBAL_STEP = "global_step" + + # Used to count the number of evaluations performed during a single evaluation + # run. + EVAL_STEP = "eval_step" + TRAIN_OP = "train_op" + + # Key for control flow context. + COND_CONTEXT = "cond_context" + WHILE_CONTEXT = "while_context" + + # Used to store v2 summary names. + _SUMMARY_COLLECTION = "_SUMMARY_V2" + + # List of all collections that keep track of variables. + _VARIABLE_COLLECTIONS = [ + GLOBAL_VARIABLES, + LOCAL_VARIABLES, + METRIC_VARIABLES, + MODEL_VARIABLES, + TRAINABLE_VARIABLES, + MOVING_AVERAGE_VARIABLES, + CONCATENATED_VARIABLES, + TRAINABLE_RESOURCE_VARIABLES, + ] + + # Key for streaming model ports. + # NOTE(yuanbyu): internal and experimental. + _STREAMING_MODEL_PORTS = "streaming_model_ports" + + @decorator_utils.classproperty + @deprecation.deprecated(None, "Use `tf.GraphKeys.GLOBAL_VARIABLES` instead.") + def VARIABLES(cls): # pylint: disable=no-self-argument + return cls.GLOBAL_VARIABLES + + +def dismantle_graph(graph) -> None: + """Cleans up reference cycles from a `Graph`. + + Helpful for making sure the garbage collector doesn't need to run after a + temporary `Graph` is no longer needed. + + Args: + graph: A `Graph` object to destroy. Neither it nor any of its ops are usable + after this function runs. + """ + graph._functions.clear() # pylint: disable=protected-access + graph.Dismantle() + + +@tf_export(v1=["add_to_collection"]) +def add_to_collection(name, value): + """Wrapper for `Graph.add_to_collection()` using the default graph. + + See `tf.Graph.add_to_collection` + for more details. + + Args: + name: The key for the collection. For example, the `GraphKeys` class + contains many standard names for collections. + value: The value to add to the collection. + + @compatibility(eager) + Collections are only supported in eager when variables are created inside + an EagerVariableStore (e.g. as part of a layer or template). + @end_compatibility + """ + get_default_graph().add_to_collection(name, value) + + +@tf_export(v1=["add_to_collections"]) +def add_to_collections(names, value): + """Wrapper for `Graph.add_to_collections()` using the default graph. + + See `tf.Graph.add_to_collections` + for more details. + + Args: + names: The key for the collections. The `GraphKeys` class contains many + standard names for collections. + value: The value to add to the collections. + + @compatibility(eager) + Collections are only supported in eager when variables are created inside + an EagerVariableStore (e.g. as part of a layer or template). + @end_compatibility + """ + get_default_graph().add_to_collections(names, value) + + +@tf_export(v1=["get_collection_ref"]) +def get_collection_ref(key): + """Wrapper for `Graph.get_collection_ref()` using the default graph. + + See `tf.Graph.get_collection_ref` + for more details. + + Args: + key: The key for the collection. For example, the `GraphKeys` class contains + many standard names for collections. + + Returns: + The list of values in the collection with the given `name`, or an empty + list if no value has been added to that collection. Note that this returns + the collection list itself, which can be modified in place to change the + collection. + + @compatibility(eager) + Collections are not supported when eager execution is enabled. + @end_compatibility + """ + return get_default_graph().get_collection_ref(key) + + +@tf_export(v1=["get_collection"]) +def get_collection(key, scope=None): + """Wrapper for `Graph.get_collection()` using the default graph. + + See `tf.Graph.get_collection` + for more details. + + Args: + key: The key for the collection. For example, the `GraphKeys` class contains + many standard names for collections. + scope: (Optional.) If supplied, the resulting list is filtered to include + only items whose `name` attribute matches using `re.match`. Items without + a `name` attribute are never returned if a scope is supplied and the + choice or `re.match` means that a `scope` without special tokens filters + by prefix. + + Returns: + The list of values in the collection with the given `name`, or + an empty list if no value has been added to that collection. The + list contains the values in the order under which they were + collected. + + @compatibility(eager) + Collections are not supported when eager execution is enabled. + @end_compatibility + """ + return get_default_graph().get_collection(key, scope) + + +def get_all_collection_keys(): + """Returns a list of collections used in the default graph.""" + return get_default_graph().get_all_collection_keys() + + +def name_scope(name, default_name=None, values=None, skip_on_eager=True): + """Internal-only entry point for `name_scope*`. + + Internal ops do not use the public API and instead rely on + `ops.name_scope` regardless of the execution mode. This function + dispatches to the correct `name_scope*` implementation based on + the arguments provided and the current mode. Specifically, + + * if `values` contains a graph tensor `Graph.name_scope` is used; + * `name_scope_v1` is used in graph mode; + * `name_scope_v2` -- in eager mode. + + Args: + name: The name argument that is passed to the op function. + default_name: The default name to use if the `name` argument is `None`. + values: The list of `Tensor` arguments that are passed to the op function. + skip_on_eager: Indicates to return NullContextmanager if executing eagerly. + By default this is True since naming tensors and operations in eager mode + have little use and cause unnecessary performance overhead. However, it is + important to preserve variable names since they are often useful for + debugging and saved models. + + Returns: + `name_scope*` context manager. + """ + if not context.executing_eagerly(): + return internal_name_scope_v1(name, default_name, values) + + if skip_on_eager: + return NullContextmanager() + + name = default_name if name is None else name + if values: + # The presence of a graph tensor in `values` overrides the context. + # TODO(slebedev): this is Keras-specific and should be removed. + graph_value = next( + (value for value in values if is_symbolic_tensor(value)), None + ) + # pylint: enable=unidiomatic-typecheck + if graph_value is not None: + return graph_value.graph.name_scope(name) + + return name_scope_v2(name or "") + + +class internal_name_scope_v1(object): # pylint: disable=invalid-name + """Graph-only version of `name_scope_v1`.""" + + @property + def name(self): + return self._name + + def __init__(self, name, default_name=None, values=None) -> None: + """Initialize the context manager. + + Args: + name: The name argument that is passed to the op function. + default_name: The default name to use if the `name` argument is `None`. + values: The list of `Tensor` arguments that are passed to the op function. + + Raises: + TypeError: if `default_name` is passed in but not a string. + """ + if not (default_name is None or isinstance(default_name, str)): + raise TypeError( + "`default_name` type (%s) is not a string type. You likely meant to " + "pass this into the `values` kwarg." % type(default_name)) + self._name = default_name if name is None else name + self._default_name = default_name + self._values = values + + def __enter__(self): + """Start the scope block. + + Returns: + The scope name. + + Raises: + ValueError: if neither `name` nor `default_name` is provided + but `values` are. + """ + if self._name is None and self._values is not None: + # We only raise an error if values is not None (provided) because + # currently tf.name_scope(None) (values=None then) is sometimes used as + # an idiom to reset to top scope. + raise ValueError( + "At least one of name (%s) and default_name (%s) must be provided." + % (self._name, self._default_name)) + + g = get_default_graph() + if self._values and not g.building_function: + # Specialize based on the knowledge that `_get_graph_from_inputs()` + # ignores `inputs` when building a function. + g_from_inputs = _get_graph_from_inputs(self._values) + if g_from_inputs is not g: + g = g_from_inputs + self._g_manager = g.as_default() + self._g_manager.__enter__() + else: + self._g_manager = None + else: + self._g_manager = None + + try: + self._name_scope = g.name_scope(self._name) + return self._name_scope.__enter__() + except: + if self._g_manager is not None: + self._g_manager.__exit__(*sys.exc_info()) + raise + + def __exit__(self, *exc_info) -> None: + self._name_scope.__exit__(*exc_info) + if self._g_manager is not None: + self._g_manager.__exit__(*exc_info) + + +# Named like a function for backwards compatibility with the +# @tf_contextlib.contextmanager version, which was switched to a class to avoid +# some object creation overhead. +@tf_export(v1=["name_scope"]) +class name_scope_v1(object): # pylint: disable=invalid-name + """A context manager for use when defining a Python op. + + This context manager validates that the given `values` are from the + same graph, makes that graph the default graph, and pushes a + name scope in that graph (see + `tf.Graph.name_scope` + for more details on that). + + For example, to define a new Python op called `my_op`: + + ```python + def my_op(a, b, c, name=None): + with tf.name_scope(name, "MyOp", [a, b, c]) as scope: + a = tf.convert_to_tensor(a, name="a") + b = tf.convert_to_tensor(b, name="b") + c = tf.convert_to_tensor(c, name="c") + # Define some computation that uses `a`, `b`, and `c`. + return foo_op(..., name=scope) + ``` + """ + + __slots__ = ["_name", "_name_scope"] + + @property + def name(self): + return self._name + + def __init__(self, name, default_name=None, values=None): + """Initialize the context manager. + + Args: + name: The name argument that is passed to the op function. + default_name: The default name to use if the `name` argument is `None`. + values: The list of `Tensor` arguments that are passed to the op function. + + Raises: + TypeError: if `default_name` is passed in but not a string. + """ + self._name_scope = name_scope( + name, default_name, values, skip_on_eager=False) + self._name = default_name if name is None else name + + def __enter__(self): + return self._name_scope.__enter__() + + def __exit__(self, *exc_info): + return self._name_scope.__exit__(*exc_info) + + +@tf_export("get_current_name_scope", v1=[]) +def get_current_name_scope(): + """Returns current full name scope specified by `tf.name_scope(...)`s. + + For example, + ```python + with tf.name_scope("outer"): + tf.get_current_name_scope() # "outer" + + with tf.name_scope("inner"): + tf.get_current_name_scope() # "outer/inner" + ``` + + In other words, `tf.get_current_name_scope()` returns the op name prefix that + will be prepended to, if an op is created at that place. + + Note that `@tf.function` resets the name scope stack as shown below. + + ``` + with tf.name_scope("outer"): + + @tf.function + def foo(x): + with tf.name_scope("inner"): + return tf.add(x * x) # Op name is "inner/Add", not "outer/inner/Add" + ``` + """ + + ctx = context.context() + if ctx.executing_eagerly(): + return ctx.scope_name.rstrip("/") + else: + return get_default_graph().get_name_scope() + + +@tf_export("name_scope", v1=[]) +class name_scope_v2(object): + """A context manager for use when defining a Python op. + + This context manager pushes a name scope, which will make the name of all + operations added within it have a prefix. + + For example, to define a new Python op called `my_op`: + + ```python + def my_op(a, b, c, name=None): + with tf.name_scope("MyOp") as scope: + a = tf.convert_to_tensor(a, name="a") + b = tf.convert_to_tensor(b, name="b") + c = tf.convert_to_tensor(c, name="c") + # Define some computation that uses `a`, `b`, and `c`. + return foo_op(..., name=scope) + ``` + + When executed, the Tensors `a`, `b`, `c`, will have names `MyOp/a`, `MyOp/b`, + and `MyOp/c`. + + Inside a `tf.function`, if the scope name already exists, the name will be + made unique by appending `_n`. For example, calling `my_op` the second time + will generate `MyOp_1/a`, etc. + """ + + __slots__ = ["_name", "_exit_fns"] + + def __init__(self, name): + """Initialize the context manager. + + Args: + name: The prefix to use on all names created within the name scope. + + Raises: + ValueError: If name is not a string. + """ + if not isinstance(name, str): + raise ValueError("name for name_scope must be a string.") + self._name = name + self._exit_fns = [] + + @property + def name(self): + return self._name + + def __enter__(self): + """Start the scope block. + + Returns: + The scope name. + """ + ctx = context.context() + if ctx.executing_eagerly(): + # Names are not auto-incremented in eager mode. + # A trailing slash breaks out of nested name scopes, indicating a + # fully specified scope name, for compatibility with Graph.name_scope. + # This also prevents auto-incrementing. + old_name = ctx.scope_name + name = self._name + if not name: + scope_name = "" + elif name[-1] == "/": + scope_name = name + elif old_name: + scope_name = old_name + name + "/" + else: + scope_name = name + "/" + ctx.scope_name = scope_name + + def _restore_name_scope(*_): + ctx.scope_name = old_name + + self._exit_fns.append(_restore_name_scope) + else: + scope = get_default_graph().name_scope(self._name) + scope_name = scope.__enter__() + self._exit_fns.append(scope.__exit__) + return scope_name + + def __exit__(self, type_arg, value_arg, traceback_arg): + self._exit_fns.pop()(type_arg, value_arg, traceback_arg) + return False # False values do not suppress exceptions + + def __getstate__(self): + return self._name, self._exit_fns + + def __setstate__(self, state): + self._name = state[0] + self._exit_fns = state[1] + + +def strip_name_scope(name: str, export_scope) -> str: + """Removes name scope from a name. + + Args: + name: A `string` name. + export_scope: Optional `string`. Name scope to remove. + + Returns: + Name with name scope removed, or the original name if export_scope + is None. + """ + if export_scope: + if export_scope[-1] == "/": + export_scope = export_scope[:-1] + + try: + # Strips export_scope/, export_scope///, + # ^export_scope/, loc:@export_scope/. + str_to_replace = r"([\^]|loc:@|^)" + export_scope + r"[\/]+(.*)" + return re.sub(str_to_replace, r"\1\2", compat.as_str(name), count=1) + except TypeError as e: + # If the name is not of a type we can process, simply return it. + logging.warning(e) + return name + else: + return name + + +def prepend_name_scope(name: str, import_scope) -> str: + """Prepends name scope to a name. + + Args: + name: A `string` name. + import_scope: Optional `string`. Name scope to add. + + Returns: + Name with name scope added, or the original name if import_scope + is None. + """ + if import_scope: + if import_scope[-1] == "/": + import_scope = import_scope[:-1] + + try: + str_to_replace = r"([\^]|loc:@|^)(.*)" + return re.sub(str_to_replace, r"\1" + import_scope + r"/\2", + compat.as_str(name)) + except TypeError as e: + # If the name is not of a type we can process, simply return it. + logging.warning(e) + return name + else: + return name + + +# pylint: disable=g-doc-return-or-yield +# pylint: disable=not-context-manager +@tf_export(v1=["op_scope"]) +@tf_contextlib.contextmanager +def op_scope(values, name, default_name=None): + """DEPRECATED. Same as name_scope above, just different argument order.""" + logging.warn("tf.op_scope(values, name, default_name) is deprecated," + " use tf.name_scope(name, default_name, values)") + with name_scope(name, default_name=default_name, values=values) as scope: + yield scope + + +_proto_function_registry = registry.Registry("proto functions") + + +def register_proto_function(collection_name, + proto_type=None, + to_proto=None, + from_proto=None) -> None: + """Registers `to_proto` and `from_proto` functions for collection_name. + + `to_proto` function converts a Python object to the corresponding protocol + buffer, and returns the protocol buffer. + + `from_proto` function converts protocol buffer into a Python object, and + returns the object.. + + Args: + collection_name: Name of the collection. + proto_type: Protobuf type, such as `saver_pb2.SaverDef`, + `variable_pb2.VariableDef`, `queue_runner_pb2.QueueRunnerDef`.. + to_proto: Function that implements Python object to protobuf conversion. + from_proto: Function that implements protobuf to Python object conversion. + """ + if to_proto and not callable(to_proto): + raise TypeError("to_proto must be callable.") + if from_proto and not callable(from_proto): + raise TypeError("from_proto must be callable.") + + _proto_function_registry.register((proto_type, to_proto, from_proto), + collection_name) + + +def get_collection_proto_type(collection_name): + """Returns the proto_type for collection_name.""" + try: + return _proto_function_registry.lookup(collection_name)[0] + except LookupError: + return None + + +def get_to_proto_function(collection_name): + """Returns the to_proto function for collection_name.""" + try: + return _proto_function_registry.lookup(collection_name)[1] + except LookupError: + return None + + +def get_from_proto_function(collection_name): + """Returns the from_proto function for collection_name.""" + try: + return _proto_function_registry.lookup(collection_name)[2] + except LookupError: + return None + + +def _op_to_colocate_with(v, graph): + """Operation object corresponding to v to use for colocation constraints.""" + if v is None: + return None, None + if isinstance(v, Operation): + return v, None + + # We always want to colocate with the reference op. + # When 'v' is a ResourceVariable, the reference op is the handle creating op. + # + # What this should be is: + # if isinstance(v, ResourceVariable): + # return v.handle.op, v + # However, that would require a circular import dependency. + # As of October 2018, there were attempts underway to remove + # colocation constraints altogether. Assuming that will + # happen soon, perhaps this hack to work around the circular + # import dependency is acceptable. + if hasattr(v, "handle") and isinstance(v.handle, tensor_lib.Tensor): + device_only_candidate = lambda: None + device_only_candidate.device = v.device + device_only_candidate.name = v.name + if graph.building_function: + return graph.capture(v.handle).op, device_only_candidate + else: + return v.handle.op, device_only_candidate + if isinstance(v, EagerTensor) and not context.executing_eagerly(): + return convert_to_tensor(v, as_ref=True).op, None + elif isinstance(v, internal.NativeObject): + return v.op, None + else: + return convert_to_tensor(v, as_ref=True).op, None + + +# Helper functions for op wrapper modules generated by `python_op_gen`. + + +def to_raw_op(f): + """Make a given op wrapper function `f` raw. + + Raw op wrappers can only be called with keyword arguments. + + Args: + f: An op wrapper function to make raw. + + Returns: + Raw `f`. + """ + # Copy `f` to get a new `__dict__`, otherwise `tf_export` will fail + # due to double-registration. + f = types.FunctionType(f.__code__, f.__globals__, f.__name__, f.__defaults__, + f.__closure__) + return kwarg_only(f) + + +def raise_from_not_ok_status(e, name) -> NoReturn: + e.message += (" name: " + str(name if name is not None else "")) + raise core._status_to_exception(e) from None # pylint: disable=protected-access + + +def add_exit_callback_to_default_func_graph(fn) -> None: + """Add a callback to run when the default function graph goes out of scope. + + Usage: + + ```python + @tf.function + def fn(x, v): + expensive = expensive_object(v) + add_exit_callback_to_default_func_graph(lambda: expensive.release()) + return g(x, expensive) + + fn(x=tf.constant(...), v=...) + # `expensive` has been released. + ``` + + Args: + fn: A callable that takes no arguments and whose output is ignored. + To be executed when exiting func graph scope. + + Raises: + RuntimeError: If executed when the current default graph is not a FuncGraph, + or not currently executing in function creation mode (e.g., if inside + an init_scope). + """ + default_graph = get_default_graph() + if not default_graph._building_function: # pylint: disable=protected-access + raise RuntimeError( + "Cannot add scope exit callbacks when not building a function. " + "Default graph: {}".format(default_graph)) + default_graph._add_scope_exit_callback(fn) # pylint: disable=protected-access + + +def _reconstruct_sequence_inputs(op_def, inputs, attrs): + """Regroups a flat list of input tensors into scalar and sequence inputs. + + Args: + op_def: The `op_def_pb2.OpDef` (for knowing the input types) + inputs: a list of input `Tensor`s to the op. + attrs: mapping from attr name to `attr_value_pb2.AttrValue` (these define + how long each sequence is) + + Returns: + A list of `Tensor`s (corresponding to scalar inputs) and lists of + `Tensor`s (corresponding to sequence inputs). + """ + grouped_inputs = [] + i = 0 + for input_arg in op_def.input_arg: + if input_arg.number_attr: + input_len = attrs[input_arg.number_attr].i + is_sequence = True + elif input_arg.type_list_attr: + input_len = len(attrs[input_arg.type_list_attr].list.type) + is_sequence = True + else: + input_len = 1 + is_sequence = False + + if is_sequence: + grouped_inputs.append(inputs[i:i + input_len]) + else: + grouped_inputs.append(inputs[i]) + i += input_len + + assert i == len(inputs) + return grouped_inputs + + +# OFF mode is the current TF dtype promotion semantics - no dtype conversion +# allowed. LEGACY mode maintains the old Tf-NumPy promotion semantics, similar +# to NumPy's dtype promotion semantics. ALL mode allows all conversions while +# SAFE mode disallows “risky” promotions that can result in dtype widening or +# potential precision loss. +class PromoMode(enum.Enum): + OFF: int = 0 + LEGACY: int = 1 + SAFE: int = 2 + ALL: int = 3 + + +_dtype_conversion_mode: PromoMode = PromoMode.OFF + + +def get_dtype_conversion_mode(): + return _dtype_conversion_mode + + +# TODO(b/289395872): Make sure all WeakTensor construction is guarded with this +# check. +def is_auto_dtype_conversion_enabled(): + return ( + _dtype_conversion_mode == PromoMode.ALL + or _dtype_conversion_mode == PromoMode.SAFE + ) + + +def is_numpy_style_type_promotion(): + return _dtype_conversion_mode == PromoMode.LEGACY + + +def set_dtype_conversion_mode(dtype_conversion_mode) -> None: + """Enables the specified dtype conversion mode. + + Args: + dtype_conversion_mode: a string that specifies dtype conversion mode. This + string corresponds to a PromoMode Enum and can be 'off', 'legacy', 'safe' + or 'all'. + """ + global _dtype_conversion_mode + _dtype_conversion_mode = _get_promo_mode_enum(dtype_conversion_mode) + + +def _get_promo_mode_enum(dtype_conversion_mode): + """Returns the corresponding PromoMode enum value from string.""" + if dtype_conversion_mode == "off": + return PromoMode.OFF + if dtype_conversion_mode == "legacy": + return PromoMode.LEGACY + elif dtype_conversion_mode == "safe": + return PromoMode.SAFE + elif dtype_conversion_mode == "all": + return PromoMode.ALL + else: + raise ValueError( + f"The provided promotion mode {dtype_conversion_mode} does not exist." + " Make sure the provided dtype conversion mode is one of the" + " followings: 'off', 'legacy', 'safe' or 'all'." + ) + + +def promo_mode_enum_to_string(promo_safety_mode_enum) -> str: + """Returns the corresponding PromoMode string value from PromoMode enum.""" + if promo_safety_mode_enum == PromoMode.OFF: + return "off" + if promo_safety_mode_enum == PromoMode.LEGACY: + return "legacy" + elif promo_safety_mode_enum == PromoMode.SAFE: + return "safe" + elif promo_safety_mode_enum == PromoMode.ALL: + return "all" + else: + raise ValueError( + f"The provided promotion mode {promo_safety_mode_enum} does not exist." + ) + + +_numpy_style_slicing: bool = False + + +def enable_numpy_style_slicing() -> None: + """If called, follows NumPy's rules for slicing Tensors. + + Used for enabling NumPy behavior on slicing for TF NumPy. + """ + global _numpy_style_slicing + _numpy_style_slicing = True + + +def set_int_list_attr(op, attr_name, ints) -> None: + """TF internal method used to set a list(int) attribute in the node_def.""" + ints_list = attr_value_pb2.AttrValue.ListValue(i=ints) + op._set_attr(attr_name, attr_value_pb2.AttrValue(list=ints_list)) # pylint:disable=protected-access + + +def _get_enclosing_context(graph) -> Any: + # pylint: disable=protected-access + if graph is None: + return None + + if graph._control_flow_context is not None: + return graph._control_flow_context + + if graph.building_function and hasattr(graph, "outer_graph"): + return _get_enclosing_context(graph.outer_graph) + + +# TODO(b/271463878): Remove in favor of direct references to `handle_data_util`. +get_resource_handle_data = handle_data_util.get_resource_handle_data + + +def _copy_handle_data_to_arg_def(tensor, arg_def) -> None: + handle_data = handle_data_util.get_resource_handle_data(tensor) + if handle_data.shape_and_type: + shape_and_type = handle_data.shape_and_type[0] + proto = arg_def.handle_data.add() + proto.dtype = shape_and_type.dtype + proto.shape.CopyFrom(handle_data.shape_and_type[0].shape) + + +@tf_export("is_symbolic_tensor", v1=["is_symbolic_tensor"]) +def is_symbolic_tensor(tensor): + """Test if `tensor` is a symbolic Tensor. + + Args: + tensor: a tensor-like object + + Returns: + True if `tensor` is a symbolic tensor (not an eager tensor). + """ + return isinstance(tensor, SymbolicTensor) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/python_memory_checker.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/python_memory_checker.py new file mode 100644 index 0000000000000000000000000000000000000000..aa0d2023585bf500833bf667b5cea111cc15ea79 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/python_memory_checker.py @@ -0,0 +1,153 @@ +# 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. +# ============================================================================== +"""Python memory leak detection utility. + +Please don't use this class directly. Instead, use `MemoryChecker` wrapper. +""" + +import collections +import copy +import gc + +from tensorflow.python.framework import _python_memory_checker_helper +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import trace + + +def _get_typename(obj): + """Return human readable pretty type name string.""" + objtype = type(obj) + name = objtype.__name__ + module = getattr(objtype, '__module__', None) + if module: + return '{}.{}'.format(module, name) + else: + return name + + +def _create_python_object_snapshot(): + gc.collect() + all_objects = gc.get_objects() + result = collections.defaultdict(set) + for obj in all_objects: + result[_get_typename(obj)].add(id(obj)) + return result + + +def _snapshot_diff(old_snapshot, new_snapshot, exclude_ids): + result = collections.Counter() + for new_name, new_ids in new_snapshot.items(): + old_ids = old_snapshot[new_name] + result[new_name] = len(new_ids - exclude_ids) - len(old_ids - exclude_ids) + + # This removes zero or negative value entries. + result += collections.Counter() + return result + + +class _PythonMemoryChecker(object): + """Python memory leak detection class.""" + + def __init__(self): + self._snapshots = [] + # cache the function used by mark_stack_trace_and_call to avoid + # contaminating the leak measurement. + def _record_snapshot(): + self._snapshots.append(_create_python_object_snapshot()) + + self._record_snapshot = _record_snapshot + + # We do not enable trace_wrapper on this function to avoid contaminating + # the snapshot. + def record_snapshot(self): + # Function called using `mark_stack_trace_and_call` will have + # "_python_memory_checker_helper" string in the C++ stack trace. This will + # be used to filter out C++ memory allocations caused by this function, + # because we are not interested in detecting memory growth caused by memory + # checker itself. + _python_memory_checker_helper.mark_stack_trace_and_call( + self._record_snapshot) + + @trace.trace_wrapper + def report(self): + # TODO(kkb): Implement. + pass + + @trace.trace_wrapper + def assert_no_leak_if_all_possibly_except_one(self): + """Raises an exception if a leak is detected. + + This algorithm classifies a series of allocations as a leak if it's the same + type at every snapshot, but possibly except one snapshot. + """ + + snapshot_diffs = [] + for i in range(0, len(self._snapshots) - 1): + snapshot_diffs.append(self._snapshot_diff(i, i + 1)) + + allocation_counter = collections.Counter() + for diff in snapshot_diffs: + for name, count in diff.items(): + if count > 0: + allocation_counter[name] += 1 + + leaking_object_names = { + name for name, count in allocation_counter.items() + if count >= len(snapshot_diffs) - 1 + } + + if leaking_object_names: + object_list_to_print = '\n'.join( + [' - ' + name for name in leaking_object_names]) + raise AssertionError( + 'These Python objects were allocated in every snapshot possibly ' + f'except one.\n\n{object_list_to_print}') + + @trace.trace_wrapper + def assert_no_new_objects(self, threshold=None): + """Assert no new Python objects.""" + + if not threshold: + threshold = {} + + count_diff = self._snapshot_diff(0, -1) + original_count_diff = copy.deepcopy(count_diff) + count_diff.subtract(collections.Counter(threshold)) + + if max(count_diff.values() or [0]) > 0: + raise AssertionError('New Python objects created exceeded the threshold.' + '\nPython object threshold:\n' + f'{threshold}\n\nNew Python objects:\n' + f'{original_count_diff.most_common()}') + elif min(count_diff.values(), default=0) < 0: + logging.warning('New Python objects created were less than the threshold.' + '\nPython object threshold:\n' + f'{threshold}\n\nNew Python objects:\n' + f'{original_count_diff.most_common()}') + + @trace.trace_wrapper + def _snapshot_diff(self, old_index, new_index): + return _snapshot_diff(self._snapshots[old_index], + self._snapshots[new_index], + self._get_internal_object_ids()) + + @trace.trace_wrapper + def _get_internal_object_ids(self): + ids = set() + for snapshot in self._snapshots: + ids.add(id(snapshot)) + for v in snapshot.values(): + ids.add(id(v)) + return ids diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/random_seed.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/random_seed.py new file mode 100644 index 0000000000000000000000000000000000000000..8f6c7cf7af22a62716822e4124851a28dfea42ba --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/random_seed.py @@ -0,0 +1,358 @@ +# 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. +# ============================================================================== + +"""For seeding individual ops based on a graph-level seed. +""" + +import weakref + +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import ops +from tensorflow.python.util import deprecation +from tensorflow.python.util.tf_export import tf_export + + +DEFAULT_GRAPH_SEED = 87654321 +_MAXINT32 = 2**31 - 1 + +_graph_to_seed_dict = weakref.WeakKeyDictionary() + + +def _truncate_seed(seed): + return seed % _MAXINT32 # Truncate to fit into 32-bit integer + + +@tf_export(v1=['random.get_seed', 'get_seed']) +@deprecation.deprecated_endpoints('get_seed') +def get_seed(op_seed): + """Returns the local seeds an operation should use given an op-specific seed. + + Given operation-specific seed, `op_seed`, this helper function returns two + seeds derived from graph-level and op-level seeds. Many random operations + internally use the two seeds to allow user to change the seed globally for a + graph, or for only specific operations. + + For details on how the graph-level seed interacts with op seeds, see + `tf.compat.v1.random.set_random_seed`. + + Args: + op_seed: integer. + + Returns: + A tuple of two integers that should be used for the local seed of this + operation. + """ + eager = context.executing_eagerly() + + if eager: + global_seed = context.global_seed() + else: + global_seed = ops.get_default_graph().seed + + if global_seed is not None: + if op_seed is None: + # pylint: disable=protected-access + if hasattr(ops.get_default_graph(), '_seed_used'): + ops.get_default_graph()._seed_used = True + if eager: + op_seed = context.internal_operation_seed() + else: + op_seed = _graph_to_seed_dict.setdefault(ops.get_default_graph(), 0) + _graph_to_seed_dict[ops.get_default_graph()] += 1 + + seeds = _truncate_seed(global_seed), _truncate_seed(op_seed) + else: + if op_seed is not None: + seeds = DEFAULT_GRAPH_SEED, _truncate_seed(op_seed) + else: + seeds = None, None + + if seeds == (None, None) and config.is_op_determinism_enabled(): + raise RuntimeError( # pylint: disable=g-doc-exception + 'Random ops require a seed to be set when determinism is enabled. ' + 'Please set a seed before running the op, e.g. by calling ' + 'tf.random.set_seed(1).') + + # Avoid (0, 0) as the C++ ops interpret it as nondeterminism, which would + # be unexpected since Python docs say nondeterminism is (None, None). + if seeds == (0, 0): + return (0, _MAXINT32) + return seeds + + +@tf_export(v1=['random.set_random_seed', 'set_random_seed']) +def set_random_seed(seed): + """Sets the graph-level random seed for the default graph. + + Operations that rely on a random seed actually derive it from two seeds: + the graph-level and operation-level seeds. This sets the graph-level seed. + + Its interactions with operation-level seeds is as follows: + + 1. If neither the graph-level nor the operation seed is set: + A random seed is used for this op. + 2. If the graph-level seed is set, but the operation seed is not: + The system deterministically picks an operation seed in conjunction with + the graph-level seed so that it gets a unique random sequence. Within the + same version of tensorflow and user code, this sequence is deterministic. + However across different versions, this sequence might change. If the + code depends on particular seeds to work, specify both graph-level + and operation-level seeds explicitly. + 3. If the graph-level seed is not set, but the operation seed is set: + A default graph-level seed and the specified operation seed are used to + determine the random sequence. + 4. If both the graph-level and the operation seed are set: + Both seeds are used in conjunction to determine the random sequence. + + To illustrate the user-visible effects, consider these examples: + + To generate different sequences across sessions, set neither + graph-level nor op-level seeds: + + ```python + a = tf.random.uniform([1]) + b = tf.random.normal([1]) + + print("Session 1") + with tf.compat.v1.Session() as sess1: + print(sess1.run(a)) # generates 'A1' + print(sess1.run(a)) # generates 'A2' + print(sess1.run(b)) # generates 'B1' + print(sess1.run(b)) # generates 'B2' + + print("Session 2") + with tf.compat.v1.Session() as sess2: + print(sess2.run(a)) # generates 'A3' + print(sess2.run(a)) # generates 'A4' + print(sess2.run(b)) # generates 'B3' + print(sess2.run(b)) # generates 'B4' + ``` + + To generate the same repeatable sequence for an op across sessions, set the + seed for the op: + + ```python + a = tf.random.uniform([1], seed=1) + b = tf.random.normal([1]) + + # Repeatedly running this block with the same graph will generate the same + # sequence of values for 'a', but different sequences of values for 'b'. + print("Session 1") + with tf.compat.v1.Session() as sess1: + print(sess1.run(a)) # generates 'A1' + print(sess1.run(a)) # generates 'A2' + print(sess1.run(b)) # generates 'B1' + print(sess1.run(b)) # generates 'B2' + + print("Session 2") + with tf.compat.v1.Session() as sess2: + print(sess2.run(a)) # generates 'A1' + print(sess2.run(a)) # generates 'A2' + print(sess2.run(b)) # generates 'B3' + print(sess2.run(b)) # generates 'B4' + ``` + + To make the random sequences generated by all ops be repeatable across + sessions, set a graph-level seed: + + ```python + tf.compat.v1.random.set_random_seed(1234) + a = tf.random.uniform([1]) + b = tf.random.normal([1]) + + # Repeatedly running this block with the same graph will generate the same + # sequences of 'a' and 'b'. + print("Session 1") + with tf.compat.v1.Session() as sess1: + print(sess1.run(a)) # generates 'A1' + print(sess1.run(a)) # generates 'A2' + print(sess1.run(b)) # generates 'B1' + print(sess1.run(b)) # generates 'B2' + + print("Session 2") + with tf.compat.v1.Session() as sess2: + print(sess2.run(a)) # generates 'A1' + print(sess2.run(a)) # generates 'A2' + print(sess2.run(b)) # generates 'B1' + print(sess2.run(b)) # generates 'B2' + ``` + + @compatibility(TF2) + 'tf.compat.v1.set_random_seed' is compatible with eager mode. However, + in eager mode this API will set the global seed instead of the + graph-level seed of the default graph. In TF2 this API is changed to + [tf.random.set_seed] + (https://www.tensorflow.org/api_docs/python/tf/random/set_seed). + @end_compatibility + + Args: + seed: integer. + """ + if context.executing_eagerly(): + context.set_global_seed(seed) + else: + ops.get_default_graph().seed = seed + + +@tf_export('random.set_seed', v1=[]) +def set_seed(seed): + """Sets the global random seed. + + Operations that rely on a random seed actually derive it from two seeds: + the global and operation-level seeds. This sets the global seed. + + Its interactions with operation-level seeds is as follows: + + 1. If neither the global seed nor the operation seed is set: A randomly + picked seed is used for this op. + 2. If the global seed is set, but the operation seed is not: + The system deterministically picks an operation seed in conjunction with + the global seed so that it gets a unique random sequence. Within the + same version of tensorflow and user code, this sequence is deterministic. + However across different versions, this sequence might change. If the + code depends on particular seeds to work, specify both global + and operation-level seeds explicitly. + 3. If the operation seed is set, but the global seed is not set: + A default global seed and the specified operation seed are used to + determine the random sequence. + 4. If both the global and the operation seed are set: + Both seeds are used in conjunction to determine the random sequence. + + To illustrate the user-visible effects, consider these examples: + + If neither the global seed nor the operation seed is set, we get different + results for every call to the random op and every re-run of the program: + + ```python + print(tf.random.uniform([1])) # generates 'A1' + print(tf.random.uniform([1])) # generates 'A2' + ``` + + (now close the program and run it again) + + ```python + print(tf.random.uniform([1])) # generates 'A3' + print(tf.random.uniform([1])) # generates 'A4' + ``` + + If the global seed is set but the operation seed is not set, we get different + results for every call to the random op, but the same sequence for every + re-run of the program: + + ```python + tf.random.set_seed(1234) + print(tf.random.uniform([1])) # generates 'A1' + print(tf.random.uniform([1])) # generates 'A2' + ``` + + (now close the program and run it again) + + ```python + tf.random.set_seed(1234) + print(tf.random.uniform([1])) # generates 'A1' + print(tf.random.uniform([1])) # generates 'A2' + ``` + + The reason we get 'A2' instead 'A1' on the second call of `tf.random.uniform` + above is because the second call uses a different operation seed. + + Note that `tf.function` acts like a re-run of a program in this case. When + the global seed is set but operation seeds are not set, the sequence of random + numbers are the same for each `tf.function`. For example: + + ```python + tf.random.set_seed(1234) + + @tf.function + def f(): + a = tf.random.uniform([1]) + b = tf.random.uniform([1]) + return a, b + + @tf.function + def g(): + a = tf.random.uniform([1]) + b = tf.random.uniform([1]) + return a, b + + print(f()) # prints '(A1, A2)' + print(g()) # prints '(A1, A2)' + ``` + + If the operation seed is set, we get different results for every call to the + random op, but the same sequence for every re-run of the program: + + ```python + print(tf.random.uniform([1], seed=1)) # generates 'A1' + print(tf.random.uniform([1], seed=1)) # generates 'A2' + ``` + + (now close the program and run it again) + + ```python + print(tf.random.uniform([1], seed=1)) # generates 'A1' + print(tf.random.uniform([1], seed=1)) # generates 'A2' + ``` + + The reason we get 'A2' instead 'A1' on the second call of `tf.random.uniform` + above is because the same `tf.random.uniform` kernel (i.e. internal + representation) is used by TensorFlow for all calls of it with the same + arguments, and the kernel maintains an internal counter which is incremented + every time it is executed, generating different results. + + Calling `tf.random.set_seed` will reset any such counters: + + ```python + tf.random.set_seed(1234) + print(tf.random.uniform([1], seed=1)) # generates 'A1' + print(tf.random.uniform([1], seed=1)) # generates 'A2' + tf.random.set_seed(1234) + print(tf.random.uniform([1], seed=1)) # generates 'A1' + print(tf.random.uniform([1], seed=1)) # generates 'A2' + ``` + + When multiple identical random ops are wrapped in a `tf.function`, their + behaviors change because the ops no long share the same counter. For example: + + ```python + @tf.function + def foo(): + a = tf.random.uniform([1], seed=1) + b = tf.random.uniform([1], seed=1) + return a, b + print(foo()) # prints '(A1, A1)' + print(foo()) # prints '(A2, A2)' + + @tf.function + def bar(): + a = tf.random.uniform([1]) + b = tf.random.uniform([1]) + return a, b + print(bar()) # prints '(A1, A2)' + print(bar()) # prints '(A3, A4)' + ``` + + The second call of `foo` returns '(A2, A2)' instead of '(A1, A1)' because + `tf.random.uniform` maintains an internal counter. If you want `foo` to return + '(A1, A1)' every time, use the stateless random ops such as + `tf.random.stateless_uniform`. Also see `tf.random.experimental.Generator` for + a new set of stateful random ops that use external variables to manage their + states. + + Args: + seed: integer. + """ + set_random_seed(seed) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/registry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..43417434090eae610da641b8836358fbf9d8ac9f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/registry.py @@ -0,0 +1,96 @@ +# 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. +# ============================================================================== + +"""Registry mechanism for "registering" classes/functions for general use. + +This is typically used with a decorator that calls Register for adding +a class or function to a registry. +""" + +import traceback + +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import compat + + +# Registry mechanism below is based on mapreduce.python.mrpython.Register. +_LOCATION_TAG = "location" +_TYPE_TAG = "type" + + +class Registry(object): + """Provides a registry for saving objects.""" + + __slots__ = ["_name", "_registry"] + + def __init__(self, name): + """Creates a new registry.""" + self._name = name + self._registry = {} + + def register(self, candidate, name=None): + """Registers a Python object "candidate" for the given "name". + + Args: + candidate: The candidate object to add to the registry. + name: An optional string specifying the registry key for the candidate. + If None, candidate.__name__ will be used. + Raises: + KeyError: If same name is used twice. + """ + if not name: + name = candidate.__name__ + if name in self._registry: + frame = self._registry[name][_LOCATION_TAG] + raise KeyError( + "Registering two %s with name '%s'! " + "(Previous registration was in %s %s:%d)" % + (self._name, name, frame.name, frame.filename, frame.lineno)) + + logging.vlog(1, "Registering %s (%s) in %s.", name, candidate, self._name) + # stack trace is [this_function, Register(), user_function,...] + # so the user function is #2. + stack = traceback.extract_stack(limit=3) + stack_index = min(2, len(stack) - 1) + if stack_index >= 0: + location_tag = stack[stack_index] + else: + location_tag = ("UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN") + self._registry[name] = {_TYPE_TAG: candidate, _LOCATION_TAG: location_tag} + + def list(self): + """Lists registered items. + + Returns: + A list of names of registered objects. + """ + return self._registry.keys() + + def lookup(self, name): + """Looks up "name". + + Args: + name: a string specifying the registry key for the candidate. + Returns: + Registered object if found + Raises: + LookupError: if "name" has not been registered. + """ + name = compat.as_str(name) + if name in self._registry: + return self._registry[name][_TYPE_TAG] + else: + raise LookupError( + "%s registry has no entry for: %s" % (self._name, name)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/smart_cond.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/smart_cond.py new file mode 100644 index 0000000000000000000000000000000000000000..efaee2c1549111424af7c54d3efba21a005cdfed --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/smart_cond.py @@ -0,0 +1,122 @@ +# 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. +# ============================================================================== +"""smart_cond and related utilities.""" + +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_util +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_case +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.smart_cond.smart_cond", v1=[]) +def smart_cond(pred, true_fn=None, false_fn=None, name=None): + """Return either `true_fn()` if predicate `pred` is true else `false_fn()`. + + If `pred` is a bool or has a constant value, we return either `true_fn()` + or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both. + + Args: + pred: A scalar determining whether to return the result of `true_fn` or + `false_fn`. + true_fn: The callable to be performed if pred is true. + false_fn: The callable to be performed if pred is false. + name: Optional name prefix when using `tf.cond`. + + Returns: + Tensors returned by the call to either `true_fn` or `false_fn`. + + Raises: + TypeError: If `true_fn` or `false_fn` is not callable. + """ + if not callable(true_fn): + raise TypeError(f"Argument `true_fn` must be callable. Received {true_fn}") + if not callable(false_fn): + raise TypeError( + f"Argument `false_fn` must be callable. Received {false_fn}") + + pred_value = smart_constant_value(pred) + if pred_value is not None: + if pred_value: + return true_fn() + else: + return false_fn() + else: + return cond.cond(pred, true_fn=true_fn, false_fn=false_fn, + name=name) + + +def smart_constant_value(pred): + """Return the bool value for `pred`, or None if `pred` had a dynamic value. + + Args: + pred: A scalar, either a Python bool or tensor. + + Returns: + True or False if `pred` has a constant boolean value, None otherwise. + + Raises: + TypeError: If `pred` is not a Tensor or bool. + """ + if isinstance(pred, tensor.Tensor): + pred_value = tensor_util.constant_value(pred) + # TODO(skyewm): consider folding this into tensor_util.constant_value. + # pylint: disable=protected-access + if pred_value is None: + pred_value = tensor_util.try_evaluate_constant(pred) + # pylint: enable=protected-access + elif pred in {0, 1}: # Accept 1/0 as valid boolean values + pred_value = bool(pred) + elif isinstance(pred, bool): + pred_value = pred + else: + raise TypeError("Argument `pred` must be a Tensor, or a Python bool, or 1 " + f"or 0. Received: pred={pred} of type " + f"{type(pred).__name__}") + + return pred_value + + +def smart_case(pred_fn_pairs, default=None, exclusive=False, name="smart_case"): + """Like tf.case, except attempts to statically evaluate predicates. + + If any predicate in `pred_fn_pairs` is a bool or has a constant value, the + associated callable will be called or omitted depending on its value. + Otherwise this functions like tf.case. + + Args: + pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor and a + callable which returns a list of tensors. + default: Optional callable that returns a list of tensors. + exclusive: True iff at most one predicate is allowed to evaluate to `True`. + name: A name for this operation (optional). + + Returns: + The tensors returned by the first pair whose predicate evaluated to True, or + those returned by `default` if none does. + + Raises: + TypeError: If `pred_fn_pairs` is not a list/dictionary. + TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. + TypeError: If `fns[i]` is not callable for any i, or `default` is not + callable. + """ + return control_flow_case._case_helper( # pylint: disable=protected-access + smart_cond, + pred_fn_pairs, + default, + exclusive, + name, + allow_python_preds=True) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/sparse_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/sparse_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..0b870b54c9666223c33c460c3ed2630ed3abe9d8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/sparse_tensor.py @@ -0,0 +1,576 @@ +# 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. +# ============================================================================== +"""Sparse tensors.""" +# pylint: disable=g-bad-name +import collections + +import numpy as np + +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import +from tensorflow.python import tf2 +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import gen_sparse_ops +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import internal +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util.tf_export import tf_export + +# pylint: disable=protected-access +_eval_using_default_session = tensor._eval_using_default_session +_override_helper = tensor._override_helper +# pylint: enable=protected-access + + +@tf_export("sparse.SparseTensor", "SparseTensor") +class SparseTensor(internal.NativeObject, composite_tensor.CompositeTensor): + """Represents a sparse tensor. + + TensorFlow represents a sparse tensor as three separate dense tensors: + `indices`, `values`, and `dense_shape`. In Python, the three tensors are + collected into a `SparseTensor` class for ease of use. If you have separate + `indices`, `values`, and `dense_shape` tensors, wrap them in a `SparseTensor` + object before passing to the ops below. + + Concretely, the sparse tensor `SparseTensor(indices, values, dense_shape)` + comprises the following components, where `N` and `ndims` are the number + of values and number of dimensions in the `SparseTensor`, respectively: + + * `indices`: A 2-D int64 tensor of shape `[N, ndims]`, which specifies the + indices of the elements in the sparse tensor that contain nonzero values + (elements are zero-indexed). For example, `indices=[[1,3], [2,4]]` specifies + that the elements with indexes of [1,3] and [2,4] have nonzero values. + + * `values`: A 1-D tensor of any type and shape `[N]`, which supplies the + values for each element in `indices`. For example, given `indices=[[1,3], + [2,4]]`, the parameter `values=[18, 3.6]` specifies that element [1,3] of + the sparse tensor has a value of 18, and element [2,4] of the tensor has a + value of 3.6. + + * `dense_shape`: A 1-D int64 tensor of shape `[ndims]`, which specifies the + dense_shape of the sparse tensor. Takes a list indicating the number of + elements in each dimension. For example, `dense_shape=[3,6]` specifies a + two-dimensional 3x6 tensor, `dense_shape=[2,3,4]` specifies a + three-dimensional 2x3x4 tensor, and `dense_shape=[9]` specifies a + one-dimensional tensor with 9 elements. + + The corresponding dense tensor satisfies: + + ```python + dense.shape = dense_shape + dense[tuple(indices[i])] = values[i] + ``` + + By convention, `indices` should be sorted in row-major order (or equivalently + lexicographic order on the tuples `indices[i]`). This is not enforced when + `SparseTensor` objects are constructed, but most ops assume correct ordering. + If the ordering of sparse tensor `st` is wrong, a fixed version can be + obtained by calling `tf.sparse.reorder(st)`. + + Example: The sparse tensor + + ```python + SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]) + ``` + + represents the dense tensor + + ```python + [[1, 0, 0, 0] + [0, 0, 2, 0] + [0, 0, 0, 0]] + ``` + """ + + @classmethod + def from_value(cls, sparse_tensor_value): + if not is_sparse(sparse_tensor_value): + raise TypeError(f"Argument sparse_tensor_value={sparse_tensor_value} " + "is neither a SparseTensor nor SparseTensorValue.") + return SparseTensor( + indices=sparse_tensor_value.indices, + values=sparse_tensor_value.values, + dense_shape=sparse_tensor_value.dense_shape) + + def __init__(self, indices, values, dense_shape): + """Creates a `SparseTensor`. + + Args: + indices: A 2-D int64 tensor of shape `[N, ndims]`. + values: A 1-D tensor of any type and shape `[N]`. + dense_shape: A 1-D int64 tensor of shape `[ndims]`. + + Raises: + ValueError: When building an eager SparseTensor if `dense_shape` is + unknown or contains unknown elements (None or -1). + """ + with ops.name_scope(None, "SparseTensor", [indices, values, dense_shape]): + indices = ops.convert_to_tensor( + indices, name="indices", dtype=dtypes.int64) + # TODO(touts): Consider adding mutable_values() when 'values' + # is a VariableOp and updating users of SparseTensor. + values = ops.convert_to_tensor(values, name="values") + + dense_shape = ops.convert_to_tensor( + dense_shape, name="dense_shape", dtype=dtypes.int64) + dense_shape_default = tensor_util.constant_value_as_shape(dense_shape) + + self._indices = indices + self._values = values + self._dense_shape = dense_shape + self._dense_shape_default = dense_shape_default + + indices_shape = indices.shape.with_rank(2) + values_shape = values.shape.with_rank(1) + dense_shape_shape = dense_shape.shape.with_rank(1) + + # Assert number of rows in indices match the number of elements in values. + indices_shape.dims[0].assert_is_compatible_with(values_shape.dims[0]) + # Assert number of columns in indices matches the number of elements in + # dense_shape. + indices_shape.dims[1].assert_is_compatible_with(dense_shape_shape.dims[0]) + + def get_shape(self) -> tensor_shape.TensorShape: + """Get the `TensorShape` representing the shape of the dense tensor. + + Returns: + A `TensorShape` object. + """ + return self._dense_shape_default + + @property + def indices(self): + """The indices of non-zero values in the represented dense tensor. + + Returns: + A 2-D Tensor of int64 with dense_shape `[N, ndims]`, where `N` is the + number of non-zero values in the tensor, and `ndims` is the rank. + """ + return self._indices + + @property + def values(self): + """The non-zero values in the represented dense tensor. + + Returns: + A 1-D Tensor of any data type. + """ + return self._values + + def with_values(self, new_values): + """Returns a copy of `self` with `values` replaced by `new_values`. + + This method produces a new `SparseTensor` that has the same nonzero + `indices` and same `dense_shape`, but updated values. + + Args: + new_values: The values of the new `SparseTensor`. Needs to have the same + shape as the current `.values` `Tensor`. May have a different type than + the current `values`. + + Returns: + A `SparseTensor` with identical indices and shape but updated values. + + Example usage: + + >>> st = tf.sparse.from_dense([[1, 0, 2, 0], [3, 0, 0, 4]]) + >>> tf.sparse.to_dense(st.with_values([10, 20, 30, 40])) # 4 nonzero values + + + """ + return SparseTensor(self._indices, new_values, self._dense_shape) + + @property + def op(self) -> ops.Operation: + """The `Operation` that produces `values` as an output.""" + return self._values.op + + @property + def dtype(self): + """The `DType` of elements in this tensor.""" + return self._values.dtype + + @property + def dense_shape(self): + """A 1-D Tensor of int64 representing the shape of the dense tensor.""" + return self._dense_shape + + @property + def shape(self): + """Get the `TensorShape` representing the shape of the dense tensor. + + Returns: + A `TensorShape` object. + """ + return self._dense_shape_default + + def set_shape(self, shape): + """Updates the `TensorShape` representing the shape of the dense tensor. + + With eager execution this operates as a shape assertion. + Here the shapes match: + + >>> st = tf.SparseTensor( + ... indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]) + >>> st.set_shape([3, 4]) + + Passing a `None` in the new shape allows any value for that axis: + + >>> st.set_shape([3, None]) + + An error is raised if an incompatible shape is passed. + + >>> st.set_shape([1, 4]) + Traceback (most recent call last): + ... + ValueError: Tensor's shape (3, 4) is not compatible with supplied + shape [1, 4] + + When executing in a `tf.function`, or building a model using + `tf.keras.Input`, `SparseTensor.set_shape` will *merge* the given `shape` + with the current shape of this tensor, and set the tensor's shape to the + merged value (see `tf.TensorShape.merge_with` for details): + + >>> st = tf.keras.Input(shape=[None, None, 3], sparse=True) + >>> print(st.shape) + (None, None, None, 3) + + Dimensions set to `None` are not updated: + + >>> st.set_shape([None, 224, 224, None]) + >>> print(st.shape) + (None, 224, 224, 3) + + The main use case for this is to provide additional shape information + that cannot be inferred from the graph alone. + + Caution: `set_shape` ensures that the applied shape is compatible with + the existing shape, but it does not check at runtime. Setting + incorrect shapes can result in inconsistencies between the + statically-known graph and the runtime value of tensors. + + Args: + shape: A `TensorShape` representing the shape of this tensor, a + `TensorShapeProto`, a list, a tuple, or None. + + Raises: + ValueError: If `shape` is not compatible with the current shape of + this tensor. + """ + if not isinstance(shape, tensor_shape.TensorShape): + shape = tensor_shape.TensorShape(shape) + self._dense_shape_default = self._dense_shape_default.merge_with(shape) + + @property + def graph(self): + """The `Graph` that contains the index, value, and dense_shape tensors.""" + return self._indices.graph + + def __repr__(self): + return "SparseTensor(indices=%s, values=%s, dense_shape=%s)" % ( + self._indices, self._values, self._dense_shape) + + def eval(self, feed_dict=None, session=None): + """Evaluates this sparse tensor in a `Session`. + + Calling this method will execute all preceding operations that + produce the inputs needed for the operation that produces this + tensor. + + *N.B.* Before invoking `SparseTensor.eval()`, its graph must have been + launched in a session, and either a default session must be + available, or `session` must be specified explicitly. + + Args: + feed_dict: A dictionary that maps `Tensor` objects to feed values. See + `tf.Session.run` for a description of the valid feed values. + session: (Optional.) The `Session` to be used to evaluate this sparse + tensor. If none, the default session will be used. + + Returns: + A `SparseTensorValue` object. + """ + indices, values, dense_shape = _eval_using_default_session( + [self.indices, self.values, self.dense_shape], feed_dict, self.graph, + session) + return SparseTensorValue(indices, values, dense_shape) + + @staticmethod + def _override_operator(operator, func): + _override_helper(SparseTensor, operator, func) + + @property + def _type_spec(self): + return SparseTensorSpec(self.shape, self.dtype) + + def _shape_invariant_to_type_spec(self, shape): + # From the tf.while_loop docs: "If a loop variable is a SparseTensor, the + # shape invariant must be TensorShape([r]) where r is the rank of the dense + # tensor represented by the sparse tensor. It means the shapes of the three + # tensors of the SparseTensor are ([None], [None, r], [r]). NOTE: The shape + # invariant here is the shape of the SparseTensor.dense_shape property. It + # must be the shape of a vector. + if shape.ndims is not None and shape.ndims != 1: + raise ValueError(f"Expected a shape with 1 dimension. Obtained: {shape} " + f"which has {shape.ndims} dimensions.") + rank = tensor_shape.dimension_value(shape[0]) + return SparseTensorSpec(tensor_shape.unknown_shape(rank), self.dtype) + + def consumers(self): + return self._consumers() + + def _numpy(self): + """Returns a numpy `array` with the values for this `SparseTensor`. + + Requires that this `SparseTensor` was constructed in eager execution mode. + """ + if not self._is_eager(): + raise ValueError("SparseTensor.numpy() is only supported in eager mode.") + arr = np.zeros(self.dense_shape, dtype=self.dtype.as_numpy_dtype()) + for i, v in zip(self.indices, self.values): + arr[tuple(i)] = v + + return arr + + def _is_eager(self): + """Returns True if this `SparseTensor` was constructed in eager execution. + + Requires that each individual component of `SparseTensor` + (`indices`, `values` and `dense_shape`) is an instance of `EagerTensor`. + """ + + return all( + isinstance(t, ops.EagerTensor) + for t in (self.indices, self.values, self.dense_shape)) + + +SparseTensorValue = collections.namedtuple("SparseTensorValue", + ["indices", "values", "dense_shape"]) +tf_export(v1=["SparseTensorValue"])(SparseTensorValue) +_pywrap_utils.RegisterType("SparseTensorValue", SparseTensorValue) + + +@tf_export("SparseTensorSpec") +@type_spec_registry.register("tf.SparseTensorSpec") +class SparseTensorSpec(type_spec.BatchableTypeSpec): + """Type specification for a `tf.sparse.SparseTensor`.""" + + __slots__ = ["_shape", "_dtype"] + + value_type = property(lambda self: SparseTensor) + + def __init__(self, shape=None, dtype=dtypes.float32): + """Constructs a type specification for a `tf.sparse.SparseTensor`. + + Args: + shape: The dense shape of the `SparseTensor`, or `None` to allow any dense + shape. + dtype: `tf.DType` of values in the `SparseTensor`. + """ + self._shape = tensor_shape.as_shape(shape) + self._dtype = dtypes.as_dtype(dtype) + + def _serialize(self): + return (self._shape, self._dtype) + + @property + def dtype(self): + """The `tf.dtypes.DType` specified by this type for the SparseTensor.""" + return self._dtype + + @property + def shape(self): + """The `tf.TensorShape` specified by this type for the SparseTensor.""" + return self._shape + + @property + def _component_specs(self): + rank = self._shape.ndims + num_values = None + return [ + tensor_spec.TensorSpec([num_values, rank], dtypes.int64), + tensor_spec.TensorSpec([num_values], self._dtype), + tensor_spec.TensorSpec([rank], dtypes.int64)] + + def _to_components(self, value): + if isinstance(value, SparseTensorValue): + value = SparseTensor.from_value(value) + return [value.indices, value.values, value.dense_shape] + + def _from_components(self, tensor_list): + if (all(isinstance(t, np.ndarray) for t in tensor_list) and + not tf2.enabled()): + return SparseTensorValue(*tensor_list) + else: + result = SparseTensor(*tensor_list) + # Augment the static dense shape with the shape carried by the spec. + result._dense_shape_default = result._dense_shape_default.merge_with( # pylint: disable=protected-access + self._shape) + return result + + # The SparseTensorSpec tensor_list encoding uses (de)serialize_sparse ops + # to (un)box the component tensors in a way that allows for batching & + # unbatching. + @property + def _flat_tensor_specs(self): + # NOTE(mrry): The default flat shape of a boxed `SparseTensor` is `(3,)`, + # but a `SparseTensorSpec` can also represent a batch of boxed + # `SparseTensor` objects with shape `(..., 3)` (and batches of batches, + # etc.), so the flat shape must be unknown. + return [tensor_spec.TensorSpec(None, dtypes.variant)] + + def _to_tensor_list(self, value): + value = SparseTensor.from_value(value) + return [gen_sparse_ops.serialize_sparse( + value.indices, value.values, value.dense_shape, + out_type=dtypes.variant)] + + def _to_batched_tensor_list(self, value): + dense_shape = tensor_util.constant_value_as_shape(value.dense_shape) + if self._shape.merge_with(dense_shape).ndims == 0: + raise ValueError( + "Unbatching a sparse tensor is only supported for rank >= 1. " + f"Obtained input: {value}.") + return [gen_sparse_ops.serialize_many_sparse( + value.indices, value.values, value.dense_shape, + out_type=dtypes.variant)] + + def _from_compatible_tensor_list(self, tensor_list): + tensor_list = gen_sparse_ops.deserialize_sparse(tensor_list[0], self._dtype) + indices, values, dense_shape = tensor_list + rank = self._shape.ndims + indices.set_shape([None, rank]) + # We restore the dense_shape from the SparseTypeSpec. This is necessary + # for shape inference when using placeholder SparseTensors in function + # tracing. + if self._shape.is_fully_defined(): + dense_shape = ops.convert_to_tensor( + self._shape, dtype=dtypes.int64, name="shape") + elif (self._shape.rank is not None and + any(dim.value is not None for dim in self._shape.dims)): + pieces = array_ops_stack.unstack(dense_shape, num=self._shape.rank) + for i, dim in enumerate(self._shape.dims): + if dim.value is not None: + pieces[i] = constant_op.constant(dim.value, dense_shape.dtype) + dense_shape = array_ops_stack.stack(pieces) + else: + dense_shape.set_shape([rank]) + + return SparseTensor(indices, values, dense_shape) + + def _batch(self, batch_size): + return SparseTensorSpec( + tensor_shape.TensorShape([batch_size]).concatenate(self._shape), + self._dtype) + + def _unbatch(self): + if self._shape.ndims == 0: + raise ValueError("Unbatching a tensor is only supported for rank >= 1") + return SparseTensorSpec(self._shape[1:], self._dtype) + + def _to_legacy_output_types(self): + return self._dtype + + def _to_legacy_output_shapes(self): + return self._shape + + def _to_legacy_output_classes(self): + return SparseTensor + + @classmethod + def from_value(cls, value): + if isinstance(value, SparseTensor): + return cls(value.shape, value.dtype) + if isinstance(value, SparseTensorValue): + if isinstance(value.values, np.ndarray): + return cls(value.dense_shape, value.values.dtype) + else: + return cls.from_value(SparseTensor.from_value(value)) + else: + raise TypeError("Expected SparseTensor or SparseTensorValue. Received: " + f"{value} of type {type(value).__name__}.") + + +nested_structure_coder.register_codec( + nested_structure_coder.BuiltInTypeSpecCodec( + SparseTensorSpec, struct_pb2.TypeSpecProto.SPARSE_TENSOR_SPEC + ) +) + + +# TODO(b/133606651) Delete the SparseTensor registration when CompositeTensor +# is updated to define a _type_spec field (since registration will be +# automatic). Do *not* delete the SparseTensorValue registration. +type_spec.register_type_spec_from_value_converter( + SparseTensor, SparseTensorSpec.from_value) +type_spec.register_type_spec_from_value_converter( + SparseTensorValue, SparseTensorSpec.from_value) + + +@tf_export(v1=["convert_to_tensor_or_sparse_tensor"]) +def convert_to_tensor_or_sparse_tensor(value, dtype=None, name=None): + """Converts value to a `SparseTensor` or `Tensor`. + + Args: + value: A `SparseTensor`, `SparseTensorValue`, or an object whose type has a + registered `Tensor` conversion function. + dtype: Optional element type for the returned tensor. If missing, the type + is inferred from the type of `value`. + name: Optional name to use if a new `Tensor` is created. + + Returns: + A `SparseTensor` or `Tensor` based on `value`. + + Raises: + RuntimeError: If result type is incompatible with `dtype`. + """ + if dtype is not None: + dtype = dtypes.as_dtype(dtype) + if isinstance(value, SparseTensorValue): + value = SparseTensor.from_value(value) + if isinstance(value, SparseTensor): + if dtype and not dtype.is_compatible_with(value.dtype): + raise RuntimeError(f"Sparse dtype mismatch. Requested: {dtype.name}, " + f" Actual: {value.dtype.name}") + return value + return ops.convert_to_tensor(value, dtype=dtype, name=name) + + +def is_sparse(x): + """Check whether `x` is sparse. + + Check whether an object is a `tf.sparse.SparseTensor` or + `tf.compat.v1.SparseTensorValue`. + + Args: + x: A python object to check. + + Returns: + `True` iff `x` is a `tf.sparse.SparseTensor` or + `tf.compat.v1.SparseTensorValue`. + """ + return isinstance(x, (SparseTensor, SparseTensorValue)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/stack.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/stack.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1e8fbd1311fd67a351f85e1d2ee7bb57a61c22 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/stack.py @@ -0,0 +1,133 @@ +# 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. +# ============================================================================== +"""Classes used to handle thread-local stacks.""" + +import threading + +from tensorflow.python.util import tf_contextlib +from tensorflow.python.util.tf_export import tf_export + + +class DefaultStack(threading.local): + """A thread-local stack of objects for providing implicit defaults.""" + + def __init__(self): + super().__init__() + self._enforce_nesting = True + self.stack = [] + + def get_default(self): + return self.stack[-1] if self.stack else None + + def reset(self): + self.stack = [] + + def is_cleared(self): + return not self.stack + + @property + def enforce_nesting(self): + return self._enforce_nesting + + @enforce_nesting.setter + def enforce_nesting(self, value): + self._enforce_nesting = value + + @tf_contextlib.contextmanager + def get_controller(self, default): + """A context manager for manipulating a default stack.""" + self.stack.append(default) + try: + yield default + finally: + # stack may be empty if reset() was called + if self.stack: + if self._enforce_nesting: + if self.stack[-1] is not default: + raise AssertionError( + "Nesting violated for default stack of %s objects" % + type(default)) + self.stack.pop() + else: + self.stack.remove(default) + + +_default_session_stack = DefaultStack() + + +def default_session(session): + """Python "with" handler for defining a default session. + + This function provides a means of registering a session for handling + Tensor.eval() and Operation.run() calls. It is primarily intended for use + by session.Session, but can be used with any object that implements + the Session.run() interface. + + Use with the "with" keyword to specify that Tensor.eval() and Operation.run() + invocations within the scope of a block should be executed by a particular + session. + + The default session applies to the current thread only, so it is always + possible to inspect the call stack and determine the scope of a default + session. If you create a new thread, and wish to use the default session + in that thread, you must explicitly add a "with ops.default_session(sess):" + block in that thread's function. + + Example: + The following code examples are equivalent: + + # 1. Using the Session object directly: + sess = ... + c = tf.constant(5.0) + sess.run(c) + + # 2. Using default_session(): + sess = ... + with ops.default_session(sess): + c = tf.constant(5.0) + result = c.eval() + + # 3. Overriding default_session(): + sess = ... + with ops.default_session(sess): + c = tf.constant(5.0) + with ops.default_session(...): + c.eval(session=sess) + + Args: + session: The session to be installed as the default session. + + Returns: + A context manager for the default session. + """ + return _default_session_stack.get_controller(session) + + +@tf_export(v1=["get_default_session"]) +def get_default_session(): + """Returns the default session for the current thread. + + The returned `Session` will be the innermost session on which a + `Session` or `Session.as_default()` context has been entered. + + NOTE: The default session is a property of the current thread. If you + create a new thread, and wish to use the default session in that + thread, you must explicitly add a `with sess.as_default():` in that + thread's function. + + Returns: + The default `Session` being used in the current thread. + """ + return _default_session_stack.get_default() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/strict_mode.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/strict_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..244e9de8ad0f9e455e8a82114077b2987554ada3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/strict_mode.py @@ -0,0 +1,29 @@ +# 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. +# ============================================================================== +"""Python strict deprecation mode enabler.""" + +from tensorflow.python.util.tf_export import tf_export + +STRICT_MODE = False + + +@tf_export("experimental.enable_strict_mode") +def enable_strict_mode(): + """If called, enables strict mode for all behaviors. + + Used to switch all deprecation warnings to raise errors instead. + """ + global STRICT_MODE + STRICT_MODE = True diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/subscribe.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/subscribe.py new file mode 100644 index 0000000000000000000000000000000000000000..3e48388542930b04c676b1a91aa95ef5d290e62e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/subscribe.py @@ -0,0 +1,354 @@ +# 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. +# ============================================================================== +"""Subscribe function.""" + +import contextlib +import re + +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging + + +def _recursive_apply(tensors, apply_fn): + """Helper method to recursively apply a function to structure of tensors. + + The structure of the tensors should take the form similar to fetches in + `tf.compat.v1.Session` and includes single `Tensor`, `list`, nested `list`, + `tuple`, + `namedtuple`, or `dict`. + + Args: + tensors: Single `Tensor`, `list`, nested `list, `tuple`, `namedtuple`, or + `dict`. + apply_fn: Function to apply to each `Tensor` and should return a `Tensor`. + + Returns: + Returns the modified tensors with the same structure. + Raises: + `TypeError` if undefined type in the tensors structure. + """ + tensors_type = type(tensors) + if isinstance(tensors, tensor_lib.Tensor): + return apply_fn(tensors) + elif isinstance(tensors, variables.Variable): + return apply_fn(tensors.value()) + elif isinstance(tensors, (list, tuple)): + tensors = [_recursive_apply(t, apply_fn) for t in tensors] + if tensors_type is list: + return list(tensors) + elif tensors_type is tuple: + return tuple(tensors) + return tensors_type(*tensors) # collections.namedtuple + elif tensors_type is dict: + return dict((k, _recursive_apply(v, apply_fn)) for k, v in tensors.items()) + else: + raise TypeError(f'_recursive_apply argument {tensors!r} has invalid type ' + f'{tensors_type!r}') + + +class _ControlOutputCache(object): + """Helper class to manage calculating and caching control_outputs in graph.""" + + __slots__ = ['cache'] + + def __init__(self): + self.cache = {} + + def calc_control_outputs(self, graph): + """Returns the map of control_outputs for a given graph. + + Args: + graph: The graph to parse. + + Returns: + A map of the control outputs. + """ + control_outputs = {} + for op in graph.get_operations(): + for control_input in op.control_inputs: + if control_input not in control_outputs: + control_outputs[control_input] = set() + control_outputs[control_input].add(op) + return control_outputs + + def get_control_outputs(self, op): + """Return the control outputs for a given op. + + Args: + op: The op to fetch control outputs for. + + Returns: + Iterable of control output ops. + """ + if op.graph not in self.cache: + control_outputs = self.calc_control_outputs(op.graph) + self.cache[op.graph] = control_outputs + else: + control_outputs = self.cache[op.graph] + return control_outputs.get(op, []) + + +def _subscribe_new(tensor, side_effects, control_cache): + """Helper method that subscribes a single tensor to a list of side_effects. + + Args: + tensor: `tf.Tensor` + side_effects: List of side_effect functions see subscribe for details. + control_cache: `_ControlOutputCache` helper to get control_outputs faster. + + Returns: + The modified replacement to the passed in tensor which triggers the side + effects. + """ + update_input = [] + for consumer_op in list(tensor.consumers()): # explicit copy + update_input.append((consumer_op, list(consumer_op.inputs).index(tensor))) + + update_control_input = control_cache.get_control_outputs(tensor.op) + + # Trailing slash on name scope to replace the scope. + name_scope = tensor.op.name + '/subscription/' + with ops.name_scope(name_scope): + outs = [] + for s in side_effects: + outs += s(tensor) + + with ops.control_dependencies(outs): + out = array_ops.identity(tensor) + + for consumer_op, index in update_input: + consumer_op._update_input(index, out) # pylint: disable=protected-access + + for consumer_op in update_control_input: + # If an op has more than one output and two or more of its output tensors + # are subscribed at the same time, we remove the control dependency from + # the original op only once and we add the dependencies to all the + # new identities. + new_control_inputs = consumer_op.control_inputs + if tensor.op in new_control_inputs: + new_control_inputs.remove(tensor.op) + new_control_inputs.append(out.op) + # pylint: disable=protected-access + consumer_op._remove_all_control_inputs() + consumer_op._add_control_inputs(new_control_inputs) + # pylint: enable=protected-access + return out + + +def _subscribe_extend(tensor, side_effects): + """Helper method to extend the list of side_effects for a subscribed tensor. + + Args: + tensor: A `tf.Tensor` as returned by subscribe(). + side_effects: List of side_effect functions, see subscribe for details. + + Returns: + The given subscribed tensor (for API consistency). + """ + assert len(tensor.op.inputs) == 1, 'Op {} must only have one input'.format( + tensor.op.name) + source_tensor = tensor.op.inputs[0] + + # Build the side effect graphs and add their outputs to the list of control + # dependencies for the subscribed tensor. + outs = [] + name_scope = source_tensor.op.name + '/subscription/' + with ops.name_scope(name_scope): + for s in side_effects: + outs += s(source_tensor) + + out_ops = [ + out.op if isinstance(out, tensor_lib.Tensor) else out for out in outs + ] + tensor.op._add_control_inputs(out_ops) # pylint: disable=protected-access + + return tensor + + +def _is_subscribed_identity(tensor): + """Checks if the given tensor is an identity op returned by `subscribe()`. + + Args: + tensor: A `tf.Tensor` to check. + + Returns: + True if the given tensor matches the criteria for subscription identities: + its op type is `Identity`, its name matches the name of its input and + conforms to the convention for subscribed nodes. + False otherwise. + """ + # Subscribed tensor are assumed to be identity ops. + if tensor.op.type != 'Identity': + return False + + # Check that the tensor name matches the convention in place for identity ops + # created by subscribe(). + match = re.match(r'(?P^.*?)/subscription/Identity[^/]+', + tensor.name) + if match is None or len(match.groups()) != 1: + return False + prefix_name = match.group('prefix_name') + + # Get a reference to the source tensor and check that it has a matching name. + assert len(tensor.op.inputs) == 1, 'Op {} must only have one input'.format( + tensor.op.name) + source_tensor = tensor.op.inputs[0] + if prefix_name != source_tensor.op.name: + return False + + return True + + +def _subscribe(tensor, side_effects, control_cache): + """Helper method that subscribes a single tensor to a list of side_effects. + + This method will check if the given tensor has already been subscribed or if + it's a tensor returned by a previous call to `subscribe()` and, if so, will + reuse the existing identity op, appending the given side effects to the list + of existing ones. + + Args: + tensor: The `tf.Tensor` to be subscribed. + side_effects: List of side_effect functions, see subscribe for details. + control_cache: `_ControlOutputCache` helper to get control_outputs faster. + + Returns: + The modified replacement to the passed in tensor which triggers the side + effects or the given tensor, if it was already been subscribed. + """ + # Check if the given tensor has a numpy compatible type (see dtypes.py). + # If not, we cannot subscribe it, so we just return the original tensor. + if not tensor.dtype.is_numpy_compatible: + logging.debug(('Tensor {} has an un-supported {} type and cannot be ' + 'subscribed.').format(tensor.name, tensor.dtype)) + return tensor + + if _is_subscribed_identity(tensor): + return _subscribe_extend(tensor, side_effects) + + # Check if the given tensor has already been subscribed by inspecting its + # outputs. + name_scope = tensor.op.name + '/subscription/Identity' + consumers = tensor.consumers() + matching_ops = [op for op in consumers if op.name.startswith(name_scope)] + assert len(matching_ops) <= 1, ('Op {} must only have one subscription ' + 'op connected to it').format(tensor.op.name) + if len(matching_ops) == 1: + candidate_tensor = matching_ops[0].outputs[0] + if _is_subscribed_identity(candidate_tensor): + return _subscribe_extend(candidate_tensor, side_effects) + + return _subscribe_new(tensor, side_effects, control_cache) + + +@contextlib.contextmanager +def _preserve_control_flow_context(tensor): + """Preserve the control flow context for the given tensor. + + Sets the graph context to the tensor's context so that side effect ops are + added under the same context. + + This is needed when subscribing to tensors defined within a conditional + block or a while loop. In these cases we need that the side-effect ops + are created within the same control flow context as that of the tensor + they are attached to. + + Args: + tensor: tensor whose context should be preserved. + + Yields: + None + """ + + # pylint: disable=protected-access + context = tensor.op._get_control_flow_context() + # pylint: enable=protected-access + if context: + context.Enter() + try: + yield + finally: + if context: + context.Exit() + + +def _scoped_subscribe(tensor, side_effects, control_cache): + """Helper method that subscribes a single tensor to a list of side_effects. + + This is a thin wrapper around `_subscribe` and ensures that the side effect + ops are added within the same device and control flow context of the + subscribed tensor. + + Args: + tensor: The `tf.Tensor` to be subscribed. + side_effects: List of side_effect functions, see subscribe for details. + control_cache: `_ControlOutputCache` helper to get control_outputs faster. + + Returns: + The modified replacement to the passed in tensor which triggers the side + effects or the given tensor, if it was already been subscribed. + """ + + with ops.device(tensor.device): + with _preserve_control_flow_context(tensor): + return _subscribe(tensor, side_effects, control_cache) + + +def subscribe(tensors, side_effects): + """Subscribe to a tensor. + + This method will attach side effect graphs to a given set + of tensors. Set of tensors follows from session.run and supports + single `Tensor`, `list`, nested `list`, `tuple`, `namedtuple`, or `dict`. It + returns the tensors in the same passed in structure, but as clones with + side effects applied. The supplied side effect graphs are specified + as a constructor function which takes the target tensor and + constructs a side effect graph and returns a list of ops that should + be control dependencies on fetching the tensor. It will append + 'subscription' to the name scope of the tensor for every node in + the side effect graph. These control dependencies are what trigger + the side effects. Subscribe will construct the additions to your + graph and return the created identity tensor downstream of the control + dependencies. Use these tensors as you would normally in the rest of + your tensorflow code. If a given tensor has already been subscribed or a + tensor returned by a call to subscribe is passed, the previously created + identity tensor will be reused and the side effect graphs will be added to + the existing ones. + + Args: + tensors: `Tensor` or set of tensors to subscribe to. Set of tensors format + follows from `Session.run` and supports single `Tensor`, `list`, nested + `list`, `tuple`, `namedtuple`, or `dict`. + side_effects: Function(s) that takes a `Tensor`, construct a subgraph, and + return a nonempty list of control dependencies. This can be a single + function or list of functions. + + Returns: + Subscribed tensors, which are identity copies of the passed in tensors + in the same passed in structure, but the graph has been modified + such that these are downstream of the control dependencies for + the side effect graphs. Use these functionally equivalent tensors + instead of the passed in tensors for further construction or running. + """ + if not hasattr(side_effects, '__iter__'): + side_effects = [side_effects] + + control_outputs = _ControlOutputCache() + result = _recursive_apply( + tensors, lambda t: _scoped_subscribe(t, side_effects, control_outputs)) + return result diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa83194866e8d8e43f2fe92f6d9b8fea65dcbee --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor.py @@ -0,0 +1,1465 @@ +# 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. +# ============================================================================== +"""Tensor and TensorSpec classes.""" + +from typing import Optional, Type + +import numpy as np + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.function import trace_type +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python import tf2 +from tensorflow.python.eager import context +from tensorflow.python.eager import monitoring +from tensorflow.python.eager import record +from tensorflow.python.framework import common_shapes +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import op_callbacks +from tensorflow.python.framework import stack +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import type_spec +from tensorflow.python.framework import type_spec_registry +from tensorflow.python.ops import handle_data_util +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import core as core_tf_types +from tensorflow.python.types import internal +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import object_identity +from tensorflow.python.util.tf_export import tf_export + + +_tensor_equality_api_usage_gauge = monitoring.BoolGauge( + "/tensorflow/api/enable_tensor_equality", + "Whether ops.enable_tensor_equality() is called.") + + +def _override_helper(clazz_object, operator, func): + """Overrides (string) operator on Tensors to call func. + + Args: + clazz_object: the class to override for; either Tensor or SparseTensor. + operator: the string name of the operator to override. + func: the function that replaces the overridden operator. + + Raises: + ValueError: If operator is not allowed to be overwritten. + """ + if operator not in Tensor.OVERLOADABLE_OPERATORS: + raise ValueError(f"Overriding {operator} is disallowed. " + f"Allowed operators are {Tensor.OVERLOADABLE_OPERATORS}.") + setattr(clazz_object, operator, func) + + +def _eval_using_default_session(tensors, feed_dict, graph, session=None): + """Uses the default session to evaluate one or more tensors. + + Args: + tensors: A single Tensor, or a list of Tensor objects. + feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists, + numpy ndarrays, TensorProtos, or strings. + graph: The graph in which the tensors are defined. + session: (Optional) A different session to use to evaluate "tensors". + + Returns: + Either a single numpy ndarray if "tensors" is a single tensor; or a list + of numpy ndarrays that each correspond to the respective element in + "tensors". + + Raises: + ValueError: If no default session is available; the default session + does not have "graph" as its graph; or if "session" is specified, + and it does not have "graph" as its graph. + """ + if session is None: + session = stack.get_default_session() + if session is None: + raise ValueError("Cannot evaluate tensor using `eval()`: No default " + "session is registered. Use `with " + "sess.as_default()` or pass an explicit session to " + "`eval(session=sess)`") + if session.graph is not graph: + raise ValueError("Cannot use the default session to evaluate tensor: " + "the tensor's graph is different from the session's " + "graph. Pass an explicit session to " + "`eval(session=sess)`.") + else: + if session.graph is not graph: + raise ValueError("Cannot use the given session to evaluate tensor: " + "the tensor's graph is different from the session's " + "graph.") + return session.run(tensors, feed_dict) + + +def _add_error_prefix(msg, *, name=None): + return msg if name is None else f"{name}: {msg}" + + +class _TensorIterator(object): + """Iterates over the leading dim of a Tensor. Performs no error checks.""" + + __slots__ = ["_tensor", "_index", "_limit"] + + def __init__(self, tensor, dim0): + self._tensor = tensor + self._index = 0 + self._limit = dim0 + + def __iter__(self): + return self + + def __next__(self): + if self._index == self._limit: + raise StopIteration + result = self._tensor[self._index] + self._index += 1 + return result + + next = __next__ # python2.x compatibility. + + +@tf_export("Tensor", "experimental.numpy.ndarray", v1=["Tensor"]) +class Tensor(internal.NativeObject, core_tf_types.Symbol): + """A `tf.Tensor` represents a multidimensional array of elements. + + All elements are of a single known data type. + + When writing a TensorFlow program, the main object that is + manipulated and passed around is the `tf.Tensor`. + + A `tf.Tensor` has the following properties: + + * a single data type (float32, int32, or string, for example) + * a shape + + TensorFlow supports eager execution and graph execution. In eager + execution, operations are evaluated immediately. In graph + execution, a computational graph is constructed for later + evaluation. + + TensorFlow defaults to eager execution. In the example below, the + matrix multiplication results are calculated immediately. + + >>> # Compute some values using a Tensor + >>> c = tf.constant([[1.0, 2.0], [3.0, 4.0]]) + >>> d = tf.constant([[1.0, 1.0], [0.0, 1.0]]) + >>> e = tf.matmul(c, d) + >>> print(e) + tf.Tensor( + [[1. 3.] + [3. 7.]], shape=(2, 2), dtype=float32) + + Note that during eager execution, you may discover your `Tensors` are actually + of type `EagerTensor`. This is an internal detail, but it does give you + access to a useful function, `numpy`: + + >>> type(e) + + >>> print(e.numpy()) + [[1. 3.] + [3. 7.]] + + In TensorFlow, `tf.function`s are a common way to define graph execution. + + A Tensor's shape (that is, the rank of the Tensor and the size of + each dimension) may not always be fully known. In `tf.function` + definitions, the shape may only be partially known. + + Most operations produce tensors of fully-known shapes if the shapes of their + inputs are also fully known, but in some cases it's only possible to find the + shape of a tensor at execution time. + + A number of specialized tensors are available: see `tf.Variable`, + `tf.constant`, `tf.placeholder`, `tf.sparse.SparseTensor`, and + `tf.RaggedTensor`. + + Caution: when constructing a tensor from a numpy array or pandas dataframe + the underlying buffer may be re-used: + + ```python + a = np.array([1, 2, 3]) + b = tf.constant(a) + a[0] = 4 + print(b) # tf.Tensor([4 2 3], shape=(3,), dtype=int64) + ``` + + Note: this is an implementation detail that is subject to change and users + should not rely on this behaviour. + + For more on Tensors, see the [guide](https://tensorflow.org/guide/tensor). + """ + # List of Python operators that we allow to override. + OVERLOADABLE_OPERATORS = { + # Binary. + "__add__", + "__radd__", + "__sub__", + "__rsub__", + "__mul__", + "__rmul__", + "__div__", + "__rdiv__", + "__truediv__", + "__rtruediv__", + "__floordiv__", + "__rfloordiv__", + "__mod__", + "__rmod__", + "__lt__", + "__le__", + "__gt__", + "__ge__", + "__ne__", + "__eq__", + "__and__", + "__rand__", + "__or__", + "__ror__", + "__xor__", + "__rxor__", + "__getitem__", + "__pow__", + "__rpow__", + # Unary. + "__invert__", + "__neg__", + "__abs__", + "__matmul__", + "__rmatmul__" + } + + # Whether to allow hashing or numpy-style equality + _USE_EQUALITY = tf2.enabled() + + def __getattr__(self, name): + if name in {"T", "astype", "ravel", "transpose", "reshape", "clip", "size", + "tolist", "data"}: + # TODO(wangpeng): Export the enable_numpy_behavior knob + raise AttributeError( + f"{type(self).__name__} object has no attribute '{name}'. " + """ + If you are looking for numpy-related methods, please run the following: + tf.experimental.numpy.experimental_enable_numpy_behavior() + """) + self.__getattribute__(name) + + @property + def dtype(self): + """The `DType` of elements in this tensor.""" + return self._dtype + + @property + def name(self): + return self._name + + @property + def shape(self) -> tensor_shape.TensorShape: + """Returns a `tf.TensorShape` that represents the shape of this tensor. + + >>> t = tf.constant([1,2,3,4,5]) + >>> t.shape + TensorShape([5]) + + `tf.Tensor.shape` is equivalent to `tf.Tensor.get_shape()`. + + In a `tf.function` or when building a model using + `tf.keras.Input`, they return the build-time shape of the + tensor, which may be partially unknown. + + A `tf.TensorShape` is not a tensor. Use `tf.shape(t)` to get a tensor + containing the shape, calculated at runtime. + + See `tf.Tensor.get_shape()`, and `tf.TensorShape` for details and examples. + """ + if self._shape_val is None: + dims, unknown_shape = self._shape + if unknown_shape: + self._shape_val = tensor_shape.unknown_shape() + else: + self._shape_val = tensor_shape.TensorShape(dims) + return self._shape_val + + @property + def ndim(self): + return self.shape.rank + + def _disallow(self, task): + raise errors.OperatorNotAllowedInGraphError( + f"{task} is not allowed." + " You can attempt the following resolutions to the problem:" + " If you are running in Graph mode, use Eager execution mode" + " or decorate this function with @tf.function." + " If you are using AutoGraph, you can try decorating this function" + " with @tf.function. If that does not work, then you may be using" + " an unsupported feature or your source code may not be visible" + " to AutoGraph. See" + " https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#access-to-source-code" + " for more information.") + + def _disallow_bool_casting(self): + self._disallow("Using a symbolic `tf.Tensor` as a Python `bool`") + + def _disallow_iteration(self): + self._disallow("Iterating over a symbolic `tf.Tensor`") + + def __iter__(self): + if not context.executing_eagerly(): + self._disallow_iteration() + + first_dim = self._get_first_dim() + return _TensorIterator(self, first_dim) + + def _get_first_dim(self): + shape = self._shape_tuple() + if shape is None: + raise TypeError("Cannot iterate over a tensor with unknown shape.") + if not shape: + raise TypeError("Cannot iterate over a scalar tensor.") + if shape[0] is None: + raise TypeError( + "Cannot iterate over a tensor with unknown first dimension.") + return shape[0] + + def _shape_as_list(self): + if self.shape.ndims is not None: + return [dim.value for dim in self.shape.dims] + else: + return None + + def _shape_tuple(self): + shape = self._shape_as_list() + if shape is None: + return None + return tuple(shape) + + def _record_tape(self, capture): + """Connect this graph tensor with capture for gradients calculation.""" + record.record_operation( + "captured_value", + [self], [capture], + backward_function=lambda x: [x], + forward_function=lambda x: [x]) + + def get_shape(self) -> tensor_shape.TensorShape: + """Returns a `tf.TensorShape` that represents the shape of this tensor. + + In eager execution the shape is always fully-known. + + >>> a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) + >>> print(a.shape) + (2, 3) + + `tf.Tensor.get_shape()` is equivalent to `tf.Tensor.shape`. + + + When executing in a `tf.function` or building a model using + `tf.keras.Input`, `Tensor.shape` may return a partial shape (including + `None` for unknown dimensions). See `tf.TensorShape` for more details. + + >>> inputs = tf.keras.Input(shape = [10]) + >>> # Unknown batch size + >>> print(inputs.shape) + (None, 10) + + The shape is computed using shape inference functions that are + registered for each `tf.Operation`. + + The returned `tf.TensorShape` is determined at *build* time, without + executing the underlying kernel. It is not a `tf.Tensor`. If you need a + shape *tensor*, either convert the `tf.TensorShape` to a `tf.constant`, or + use the `tf.shape(tensor)` function, which returns the tensor's shape at + *execution* time. + + This is useful for debugging and providing early errors. For + example, when tracing a `tf.function`, no ops are being executed, shapes + may be unknown (See the [Concrete Functions + Guide](https://www.tensorflow.org/guide/concrete_function) for details). + + >>> @tf.function + ... def my_matmul(a, b): + ... result = a@b + ... # the `print` executes during tracing. + ... print("Result shape: ", result.shape) + ... return result + + The shape inference functions propagate shapes to the extent possible: + + >>> f = my_matmul.get_concrete_function( + ... tf.TensorSpec([None,3]), + ... tf.TensorSpec([3,5])) + Result shape: (None, 5) + + Tracing may fail if a shape missmatch can be detected: + + >>> cf = my_matmul.get_concrete_function( + ... tf.TensorSpec([None,3]), + ... tf.TensorSpec([4,5])) + Traceback (most recent call last): + ... + ValueError: Dimensions must be equal, but are 3 and 4 for 'matmul' (op: + 'MatMul') with input shapes: [?,3], [4,5]. + + In some cases, the inferred shape may have unknown dimensions. If + the caller has additional information about the values of these + dimensions, `tf.ensure_shape` or `Tensor.set_shape()` can be used to augment + the inferred shape. + + >>> @tf.function + ... def my_fun(a): + ... a = tf.ensure_shape(a, [5, 5]) + ... # the `print` executes during tracing. + ... print("Result shape: ", a.shape) + ... return a + + >>> cf = my_fun.get_concrete_function( + ... tf.TensorSpec([None, None])) + Result shape: (5, 5) + + Returns: + A `tf.TensorShape` representing the shape of this tensor. + + """ + return self.shape + + def set_shape(self, shape): + """Updates the shape of this tensor. + + Note: It is recommended to use `tf.ensure_shape` instead of + `Tensor.set_shape`, because `tf.ensure_shape` provides better checking for + programming errors and can create guarantees for compiler + optimization. + + With eager execution this operates as a shape assertion. + Here the shapes match: + + >>> t = tf.constant([[1,2,3]]) + >>> t.set_shape([1, 3]) + + Passing a `None` in the new shape allows any value for that axis: + + >>> t.set_shape([1,None]) + + An error is raised if an incompatible shape is passed. + + >>> t.set_shape([1,5]) + Traceback (most recent call last): + ... + ValueError: Tensor's shape (1, 3) is not compatible with supplied + shape [1, 5] + + When executing in a `tf.function`, or building a model using + `tf.keras.Input`, `Tensor.set_shape` will *merge* the given `shape` with + the current shape of this tensor, and set the tensor's shape to the + merged value (see `tf.TensorShape.merge_with` for details): + + >>> t = tf.keras.Input(shape=[None, None, 3]) + >>> print(t.shape) + (None, None, None, 3) + + Dimensions set to `None` are not updated: + + >>> t.set_shape([None, 224, 224, None]) + >>> print(t.shape) + (None, 224, 224, 3) + + The main use case for this is to provide additional shape information + that cannot be inferred from the graph alone. + + For example if you know all the images in a dataset have shape [28,28,3] you + can set it with `tf.set_shape`: + + >>> @tf.function + ... def load_image(filename): + ... raw = tf.io.read_file(filename) + ... image = tf.image.decode_png(raw, channels=3) + ... # the `print` executes during tracing. + ... print("Initial shape: ", image.shape) + ... image.set_shape([28, 28, 3]) + ... print("Final shape: ", image.shape) + ... return image + + Trace the function, see the [Concrete Functions + Guide](https://www.tensorflow.org/guide/concrete_function) for details. + + >>> cf = load_image.get_concrete_function( + ... tf.TensorSpec([], dtype=tf.string)) + Initial shape: (None, None, 3) + Final shape: (28, 28, 3) + + Similarly the `tf.io.parse_tensor` function could return a tensor with + any shape, even the `tf.rank` is unknown. If you know that all your + serialized tensors will be 2d, set it with `set_shape`: + + >>> @tf.function + ... def my_parse(string_tensor): + ... result = tf.io.parse_tensor(string_tensor, out_type=tf.float32) + ... # the `print` executes during tracing. + ... print("Initial shape: ", result.shape) + ... result.set_shape([None, None]) + ... print("Final shape: ", result.shape) + ... return result + + Trace the function + + >>> concrete_parse = my_parse.get_concrete_function( + ... tf.TensorSpec([], dtype=tf.string)) + Initial shape: + Final shape: (None, None) + + Make sure it works: + + >>> t = tf.ones([5,3], dtype=tf.float32) + >>> serialized = tf.io.serialize_tensor(t) + >>> print(serialized.dtype) + + >>> print(serialized.shape) + () + >>> t2 = concrete_parse(serialized) + >>> print(t2.shape) + (5, 3) + + Caution: `set_shape` ensures that the applied shape is compatible with + the existing shape, but it does not check at runtime. Setting + incorrect shapes can result in inconsistencies between the + statically-known graph and the runtime value of tensors. For runtime + validation of the shape, use `tf.ensure_shape` instead. It also modifies + the `shape` of the tensor. + + >>> # Serialize a rank-3 tensor + >>> t = tf.ones([5,5,5], dtype=tf.float32) + >>> serialized = tf.io.serialize_tensor(t) + >>> # The function still runs, even though it `set_shape([None,None])` + >>> t2 = concrete_parse(serialized) + >>> print(t2.shape) + (5, 5, 5) + + Args: + shape: A `TensorShape` representing the shape of this tensor, a + `TensorShapeProto`, a list, a tuple, or None. + + Raises: + ValueError: If `shape` is not compatible with the current shape of + this tensor. + """ + # Reset cached shape. + self._shape_val = None + + # We want set_shape to be reflected in the C API graph for when we run it. + if not isinstance(shape, tensor_shape.TensorShape): + shape = tensor_shape.TensorShape(shape) + dim_list = [] + if shape.dims is None: + unknown_shape = True + else: + unknown_shape = False + for dim in shape.dims: + if dim.value is None: + dim_list.append(-1) + else: + dim_list.append(dim.value) + self._set_shape(dim_list, unknown_shape) + + def _as_node_def_input(self): + """Return a value to use for the NodeDef "input" attribute. + + The returned string can be used in a NodeDef "input" attribute + to indicate that the NodeDef uses this Tensor as input. + + Raises: + ValueError: if this Tensor's Operation does not have a name. + + Returns: + a string. + """ + assert self._op.name + if self.value_index == 0: + return self._op.name + else: + return "%s:%d" % (self._op.name, self.value_index) + + def __str__(self): + return "Tensor(\"%s\"%s%s%s)" % ( + self.name, + (", shape=%s" % + self.get_shape()) if self.get_shape().ndims is not None else "", + (", dtype=%s" % self._dtype.name) if self._dtype else "", + (", device=%s" % self.device) if self.device else "") + + def __repr__(self): + return "" % (self.name, self.get_shape(), + self._dtype.name) + + def __hash__(self): + g = getattr(self, "graph", None) + if (Tensor._USE_EQUALITY and (g is None or g.building_function)): + raise TypeError("Tensor is unhashable. " + "Instead, use tensor.ref() as the key.") + else: + return id(self) + + # NOTE(mrry): This enables the Tensor's overloaded "right" binary + # operators to run when the left operand is an ndarray, because it + # accords the Tensor class higher priority than an ndarray, or a + # numpy matrix. + # TODO(mrry): Convert this to using numpy's __numpy_ufunc__ + # mechanism, which allows more control over how Tensors interact + # with ndarrays. + __array_priority__ = 100 + + def __array__(self, dtype=None): + del dtype + raise NotImplementedError( + f"Cannot convert a symbolic tf.Tensor ({self.name}) to a numpy array." + f" This error may indicate that you're trying to pass a Tensor to" + f" a NumPy call, which is not supported.") + + def __len__(self): + raise TypeError(f"len is not well defined for a symbolic Tensor " + f"({self.name}). Please call `x.shape` rather than " + f"`len(x)` for shape information.") + + # TODO(mdan): This convoluted machinery is hard to maintain. Clean up. + @staticmethod + def _override_operator(operator, func): + _override_helper(Tensor, operator, func) + + def __bool__(self): # pylint: disable=invalid-bool-returned + """Dummy method to prevent a tensor from being used as a Python `bool`. + + This overload raises a `TypeError` when the user inadvertently + treats a `Tensor` as a boolean (most commonly in an `if` or `while` + statement), in code that was not converted by AutoGraph. For example: + + ```python + if tf.constant(True): # Will raise. + # ... + + if tf.constant(5) < tf.constant(7): # Will raise. + # ... + ``` + + Raises: + `TypeError`. + """ + self._disallow_bool_casting() + + def __nonzero__(self): + """Dummy method to prevent a tensor from being used as a Python `bool`. + + This is the Python 2.x counterpart to `__bool__()` above. + + Raises: + `TypeError`. + """ + self._disallow_bool_casting() + + def eval(self, feed_dict=None, session=None): + """Evaluates this tensor in a `Session`. + + Note: If you are not using `compat.v1` libraries, you should not need this, + (or `feed_dict` or `Session`). In eager execution (or within `tf.function`) + you do not need to call `eval`. + + Calling this method will execute all preceding operations that + produce the inputs needed for the operation that produces this + tensor. + + *N.B.* Before invoking `Tensor.eval()`, its graph must have been + launched in a session, and either a default session must be + available, or `session` must be specified explicitly. + + Args: + feed_dict: A dictionary that maps `Tensor` objects to feed values. See + `tf.Session.run` for a description of the valid feed values. + session: (Optional.) The `Session` to be used to evaluate this tensor. If + none, the default session will be used. + + Returns: + A numpy array corresponding to the value of this tensor. + """ + return _eval_using_default_session(self, feed_dict, self.graph, session) + + @deprecation.deprecated(None, "Use ref() instead.") + def experimental_ref(self): + return self.ref() + + def ref(self): + # tf.Variable also has the same ref() API. If you update the + # documentation here, please update tf.Variable.ref() as well. + """Returns a hashable reference object to this Tensor. + + The primary use case for this API is to put tensors in a set/dictionary. + We can't put tensors in a set/dictionary as `tensor.__hash__()` is no longer + available starting Tensorflow 2.0. + + The following will raise an exception starting 2.0 + + >>> x = tf.constant(5) + >>> y = tf.constant(10) + >>> z = tf.constant(10) + >>> tensor_set = {x, y, z} + Traceback (most recent call last): + ... + TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key. + >>> tensor_dict = {x: 'five', y: 'ten'} + Traceback (most recent call last): + ... + TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key. + + Instead, we can use `tensor.ref()`. + + >>> tensor_set = {x.ref(), y.ref(), z.ref()} + >>> x.ref() in tensor_set + True + >>> tensor_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'} + >>> tensor_dict[y.ref()] + 'ten' + + Also, the reference object provides `.deref()` function that returns the + original Tensor. + + >>> x = tf.constant(5) + >>> x.ref().deref() + + """ + return object_identity.Reference(self) + + def __tf_tracing_type__(self, signature_context): + if self.dtype == dtypes.resource or self.dtype == dtypes.variant: + shape_inference_handle_data = handle_data_util.get_handle_data(self) + handle_data = ( + dtypes.HandleData(shape_inference_handle_data) + if shape_inference_handle_data + else None + ) + dtype = dtypes.DType(self.dtype._type_enum, handle_data) + else: + dtype = self.dtype + spec = TensorSpec(self.shape, dtype) + return spec + + def __tf_tensor__( + self, dtype: Optional[dtypes.DType] = None, name: Optional[str] = None + ) -> "Tensor": + if dtype is not None and not dtype.is_compatible_with(self.dtype): + raise ValueError( + _add_error_prefix( + f"Tensor conversion requested dtype {dtype.name} " + f"for Tensor with dtype {self.dtype.name}: {self!r}", + name=name)) + return self + + +@tf_export(v1=["enable_tensor_equality"]) +def enable_tensor_equality(): + """Compare Tensors with element-wise comparison and thus be unhashable. + + Comparing tensors with element-wise allows comparisons such as + tf.Variable(1.0) == 1.0. Element-wise equality implies that tensors are + unhashable. Thus tensors can no longer be directly used in sets or as a key in + a dictionary. + """ + logging.vlog(1, "Enabling tensor equality") + _tensor_equality_api_usage_gauge.get_cell().set(True) + Tensor._USE_EQUALITY = True # pylint: disable=protected-access + + +@tf_export(v1=["disable_tensor_equality"]) +def disable_tensor_equality(): + """Compare Tensors by their id and be hashable. + + This is a legacy behaviour of TensorFlow and is highly discouraged. + """ + logging.vlog(1, "Disabling tensor equality") + _tensor_equality_api_usage_gauge.get_cell().set(False) + Tensor._USE_EQUALITY = False # pylint: disable=protected-access + + +# TODO(b/249802365): Sanitize all TensorSpec names. +def sanitize_spec_name(name: str) -> str: + """Sanitizes Spec names. Matches Graph Node and Python naming conventions. + + Without sanitization, names that are not legal Python parameter names can be + set which makes it challenging to represent callables supporting the named + calling capability. + + Args: + name: The name to sanitize. + + Returns: + A string that meets Python parameter conventions. + """ + if not name: + return "unknown" + + # Lower case and replace non-alphanumeric chars with '_' + swapped = "".join([c if c.isalnum() else "_" for c in name.lower()]) + + if swapped[0].isalpha(): + return swapped + else: + return "tensor_" + swapped + + +def get_op_name(tensor_name): + """Extract the Op name from a Tensor name. + + The Op name is everything before a colon, if present, + not including any ^ prefix denoting a control dependency. + + Args: + tensor_name: the full name of a Tensor in the graph. + Returns: + The name of the Op of which the given Tensor is an output. + Raises: + ValueError: if tensor_name is None or empty. + """ + if not tensor_name: + raise ValueError( + f"Tensor name cannot be empty or None. Received: {tensor_name}.") + + # Control dependency inputs start with ^. + if tensor_name.startswith("^"): + tensor_name = tensor_name[1:] + if ":" in tensor_name: + op_name, _ = tensor_name.split(":") + return op_name + return tensor_name + + +class DenseSpec(type_spec.TypeSpec): + """Describes a dense object with shape, dtype, and name.""" + + __slots__ = ["_shape", "_dtype", "_name"] + + _component_specs = property(lambda self: self) + + def __init__(self, shape, dtype=dtypes.float32, name=None): + """Creates a TensorSpec. + + Args: + shape: Value convertible to `tf.TensorShape`. The shape of the tensor. + dtype: Value convertible to `tf.DType`. The type of the tensor values. + name: Optional name for the Tensor. + + Raises: + TypeError: If shape is not convertible to a `tf.TensorShape`, or dtype is + not convertible to a `tf.DType`. + """ + self._shape = tensor_shape.TensorShape(shape) + self._dtype = dtypes.as_dtype(dtype) + self._name = name + + @property + def shape(self): + """Returns the `TensorShape` that represents the shape of the tensor.""" + return self._shape + + @property + def dtype(self): + """Returns the `dtype` of elements in the tensor.""" + return self._dtype + + @property + def name(self): + """Returns the (optionally provided) name of the described tensor.""" + return self._name + + def is_compatible_with(self, spec_or_value): + return (isinstance(spec_or_value, (DenseSpec, self.value_type)) and + self._dtype.is_compatible_with(spec_or_value.dtype) and + self._shape.is_compatible_with(spec_or_value.shape)) + + def __repr__(self): + return "{}(shape={}, dtype={}, name={})".format( + type(self).__name__, self.shape, repr(self.dtype), repr(self.name)) + + def __hash__(self): + return hash((self._shape, self.dtype)) + + def __eq__(self, other): + # pylint: disable=protected-access + return (type(self) is type(other) and self._shape == other._shape and + self._dtype == other._dtype and self._name == other._name) + + def __ne__(self, other): + return not self == other + + def _serialize(self): + return (self._shape, self._dtype, self._name) + + def _to_legacy_output_types(self): + return self._dtype + + def _to_legacy_output_shapes(self): + return self._shape + + def _to_legacy_output_classes(self): + return self.value_type + + +@tf_export("TensorSpec") +@type_spec_registry.register("tf.TensorSpec") +class TensorSpec(DenseSpec, type_spec.BatchableTypeSpec, + trace_type.Serializable, internal.TensorSpec): + """Describes the type of a tf.Tensor. + + >>> t = tf.constant([[1,2,3],[4,5,6]]) + >>> tf.TensorSpec.from_tensor(t) + TensorSpec(shape=(2, 3), dtype=tf.int32, name=None) + + Contains metadata for describing the nature of `tf.Tensor` objects + accepted or returned by some TensorFlow APIs. + + For example, it can be used to constrain the type of inputs accepted by + a tf.function: + + >>> @tf.function(input_signature=[tf.TensorSpec([1, None])]) + ... def constrained_foo(t): + ... print("tracing...") + ... return t + + Now the `tf.function` is able to assume that `t` is always of the type + `tf.TensorSpec([1, None])` which will avoid retracing as well as enforce the + type restriction on inputs. + + As a result, the following call with tensor of type `tf.TensorSpec([1, 2])` + triggers a trace and succeeds: + >>> constrained_foo(tf.constant([[1., 2]])).numpy() + tracing... + array([[1., 2.]], dtype=float32) + + The following subsequent call with tensor of type `tf.TensorSpec([1, 4])` + does not trigger a trace and succeeds: + >>> constrained_foo(tf.constant([[1., 2, 3, 4]])).numpy() + array([[1., 2., 3., 4.], dtype=float32) + + But the following call with tensor of type `tf.TensorSpec([2, 2])` fails: + >>> constrained_foo(tf.constant([[1., 2], [3, 4]])).numpy() + Traceback (most recent call last): + ... + TypeError: Binding inputs to tf.function `constrained_foo` failed ... + + """ + + __slots__ = [] + + @classmethod + def experimental_type_proto(cls) -> Type[struct_pb2.TensorSpecProto]: + """Returns the type of proto associated with TensorSpec serialization.""" + return struct_pb2.TensorSpecProto + + @classmethod + def experimental_from_proto( + cls, proto: struct_pb2.TensorSpecProto) -> "TensorSpec": + """Returns a TensorSpec instance based on the serialized proto.""" + return TensorSpec( + shape=tensor_shape.TensorShape.experimental_from_proto(proto.shape), + dtype=proto.dtype, + name=proto.name if proto.name else None) + + def experimental_as_proto(self) -> struct_pb2.TensorSpecProto: + """Returns a proto representation of the TensorSpec instance.""" + return struct_pb2.TensorSpecProto( + shape=self.shape.experimental_as_proto(), + dtype=self.dtype.experimental_as_proto().datatype, + name=self.name) + + def is_compatible_with(self, spec_or_tensor): # pylint:disable=useless-super-delegation,arguments-renamed + """Returns True if spec_or_tensor is compatible with this TensorSpec. + + Two tensors are considered compatible if they have the same dtype + and their shapes are compatible (see `tf.TensorShape.is_compatible_with`). + + Args: + spec_or_tensor: A tf.TensorSpec or a tf.Tensor + + Returns: + True if spec_or_tensor is compatible with self. + """ + return super(TensorSpec, self).is_compatible_with(spec_or_tensor) + + def is_subtype_of(self, other): + if not isinstance(other, TensorSpec): + return False + + return ( + (not self.name or self.name == other.name) + and self.shape.is_subtype_of(other.shape) + and self.dtype.is_subtype_of(other.dtype) + ) + + def placeholder_value(self, placeholder_context): + """Generates a graph placholder with the given TensorSpec information.""" + if placeholder_context.unnest_only: + return self + + name = self.name or placeholder_context.naming_scope + context_graph = placeholder_context.context_graph + if placeholder_context.with_none_control_dependencies: + # Note: setting ops.control_dependencies(None) ensures we always put + # capturing placeholders outside of any control flow context. + with context_graph.control_dependencies(None): + placeholder = self._graph_placeholder(context_graph, name=name) + else: + placeholder = self._graph_placeholder(context_graph, name=name) + + if name is not None: + # Record the requested/user-specified name in case it's different than + # the uniquified name, for validation when exporting signatures. + placeholder.op._set_attr( # pylint: disable=protected-access + "_user_specified_name", + attr_value_pb2.AttrValue(s=compat.as_bytes(name))) + + handle_data = self.dtype._handle_data # pylint: disable=protected-access + if ( + handle_data is not None + and handle_data.shape_inference.is_set + and handle_data.shape_inference.shape_and_type + ): + handle_data_util.set_handle_data(placeholder, handle_data.shape_inference) + + # Record the composite device as an attribute to the placeholder. + # This attribute would be propagated into the arg_attr of the FunctionDef. + # Currently, a packed eager tensor is always placed on a CompositeDevice. + if placeholder_context.composite_device_name is not None: + placeholder.op._set_attr( # pylint: disable=protected-access + "_composite_device", + attr_value_pb2.AttrValue(s=compat.as_bytes( + placeholder_context.composite_device_name))) + + return placeholder + + def _graph_placeholder(self, graph, name=None): + """Graph-only version of tf.compat.v1.placeholder(), for internal use only.""" + dtype = self.dtype.base_dtype + shape = self.shape + dtype_value = attr_value_pb2.AttrValue(type=dtype.as_datatype_enum) + if isinstance(shape, (list, tuple)): + shape = tensor_shape.TensorShape(shape) + shape = attr_value_pb2.AttrValue(shape=shape.as_proto()) + attrs = {"dtype": dtype_value, "shape": shape} + try: + op = graph._create_op_internal( # pylint: disable=protected-access + "Placeholder", [], [dtype], input_types=[], + attrs=attrs, name=name) + except ValueError as e: + # TODO(b/262413656) Sometimes parameter names are not valid op names, in + # which case an unnamed placeholder is created instead. Update this logic + # to sanitize the name instead of falling back on unnamed placeholders. + logging.warning(e) + op = graph._create_op_internal( # pylint: disable=protected-access + "Placeholder", [], [dtype], input_types=[], attrs=attrs) + (result,) = op.outputs + if op_callbacks.should_invoke_op_callbacks(): + # TODO(b/147670703): Once the special-op creation code paths + # are unified. Remove this `if` block. + callback_outputs = op_callbacks.invoke_op_callbacks( + "Placeholder", tuple(), attrs, tuple(op.outputs), + op_name=name, graph=graph) + if callback_outputs is not None: + (result,) = callback_outputs + return result + + def to_tensors(self, value): + value = self.cast(value, trace_type.InternalCastContext()) + if not value.shape.is_subtype_of(self.shape): + raise TypeError( + f"Received tensor of shape {value.shape} instead of {self.shape}" + ) + return [value] + + def from_tensors(self, tensors): + tensor = next(tensors) + handle_data = self.dtype._handle_data # pylint: disable=protected-access + if handle_data: + handle_data_util.set_handle_data(tensor, handle_data.shape_inference) + return tensor + + def flatten(self): + return [self] + + def cast(self, value, casting_context): + """Cast value to a tensor that is a subtype of this TensorSpec.""" + # This method is mainly used to cast Python primitives to tensor. + # Currently, cast tensor to tensor with different types are not supported. + # For example, casting int32 to float32 would raise a ValueError. + if casting_context.allow_specs and isinstance(value, TensorSpec): + assert value.is_subtype_of(self), f"Can not cast {value!r} to {self!r}" + return self + + if not isinstance(value, Tensor): + value = tensor_conversion_registry.convert(value, self.dtype) + value_spec = TensorSpec(value.shape, value.dtype, self.name) + + if not value_spec.is_subtype_of(self): + if self.is_subtype_of(value_spec): + value.set_shape(self.shape) + else: + raise TypeError(f"Can not cast {value_spec!r} to {self!r}") + + return value + + def _alias_id(self): + """Returns an id specifying identical tensors to avoid duplication.""" + alias_id = None + if self.dtype._handle_data: # pylint: disable=protected-access + alias_id = self.dtype._handle_data.alias_id # pylint: disable=protected-access + return alias_id + + @classmethod + def from_spec(cls, spec, name=None): + """Returns a `TensorSpec` with the same shape and dtype as `spec`. + + >>> spec = tf.TensorSpec(shape=[8, 3], dtype=tf.int32, name="OriginalName") + >>> tf.TensorSpec.from_spec(spec, "NewName") + TensorSpec(shape=(8, 3), dtype=tf.int32, name='NewName') + + Args: + spec: The `TypeSpec` used to create the new `TensorSpec`. + name: The name for the new `TensorSpec`. Defaults to `spec.name`. + """ + return cls(spec.shape, spec.dtype, name or spec.name) + + @classmethod + def from_tensor(cls, tensor, name=None): + """Returns a `TensorSpec` that describes `tensor`. + + >>> tf.TensorSpec.from_tensor(tf.constant([1, 2, 3])) + TensorSpec(shape=(3,), dtype=tf.int32, name=None) + + Args: + tensor: The `tf.Tensor` that should be described. + name: A name for the `TensorSpec`. Defaults to `tensor.op.name`. + + Returns: + A `TensorSpec` that describes `tensor`. + """ + if isinstance(tensor, core_tf_types.Value): + return TensorSpec(tensor.shape, tensor.dtype, name) + elif isinstance(tensor, core_tf_types.Symbol): + # TODO(b/249802365): Return a sanitized version of op name or no name. + return TensorSpec(tensor.shape, tensor.dtype, name or tensor.op.name) + else: + raise ValueError( + f"`tensor` should be a tf.Tensor, but got type {type(tensor)}.") + + @property + def value_type(self): + """The Python type for values that are compatible with this TypeSpec.""" + return Tensor + + def _to_components(self, value): + assert isinstance(value, core_tf_types.Tensor) + return value + + def _from_components(self, components): + return components + + def _from_compatible_tensor_list(self, tensor_list): + # TODO(b/112266545): It would be cleaner to create a new `ensure_shape()` + # op here and return that, instead of mutating the input's shape using + # `Tensor.set_shape()`. However, that would add extra ops, which could + # impact performance. When this bug is resolved, we should be able to add + # the `ensure_shape()` ops and optimize them away using contextual shape + # information. + assert len(tensor_list) == 1 + tensor_list[0].set_shape(self._shape) + return tensor_list[0] + + def _to_batchable_tensor_list(self, value, batched=False): + if batched and self._shape.merge_with(value.shape).ndims == 0: + raise ValueError("Unbatching a tensor is only supported for rank >= 1") + return self._to_components(value) + + def _batch(self, batch_size): + return TensorSpec( + tensor_shape.TensorShape([batch_size]).concatenate(self._shape), + self._dtype) + + def _unbatch(self): + if self._shape.ndims == 0: + raise ValueError("Unbatching a tensor is only supported for rank >= 1") + return TensorSpec(self._shape[1:], self._dtype) + + @property + def _flat_tensor_specs(self): + return [self] + + def _to_tensor_list(self, value): + return [self._to_components(value)] + + def _to_batched_tensor_list(self, value): + return self._to_tensor_list(value) + + # TODO(b/206014848): Helper function to support logic that does not consider + # Tensor name. Will be removed once load-bearing usages of Tensor name are + # fixed. + def _without_tensor_names(self) -> "TensorSpec": + """Returns a version of `TensorSpec` with the name removed.""" + if self.name is None: + return self + else: + return TensorSpec(self.shape, self.dtype) + +trace_type.register_serializable(TensorSpec) +trace_type.register_tensor_type(TensorSpec) + + +class _TensorSpecCodec: + """Codec for `TensorSpec`.""" + + def can_encode(self, pyobj): + # BoundedTensorSpec has its own decoder. + return (isinstance(pyobj, TensorSpec) and + not isinstance(pyobj, BoundedTensorSpec)) + + def do_encode(self, tensor_spec_value, encode_fn): + encoded_tensor_spec = struct_pb2.StructuredValue() + encoded_tensor_spec.tensor_spec_value.CopyFrom( + struct_pb2.TensorSpecProto( + shape=encode_fn(tensor_spec_value.shape).tensor_shape_value, + dtype=encode_fn(tensor_spec_value.dtype).tensor_dtype_value, + name=tensor_spec_value.name)) + return encoded_tensor_spec + + def can_decode(self, value): + return value.HasField("tensor_spec_value") + + def do_decode(self, value, decode_fn): + name = value.tensor_spec_value.name + return TensorSpec( + shape=decode_fn( + struct_pb2.StructuredValue( + tensor_shape_value=value.tensor_spec_value.shape)), + dtype=decode_fn( + struct_pb2.StructuredValue( + tensor_dtype_value=value.tensor_spec_value.dtype)), + name=(name if name else None)) + + +nested_structure_coder.register_codec(_TensorSpecCodec()) + + +# TODO(b/133606651): Should is_compatible_with should check min/max bounds? +@type_spec_registry.register("tf.BoundedTensorSpec") +class BoundedTensorSpec(TensorSpec, trace_type.Serializable): + """A `TensorSpec` that specifies minimum and maximum values. + + Example usage: + ```python + spec = tensor_spec.BoundedTensorSpec((1, 2, 3), tf.float32, 0, (5, 5, 5)) + tf_minimum = tf.convert_to_tensor(spec.minimum, dtype=spec.dtype) + tf_maximum = tf.convert_to_tensor(spec.maximum, dtype=spec.dtype) + ``` + + Bounds are meant to be inclusive. This is especially important for + integer types. The following spec will be satisfied by tensors + with values in the set {0, 1, 2}: + ```python + spec = tensor_spec.BoundedTensorSpec((3, 5), tf.int32, 0, 2) + ``` + """ + + __slots__ = ("_minimum", "_maximum") + + def __init__(self, shape, dtype, minimum, maximum, name=None): + """Initializes a new `BoundedTensorSpec`. + + Args: + shape: Value convertible to `tf.TensorShape`. The shape of the tensor. + dtype: Value convertible to `tf.DType`. The type of the tensor values. + minimum: Number or sequence specifying the minimum element bounds + (inclusive). Must be broadcastable to `shape`. + maximum: Number or sequence specifying the maximum element bounds + (inclusive). Must be broadcastable to `shape`. + name: Optional string containing a semantic name for the corresponding + array. Defaults to `None`. + + Raises: + ValueError: If `minimum` or `maximum` are not provided or not + broadcastable to `shape`. + TypeError: If the shape is not an iterable or if the `dtype` is an invalid + numpy dtype. + """ + super(BoundedTensorSpec, self).__init__(shape, dtype, name) + + if minimum is None: + raise ValueError("`minimum` can not be None.") + if maximum is None: + raise ValueError("`maximum` can not be None.") + + try: + minimum_shape = np.shape(minimum) + common_shapes.broadcast_shape( + tensor_shape.TensorShape(minimum_shape), self.shape) + except ValueError as exception: + raise ValueError( + f"`minimum` {minimum} is not compatible with shape {self.shape}." + ) from exception + + try: + maximum_shape = np.shape(maximum) + common_shapes.broadcast_shape( + tensor_shape.TensorShape(maximum_shape), self.shape) + except ValueError as exception: + raise ValueError( + f"`maximum` {maximum} is not compatible with shape {self.shape}." + ) from exception + + self._minimum = np.array(minimum, dtype=self.dtype.as_numpy_dtype) + self._minimum.setflags(write=False) + + self._maximum = np.array(maximum, dtype=self.dtype.as_numpy_dtype) + self._maximum.setflags(write=False) + + @classmethod + def experimental_type_proto(cls) -> Type[struct_pb2.BoundedTensorSpecProto]: + """Returns the type of proto associated with BoundedTensorSpec serialization.""" + return struct_pb2.BoundedTensorSpecProto + + @classmethod + def experimental_from_proto( + cls, proto: struct_pb2.BoundedTensorSpecProto) -> "BoundedTensorSpec": + """Returns a BoundedTensorSpec instance based on the serialized proto.""" + return BoundedTensorSpec( + shape=tensor_shape.TensorShape.experimental_from_proto(proto.shape), + dtype=proto.dtype, + minimum=tensor_util.MakeNdarray(proto.minimum), + maximum=tensor_util.MakeNdarray(proto.maximum), + name=proto.name if proto.name else None) + + def experimental_as_proto(self) -> struct_pb2.BoundedTensorSpecProto: + """Returns a proto representation of the BoundedTensorSpec instance.""" + return struct_pb2.BoundedTensorSpecProto( + shape=self.shape.experimental_as_proto(), + dtype=self.dtype.experimental_as_proto().datatype, + minimum=tensor_util.make_tensor_proto(self._minimum), + maximum=tensor_util.make_tensor_proto(self._maximum), + name=self.name) + + @classmethod + def from_spec(cls, spec): + """Returns a `TensorSpec` with the same shape and dtype as `spec`. + + If `spec` is a `BoundedTensorSpec`, then the new spec's bounds are set to + `spec.minimum` and `spec.maximum`; otherwise, the bounds are set to + `spec.dtype.min` and `spec.dtype.max`. + + >>> spec = tf.TensorSpec(shape=[8, 3], dtype=tf.int32, name="x") + >>> BoundedTensorSpec.from_spec(spec) + BoundedTensorSpec(shape=(8, 3), dtype=tf.int32, name='x', + minimum=array(-2147483648, dtype=int32), + maximum=array(2147483647, dtype=int32)) + + Args: + spec: The `TypeSpec` used to create the new `BoundedTensorSpec`. + """ + dtype = dtypes.as_dtype(spec.dtype) + minimum = getattr(spec, "minimum", dtype.min) + maximum = getattr(spec, "maximum", dtype.max) + return BoundedTensorSpec(spec.shape, dtype, minimum, maximum, spec.name) + + @property + def minimum(self): + """Returns a NumPy array specifying the minimum bounds (inclusive).""" + return self._minimum + + @property + def maximum(self): + """Returns a NumPy array specifying the maximum bounds (inclusive).""" + return self._maximum + + def cast(self, value, casting_context): + if casting_context.allow_specs and isinstance(value, BoundedTensorSpec): + assert value.is_subtype_of(self), f"Can not cast {value!r} to {self!r}" + return self + + actual_spec = TensorSpec(shape=self.shape, dtype=self.dtype, name=self.name) + return actual_spec.cast(value, casting_context) # pylint: disable=protected-access + + def __repr__(self): + s = "BoundedTensorSpec(shape={}, dtype={}, name={}, minimum={}, maximum={})" + return s.format(self.shape, repr(self.dtype), repr(self.name), + repr(self.minimum), repr(self.maximum)) + + def __eq__(self, other): + tensor_spec_eq = super(BoundedTensorSpec, self).__eq__(other) + return (tensor_spec_eq and np.allclose(self.minimum, other.minimum) and + np.allclose(self.maximum, other.maximum)) + + def __hash__(self): + return hash((self._shape, self.dtype)) + + def __reduce__(self): + return BoundedTensorSpec, (self._shape, self._dtype, self._minimum, + self._maximum, self._name) + + def _serialize(self): + return (self._shape, self._dtype, self._minimum, self._maximum, self._name) + + +class _BoundedTensorSpecCodec: + """Codec for `BoundedTensorSpec`.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, BoundedTensorSpec) + + def do_encode(self, bounded_tensor_spec_value, encode_fn): + """Returns an encoded proto for the given `tf.BoundedTensorSpec`.""" + encoded_bounded_tensor_spec = struct_pb2.StructuredValue() + encoded_bounded_tensor_spec.bounded_tensor_spec_value.CopyFrom( + struct_pb2.BoundedTensorSpecProto( + shape=encode_fn(bounded_tensor_spec_value.shape).tensor_shape_value, + dtype=encode_fn(bounded_tensor_spec_value.dtype).tensor_dtype_value, + name=bounded_tensor_spec_value.name, + minimum=tensor_util.make_tensor_proto( + bounded_tensor_spec_value.minimum), + maximum=tensor_util.make_tensor_proto( + bounded_tensor_spec_value.maximum))) + return encoded_bounded_tensor_spec + + def can_decode(self, value): + return value.HasField("bounded_tensor_spec_value") + + def do_decode(self, value, decode_fn): + btsv = value.bounded_tensor_spec_value + name = btsv.name + return BoundedTensorSpec( + shape=decode_fn( + struct_pb2.StructuredValue(tensor_shape_value=btsv.shape)), + dtype=decode_fn( + struct_pb2.StructuredValue(tensor_dtype_value=btsv.dtype)), + minimum=tensor_util.MakeNdarray(btsv.minimum), + maximum=tensor_util.MakeNdarray(btsv.maximum), + name=(name if name else None)) + + +nested_structure_coder.register_codec(_BoundedTensorSpecCodec()) + +trace_type.register_serializable(BoundedTensorSpec) +_pywrap_utils.RegisterType("TensorSpec", TensorSpec) + +# Note: we do not include Tensor names when constructing TypeSpecs. +type_spec.register_type_spec_from_value_converter( + Tensor, lambda tensor: TensorSpec(tensor.shape, tensor.dtype)) + +type_spec.register_type_spec_from_value_converter( + np.ndarray, lambda array: TensorSpec(array.shape, array.dtype)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_conversion.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..de7278675be05453e0080f8845c8b96971cdab7e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_conversion.py @@ -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. +# ============================================================================== +"""Tensor conversion functions.""" +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.util import deprecation +from tensorflow.python.util import dispatch +from tensorflow.python.util import tf_export + + +def convert_to_tensor_v1( + value, dtype=None, name=None, preferred_dtype=None, dtype_hint=None +) -> tensor_lib.Tensor: + """Converts the given `value` to a `Tensor` (with the TF1 API).""" + preferred_dtype = deprecation.deprecated_argument_lookup( + "dtype_hint", dtype_hint, "preferred_dtype", preferred_dtype + ) + return convert_to_tensor_v2(value, dtype, preferred_dtype, name) + + +@tf_export.tf_export(v1=["convert_to_tensor"]) +@dispatch.add_dispatch_support +def convert_to_tensor_v1_with_dispatch( + value, dtype=None, name=None, preferred_dtype=None, dtype_hint=None +) -> tensor_lib.Tensor: + """Converts the given `value` to a `Tensor`. + + This function converts Python objects of various types to `Tensor` + objects. It accepts `Tensor` objects, numpy arrays, Python lists, + and Python scalars. For example: + + ```python + import numpy as np + + def my_func(arg): + arg = tf.convert_to_tensor(arg, dtype=tf.float32) + return tf.matmul(arg, arg) + arg + + # The following calls are equivalent. + value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]])) + value_2 = my_func([[1.0, 2.0], [3.0, 4.0]]) + value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)) + ``` + + This function can be useful when composing a new operation in Python + (such as `my_func` in the example above). All standard Python op + constructors apply this function to each of their Tensor-valued + inputs, which allows those ops to accept numpy arrays, Python lists, + and scalars in addition to `Tensor` objects. + + Note: This function diverges from default Numpy behavior for `float` and + `string` types when `None` is present in a Python list or scalar. Rather + than silently converting `None` values, an error will be thrown. + + Args: + value: An object whose type has a registered `Tensor` conversion function. + dtype: Optional element type for the returned tensor. If missing, the type + is inferred from the type of `value`. + name: Optional name to use if a new `Tensor` is created. + preferred_dtype: Optional element type for the returned tensor, used when + dtype is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so preferred_dtype can be used as a soft + preference. If the conversion to `preferred_dtype` is not possible, this + argument has no effect. + dtype_hint: same meaning as preferred_dtype, and overrides it. + + Returns: + A `Tensor` based on `value`. + + Raises: + TypeError: If no conversion function is registered for `value` to `dtype`. + RuntimeError: If a registered conversion function returns an invalid value. + ValueError: If the `value` is a tensor not of given `dtype` in graph mode. + """ + return convert_to_tensor_v1( + value, + dtype=dtype, + name=name, + preferred_dtype=preferred_dtype, + dtype_hint=dtype_hint, + ) + + +@tf_export.tf_export("convert_to_tensor", v1=[]) +@dispatch.add_dispatch_support +def convert_to_tensor_v2_with_dispatch( + value, dtype=None, dtype_hint=None, name=None +) -> tensor_lib.Tensor: + """Converts the given `value` to a `Tensor`. + + This function converts Python objects of various types to `Tensor` + objects. It accepts `Tensor` objects, numpy arrays, Python lists, + and Python scalars. + + For example: + + >>> import numpy as np + >>> def my_func(arg): + ... arg = tf.convert_to_tensor(arg, dtype=tf.float32) + ... return arg + + >>> # The following calls are equivalent. + ... + >>> value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]])) + >>> print(value_1) + tf.Tensor( + [[1. 2.] + [3. 4.]], shape=(2, 2), dtype=float32) + >>> value_2 = my_func([[1.0, 2.0], [3.0, 4.0]]) + >>> print(value_2) + tf.Tensor( + [[1. 2.] + [3. 4.]], shape=(2, 2), dtype=float32) + >>> value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32)) + >>> print(value_3) + tf.Tensor( + [[1. 2.] + [3. 4.]], shape=(2, 2), dtype=float32) + + This function can be useful when composing a new operation in Python + (such as `my_func` in the example above). All standard Python op + constructors apply this function to each of their Tensor-valued + inputs, which allows those ops to accept numpy arrays, Python lists, + and scalars in addition to `Tensor` objects. + + Note: This function diverges from default Numpy behavior for `float` and + `string` types when `None` is present in a Python list or scalar. Rather + than silently converting `None` values, an error will be thrown. + + Args: + value: An object whose type has a registered `Tensor` conversion function. + dtype: Optional element type for the returned tensor. If missing, the type + is inferred from the type of `value`. + dtype_hint: Optional element type for the returned tensor, used when dtype + is None. In some cases, a caller may not have a dtype in mind when + converting to a tensor, so dtype_hint can be used as a soft preference. If + the conversion to `dtype_hint` is not possible, this argument has no + effect. + name: Optional name to use if a new `Tensor` is created. + + Returns: + A `Tensor` based on `value`. + + Raises: + TypeError: If no conversion function is registered for `value` to `dtype`. + RuntimeError: If a registered conversion function returns an invalid value. + ValueError: If the `value` is a tensor not of given `dtype` in graph mode. + """ + return convert_to_tensor_v2( + value, dtype=dtype, dtype_hint=dtype_hint, name=name + ) + + +def convert_to_tensor_v2( + value, dtype=None, dtype_hint=None, name=None +) -> tensor_lib.Tensor: + """Converts the given `value` to a `Tensor`.""" + # preferred_dtype = preferred_dtype or dtype_hint + return tensor_conversion_registry.convert( + value, dtype, name, preferred_dtype=dtype_hint + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_conversion_registry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_conversion_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..c18db9524b2574124527d3d3fc17c51ab8281ca8 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_conversion_registry.py @@ -0,0 +1,264 @@ +# 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. +# ============================================================================== +"""Registry for tensor conversion functions.""" +# pylint: disable=g-bad-name +import collections +import threading + +import numpy as np + +from tensorflow.python.framework import dtypes +from tensorflow.python.types import core +from tensorflow.python.util.tf_export import tf_export + + +_tensor_conversion_func_registry = collections.defaultdict(list) +_tensor_conversion_func_cache = {} +_tensor_conversion_func_lock = threading.Lock() + +# Instances of these types should only be converted by internally-registered +# conversion functions. +_CONSTANT_OP_CONVERTIBLES = ( + int, + float, + np.generic, + np.ndarray, +) + + +# TODO(josh11b): Add ctx argument to conversion_func() signature. +def register_tensor_conversion_function_internal(base_type, + conversion_func, + priority=100): + """Internal version of register_tensor_conversion_function. + + See docstring of `register_tensor_conversion_function` for details. + + The internal version of the function allows registering conversions + for types in the _UNCONVERTIBLE_TYPES tuple. + + Args: + base_type: The base type or tuple of base types for all objects that + `conversion_func` accepts. + conversion_func: A function that converts instances of `base_type` to + `Tensor`. + priority: Optional integer that indicates the priority for applying this + conversion function. Conversion functions with smaller priority values run + earlier than conversion functions with larger priority values. Defaults to + 100. + + Raises: + TypeError: If the arguments do not have the appropriate type. + """ + base_types = base_type if isinstance(base_type, tuple) else (base_type,) + if any(not isinstance(x, type) for x in base_types): + raise TypeError("Argument `base_type` must be a type or a tuple of types. " + f"Obtained: {base_type}") + del base_types # Only needed for validation. + if not callable(conversion_func): + raise TypeError("Argument `conversion_func` must be callable. Received " + f"{conversion_func}.") + + with _tensor_conversion_func_lock: + _tensor_conversion_func_registry[priority].append( + (base_type, conversion_func)) + _tensor_conversion_func_cache.clear() + + +@tf_export("register_tensor_conversion_function") +def register_tensor_conversion_function(base_type, + conversion_func, + priority=100): + """Registers a function for converting objects of `base_type` to `Tensor`. + + The conversion function must have the following signature: + + ```python + def conversion_func(value, dtype=None, name=None, as_ref=False): + # ... + ``` + + It must return a `Tensor` with the given `dtype` if specified. If the + conversion function creates a new `Tensor`, it should use the given + `name` if specified. All exceptions will be propagated to the caller. + + The conversion function may return `NotImplemented` for some + inputs. In this case, the conversion process will continue to try + subsequent conversion functions. + + If `as_ref` is true, the function must return a `Tensor` reference, + such as a `Variable`. + + NOTE: The conversion functions will execute in order of priority, + followed by order of registration. To ensure that a conversion function + `F` runs before another conversion function `G`, ensure that `F` is + registered with a smaller priority than `G`. + + Args: + base_type: The base type or tuple of base types for all objects that + `conversion_func` accepts. + conversion_func: A function that converts instances of `base_type` to + `Tensor`. + priority: Optional integer that indicates the priority for applying this + conversion function. Conversion functions with smaller priority values run + earlier than conversion functions with larger priority values. Defaults to + 100. + + Raises: + TypeError: If the arguments do not have the appropriate type. + """ + base_types = base_type if isinstance(base_type, tuple) else (base_type,) + if any(not isinstance(x, type) for x in base_types): + raise TypeError("Argument `base_type` must be a type or a tuple of types. " + f"Obtained: {base_type}") + if any(issubclass(x, _CONSTANT_OP_CONVERTIBLES) for x in base_types): + raise TypeError("Cannot register conversions for Python numeric types and " + "NumPy scalars and arrays.") + del base_types # Only needed for validation. + register_tensor_conversion_function_internal( + base_type, conversion_func, priority) + + +def get(query): + """Get conversion function for objects of `cls`. + + Args: + query: The type to query for. + + Returns: + A list of conversion functions in increasing order of priority. + """ + conversion_funcs = _tensor_conversion_func_cache.get(query) + if conversion_funcs is None: + with _tensor_conversion_func_lock: + # Has another thread populated the cache in the meantime? + conversion_funcs = _tensor_conversion_func_cache.get(query) + if conversion_funcs is None: + conversion_funcs = [] + for _, funcs_at_priority in sorted( + _tensor_conversion_func_registry.items()): + conversion_funcs.extend( + (base_type, conversion_func) + for base_type, conversion_func in funcs_at_priority + if issubclass(query, base_type)) + _tensor_conversion_func_cache[query] = conversion_funcs + return conversion_funcs + + +def _add_error_prefix(msg, *, name=None): + return msg if name is None else f"{name}: {msg}" + + +def convert(value, + dtype=None, + name=None, + as_ref=False, + preferred_dtype=None, + accepted_result_types=(core.Symbol,)): + """Converts `value` to a `Tensor` using registered conversion functions. + + Args: + value: An object whose type has a registered `Tensor` conversion function. + dtype: Optional element type for the returned tensor. If missing, the type + is inferred from the type of `value`. + name: Optional name to use if a new `Tensor` is created. + as_ref: Optional boolean specifying if the returned value should be a + reference-type `Tensor` (e.g. Variable). Pass-through to the registered + conversion function. Defaults to `False`. + preferred_dtype: Optional element type for the returned tensor. + Used when dtype is None. In some cases, a caller may not have a dtype + in mind when converting to a tensor, so `preferred_dtype` can be used + as a soft preference. If the conversion to `preferred_dtype` is not + possible, this argument has no effect. + accepted_result_types: Optional collection of types as an allow-list + for the returned value. If a conversion function returns an object + which is not an instance of some type in this collection, that value + will not be returned. + + Returns: + A `Tensor` converted from `value`. + + Raises: + ValueError: If `value` is a `Tensor` and conversion is requested + to a `Tensor` with an incompatible `dtype`. + TypeError: If no conversion function is registered for an element in + `values`. + RuntimeError: If a registered conversion function returns an invalid + value. + """ + + if dtype is not None: + dtype = dtypes.as_dtype(dtype) + if preferred_dtype is not None: + preferred_dtype = dtypes.as_dtype(preferred_dtype) + + overload = getattr(value, "__tf_tensor__", None) + if overload is not None: + return overload(dtype, name) # pylint: disable=not-callable + + for base_type, conversion_func in get(type(value)): + # If dtype is None but preferred_dtype is not None, we try to + # cast to preferred_dtype first. + ret = None + if dtype is None and preferred_dtype is not None: + try: + ret = conversion_func( + value, dtype=preferred_dtype, name=name, as_ref=as_ref) + except (TypeError, ValueError): + # Could not coerce the conversion to use the preferred dtype. + pass + else: + if (ret is not NotImplemented and + ret.dtype.base_dtype != preferred_dtype.base_dtype): + raise RuntimeError( + _add_error_prefix( + f"Conversion function {conversion_func!r} for type " + f"{base_type} returned incompatible dtype: requested = " + f"{preferred_dtype.base_dtype.name}, " + f"actual = {ret.dtype.base_dtype.name}", + name=name)) + + if ret is None: + ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) + + if ret is NotImplemented: + continue + # Convert ret to Tensor if it is a core.Tensor type. + if isinstance(ret, core.Tensor): + to_tensor = getattr(ret, "__tf_tensor__", None) + ret = ( + to_tensor() # pylint: disable=not-callable + if to_tensor is not None + else ret + ) + if not isinstance(ret, accepted_result_types): + raise RuntimeError( + _add_error_prefix( + f"Conversion function {conversion_func!r} for type " + f"{base_type} returned non-Tensor: {ret!r}", + name=name)) + if dtype and not dtype.is_compatible_with(ret.dtype): + raise RuntimeError( + _add_error_prefix( + f"Conversion function {conversion_func} for type {base_type} " + f"returned incompatible dtype: requested = {dtype.name}, " + f"actual = {ret.dtype.name}", + name=name)) + return ret + raise TypeError( + _add_error_prefix( + f"Cannot convert {value!r} with type {type(value)} to Tensor: " + f"no conversion function registered.", + name=name)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_shape.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_shape.py new file mode 100644 index 0000000000000000000000000000000000000000..24d2f7683207849635d464e448d2addb1b013412 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_shape.py @@ -0,0 +1,1572 @@ +# 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. +# ============================================================================== +"""Helper classes for tensor shape inference.""" +import functools +import operator +from typing import Optional, Sequence, Type, Union + +from tensorflow.core.framework import tensor_shape_pb2 +from tensorflow.core.function import trace_type +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python import tf2 +from tensorflow.python.eager import monitoring +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import trace +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + +_TENSORSHAPE_V2_OVERRIDE = None + +_api_usage_gauge = monitoring.BoolGauge( + "/tensorflow/api/v2_tensorshape", + "Whether tensor_shape.enable_v2_tensorshape() is called.") + + +@tf_export(v1=["enable_v2_tensorshape"]) +def enable_v2_tensorshape(): + """In TensorFlow 2.0, iterating over a TensorShape instance returns values. + + This enables the new behavior. + + Concretely, `tensor_shape[i]` returned a Dimension instance in V1, but + it V2 it returns either an integer, or None. + + Examples: + + ``` + ####################### + # If you had this in V1: + value = tensor_shape[i].value + + # Do this in V2 instead: + value = tensor_shape[i] + + ####################### + # If you had this in V1: + for dim in tensor_shape: + value = dim.value + print(value) + + # Do this in V2 instead: + for value in tensor_shape: + print(value) + + ####################### + # If you had this in V1: + dim = tensor_shape[i] + dim.assert_is_compatible_with(other_shape) # or using any other shape method + + # Do this in V2 instead: + if tensor_shape.rank is None: + dim = Dimension(None) + else: + dim = tensor_shape.dims[i] + dim.assert_is_compatible_with(other_shape) # or using any other shape method + + # The V2 suggestion above is more explicit, which will save you from + # the following trap (present in V1): + # you might do in-place modifications to `dim` and expect them to be reflected + # in `tensor_shape[i]`, but they would not be. + ``` + """ + global _TENSORSHAPE_V2_OVERRIDE # pylint: disable=invalid-name + _TENSORSHAPE_V2_OVERRIDE = True + logging.vlog(1, "Enabling v2 tensorshape") + _api_usage_gauge.get_cell().set(True) + + +@tf_export(v1=["disable_v2_tensorshape"]) +def disable_v2_tensorshape(): + """Disables the V2 TensorShape behavior and reverts to V1 behavior. + + See docstring for `enable_v2_tensorshape` for details about the new behavior. + """ + global _TENSORSHAPE_V2_OVERRIDE # pylint: disable=invalid-name + _TENSORSHAPE_V2_OVERRIDE = False + logging.vlog(1, "Disabling v2 tensorshape") + _api_usage_gauge.get_cell().set(False) + + +@tf_export( + "compat.dimension_value", v1=["dimension_value", "compat.dimension_value"] +) +def dimension_value( + dimension: Union["Dimension", int, None] +) -> Union[int, None]: + """Compatibility utility required to allow for both V1 and V2 behavior in TF. + + Until the release of TF 2.0, we need the legacy behavior of `TensorShape` to + coexist with the new behavior. This utility is a bridge between the two. + + When accessing the value of a TensorShape dimension, + use this utility, like this: + + ``` + # If you had this in your V1 code: + value = tensor_shape[i].value + + # Use `dimension_value` as direct replacement compatible with both V1 & V2: + value = dimension_value(tensor_shape[i]) + + # This would be the V2 equivalent: + value = tensor_shape[i] # Warning: this will return the dim value in V2! + ``` + + Args: + dimension: Either a `Dimension` instance, an integer, or None. + + Returns: + A plain value, i.e. an integer or None. + """ + if isinstance(dimension, Dimension): + return dimension.value + return dimension + + +@tf_export( + "compat.dimension_at_index", + v1=["dimension_at_index", "compat.dimension_at_index"]) +def dimension_at_index(shape, index) -> "Dimension": + """Compatibility utility required to allow for both V1 and V2 behavior in TF. + + Until the release of TF 2.0, we need the legacy behavior of `TensorShape` to + coexist with the new behavior. This utility is a bridge between the two. + + If you want to retrieve the Dimension instance corresponding to a certain + index in a TensorShape instance, use this utility, like this: + + ``` + # If you had this in your V1 code: + dim = tensor_shape[i] + + # Use `dimension_at_index` as direct replacement compatible with both V1 & V2: + dim = dimension_at_index(tensor_shape, i) + + # Another possibility would be this, but WARNING: it only works if the + # tensor_shape instance has a defined rank. + dim = tensor_shape.dims[i] # `dims` may be None if the rank is undefined! + + # In native V2 code, we recommend instead being more explicit: + if tensor_shape.rank is None: + dim = Dimension(None) + else: + dim = tensor_shape.dims[i] + + # Being more explicit will save you from the following trap (present in V1): + # you might do in-place modifications to `dim` and expect them to be reflected + # in `tensor_shape[i]`, but they would not be (as the Dimension object was + # instantiated on the fly. + ``` + + Args: + shape: A TensorShape instance. + index: An integer index. + + Returns: + A dimension object. + """ + assert isinstance(shape, TensorShape) + if shape.rank is None: + return Dimension(None) + else: + return shape.dims[index] + + +@tf_export(v1=["Dimension"]) +class Dimension(object): + """Represents the value of one dimension in a TensorShape. + + @compatibility(TF2) + In TF2, members of a `TensorShape` object are integers. The `Dimension` class + is not part of TF2's data model. + + Please refer to the [TensorShape section of the migration guide] + (https://www.tensorflow.org/guide/migrate/index#tensorshape) on common code + patterns adapting Dimension objects to a TF2 syntax. + @end_compatibility + """ + + __slots__ = ["_value"] + + def __init__(self, value): + """Creates a new Dimension with the given value.""" + if isinstance(value, int): # Most common case. + if value < 0: + raise ValueError("Dimension %d must be >= 0" % value) + self._value = value + elif value is None: + self._value = None + elif isinstance(value, Dimension): + self._value = value._value + else: + try: + # int(...) compensates for the int/long dichotomy on Python 2.X. + # TODO(b/143206389): Remove once we fully migrate to 3.X. + self._value = int(value.__index__()) + except AttributeError: + raise TypeError( + "Dimension value must be integer or None or have " + "an __index__ method, got value '{0!r}' with type '{1!r}'".format( + value, type(value))) from None + if self._value < 0: + raise ValueError("Dimension %d must be >= 0" % self._value) + + def __repr__(self): + return "Dimension(%s)" % repr(self._value) + + def __str__(self): + value = self._value + return "?" if value is None else str(value) + + def __eq__(self, other): + """Returns true if `other` has the same known value as this Dimension.""" + try: + other = as_dimension(other) + except (TypeError, ValueError): + return NotImplemented + if self._value is None or other.value is None: + return None + return self._value == other.value + + def __ne__(self, other): + """Returns true if `other` has a different known value from `self`.""" + try: + other = as_dimension(other) + except (TypeError, ValueError): + return NotImplemented + if self._value is None or other.value is None: + return None + return self._value != other.value + + def __bool__(self): + """Equivalent to `bool(self.value)`.""" + return bool(self._value) + + def __int__(self): + return self._value + + # This is needed for Windows. + # See https://github.com/tensorflow/tensorflow/pull/9780 + def __long__(self): + return self._value + + def __index__(self): + # Allow use in Python 3 range + return self._value + + @property + def value(self): + """The value of this dimension, or None if it is unknown.""" + return self._value + + # TODO(b/225058047): Reconsider semantics. + def is_compatible_with(self, other): + """Returns true if `other` is compatible with this Dimension. + + Two known Dimensions are compatible if they have the same value. + An unknown Dimension is compatible with all other Dimensions. + + Args: + other: Another Dimension. + + Returns: + True if this Dimension and `other` are compatible. + """ + other = as_dimension(other) + return (self._value is None or other.value is None or + self._value == other.value) + + def assert_is_compatible_with(self, other): + """Raises an exception if `other` is not compatible with this Dimension. + + Args: + other: Another Dimension. + + Raises: + ValueError: If `self` and `other` are not compatible (see + is_compatible_with). + """ + if not self.is_compatible_with(other): + raise ValueError("Dimensions %s and %s are not compatible" % + (self, other)) + + def merge_with(self, other): + """Returns a Dimension that combines the information in `self` and `other`. + + Dimensions are combined as follows: + + ```python + tf.compat.v1.Dimension(n) .merge_with(tf.compat.v1.Dimension(n)) == + tf.compat.v1.Dimension(n) + tf.compat.v1.Dimension(n) .merge_with(tf.compat.v1.Dimension(None)) == + tf.compat.v1.Dimension(n) + tf.compat.v1.Dimension(None).merge_with(tf.compat.v1.Dimension(n)) == + tf.compat.v1.Dimension(n) + # equivalent to tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None).merge_with(tf.compat.v1.Dimension(None)) + + # raises ValueError for n != m + tf.compat.v1.Dimension(n) .merge_with(tf.compat.v1.Dimension(m)) + ``` + + Args: + other: Another Dimension. + + Returns: + A Dimension containing the combined information of `self` and + `other`. + + Raises: + ValueError: If `self` and `other` are not compatible (see + is_compatible_with). + """ + other = as_dimension(other) + self.assert_is_compatible_with(other) + if self._value is None: + return Dimension(other.value) + else: + return Dimension(self._value) + + def __add__(self, other): + """Returns the sum of `self` and `other`. + + Dimensions are summed as follows: + + ```python + tf.compat.v1.Dimension(m) + tf.compat.v1.Dimension(n) == + tf.compat.v1.Dimension(m + n) + tf.compat.v1.Dimension(m) + tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(n) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + ``` + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is the sum of `self` and `other`. + """ + try: + other = as_dimension(other) + except (TypeError, ValueError): + return NotImplemented + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(self._value + other.value) + + def __radd__(self, other): + """Returns the sum of `other` and `self`. + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is the sum of `self` and `other`. + """ + return self + other + + def __sub__(self, other): + """Returns the subtraction of `other` from `self`. + + Dimensions are subtracted as follows: + + ```python + tf.compat.v1.Dimension(m) - tf.compat.v1.Dimension(n) == + tf.compat.v1.Dimension(m - n) + tf.compat.v1.Dimension(m) - tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(n) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + ``` + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is the subtraction of `other` from `self`. + """ + try: + other = as_dimension(other) + except (TypeError, ValueError): + return NotImplemented + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(self._value - other.value) + + def __rsub__(self, other): + """Returns the subtraction of `self` from `other`. + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is the subtraction of `self` from `other`. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(other.value - self._value) + + def __mul__(self, other): + """Returns the product of `self` and `other`. + + Dimensions are summed as follows: + + ```python + tf.compat.v1.Dimension(m) * tf.compat.v1.Dimension(n) == + tf.compat.v1.Dimension(m * n) + tf.compat.v1.Dimension(m) * tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(n) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + ``` + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is the product of `self` and `other`. + """ + try: + other = as_dimension(other) + except (TypeError, ValueError): + return NotImplemented + + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(self._value * other.value) + + def __rmul__(self, other): + """Returns the product of `self` and `other`. + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is the product of `self` and `other`. + """ + return self * other + + def __floordiv__(self, other): + """Returns the quotient of `self` and `other` rounded down. + + Dimensions are divided as follows: + + ```python + tf.compat.v1.Dimension(m) // tf.compat.v1.Dimension(n) == + tf.compat.v1.Dimension(m // n) + tf.compat.v1.Dimension(m) // tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) // tf.compat.v1.Dimension(n) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) // tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + ``` + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A `Dimension` whose value is the integer quotient of `self` and `other`. + """ + try: + other = as_dimension(other) + except (TypeError, ValueError): + return NotImplemented + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(self._value // other.value) + + def __rfloordiv__(self, other): + """Returns the quotient of `other` and `self` rounded down. + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A `Dimension` whose value is the integer quotient of `self` and `other`. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(other.value // self._value) + + def __div__(self, other): + """DEPRECATED: Use `__floordiv__` via `x // y` instead. + + This function exists only for backwards compatibility purposes; new code + should use `__floordiv__` via the syntax `x // y`. Using `x // y` + communicates clearly that the result rounds down, and is forward compatible + to Python 3. + + Args: + other: Another `Dimension`. + + Returns: + A `Dimension` whose value is the integer quotient of `self` and `other`. + """ + return self // other + + def __rdiv__(self, other): + """Use `__floordiv__` via `x // y` instead. + + This function exists only to have a better error message. Instead of: + `TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`, + this function will explicitly call for usage of `//` instead. + + Args: + other: Another `Dimension`. + + Raises: + TypeError. + """ + raise TypeError("unsupported operand type(s) for /: '{}' and 'Dimension', " + "please use // instead".format(type(other).__name__)) + + def __truediv__(self, other): + """Use `__floordiv__` via `x // y` instead. + + This function exists only to have a better error message. Instead of: + `TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'`, + this function will explicitly call for usage of `//` instead. + + Args: + other: Another `Dimension`. + + Raises: + TypeError. + """ + raise TypeError("unsupported operand type(s) for /: 'Dimension' and '{}', " + "please use // instead".format(type(other).__name__)) + + def __rtruediv__(self, other): + """Use `__floordiv__` via `x // y` instead. + + This function exists only to have a better error message. Instead of: + `TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`, + this function will explicitly call for usage of `//` instead. + + Args: + other: Another `Dimension`. + + Raises: + TypeError. + """ + raise TypeError("unsupported operand type(s) for /: '{}' and 'Dimension', " + "please use // instead".format(type(other).__name__)) + + def __mod__(self, other): + """Returns `self` modulo `other`. + + Dimension modulo are computed as follows: + + ```python + tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(n) == + tf.compat.v1.Dimension(m % n) + tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(n) # equiv. to + tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(None) # equiv. to + tf.compat.v1.Dimension(None) + ``` + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is `self` modulo `other`. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return Dimension(None) + else: + return Dimension(self._value % other.value) + + def __rmod__(self, other): + """Returns `other` modulo `self`. + + Args: + other: Another Dimension, or a value accepted by `as_dimension`. + + Returns: + A Dimension whose value is `other` modulo `self`. + """ + other = as_dimension(other) + return other % self + + def __lt__(self, other): + """Returns True if `self` is known to be less than `other`. + + Dimensions are compared as follows: + + ```python + (tf.compat.v1.Dimension(m) < tf.compat.v1.Dimension(n)) == (m < n) + (tf.compat.v1.Dimension(m) < tf.compat.v1.Dimension(None)) == None + (tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(n)) == None + (tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(None)) == None + ``` + + Args: + other: Another Dimension. + + Returns: + The value of `self.value < other.value` if both are known, otherwise + None. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return None + else: + return self._value < other.value + + def __le__(self, other): + """Returns True if `self` is known to be less than or equal to `other`. + + Dimensions are compared as follows: + + ```python + (tf.compat.v1.Dimension(m) <= tf.compat.v1.Dimension(n)) == (m <= n) + (tf.compat.v1.Dimension(m) <= tf.compat.v1.Dimension(None)) == None + (tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(n)) == None + (tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(None)) == None + ``` + + Args: + other: Another Dimension. + + Returns: + The value of `self.value <= other.value` if both are known, otherwise + None. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return None + else: + return self._value <= other.value + + def __gt__(self, other): + """Returns True if `self` is known to be greater than `other`. + + Dimensions are compared as follows: + + ```python + (tf.compat.v1.Dimension(m) > tf.compat.v1.Dimension(n)) == (m > n) + (tf.compat.v1.Dimension(m) > tf.compat.v1.Dimension(None)) == None + (tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(n)) == None + (tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(None)) == None + ``` + + Args: + other: Another Dimension. + + Returns: + The value of `self.value > other.value` if both are known, otherwise + None. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return None + else: + return self._value > other.value + + def __ge__(self, other): + """Returns True if `self` is known to be greater than or equal to `other`. + + Dimensions are compared as follows: + + ```python + (tf.compat.v1.Dimension(m) >= tf.compat.v1.Dimension(n)) == (m >= n) + (tf.compat.v1.Dimension(m) >= tf.compat.v1.Dimension(None)) == None + (tf.compat.v1.Dimension(None) >= tf.compat.v1.Dimension(n)) == None + (tf.compat.v1.Dimension(None) >= tf.compat.v1.Dimension(None)) == None + ``` + + Args: + other: Another Dimension. + + Returns: + The value of `self.value >= other.value` if both are known, otherwise + None. + """ + other = as_dimension(other) + if self._value is None or other.value is None: + return None + else: + return self._value >= other.value + + def __reduce__(self): + return Dimension, (self._value,) + + +def as_dimension(value): + """Converts the given value to a Dimension. + + A Dimension input will be returned unmodified. + An input of `None` will be converted to an unknown Dimension. + An integer input will be converted to a Dimension with that value. + + Args: + value: The value to be converted. + + Returns: + A Dimension corresponding to the given value. + """ + if isinstance(value, Dimension): + return value + else: + return Dimension(value) + + +@tf_export("TensorShape") +class TensorShape(trace.TraceType, trace_type.Serializable): + """Represents the shape of a `Tensor`. + + >>> t = tf.constant([[1,2,3],[4,5,6]]) + >>> t.shape + TensorShape([2, 3]) + + `TensorShape` is the *static* shape representation of a Tensor. + During eager execution a Tensor always has a fully specified shape but + when tracing a `tf.function` it may be one of the following: + + * *Fully-known shape:* has a known number of dimensions and a known size + for each dimension. e.g. `TensorShape([16, 256])` + * *Partially-known shape:* has a known number of dimensions, and an unknown + size for one or more dimension. e.g. `TensorShape([None, 256])` + * *Unknown shape:* has an unknown number of dimensions, and an unknown + size in all dimensions. e.g. `TensorShape(None)` + + During function tracing `t.shape` will return a `TensorShape` object + representing the shape of Tensor as it is known during tracing. + This static representation will be partially defined in cases where the + exact shape depends on the values within the tensors. To get the + *dynamic* representation, please use `tf.shape(t)` + which will return Tensor representing the fully defined shape of `t`. + This way, you can express logic that manipulates the shapes of tensors by + building other tensors that depend on the dynamic shape of `t`. + + Note: `tf.RaggedTensor.shape` also returns a `tf.TensorShape`, + the lengths of any ragged dimensions are unknown (`None`). + + For example, this function prints the `TensorShape' (`t.shape`), when you + trace the function, and returns a tensor `tf.shape(t)` for given input `t`: + + >>> @tf.function + ... def get_dynamic_shape(t): + ... print("tracing...") + ... print(f"static shape is {t.shape}") + ... return tf.shape(t) + + Just calling the function traces it with a fully-specified static shape: + + >>> result = get_dynamic_shape(tf.constant([[1, 1, 1], [0, 0, 0]])) + tracing... + static shape is (2, 3) + >>> result.numpy() + array([2, 3], dtype=int32) + + But `tf.function` can also trace the function with a partially specified + (or even unspecified) shape: + + >>> cf1 = get_dynamic_shape.get_concrete_function(tf.TensorSpec( + ... shape=[None, 2])) + tracing... + static shape is (None, 2) + >>> cf1(tf.constant([[1., 0],[1, 0],[1, 0]])).numpy() + array([3, 2], dtype=int32) + + >>> cf2 = get_dynamic_shape.get_concrete_function(tf.TensorSpec(shape=None)) + tracing... + static shape is + >>> cf2(tf.constant([[[[[1., 0]]]]])).numpy() + array([1, 1, 1, 1, 2], dtype=int32) + + If a tensor is produced by an operation of type `"Foo"`, its shape + may be inferred if there is a registered shape function for + `"Foo"`. See [Shape + functions](https://www.tensorflow.org/guide/create_op#shape_functions_in_c) + for details of shape functions and how to register them. Alternatively, + you may set the shape explicitly using `tf.Tensor.ensure_shape`. + """ + __slots__ = ["_dims"] + + def __init__(self, dims): + """Creates a new TensorShape with the given dimensions. + + Args: + dims: A list of Dimensions, or None if the shape is unspecified. + + Raises: + TypeError: If dims cannot be converted to a list of dimensions. + """ + if isinstance(dims, (tuple, list)): # Most common case. + self._dims = tuple(as_dimension(d).value for d in dims) + elif dims is None: + self._dims = None + elif isinstance(dims, tensor_shape_pb2.TensorShapeProto): + if dims.unknown_rank: + self._dims = None + else: + self._dims = tuple( + # Protos store variable-size dimensions as -1 + dim.size if dim.size != -1 else None + for dim in dims.dim + ) + elif isinstance(dims, TensorShape): + self._dims = dims._dims + else: + try: + dims_iter = iter(dims) + except TypeError: + # Treat as a singleton dimension + self._dims = (as_dimension(dims).value,) + else: + self._dims = [] + for d in dims_iter: + try: + self._dims.append(as_dimension(d).value) + except TypeError as e: + raise TypeError( + "Failed to convert '{0!r}' to a shape: '{1!r}'" + "could not be converted to a dimension. A shape should " + "either be single dimension (e.g. 10), or an iterable of " + "dimensions (e.g. [1, 10, None]).".format(dims, d)) from e + self._dims = tuple(self._dims) + + @property + def _v2_behavior(self): + if _TENSORSHAPE_V2_OVERRIDE is None: + return tf2.enabled() + return _TENSORSHAPE_V2_OVERRIDE + + def __repr__(self): + if self._v2_behavior: + if self._dims is not None: + return f"TensorShape({list(self._dims)})" + else: + return "TensorShape(None)" + else: + return f"TensorShape({self.dims})" + + def __str__(self): + if self.rank is None: + return "" + elif self.rank == 1: + if self._v2_behavior: + return "(%s,)" % self._dims[0] + else: + return "(%s,)" % self.dims[0] + else: + if self._v2_behavior: + return "(%s)" % ", ".join(str(d) for d in self._dims) + else: + return "(%s)" % ", ".join(str(d) for d in self.dims) + + @property + def rank(self): + """Returns the rank of this shape, or None if it is unspecified.""" + if self._dims is not None: + return len(self._dims) + return None + + @property + def dims(self): + """Deprecated. Returns list of dimensions for this shape. + + Suggest `TensorShape.as_list` instead. + + Returns: + A list containing `tf.compat.v1.Dimension`s, or None if the shape is + unspecified. + """ + if self._dims is None: + return None + return [as_dimension(d) for d in self._dims] + + @property + def ndims(self): + """Deprecated accessor for `rank`.""" + return self.rank + + def __len__(self): + """Returns the rank of this shape, or raises ValueError if unspecified.""" + if self._dims is None: + raise ValueError("Cannot take the length of shape with unknown rank.") + return len(self._dims) + + def __bool__(self): + """Returns True if this shape contains non-zero information.""" + return self._dims is not None + + # Python 3 wants __bool__, Python 2.7 wants __nonzero__ + __nonzero__ = __bool__ + + def __iter__(self): + """Returns `self.dims` if the rank is known, otherwise raises ValueError.""" + if self._dims is None: + raise ValueError("Cannot iterate over a shape with unknown rank.") + else: + if self._v2_behavior: + return iter(d for d in self._dims) + else: + return iter(d for d in self.dims) + + def __getitem__(self, key): + """Returns the value of a dimension or a shape, depending on the key. + + Args: + key: If `key` is an integer, returns the dimension at that index; + otherwise if `key` is a slice, returns a TensorShape whose dimensions + are those selected by the slice from `self`. + + Returns: + An integer if `key` is an integer, or a `TensorShape` if `key` is a + slice. + + Raises: + ValueError: If `key` is a slice and `self` is completely unknown and + the step is set. + """ + if self._dims is not None: + if isinstance(key, slice): + return TensorShape(self._dims[key]) + else: + if self._v2_behavior: + return self._dims[key] + else: + return self.dims[key] + else: + if isinstance(key, slice): + start = key.start if key.start is not None else 0 + stop = key.stop + + if key.step is not None: + # TODO(mrry): Handle these maybe. + raise ValueError("Steps are not yet handled") + if stop is None: + # NOTE(mrry): This implies that TensorShape(None) is compatible with + # TensorShape(None)[1:], which is obviously not true. It would be + # possible to track the number of dimensions symbolically, + # and perhaps we should do that. + return unknown_shape() + elif start < 0 or stop < 0: + # TODO(mrry): Handle this better, as it will be useful for handling + # suffixes of otherwise unknown shapes. + return unknown_shape() + else: + return unknown_shape(rank=stop - start) + else: + if self._v2_behavior: + return None + else: + return Dimension(None) + + def num_elements(self): + """Returns the total number of elements, or none for incomplete shapes.""" + if self.is_fully_defined(): + return functools.reduce(operator.mul, self.as_list(), 1) + else: + return None + + def merge_with(self, other): + """Returns a `TensorShape` combining the information in `self` and `other`. + + The dimensions in `self` and `other` are merged element-wise, + according to the rules below: + + ```python + Dimension(n).merge_with(Dimension(None)) == Dimension(n) + Dimension(None).merge_with(Dimension(n)) == Dimension(n) + Dimension(None).merge_with(Dimension(None)) == Dimension(None) + # raises ValueError for n != m + Dimension(n).merge_with(Dimension(m)) + ``` + >> ts = tf.TensorShape([1,2]) + >> ot1 = tf.TensorShape([1,2]) + >> ts.merge_with(ot).as_list() + [1,2] + + >> ot2 = tf.TensorShape([1,None]) + >> ts.merge_with(ot2).as_list() + [1,2] + + >> ot3 = tf.TensorShape([None, None]) + >> ot3.merge_with(ot2).as_list() + [1, None] + + Args: + other: Another `TensorShape`. + + Returns: + A `TensorShape` containing the combined information of `self` and + `other`. + + Raises: + ValueError: If `self` and `other` are not compatible. + """ + other = as_shape(other) + if self.dims is None: + return other + if other.dims is None: + return self + else: + try: + self.assert_same_rank(other) + new_dims = [ + dim.merge_with(other_dim) + for dim, other_dim in zip(self.dims, other.dims) + ] + return TensorShape(new_dims) + except ValueError: + raise ValueError("Shapes %s and %s are not compatible" % (self, other)) + + def __add__(self, other): + return self.concatenate(other) + + def __radd__(self, other): + if not isinstance(other, TensorShape): + other = TensorShape(other) + return other.concatenate(self) + + def concatenate(self, other): + """Returns the concatenation of the dimension in `self` and `other`. + + *N.B.* If either `self` or `other` is completely unknown, + concatenation will discard information about the other shape. In + future, we might support concatenation that preserves this + information for use with slicing. + + Args: + other: Another `TensorShape`. + + Returns: + A `TensorShape` whose dimensions are the concatenation of the + dimensions in `self` and `other`. + """ + # TODO(mrry): Handle the case where we concatenate a known shape with a + # completely unknown shape, so that we can use the partial information. + other = as_shape(other) + if self.dims is None or other.dims is None: + return unknown_shape() + else: + return TensorShape(self.dims + other.dims) + + def assert_same_rank(self, other): + """Raises an exception if `self` and `other` do not have compatible ranks. + + Args: + other: Another `TensorShape`. + + Raises: + ValueError: If `self` and `other` do not represent shapes with the + same rank. + """ + other = as_shape(other) + if self.rank is not None and other.rank is not None: + if self.rank != other.rank: + raise ValueError("Shapes %s and %s must have the same rank" % + (self, other)) + + def assert_has_rank(self, rank): + """Raises an exception if `self` is not compatible with the given `rank`. + + Args: + rank: An integer. + + Raises: + ValueError: If `self` does not represent a shape with the given `rank`. + """ + if self.rank not in (None, rank): + raise ValueError("Shape %s must have rank %d" % (self, rank)) + + def with_rank(self, rank): + """Returns a shape based on `self` with the given rank. + + This method promotes a completely unknown shape to one with a + known rank. + + Args: + rank: An integer. + + Returns: + A shape that is at least as specific as `self` with the given rank. + + Raises: + ValueError: If `self` does not represent a shape with the given `rank`. + """ + try: + return self.merge_with(unknown_shape(rank=rank)) + except ValueError: + raise ValueError("Shape %s must have rank %d" % (self, rank)) + + def with_rank_at_least(self, rank): + """Returns a shape based on `self` with at least the given rank. + + Args: + rank: An integer. + + Returns: + A shape that is at least as specific as `self` with at least the given + rank. + + Raises: + ValueError: If `self` does not represent a shape with at least the given + `rank`. + """ + if self.rank is not None and self.rank < rank: + raise ValueError("Shape %s must have rank at least %d" % (self, rank)) + else: + return self + + def with_rank_at_most(self, rank): + """Returns a shape based on `self` with at most the given rank. + + Args: + rank: An integer. + + Returns: + A shape that is at least as specific as `self` with at most the given + rank. + + Raises: + ValueError: If `self` does not represent a shape with at most the given + `rank`. + """ + if self.rank is not None and self.rank > rank: + raise ValueError("Shape %s must have rank at most %d" % (self, rank)) + else: + return self + + def is_subtype_of(self, other: trace.TraceType) -> bool: + """Returns True iff `self` is subtype of `other`. + + Shape A is a subtype of shape B if shape B can successfully represent it: + + * A `TensorShape` of any rank is a subtype of `TensorShape(None)`. + + * TensorShapes of equal ranks are covariant, i.e. + `TensorShape([A1, A2, ..])` is a subtype of + `TensorShape([B1, B2, ..])` iff An is a subtype of Bn. + + An is subtype of Bn iff An == Bn or Bn is None. + + * TensorShapes of different defined ranks have no subtyping relation. + + The subtyping relation is reflexive and transitive, but not symmetric. + + Some examples: + * `TensorShape([32, 784])` is a subtype of `TensorShape(None)`, and + `TensorShape([4, 4])` is also a subtype of `TensorShape(None)` but + `TensorShape([32, 784])` and `TensorShape([4, 4])` are not subtypes of + each other. + + * All two-dimensional shapes are subtypes of `TensorShape([None, None])`, + such as `TensorShape([32, 784])`. There is no subtype relationship with, + for example, `TensorShape([None])` or `TensorShape([None, None, None])`. + + * `TensorShape([32, None])` is also a subtype of `TensorShape([None, None])` + and `TensorShape(None)`. It is not a subtype of, for example, + `TensorShape([32])`, `TensorShape([32, None, 1])`, + `TensorShape([64, None])` or `TensorShape([None, 32])`. + + * `TensorShape([32, 784])` is a subtype of itself, and also + `TensorShape([32, None])`, `TensorShape([None, 784])`, + `TensorShape([None, None])` and `TensorShape(None)`. + It has no subtype relation with, for example, `TensorShape([32, 1, 784])` + or `TensorShape([None])`. + + Args: + other: Another `TensorShape`. + + Returns: + True iff `self` is subtype of `other`. + + """ + if not isinstance(other, TensorShape): + return False + + # All Tensors are subtypes of a Tensor with no shape. + if other.rank is None: + return True + + # Tensor with a defined shape can only be subtype of another with a defined + # shape if they have the same number of dimensions. + if self.rank != other.rank: + return False + + # A Tensor is a subtype if each corresponding dimension is a subtype. + return all(o is None or s == o for s, o in zip(self._dims, other._dims)) # pylint: disable=protected-access + + def most_specific_common_supertype( + self, others: Sequence[trace.TraceType]) -> Optional["TensorShape"]: + """Returns the most specific supertype `TensorShape` of self and others. + + * `TensorShape([None, 1])` is the most specific `TensorShape` supertyping + both `TensorShape([2, 1])` and `TensorShape([5, 1])`. Note that + `TensorShape(None)` is also a supertype but it is not "most specific". + + * `TensorShape([1, 2, 3])` is the most specific `TensorShape` supertyping + both `TensorShape([1, 2, 3])` and `TensorShape([1, 2, 3]`). There are + other less specific TensorShapes that supertype above mentioned + TensorShapes, e.g. `TensorShape([1, 2, None])`, `TensorShape(None)`. + + * `TensorShape([None, None])` is the most specific `TensorShape` + supertyping both `TensorShape([2, None])` and `TensorShape([None, 3])`. + As always, `TensorShape(None)` is also a supertype but not the most + specific one. + + * `TensorShape(None`) is the only `TensorShape` supertyping both + `TensorShape([1, 2, 3])` and `TensorShape([1, 2])`. In general, any two + shapes that have different ranks will only have `TensorShape(None)` + as a common supertype. + + * `TensorShape(None)` is the only `TensorShape` supertyping both + `TensorShape([1, 2, 3])` and `TensorShape(None)`. In general, the common + supertype of any shape with `TensorShape(None)` is `TensorShape(None)`. + + Args: + others: Sequence of `TensorShape`. + + Returns: + A `TensorShape` which is the most specific supertype shape of `self` + and `others`. None if it does not exist. + """ + if any(not isinstance(other, TensorShape) for other in others): + return None + + # A Rankless TensorShape is already a global supertype so we return another + # instance of it. + if self.rank is None: + return unknown_shape() + + # A Rankless TensorShape is the most specific supertype for shapes whose + # ranks do not match. + if any(other.dims is None or self.rank != other.rank for other in others): + return unknown_shape() + + # Retain the integer dimension if it is the same across all others, else + # use an undefined dimension. + dims = [ + dim if all(dim == other._dims[i] + for other in others) else None + for i, dim in enumerate(self._dims) + ] + return TensorShape(dims) + + @doc_controls.do_not_doc_inheritable + def placeholder_value(self, placeholder_context): + """See tf.types.experimental.TraceType base class.""" + return super().placeholder_value(placeholder_context) + + @doc_controls.do_not_doc_inheritable + def from_tensors(self, tensors): + """See tf.types.experimental.TraceType base class.""" + return super().from_tensors(tensors) + + @doc_controls.do_not_doc_inheritable + def to_tensors(self, value): + """See tf.types.experimental.TraceType base class.""" + return super().to_tensors(value) + + @doc_controls.do_not_doc_inheritable + def flatten(self): + """See tf.types.experimental.TraceType base class.""" + return super().flatten() + + @doc_controls.do_not_doc_inheritable + def cast(self, value, cast_context): + """See tf.types.experimental.TraceType base class.""" + return super().cast(value, cast_context) + + @classmethod + def experimental_type_proto(cls) -> Type[tensor_shape_pb2.TensorShapeProto]: + """Returns the type of proto associated with TensorShape serialization.""" + return tensor_shape_pb2.TensorShapeProto + + @classmethod + def experimental_from_proto( + cls, proto: tensor_shape_pb2.TensorShapeProto) -> "TensorShape": + """Returns a TensorShape instance based on the serialized proto.""" + return TensorShape(proto) + + def experimental_as_proto(self) -> tensor_shape_pb2.TensorShapeProto: + """Returns a proto representation of the TensorShape instance.""" + return self.as_proto() + + # TODO(b/216206374): Consider deprecation at TraceType release. + def is_compatible_with(self, other): + """Returns True iff `self` is compatible with `other`. + + Two possibly-partially-defined shapes are compatible if there + exists a fully-defined shape that both shapes can represent. Thus, + compatibility allows the shape inference code to reason about + partially-defined shapes. For example: + + * TensorShape(None) is compatible with all shapes. + + * TensorShape([None, None]) is compatible with all two-dimensional + shapes, such as TensorShape([32, 784]), and also TensorShape(None). It is + not compatible with, for example, TensorShape([None]) or + TensorShape([None, None, None]). + + * TensorShape([32, None]) is compatible with all two-dimensional shapes + with size 32 in the 0th dimension, and also TensorShape([None, None]) + and TensorShape(None). It is not compatible with, for example, + TensorShape([32]), TensorShape([32, None, 1]) or TensorShape([64, None]). + + * TensorShape([32, 784]) is compatible with itself, and also + TensorShape([32, None]), TensorShape([None, 784]), TensorShape([None, + None]) and TensorShape(None). It is not compatible with, for example, + TensorShape([32, 1, 784]) or TensorShape([None]). + + The compatibility relation is reflexive and symmetric, but not + transitive. For example, TensorShape([32, 784]) is compatible with + TensorShape(None), and TensorShape(None) is compatible with + TensorShape([4, 4]), but TensorShape([32, 784]) is not compatible with + TensorShape([4, 4]). + + Args: + other: Another TensorShape. + + Returns: + True iff `self` is compatible with `other`. + + """ + other = as_shape(other) + if self.dims is not None and other.dims is not None: + if self.rank != other.rank: + return False + for x_dim, y_dim in zip(self.dims, other.dims): + if not x_dim.is_compatible_with(y_dim): + return False + return True + + def assert_is_compatible_with(self, other): + """Raises exception if `self` and `other` do not represent the same shape. + + This method can be used to assert that there exists a shape that both + `self` and `other` represent. + + Args: + other: Another TensorShape. + + Raises: + ValueError: If `self` and `other` do not represent the same shape. + """ + if not self.is_compatible_with(other): + raise ValueError("Shapes %s and %s are incompatible" % (self, other)) + + def most_specific_compatible_shape(self, other) -> "TensorShape": + """Returns the most specific TensorShape compatible with `self` and `other`. + + * TensorShape([None, 1]) is the most specific TensorShape compatible with + both TensorShape([2, 1]) and TensorShape([5, 1]). Note that + TensorShape(None) is also compatible with above mentioned TensorShapes. + + * TensorShape([1, 2, 3]) is the most specific TensorShape compatible with + both TensorShape([1, 2, 3]) and TensorShape([1, 2, 3]). There are more + less specific TensorShapes compatible with above mentioned TensorShapes, + e.g. TensorShape([1, 2, None]), TensorShape(None). + + Args: + other: Another `TensorShape`. + + Returns: + A `TensorShape` which is the most specific compatible shape of `self` + and `other`. + """ + + other = as_shape(other) + if self.dims is None or other.dims is None or self.rank != other.rank: + return unknown_shape() + + dims = [ + d1 if d1 is not None and d2 is not None and d1 == d2 else None + for d1, d2 in zip(self.dims, other.dims) + ] + return TensorShape(dims) + + def is_fully_defined(self): + """Returns True iff `self` is fully defined in every dimension.""" + return (self._dims is not None and + all(dim is not None for dim in self._dims)) + + def assert_is_fully_defined(self): + """Raises an exception if `self` is not fully defined in every dimension. + + Raises: + ValueError: If `self` does not have a known value for every dimension. + """ + if not self.is_fully_defined(): + raise ValueError("Shape %s is not fully defined" % self) + + def as_list(self): + """Returns a list of integers or `None` for each dimension. + + Returns: + A list of integers or `None` for each dimension. + + Raises: + ValueError: If `self` is an unknown shape with an unknown rank. + """ + if self._dims is None: + raise ValueError("as_list() is not defined on an unknown TensorShape.") + return list(self._dims) + + def as_proto(self): + """Returns this shape as a `TensorShapeProto`.""" + if self._dims is None: + return tensor_shape_pb2.TensorShapeProto(unknown_rank=True) + else: + return tensor_shape_pb2.TensorShapeProto(dim=[ + tensor_shape_pb2.TensorShapeProto.Dim( + size=-1 if d is None else d) for d in self._dims + ]) + + def __eq__(self, other): + """Returns True if `self` is equivalent to `other`. + + It first tries to convert `other` to `TensorShape`. `TypeError` is thrown + when the conversion fails. Otherwise, it compares each element in the + TensorShape dimensions. + + * Two *Fully known* shapes, return True iff each element is equal. + >>> t_a = tf.TensorShape([1,2]) + >>> a = [1, 2] + >>> t_b = tf.TensorShape([1,2]) + >>> t_c = tf.TensorShape([1,2,3]) + >>> t_a.__eq__(a) + True + >>> t_a.__eq__(t_b) + True + >>> t_a.__eq__(t_c) + False + + * Two *Partially-known* shapes, return True iff each element is equal. + >>> p_a = tf.TensorShape([1,None]) + >>> p_b = tf.TensorShape([1,None]) + >>> p_c = tf.TensorShape([2,None]) + >>> p_a.__eq__(p_b) + True + >>> t_a.__eq__(p_a) + False + >>> p_a.__eq__(p_c) + False + + * Two *Unknown shape*, return True. + >>> unk_a = tf.TensorShape(None) + >>> unk_b = tf.TensorShape(None) + >>> unk_a.__eq__(unk_b) + True + >>> unk_a.__eq__(t_a) + False + + Args: + other: A `TensorShape` or type that can be converted to `TensorShape`. + + Returns: + True if the dimensions are all equal. + + Raises: + TypeError if `other` can not be converted to `TensorShape`. + """ + + try: + other = as_shape(other) + except TypeError: + return NotImplemented + + return self._dims == other._dims + + def __hash__(self): + return hash(self._dims) + + def __reduce__(self): + return TensorShape, (self.dims,) + + def __concat__(self, other): + return self.concatenate(other) + +trace_type.register_serializable(TensorShape) + + +class _TensorShapeCodec: + """Codec for `TensorShape`.""" + + def can_encode(self, pyobj): + return isinstance(pyobj, TensorShape) + + def do_encode(self, tensor_shape_value, encode_fn): + del encode_fn + encoded_tensor_shape = struct_pb2.StructuredValue() + encoded_tensor_shape.tensor_shape_value.CopyFrom( + tensor_shape_value.as_proto()) + return encoded_tensor_shape + + def can_decode(self, value): + return value.HasField("tensor_shape_value") + + def do_decode(self, value, decode_fn): + del decode_fn + return TensorShape(value.tensor_shape_value) + + +nested_structure_coder.register_codec(_TensorShapeCodec()) + + +def as_shape(shape) -> "TensorShape": + """Converts the given object to a TensorShape.""" + if isinstance(shape, TensorShape): + return shape + else: + return TensorShape(shape) + + +def unknown_shape(rank=None, **kwargs) -> "TensorShape": + """Returns an unknown TensorShape, optionally with a known rank. + + Args: + rank: (Optional) If specified, the number of dimensions in the shape. + **kwargs: For backwards compatibility. + + Returns: + An unknown TensorShape. + + Raises: + TypeError: In case of invalid arguments. + """ + if rank is None and "ndims" in kwargs: + rank = kwargs.pop("ndims") + if kwargs: + raise TypeError("Unknown argument: %s" % kwargs) + if rank is None: + return TensorShape(None) + else: + return TensorShape([Dimension(None)] * rank) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_spec.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..57fff6c213c2d60420fafb6c52c19e9122900e40 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_spec.py @@ -0,0 +1,25 @@ +# 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. +# ============================================================================== +"""A TensorSpec class.""" + +from tensorflow.python.framework import tensor + +# This file is a pass-through to `tensor.py`. New references to this file +# should not be added - use `framework.tensor` directly instead. + +# TODO(tristenallen) - Remove once existing references are updated. +DenseSpec = tensor.DenseSpec +TensorSpec = tensor.TensorSpec +BoundedTensorSpec = tensor.BoundedTensorSpec diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_util.py new file mode 100644 index 0000000000000000000000000000000000000000..59fbeb3429c68da519ca6ae07035cd447f1149d9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tensor_util.py @@ -0,0 +1,1175 @@ +# 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. +# ============================================================================== +"""Utilities to create TensorProtos.""" +import typing +from typing import Protocol +import numpy as np + +from tensorflow.core.framework import tensor_pb2 +from tensorflow.core.framework import tensor_shape_pb2 +from tensorflow.python.client import pywrap_tf_session as c_api +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import tensor_shape +from tensorflow.python.types import core +from tensorflow.python.types import internal +from tensorflow.python.util import compat +from tensorflow.python.util import nest +from tensorflow.python.util.tf_export import tf_export + +# Fallback in case fast_tensor_util is not properly compiled. +# pylint: disable=g-import-not-at-top +try: + from tensorflow.python.framework import fast_tensor_util + _FAST_TENSOR_UTIL_AVAILABLE = True +except ImportError: + _FAST_TENSOR_UTIL_AVAILABLE = False +# pylint: enable=g-import-not-at-top + + +def ExtractBitsFromFloat16(x): + return np.asarray(x, dtype=np.float16).view(np.uint16).item() + + +def SlowAppendFloat16ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.half_val.extend( + [ExtractBitsFromFloat16(x) for x in proto_values] + ) + + +def _MediumAppendFloat16ArrayToTensorProto(tensor_proto, proto_values): + # TODO: Remove the conversion if cython supports np.float16_t + fast_tensor_util.AppendFloat16ArrayToTensorProto( + tensor_proto, + np.asarray(proto_values, dtype=np.float16).view(np.uint16)) + + +def ExtractBitsFromBFloat16(x): + return np.asarray( + x, dtype=dtypes.bfloat16.as_numpy_dtype).view(np.uint16).item() + + +def SlowAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.half_val.extend( + [ExtractBitsFromBFloat16(x) for x in proto_values] + ) + + +def FastAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values): + fast_tensor_util.AppendBFloat16ArrayToTensorProto( + tensor_proto, np.asarray( + proto_values, dtype=dtypes.bfloat16.as_numpy_dtype).view(np.uint16)) + + +def SlowAppendFloat8e5m2ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.float8_val += ( + np.asarray(proto_values, dtype=dtypes.float8_e5m2.as_numpy_dtype) + .view(np.uint8) + .tobytes() + ) + + +def FastAppendFloat8e5m2ArrayToTensorProto(tensor_proto, proto_values): + fast_tensor_util.AppendFloat8ArrayToTensorProto( + tensor_proto, + np.asarray(proto_values, + dtype=dtypes.float8_e5m2.as_numpy_dtype).view(np.uint8)) + + +def SlowAppendFloat8e4m3fnArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.float8_val += ( + np.asarray(proto_values, dtype=dtypes.float8_e4m3fn.as_numpy_dtype) + .view(np.uint8) + .tobytes() + ) + + +def FastAppendFloat8e4m3fnArrayToTensorProto(tensor_proto, proto_values): + fast_tensor_util.AppendFloat8ArrayToTensorProto( + tensor_proto, + np.asarray(proto_values, + dtype=dtypes.float8_e4m3fn.as_numpy_dtype).view(np.uint8)) + + +def SlowAppendInt4ArrayToTensorProto(tensor_proto, proto_values): + # The actual bit representation of int4 as a bit-field is + # implementation-defined, so we need to explicitly cast each + # value to an int for packing. + x = np.asarray(proto_values, dtype=dtypes.int4.as_numpy_dtype).astype(np.int8) + tensor_proto.int_val.extend(x.tolist()) + + +def SlowAppendUInt4ArrayToTensorProto(tensor_proto, proto_values): + # The actual bit representation of int4 as a bit-field is + # implementation-defined, so we need to explicitly cast each + # value to an int for packing. + x = np.asarray(proto_values, dtype=dtypes.uint4.as_numpy_dtype).astype( + np.int8 + ) + tensor_proto.int_val.extend(x.tolist()) + + +if _FAST_TENSOR_UTIL_AVAILABLE: + _NP_TO_APPEND_FN = { + np.float16: _MediumAppendFloat16ArrayToTensorProto, + np.float32: fast_tensor_util.AppendFloat32ArrayToTensorProto, + np.float64: fast_tensor_util.AppendFloat64ArrayToTensorProto, + np.int32: fast_tensor_util.AppendInt32ArrayToTensorProto, + np.int64: fast_tensor_util.AppendInt64ArrayToTensorProto, + np.uint8: fast_tensor_util.AppendUInt8ArrayToTensorProto, + np.uint16: fast_tensor_util.AppendUInt16ArrayToTensorProto, + np.uint32: fast_tensor_util.AppendUInt32ArrayToTensorProto, + np.uint64: fast_tensor_util.AppendUInt64ArrayToTensorProto, + np.int8: fast_tensor_util.AppendInt8ArrayToTensorProto, + np.int16: fast_tensor_util.AppendInt16ArrayToTensorProto, + np.complex64: fast_tensor_util.AppendComplex64ArrayToTensorProto, + np.complex128: fast_tensor_util.AppendComplex128ArrayToTensorProto, + np.object_: fast_tensor_util.AppendObjectArrayToTensorProto, + np.bool_: fast_tensor_util.AppendBoolArrayToTensorProto, + dtypes.qint8.as_numpy_dtype: ( + fast_tensor_util.AppendInt8ArrayToTensorProto + ), + dtypes.quint8.as_numpy_dtype: ( + fast_tensor_util.AppendUInt8ArrayToTensorProto + ), + dtypes.qint16.as_numpy_dtype: ( + fast_tensor_util.AppendInt16ArrayToTensorProto + ), + dtypes.quint16.as_numpy_dtype: ( + fast_tensor_util.AppendUInt16ArrayToTensorProto + ), + dtypes.qint32.as_numpy_dtype: ( + fast_tensor_util.AppendInt32ArrayToTensorProto + ), + dtypes.bfloat16.as_numpy_dtype: FastAppendBFloat16ArrayToTensorProto, + dtypes.float8_e5m2.as_numpy_dtype: FastAppendFloat8e5m2ArrayToTensorProto, + dtypes.float8_e4m3fn.as_numpy_dtype: ( + FastAppendFloat8e4m3fnArrayToTensorProto + ), + dtypes.int4.as_numpy_dtype: SlowAppendInt4ArrayToTensorProto, + dtypes.uint4.as_numpy_dtype: SlowAppendUInt4ArrayToTensorProto, + } +else: + + def SlowAppendFloat32ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.float_val.extend([x.item() for x in proto_values]) + + def SlowAppendFloat64ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.double_val.extend([x.item() for x in proto_values]) + + def SlowAppendIntArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.int_val.extend([x.item() for x in proto_values]) + + def SlowAppendInt64ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.int64_val.extend([x.item() for x in proto_values]) + + def SlowAppendQIntArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.int_val.extend([x.item()[0] for x in proto_values]) + + def SlowAppendUInt32ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.uint32_val.extend([x.item() for x in proto_values]) + + def SlowAppendUInt64ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.uint64_val.extend([x.item() for x in proto_values]) + + def SlowAppendComplex64ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.scomplex_val.extend( + [v.item() for x in proto_values for v in [x.real, x.imag]]) + + def SlowAppendComplex128ArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.dcomplex_val.extend( + [v.item() for x in proto_values for v in [x.real, x.imag]]) + + def SlowAppendObjectArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.string_val.extend([compat.as_bytes(x) for x in proto_values]) + + def SlowAppendBoolArrayToTensorProto(tensor_proto, proto_values): + tensor_proto.bool_val.extend([x.item() for x in proto_values]) + + _NP_TO_APPEND_FN = { + dtypes.bfloat16.as_numpy_dtype: SlowAppendBFloat16ArrayToTensorProto, + dtypes.float8_e5m2.as_numpy_dtype: SlowAppendFloat8e5m2ArrayToTensorProto, + dtypes.float8_e4m3fn.as_numpy_dtype: ( + SlowAppendFloat8e4m3fnArrayToTensorProto + ), + np.float16: SlowAppendFloat16ArrayToTensorProto, + np.float32: SlowAppendFloat32ArrayToTensorProto, + np.float64: SlowAppendFloat64ArrayToTensorProto, + np.int32: SlowAppendIntArrayToTensorProto, + np.int64: SlowAppendInt64ArrayToTensorProto, + np.uint8: SlowAppendIntArrayToTensorProto, + np.uint16: SlowAppendIntArrayToTensorProto, + np.uint32: SlowAppendUInt32ArrayToTensorProto, + np.uint64: SlowAppendUInt64ArrayToTensorProto, + np.int8: SlowAppendIntArrayToTensorProto, + np.int16: SlowAppendIntArrayToTensorProto, + np.complex64: SlowAppendComplex64ArrayToTensorProto, + np.complex128: SlowAppendComplex128ArrayToTensorProto, + np.object_: SlowAppendObjectArrayToTensorProto, + np.bool_: SlowAppendBoolArrayToTensorProto, + dtypes.qint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto, + dtypes.quint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto, + dtypes.qint16.as_numpy_dtype: SlowAppendQIntArrayToTensorProto, + dtypes.quint16.as_numpy_dtype: SlowAppendQIntArrayToTensorProto, + dtypes.qint32.as_numpy_dtype: SlowAppendQIntArrayToTensorProto, + dtypes.int4.as_numpy_dtype: SlowAppendInt4ArrayToTensorProto, + dtypes.uint4.as_numpy_dtype: SlowAppendUInt4ArrayToTensorProto, + } + + +def GetFromNumpyDTypeDict(dtype_dict, dtype): + # NOTE: dtype_dict.get(dtype) always returns None. + for key, val in dtype_dict.items(): + if key == dtype: + return val + return None + + +def GetNumpyAppendFn(dtype): + # numpy dtype for strings are variable length. We can not compare + # dtype with a single constant (np.string does not exist) to decide + # dtype is a "string" type. We need to compare the dtype.type to be + # sure it's a string type. + if dtype.type == np.bytes_ or dtype.type == np.str_: + if _FAST_TENSOR_UTIL_AVAILABLE: + return fast_tensor_util.AppendObjectArrayToTensorProto + else: + return SlowAppendObjectArrayToTensorProto + return GetFromNumpyDTypeDict(_NP_TO_APPEND_FN, dtype) + + +def TensorShapeProtoToList(shape): + """Convert a TensorShape to a list. + + Args: + shape: A TensorShapeProto. + + Returns: + List of integers representing the dimensions of the tensor. + """ + return [dim.size for dim in shape.dim] + + +def _GetDenseDimensions(list_of_lists): + """Returns the inferred dense dimensions of a list of lists.""" + if not isinstance(list_of_lists, (list, tuple)): + return [] + elif not list_of_lists: + return [0] + else: + return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0]) + + +def _FlattenToStrings(nested_strings): + if isinstance(nested_strings, (list, tuple)): + for inner in nested_strings: + for flattened_string in _FlattenToStrings(inner): + yield flattened_string + else: + yield nested_strings + + +_TENSOR_CONTENT_TYPES = frozenset( + [ + dtypes.float16, + dtypes.float32, + dtypes.float64, + dtypes.int32, + dtypes.uint8, + dtypes.int16, + dtypes.int8, + dtypes.int64, + dtypes.qint8, + dtypes.quint8, + dtypes.qint16, + dtypes.quint16, + dtypes.qint32, + dtypes.uint32, + dtypes.uint64, + dtypes.float8_e5m2, + dtypes.float8_e4m3fn, + dtypes.bfloat16 + # int4/uint4 intentionally not listed, since their binary representation + # is implementation-dependent. + ] +) + + +# pylint: disable=invalid-name +def _check_failed(v): + # NB. none of the _check_* functions could raise a ValueError, so + # it is safe to use here. + raise ValueError(v) + + +def _check_quantized(values): + # Cannot rely on `nest` because the leaves are tuples. + if not isinstance(values, (list, tuple)): + _check_failed(values) + if isinstance(values, tuple): + _ = [_check_int(v) for v in values] + else: + _ = [_check_quantized(v) for v in values] + + +def _generate_isinstance_check(expected_types): + def inner(values): + for v in nest.flatten(values): + if not (isinstance(v, expected_types) or + (isinstance(v, np.ndarray) and + issubclass(v.dtype.type, expected_types))): + _check_failed(v) + + return inner + +_check_int = _generate_isinstance_check( + (compat.integral_types, tensor_shape.Dimension)) +_check_float = _generate_isinstance_check(compat.real_types) +_check_complex = _generate_isinstance_check(compat.complex_types) +_check_str = _generate_isinstance_check(compat.bytes_or_text_types) +_check_bool = _generate_isinstance_check(bool) + + +def _check_not_tensor(values): + _ = [_check_failed(v) for v in nest.flatten(values) + if isinstance(v, core.Symbol)] +# pylint: enable=invalid-name + +_TF_TO_IS_OK = { + dtypes.bool: _check_bool, + dtypes.complex128: _check_complex, + dtypes.complex64: _check_complex, + dtypes.float16: _check_float, + dtypes.float32: _check_float, + dtypes.float64: _check_float, + dtypes.int16: _check_int, + dtypes.int32: _check_int, + dtypes.int64: _check_int, + dtypes.int8: _check_int, + dtypes.qint16: _check_quantized, + dtypes.qint32: _check_quantized, + dtypes.qint8: _check_quantized, + dtypes.quint16: _check_quantized, + dtypes.quint8: _check_quantized, + dtypes.string: _check_str, + dtypes.uint16: _check_int, + dtypes.uint8: _check_int, + dtypes.uint32: _check_int, + dtypes.uint64: _check_int, +} + + +def _AssertCompatible(values, dtype): + if dtype is None: + fn = _check_not_tensor + else: + try: + fn = _TF_TO_IS_OK[dtype] + except KeyError: + # There isn't a specific fn, so we try to do the best possible. + if dtype.is_integer: + fn = _check_int + elif dtype.is_floating: + fn = _check_float + elif dtype.is_complex: + fn = _check_complex + elif dtype.is_quantized: + fn = _check_quantized + else: + fn = _check_not_tensor + + try: + fn(values) + except ValueError as e: + [mismatch] = e.args + if dtype is None: + raise TypeError("Expected any non-tensor type, but got a tensor instead.") + else: + raise TypeError(f"Expected {dtype.name}, but got {mismatch} of type " + f"'{type(mismatch).__name__}'.") + + +def _is_array_like(obj): # pylint: disable=invalid-name + """Check if a given object is array-like.""" + if isinstance(obj, core.Symbol) and not isinstance(obj, core.Value): # pylint: disable=protected-access + # Tensor implements __array__ only so it can inform the user that it is not + # a valid array. + return False + + # TODO(slebedev): an object could also implement C-level array interface. + if (callable(getattr(obj, "__array__", None)) or + isinstance(getattr(obj, "__array_interface__", None), dict)): + return True + + try: + memoryview(obj) + except TypeError: + return False + else: + return not isinstance(obj, bytes) + + +# pylint: disable=invalid-name +@tf_export("make_tensor_proto") +def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False, + allow_broadcast=False): + """Create a TensorProto. + + In TensorFlow 2.0, representing tensors as protos should no longer be a + common workflow. That said, this utility function is still useful for + generating TF Serving request protos: + + ```python + request = tensorflow_serving.apis.predict_pb2.PredictRequest() + request.model_spec.name = "my_model" + request.model_spec.signature_name = "serving_default" + request.inputs["images"].CopyFrom(tf.make_tensor_proto(X_new)) + ``` + + `make_tensor_proto` accepts "values" of a python scalar, a python list, a + numpy ndarray, or a numpy scalar. + + If "values" is a python scalar or a python list, make_tensor_proto + first convert it to numpy ndarray. If dtype is None, the + conversion tries its best to infer the right numpy data + type. Otherwise, the resulting numpy array has a compatible data + type with the given dtype. + + In either case above, the numpy ndarray (either the caller provided + or the auto-converted) must have the compatible type with dtype. + + `make_tensor_proto` then converts the numpy array to a tensor proto. + + If "shape" is None, the resulting tensor proto represents the numpy + array precisely. + + Otherwise, "shape" specifies the tensor's shape and the numpy array + can not have more elements than what "shape" specifies. + + Args: + values: Values to put in the TensorProto. + dtype: Optional tensor_pb2 DataType value. + shape: List of integers representing the dimensions of tensor. + verify_shape: Boolean that enables verification of a shape of values. + allow_broadcast: Boolean that enables allowing scalars and 1 length vector + broadcasting. Cannot be true when verify_shape is true. + + Returns: + A `TensorProto`. Depending on the type, it may contain data in the + "tensor_content" attribute, which is not directly useful to Python programs. + To access the values you should convert the proto back to a numpy ndarray + with `tf.make_ndarray(proto)`. + + If `values` is a `TensorProto`, it is immediately returned; `dtype` and + `shape` are ignored. + + Raises: + TypeError: if unsupported types are provided. + ValueError: if arguments have inappropriate values or if verify_shape is + True and shape of values is not equals to a shape from the argument. + + """ + if allow_broadcast and verify_shape: + raise ValueError("allow_broadcast and verify_shape are not both allowed.") + if isinstance(values, tensor_pb2.TensorProto): + return values + + if dtype: + dtype = dtypes.as_dtype(dtype) + + is_quantized = ( + dtype in [ + dtypes.qint8, dtypes.quint8, dtypes.qint16, dtypes.quint16, + dtypes.qint32 + ]) + + if _is_array_like(values): + values = np.asarray(values) + + # We first convert value to a numpy array or scalar. + if isinstance(values, (np.ndarray, np.generic)): + if dtype and dtype.is_numpy_compatible: + nparray = values.astype(dtype.as_numpy_dtype) + else: + nparray = values + else: + if values is None: + raise ValueError("None values not supported.") + # if dtype is provided, forces numpy array to be the type + # provided if possible. + if dtype and dtype.is_numpy_compatible: + np_dt = dtype.as_numpy_dtype + else: + np_dt = None + # If shape is None, numpy.prod returns None when dtype is not set, but + # raises exception when dtype is set to np.int64 + if shape is not None and np.prod(shape, dtype=np.int64) == 0: + nparray = np.empty(shape, dtype=np_dt) + else: + _AssertCompatible(values, dtype) + nparray = np.array(values, dtype=np_dt) + # check to them. + # We need to pass in quantized values as tuples, so don't apply the shape + if (list(nparray.shape) != _GetDenseDimensions(values) and + not is_quantized): + raise ValueError(f"Expected values {values} to be a dense tensor with " + f"shape {_GetDenseDimensions(values)}, but got shape " + f"{list(nparray.shape)}.") + + # python/numpy default float type is float64. We prefer float32 instead. + if (nparray.dtype == np.float64) and dtype is None: + nparray = nparray.astype(np.float32) + # python/numpy default int type is int64. We prefer int32 instead. + elif (nparray.dtype == np.int64) and dtype is None: + downcasted_array = nparray.astype(np.int32) + # Do not down cast if it leads to precision loss. + if np.array_equal(downcasted_array, nparray): + nparray = downcasted_array + + # if dtype is provided, it must be compatible with what numpy + # conversion says. + numpy_dtype = dtypes.as_dtype(nparray.dtype) + if numpy_dtype is None: + raise TypeError(f"Unrecognized data type: {nparray.dtype}.") + + # If dtype was specified and is a quantized type, we convert + # numpy_dtype back into the quantized version. + if is_quantized: + numpy_dtype = dtype + + if dtype is not None and (not hasattr(dtype, "base_dtype") or + dtype.base_dtype != numpy_dtype.base_dtype): + raise TypeError(f"`dtype` {dtype} is not compatible with {values} of " + f"dtype {nparray.dtype}.") + + # If shape is not given, get the shape from the numpy array. + if shape is None: + shape = nparray.shape + is_same_size = True + shape_size = nparray.size + else: + shape = [int(dim) for dim in shape] + shape_size = np.prod(shape, dtype=np.int64) + is_same_size = shape_size == nparray.size + + if allow_broadcast: + if nparray.shape == (1,) or nparray.shape == tuple(): + pass + elif nparray.size != shape_size: + raise TypeError(f"Expected Tensor's shape: {tuple(shape)}, but got " + f"{nparray.shape}.") + + else: + if verify_shape and nparray.shape != tuple(shape): + raise TypeError(f"Expected Tensor's shape: {tuple(shape)}, but got " + f"{nparray.shape}.") + + if nparray.size > shape_size: + raise ValueError("Too many elements provided. Takes at most " + f"{shape_size:d}, but got {nparray.size:d}.") + + tensor_proto = tensor_pb2.TensorProto( + dtype=numpy_dtype.as_datatype_enum, + tensor_shape=tensor_shape.as_shape(shape).as_proto()) + + if is_same_size and numpy_dtype in _TENSOR_CONTENT_TYPES and shape_size > 1: + if nparray.size * nparray.itemsize >= (1 << 31): + raise ValueError( + "Cannot create a tensor proto whose content is larger than 2GB.") + tensor_proto.tensor_content = nparray.tobytes() + return tensor_proto + + # If we were not given values as a numpy array, compute the proto_values + # from the given values directly, to avoid numpy trimming nulls from the + # strings. Since values could be a list of strings, or a multi-dimensional + # list of lists that might or might not correspond to the given shape, + # we flatten it conservatively. + if numpy_dtype == dtypes.string and not isinstance(values, np.ndarray): + proto_values = _FlattenToStrings(values) + + # At this point, values may be a list of objects that we could not + # identify a common type for (hence it was inferred as + # np.object_/dtypes.string). If we are unable to convert it to a + # string, we raise a more helpful error message. + # + # Ideally, we'd be able to convert the elements of the list to a + # common type, but this type inference requires some thinking and + # so we defer it for now. + try: + str_values = [compat.as_bytes(x) for x in proto_values] + except TypeError: + raise TypeError(f"Failed to convert elements of {values} to Tensor. " + "Consider casting elements to a supported type. See " + "https://www.tensorflow.org/api_docs/python/tf/dtypes " + "for supported TF dtypes.") + tensor_proto.string_val.extend(str_values) + return tensor_proto + + # TensorFlow expects C order (a.k.a., eigen row major). + proto_values = nparray.ravel() + + append_fn = GetNumpyAppendFn(proto_values.dtype) + if append_fn is None: + raise TypeError( + f"Element type not supported in TensorProto: {numpy_dtype.name}.") + append_fn(tensor_proto, proto_values) + + return tensor_proto +# pylint: enable=invalid-name + + +@tf_export("make_ndarray") +def MakeNdarray(tensor): + """Create a numpy ndarray from a tensor. + + Create a numpy ndarray with the same shape and data as the tensor. + + For example: + + ```python + # Tensor a has shape (2,3) + a = tf.constant([[1,2,3],[4,5,6]]) + proto_tensor = tf.make_tensor_proto(a) # convert `tensor a` to a proto tensor + tf.make_ndarray(proto_tensor) # output: array([[1, 2, 3], + # [4, 5, 6]], dtype=int32) + # output has shape (2,3) + ``` + + Args: + tensor: A TensorProto. + + Returns: + A numpy array with the tensor contents. + + Raises: + TypeError: if tensor has unsupported type. + + """ + shape = [d.size for d in tensor.tensor_shape.dim] + num_elements = np.prod(shape, dtype=np.int64) + tensor_dtype = dtypes.as_dtype(tensor.dtype) + dtype = tensor_dtype.as_numpy_dtype + + if tensor.tensor_content: + return (np.frombuffer(tensor.tensor_content, + dtype=dtype).copy().reshape(shape)) + + if tensor_dtype == dtypes.string: + # np.pad throws on these arrays of type np.object_. + values = list(tensor.string_val) + padding = num_elements - len(values) + if padding > 0: + last = values[-1] if values else "" + values.extend([last] * padding) + return np.array(values, dtype=dtype).reshape(shape) + + if tensor_dtype == dtypes.float16 or tensor_dtype == dtypes.bfloat16: + # the half_val field of the TensorProto stores the binary representation + # of the fp16: we need to reinterpret this as a proper float16 + values = np.fromiter(tensor.half_val, dtype=np.uint16) + values.dtype = dtype + elif tensor_dtype in [ + dtypes.float8_e5m2, + dtypes.float8_e4m3fn, + ]: + values = np.fromiter(tensor.float8_val, dtype=np.uint8) + values.dtype = dtype + elif tensor_dtype == dtypes.float32: + values = np.fromiter(tensor.float_val, dtype=dtype) + elif tensor_dtype == dtypes.float64: + values = np.fromiter(tensor.double_val, dtype=dtype) + elif tensor_dtype in [ + dtypes.int32, + dtypes.uint8, + dtypes.uint16, + dtypes.int16, + dtypes.int8, + dtypes.qint32, + dtypes.quint8, + dtypes.qint8, + dtypes.qint16, + dtypes.quint16, + dtypes.int4, + dtypes.uint4, + ]: + values = np.fromiter(tensor.int_val, dtype=dtype) + elif tensor_dtype == dtypes.int64: + values = np.fromiter(tensor.int64_val, dtype=dtype) + elif tensor_dtype == dtypes.uint32: + values = np.fromiter(tensor.uint32_val, dtype=dtype) + elif tensor_dtype == dtypes.uint64: + values = np.fromiter(tensor.uint64_val, dtype=dtype) + elif tensor_dtype == dtypes.complex64: + it = iter(tensor.scomplex_val) + values = np.array([complex(x[0], x[1]) for x in zip(it, it)], dtype=dtype) + elif tensor_dtype == dtypes.complex128: + it = iter(tensor.dcomplex_val) + values = np.array([complex(x[0], x[1]) for x in zip(it, it)], dtype=dtype) + elif tensor_dtype == dtypes.bool: + values = np.fromiter(tensor.bool_val, dtype=dtype) + else: + raise TypeError(f"Unsupported tensor type: {tensor.dtype}. See " + "https://www.tensorflow.org/api_docs/python/tf/dtypes " + "for supported TF dtypes.") + + if values.size == 0: + return np.zeros(shape, dtype) + + if values.size != num_elements: + values = np.pad(values, (0, num_elements - values.size), "edge") + + return values.reshape(shape) + + +def ShapeEquals(tensor_proto, shape): + """Returns True if "tensor_proto" has the given "shape". + + Args: + tensor_proto: A TensorProto. + shape: A tensor shape, expressed as a TensorShape, list, or tuple. + + Returns: + True if "tensor_proto" has the given "shape", otherwise False. + + Raises: + TypeError: If "tensor_proto" is not a TensorProto, or shape is not a + TensorShape, list, or tuple. + """ + if not isinstance(tensor_proto, tensor_pb2.TensorProto): + raise TypeError("`tensor_proto` must be a tensor_pb2.TensorProto object, " + f"but got type {type(tensor_proto)}.") + if isinstance(shape, tensor_shape_pb2.TensorShapeProto): + shape = [d.size for d in shape.dim] + elif not isinstance(shape, (list, tuple)): + raise TypeError("`shape` must be a list or tuple, but got type " + f"{type(shape)}.") + tensor_shape_list = [d.size for d in tensor_proto.tensor_shape.dim] + return all(x == y for x, y in zip(tensor_shape_list, shape)) + + +def _ConstantValue(tensor, partial): + # TODO(touts): Support Variables? + if not isinstance(tensor, core.Symbol): + raise TypeError(f"{tensor!r} must be a Tensor, but got {type(tensor)}.") + if tensor.op.type == "Const": + return MakeNdarray(tensor.op.get_attr("value")) + elif tensor.op.type == "Shape": + input_shape = tensor.op.inputs[0].get_shape() + if input_shape.is_fully_defined(): + return np.array( + [dim.value for dim in input_shape.dims], + dtype=tensor.dtype.as_numpy_dtype) + else: + return None + elif tensor.op.type == "Size": + input_shape = tensor.op.inputs[0].get_shape() + if input_shape.is_fully_defined(): + return np.prod([dim.value for dim in input_shape.dims], dtype=np.int32) + else: + return None + elif tensor.op.type == "Rank": + input_shape = tensor.op.inputs[0].get_shape() + if input_shape.ndims is not None: + return np.ndarray( + shape=(), + buffer=np.array([input_shape.ndims], dtype=np.int32), + dtype=np.int32) + else: + return None + elif tensor.op.type == "Range": + start = constant_value(tensor.op.inputs[0]) + if start is None: + return None + limit = constant_value(tensor.op.inputs[1]) + if limit is None: + return None + delta = constant_value(tensor.op.inputs[2]) + if delta is None: + return None + return np.arange(start, limit, delta, dtype=tensor.dtype.as_numpy_dtype) + elif tensor.op.type == "Cast": + pre_cast = constant_value(tensor.op.inputs[0]) + if pre_cast is None: + return None + cast_dtype = dtypes.as_dtype(tensor.op.get_attr("DstT")) + return pre_cast.astype(cast_dtype.as_numpy_dtype) + elif tensor.op.type == "Concat": + dim = constant_value(tensor.op.inputs[0]) + if dim is None: + return None + values = [] + for x in tensor.op.inputs[1:]: + value = constant_value(x) + if value is None: + return None + values.append(value) + return np.concatenate(values, axis=dim) + elif tensor.op.type == "ConcatV2": + dim = constant_value(tensor.op.inputs[-1]) + if dim is None: + return None + values = [] + for x in tensor.op.inputs[:-1]: + value = constant_value(x) + if value is None: + return None + values.append(value) + return np.concatenate(values, axis=dim) + elif tensor.op.type == "Pack": + values = [] + # Some imported GraphDefs have Pack ops with zero inputs. Those are invalid + # and shouldn't be produced, but to deal sensibly with them here we check + # and return None. + if not tensor.op.inputs: + return None + # We can't handle axis != 0 Packs at the moment. + if tensor.op.get_attr("axis") != 0: + return None + for x in tensor.op.inputs: + value = constant_value(x, partial) + if value is None and not partial: + return None + values.append(value) + try: + return np.array(values) + except ValueError: + # If partial=True, some of the elements of values may be None. + return np.array(values, dtype=object) + elif tensor.op.type == "Unpack": + # We can't handle axis != 0 Unpacks at the moment. + if tensor.op.get_attr("axis") != 0: + return None + value = constant_value(tensor.op.inputs[0], partial) + if value is None: + return None + return value[tensor.value_index] + elif tensor.op.type == "Split": + dim = constant_value(tensor.op.inputs[0]) + value = constant_value(tensor.op.inputs[1], partial) + if value is None or dim is None: + return None + split = np.split(value, tensor.op.get_attr("num_split"), dim) + return split[tensor.value_index] + elif tensor.op.type == "Fill": + fill_shape = tensor.shape + fill_value = constant_value(tensor.op.inputs[1]) + if fill_shape.is_fully_defined() and fill_value is not None: + return np.full(fill_shape.as_list(), fill_value, dtype=fill_value.dtype) + else: + return None + elif tensor.op.type == "Equal": + value1 = constant_value(tensor.op.inputs[0]) + if value1 is None: + return None + value2 = constant_value(tensor.op.inputs[1]) + if value2 is None: + return None + return np.equal(value1, value2) + elif tensor.op.type == "NotEqual": + value1 = constant_value(tensor.op.inputs[0]) + if value1 is None: + return None + value2 = constant_value(tensor.op.inputs[1]) + if value2 is None: + return None + return np.not_equal(value1, value2) + elif tensor.op.type == "StopGradient": + return constant_value(tensor.op.inputs[0], partial) + elif tensor.op.type in ("CheckNumericsV2", "DebugIdentityV2", "Identity"): + return constant_value(tensor.op.inputs[0], partial) + else: + return None + + +@tf_export("get_static_value") +def constant_value(tensor, partial=False): # pylint: disable=invalid-name + """Returns the constant value of the given tensor, if efficiently calculable. + + This function attempts to partially evaluate the given tensor, and + returns its value as a numpy ndarray if this succeeds. + + Example usage: + + >>> a = tf.constant(10) + >>> tf.get_static_value(a) + 10 + >>> b = tf.constant(20) + >>> tf.get_static_value(tf.add(a, b)) + 30 + + >>> # `tf.Variable` is not supported. + >>> c = tf.Variable(30) + >>> print(tf.get_static_value(c)) + None + + Using `partial` option is most relevant when calling `get_static_value` inside + a `tf.function`. Setting it to `True` will return the results but for the + values that cannot be evaluated will be `None`. For example: + + ```python + class Foo: + def __init__(self): + self.a = tf.Variable(1) + self.b = tf.constant(2) + + @tf.function + def bar(self, partial): + packed = tf.raw_ops.Pack(values=[self.a, self.b]) + static_val = tf.get_static_value(packed, partial=partial) + tf.print(static_val) + + f = Foo() + f.bar(partial=True) # `array([None, array(2, dtype=int32)], dtype=object)` + f.bar(partial=False) # `None` + ``` + + Compatibility(V1): If `constant_value(tensor)` returns a non-`None` result, it + will no longer be possible to feed a different value for `tensor`. This allows + the result of this function to influence the graph that is constructed, and + permits static shape optimizations. + + Args: + tensor: The Tensor to be evaluated. + partial: If True, the returned numpy array is allowed to have partially + evaluated values. Values that can't be evaluated will be None. + + Returns: + A numpy ndarray containing the constant value of the given `tensor`, + or None if it cannot be calculated. + + Raises: + TypeError: if tensor is not an tensor.Tensor. + """ + if isinstance(tensor, core.Value): + try: + return tensor.numpy() + except errors_impl.UnimplementedError: + # Some EagerTensors may not implement .numpy/resolve, e.g. parallel + # tensors with multiple components on different devices. + return None + if not is_tensor(tensor): + return tensor + if not isinstance(tensor, core.Symbol): + return None + ret = _ConstantValue(tensor, partial) + if ret is not None: + # The caller may now depend on the constant value of `tensor`, so we + # conservatively prevent it from being fed. + tensor.graph.prevent_feeding(tensor) + return ret + + +def constant_value_as_shape(tensor): # pylint: disable=invalid-name + """A version of `constant_value()` that returns a `TensorShape`. + + This version should be used when a constant tensor value is + interpreted as a (possibly partial) shape, e.g. in the shape + function for `tf.reshape()`. By explicitly requesting a + `TensorShape` as the return value, it is possible to represent + unknown dimensions; by contrast, `constant_value()` is + all-or-nothing. + + Args: + tensor: The rank-0 or rank-1 Tensor to be evaluated. + + Returns: + A `TensorShape` based on the constant value of the given `tensor`. + + Raises: + ValueError: If the shape is rank-0 and is not statically known to be -1. + """ + if isinstance(tensor, core.Value): + return tensor_shape.TensorShape( + [dim if dim != -1 else None for dim in tensor.numpy()]) + + if tensor.get_shape().ndims == 0: + value = constant_value(tensor) + if value is None: + raise ValueError( + "Received a scalar with unknown value as shape; require a statically " + "known scalar with value '-1' to describe an unknown shape.") + if value != -1: + raise ValueError( + f"Received a scalar value '{value}' as shape; require a statically " + "known scalar with value '-1' to describe an unknown shape.") + return tensor_shape.unknown_shape() + + shape = tensor.get_shape().with_rank(1) + if shape == [0]: + return tensor_shape.TensorShape([]) + elif tensor.op.type == "Cast": + pre_cast = constant_value_as_shape(tensor.op.inputs[0]) + if pre_cast.dims is None: + # the input to cast has a totally undefined shape; just return that. + return pre_cast + cast_dtype = dtypes.as_dtype(tensor.op.get_attr("DstT")) + if cast_dtype not in (dtypes.int32, dtypes.int64): + return tensor_shape.unknown_shape(shape.dims[0].value) + dest_dtype_shape_array = np.array( + [x if x is not None else -1 for x in pre_cast.as_list()]).astype( + cast_dtype.as_numpy_dtype) + return tensor_shape.TensorShape([ + x if x >= 0 else None + for x in dest_dtype_shape_array]) + elif tensor.op.type == "Shape": + return tensor.op.inputs[0].get_shape() + elif tensor.op.type == "Pack": + ret = tensor_shape.TensorShape([]) # Empty list. + # Since we expect rank 1 inputs, Pack's axis must be zero, otherwise it + # would not be rank 1. + assert tensor.op.get_attr("axis") == 0 + for pack_input in tensor.op.inputs: + # `pack_input` must be a scalar. Attempt to evaluate it, and append it + # to `ret`. + pack_input_val = constant_value(pack_input) + if pack_input_val is None or pack_input_val < 0: + new_dim = tensor_shape.Dimension(None) + else: + new_dim = tensor_shape.Dimension(pack_input_val) + ret = ret.concatenate([new_dim]) + return ret + elif tensor.op.type == "Concat": + # We assume that `tensor.op.inputs[0]` evaluates to 0, as this is + # the only legal value when concatenating vectors, and it will + # have been checked by a previous shape function. + ret = tensor_shape.TensorShape([]) # Empty list. + for concat_input in tensor.op.inputs[1:]: + # `concat_input` must be a vector. Attempt to evaluate it as a shape, + # and concatenate it with `ret`. + ret = ret.concatenate(constant_value_as_shape(concat_input)) + return ret + elif tensor.op.type == "ConcatV2": + # We assume that `tensor.op.inputs[-1]` evaluates to 0, as this is + # the only legal value when concatenating vectors, and it will + # have been checked by a previous shape function. + ret = tensor_shape.TensorShape([]) # Empty list. + for concat_input in tensor.op.inputs[:-1]: + # `concat_input` must be a vector. Attempt to evaluate it as a shape, + # and concatenate it with `ret`. + ret = ret.concatenate(constant_value_as_shape(concat_input)) + return ret + elif tensor.op.type == "StridedSlice": + try: + begin = constant_value(tensor.op.inputs[1]) + end = constant_value(tensor.op.inputs[2]) + strides = constant_value(tensor.op.inputs[3]) + if begin is not None and end is not None and strides is not None: + begin = begin[0] + end = end[0] + strides = strides[0] + begin_mask = tensor.op.get_attr("begin_mask") + if begin_mask == 1: + begin = None + end_mask = tensor.op.get_attr("end_mask") + if end_mask == 1: + end = None + + ellipsis_mask = tensor.op.get_attr("ellipsis_mask") + new_axis_mask = tensor.op.get_attr("new_axis_mask") + shrink_axis_mask = tensor.op.get_attr("shrink_axis_mask") + valid_attributes = (not ellipsis_mask and not new_axis_mask and + not shrink_axis_mask and (not begin_mask or + (begin_mask == 1)) and + (not end_mask or (end_mask == 1))) + if valid_attributes: # additional inputs not supported + prev = constant_value_as_shape(tensor.op.inputs[0]) + prev = prev[begin:end:strides] + ret = tensor_shape.TensorShape(prev) + return ret + + except ValueError: # Could come from get_attr or slicing prev. + pass + except TypeError: # Could come from slicing prev. + pass + elif (tensor.op.type == "Placeholder" and + tensor.op.graph.building_function and + hasattr(tensor.op.graph, "internal_captures")): + # If we are inside a FuncGraph try to lookup the constant value of the + # corresponding external capture. Note that we only look at captures and + # not the fed inputs because those can be fed different values in different + # instantiations of the function call or different iterations of a + # tf.while_loop. + for i, capture in enumerate(tensor.op.graph.internal_captures): + if capture is tensor: + external_capture = tensor.op.graph.external_captures[i] + return constant_value_as_shape(external_capture) + + ret = tensor_shape.unknown_shape(shape.dims[0].value) + value = constant_value(tensor) + if value is not None: + ret = ret.merge_with( + tensor_shape.TensorShape([d if d >= 0 else None for d in value])) + return ret + + +@typing.runtime_checkable +class IsTensorLike(Protocol): + + def is_tensor_like(self): # pylint: disable=invalid-name + pass + + +tf_type_classes = (internal.NativeObject, core.Tensor, IsTensorLike) + + +# TODO(mdan): Deprecate in favor of more static-friendly types. +@tf_export("is_tensor") +def is_tf_type(x): # pylint: disable=invalid-name + """Checks whether `x` is a TF-native type that can be passed to many TF ops. + + Use `is_tensor` to differentiate types that can ingested by TensorFlow ops + without any conversion (e.g., `tf.Tensor`, `tf.SparseTensor`, and + `tf.RaggedTensor`) from types that need to be converted into tensors before + they are ingested (e.g., numpy `ndarray` and Python scalars). + + For example, in the following code block: + + ```python + if not tf.is_tensor(t): + t = tf.convert_to_tensor(t) + return t.shape, t.dtype + ``` + + we check to make sure that `t` is a tensor (and convert it if not) before + accessing its `shape` and `dtype`. (But note that not all TensorFlow native + types have shapes or dtypes; `tf.data.Dataset` is an example of a TensorFlow + native type that has neither shape nor dtype.) + + Args: + x: A python object to check. + + Returns: + `True` if `x` is a TensorFlow-native type. + """ + return isinstance(x, tf_type_classes) + + +# Deprecated alias for tensor_util.is_tf_type. +is_tensor = is_tf_type + + +def try_evaluate_constant(tensor): # pylint: disable=invalid-name + """Evaluates a symbolic tensor as a constant. + + Args: + tensor: a symbolic Tensor. + + Returns: + ndarray if the evaluation succeeds, or None if it fails. + """ + # pylint: disable=protected-access + with tensor.graph._c_graph.get() as c_graph: + return c_api.TF_TryEvaluateConstant_wrapper(c_graph, tensor._as_tf_output()) + # pylint: enable=protected-access diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_combinations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_combinations.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab1d7b5e2767201ced29fc1372b4f1ea2fb7cf0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_combinations.py @@ -0,0 +1,459 @@ +# 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. +# ============================================================================== +"""Facilities for creating multiple test combinations. + +Here is a simple example for testing various optimizers in Eager and Graph: + +class AdditionExample(test.TestCase, parameterized.TestCase): + @combinations.generate( + combinations.combine(mode=["graph", "eager"], + optimizer=[AdamOptimizer(), + GradientDescentOptimizer()])) + def testOptimizer(self, optimizer): + ... f(optimizer)... + +This will run `testOptimizer` 4 times with the specified optimizers: 2 in +Eager and 2 in Graph mode. +The test is going to accept the same parameters as the ones used in `combine()`. +The parameters need to match by name between the `combine()` call and the test +signature. It is necessary to accept all parameters. See `OptionalParameter` +for a way to implement optional parameters. + +`combine()` function is available for creating a cross product of various +options. `times()` function exists for creating a product of N `combine()`-ed +results. + +The execution of generated tests can be customized in a number of ways: +- The test can be skipped if it is not running in the correct environment. +- The arguments that are passed to the test can be additionally transformed. +- The test can be run with specific Python context managers. +These behaviors can be customized by providing instances of `TestCombination` to +`generate()`. +""" + +from collections import OrderedDict +import contextlib +import re +import types +import unittest + +from absl.testing import parameterized + +from tensorflow.python.util import tf_inspect +from tensorflow.python.util.tf_export import tf_export + + +@tf_export("__internal__.test.combinations.TestCombination", v1=[]) +class TestCombination: + """Customize the behavior of `generate()` and the tests that it executes. + + Here is sequence of steps for executing a test combination: + 1. The test combination is evaluated for whether it should be executed in + the given environment by calling `should_execute_combination`. + 2. If the test combination is going to be executed, then the arguments for + all combined parameters are validated. Some arguments can be handled in + a special way. This is achieved by implementing that logic in + `ParameterModifier` instances that returned from `parameter_modifiers`. + 3. Before executing the test, `context_managers` are installed + around it. + """ + + def should_execute_combination(self, kwargs): + """Indicates whether the combination of test arguments should be executed. + + If the environment doesn't satisfy the dependencies of the test + combination, then it can be skipped. + + Args: + kwargs: Arguments that are passed to the test combination. + + Returns: + A tuple boolean and an optional string. The boolean False indicates + that the test should be skipped. The string would indicate a textual + description of the reason. If the test is going to be executed, then + this method returns `None` instead of the string. + """ + del kwargs + return (True, None) + + def parameter_modifiers(self): + """Returns `ParameterModifier` instances that customize the arguments.""" + return [] + + def context_managers(self, kwargs): + """Return context managers for running the test combination. + + The test combination will run under all context managers that all + `TestCombination` instances return. + + Args: + kwargs: Arguments and their values that are passed to the test + combination. + + Returns: + A list of instantiated context managers. + """ + del kwargs + return [] + + +@tf_export("__internal__.test.combinations.ParameterModifier", v1=[]) +class ParameterModifier: + """Customizes the behavior of a particular parameter. + + Users should override `modified_arguments()` to modify the parameter they + want, eg: change the value of certain parameter or filter it from the params + passed to the test case. + + See the sample usage below, it will change any negative parameters to zero + before it gets passed to test case. + ``` + class NonNegativeParameterModifier(ParameterModifier): + + def modified_arguments(self, kwargs, requested_parameters): + updates = {} + for name, value in kwargs.items(): + if value < 0: + updates[name] = 0 + return updates + ``` + """ + + DO_NOT_PASS_TO_THE_TEST = object() + + def __init__(self, parameter_name=None): + """Construct a parameter modifier that may be specific to a parameter. + + Args: + parameter_name: A `ParameterModifier` instance may operate on a class of + parameters or on a parameter with a particular name. Only + `ParameterModifier` instances that are of a unique type or were + initialized with a unique `parameter_name` will be executed. + See `__eq__` and `__hash__`. + """ + self._parameter_name = parameter_name + + def modified_arguments(self, kwargs, requested_parameters): + """Replace user-provided arguments before they are passed to a test. + + This makes it possible to adjust user-provided arguments before passing + them to the test method. + + Args: + kwargs: The combined arguments for the test. + requested_parameters: The set of parameters that are defined in the + signature of the test method. + + Returns: + A dictionary with updates to `kwargs`. Keys with values set to + `ParameterModifier.DO_NOT_PASS_TO_THE_TEST` are going to be deleted and + not passed to the test. + """ + del kwargs, requested_parameters + return {} + + def __eq__(self, other): + """Compare `ParameterModifier` by type and `parameter_name`.""" + if self is other: + return True + elif type(self) is type(other): + return self._parameter_name == other._parameter_name + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + """Compare `ParameterModifier` by type or `parameter_name`.""" + if self._parameter_name: + return hash(self._parameter_name) + else: + return id(self.__class__) + + +@tf_export("__internal__.test.combinations.OptionalParameter", v1=[]) +class OptionalParameter(ParameterModifier): + """A parameter that is optional in `combine()` and in the test signature. + + `OptionalParameter` is usually used with `TestCombination` in the + `parameter_modifiers()`. It allows `TestCombination` to skip certain + parameters when passing them to `combine()`, since the `TestCombination` might + consume the param and create some context based on the value it gets. + + See the sample usage below: + + ``` + class EagerGraphCombination(TestCombination): + + def context_managers(self, kwargs): + mode = kwargs.pop("mode", None) + if mode is None: + return [] + elif mode == "eager": + return [context.eager_mode()] + elif mode == "graph": + return [ops.Graph().as_default(), context.graph_mode()] + else: + raise ValueError( + "'mode' has to be either 'eager' or 'graph', got {}".format(mode)) + + def parameter_modifiers(self): + return [test_combinations.OptionalParameter("mode")] + ``` + + When the test case is generated, the param "mode" will not be passed to the + test method, since it is consumed by the `EagerGraphCombination`. + """ + + def modified_arguments(self, kwargs, requested_parameters): + if self._parameter_name in requested_parameters: + return {} + else: + return {self._parameter_name: ParameterModifier.DO_NOT_PASS_TO_THE_TEST} + + +def generate(combinations, test_combinations=()): + """A decorator for generating combinations of a test method or a test class. + + Parameters of the test method must match by name to get the corresponding + value of the combination. Tests must accept all parameters that are passed + other than the ones that are `OptionalParameter`. + + Args: + combinations: a list of dictionaries created using combine() and times(). + test_combinations: a tuple of `TestCombination` instances that customize + the execution of generated tests. + + Returns: + a decorator that will cause the test method or the test class to be run + under the specified conditions. + + Raises: + ValueError: if any parameters were not accepted by the test method + """ + def decorator(test_method_or_class): + """The decorator to be returned.""" + + # Generate good test names that can be used with --test_filter. + named_combinations = [] + for combination in combinations: + # We use OrderedDicts in `combine()` and `times()` to ensure stable + # order of keys in each dictionary. + assert isinstance(combination, OrderedDict) + name = "".join([ + "_{}_{}".format("".join(filter(str.isalnum, key)), + "".join(filter(str.isalnum, _get_name(value, i)))) + for i, (key, value) in enumerate(combination.items()) + ]) + named_combinations.append( + OrderedDict( + list(combination.items()) + + [("testcase_name", "_test{}".format(name))])) + + if isinstance(test_method_or_class, type): + class_object = test_method_or_class + class_object._test_method_ids = test_method_ids = {} + for name, test_method in class_object.__dict__.copy().items(): + if (name.startswith(unittest.TestLoader.testMethodPrefix) and + isinstance(test_method, types.FunctionType)): + delattr(class_object, name) + methods = {} + parameterized._update_class_dict_for_param_test_case( + class_object.__name__, methods, test_method_ids, name, + parameterized._ParameterizedTestIter( + _augment_with_special_arguments( + test_method, test_combinations=test_combinations), + named_combinations, parameterized._NAMED, name)) + for method_name, method in methods.items(): + setattr(class_object, method_name, method) + + return class_object + else: + test_method = _augment_with_special_arguments( + test_method_or_class, test_combinations=test_combinations) + return parameterized.named_parameters(*named_combinations)(test_method) + + return decorator + + +def _augment_with_special_arguments(test_method, test_combinations): + def decorated(self, **kwargs): + """A wrapped test method that can treat some arguments in a special way.""" + original_kwargs = kwargs.copy() + + # Skip combinations that are going to be executed in a different testing + # environment. + reasons_to_skip = [] + for combination in test_combinations: + should_execute, reason = combination.should_execute_combination( + original_kwargs.copy()) + if not should_execute: + reasons_to_skip.append(" - " + reason) + + if reasons_to_skip: + self.skipTest("\n".join(reasons_to_skip)) + + customized_parameters = [] + for combination in test_combinations: + customized_parameters.extend(combination.parameter_modifiers()) + customized_parameters = set(customized_parameters) + + # The function for running the test under the total set of + # `context_managers`: + def execute_test_method(): + requested_parameters = tf_inspect.getfullargspec(test_method).args + for customized_parameter in customized_parameters: + for argument, value in customized_parameter.modified_arguments( + original_kwargs.copy(), requested_parameters).items(): + if value is ParameterModifier.DO_NOT_PASS_TO_THE_TEST: + kwargs.pop(argument, None) + else: + kwargs[argument] = value + + omitted_arguments = set(requested_parameters).difference( + set(list(kwargs.keys()) + ["self"])) + if omitted_arguments: + raise ValueError("The test requires parameters whose arguments " + "were not passed: {} .".format(omitted_arguments)) + missing_arguments = set(list(kwargs.keys()) + ["self"]).difference( + set(requested_parameters)) + if missing_arguments: + raise ValueError("The test does not take parameters that were passed " + ": {} .".format(missing_arguments)) + + kwargs_to_pass = {} + for parameter in requested_parameters: + if parameter == "self": + kwargs_to_pass[parameter] = self + else: + kwargs_to_pass[parameter] = kwargs[parameter] + test_method(**kwargs_to_pass) + + # Install `context_managers` before running the test: + context_managers = [] + for combination in test_combinations: + for manager in combination.context_managers( + original_kwargs.copy()): + context_managers.append(manager) + + if hasattr(contextlib, "nested"): # Python 2 + # TODO(isaprykin): Switch to ExitStack when contextlib2 is available. + with contextlib.nested(*context_managers): + execute_test_method() + else: # Python 3 + with contextlib.ExitStack() as context_stack: + for manager in context_managers: + context_stack.enter_context(manager) + execute_test_method() + + return decorated + + +@tf_export("__internal__.test.combinations.combine", v1=[]) +def combine(**kwargs): + """Generate combinations based on its keyword arguments. + + Two sets of returned combinations can be concatenated using +. Their product + can be computed using `times()`. + + Args: + **kwargs: keyword arguments of form `option=[possibilities, ...]` + or `option=the_only_possibility`. + + Returns: + a list of dictionaries for each combination. Keys in the dictionaries are + the keyword argument names. Each key has one value - one of the + corresponding keyword argument values. + """ + if not kwargs: + return [OrderedDict()] + + sort_by_key = lambda k: k[0] + kwargs = OrderedDict(sorted(kwargs.items(), key=sort_by_key)) + first = list(kwargs.items())[0] + + rest = dict(list(kwargs.items())[1:]) + rest_combined = combine(**rest) + + key = first[0] + values = first[1] + if not isinstance(values, list): + values = [values] + + return [ + OrderedDict(sorted(list(combined.items()) + [(key, v)], key=sort_by_key)) + for v in values + for combined in rest_combined + ] + + +@tf_export("__internal__.test.combinations.times", v1=[]) +def times(*combined): + """Generate a product of N sets of combinations. + + times(combine(a=[1,2]), combine(b=[3,4])) == combine(a=[1,2], b=[3,4]) + + Args: + *combined: N lists of dictionaries that specify combinations. + + Returns: + a list of dictionaries for each combination. + + Raises: + ValueError: if some of the inputs have overlapping keys. + """ + assert combined + + if len(combined) == 1: + return combined[0] + + first = combined[0] + rest_combined = times(*combined[1:]) + + combined_results = [] + for a in first: + for b in rest_combined: + if set(a.keys()).intersection(set(b.keys())): + raise ValueError("Keys need to not overlap: {} vs {}".format( + a.keys(), b.keys())) + + combined_results.append(OrderedDict(list(a.items()) + list(b.items()))) + return combined_results + + +@tf_export("__internal__.test.combinations.NamedObject", v1=[]) +class NamedObject: + """A class that translates an object into a good test name.""" + + def __init__(self, name, obj): + self._name = name + self._obj = obj + + def __getattr__(self, name): + return getattr(self._obj, name) + + def __call__(self, *args, **kwargs): + return self._obj(*args, **kwargs) + + def __iter__(self): + return self._obj.__iter__() + + def __repr__(self): + return self._name + + +def _get_name(value, index): + return re.sub("0[xX][0-9a-fA-F]+", str(index), str(value)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_ops.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..8e13217fa95fd61f33175ba7a1b5373a5a30dcfc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_ops.py @@ -0,0 +1,8773 @@ +"""Python wrappers around TensorFlow ops. + +This file is MACHINE GENERATED! Do not edit. +""" + +import collections + +from tensorflow.python import pywrap_tfe as pywrap_tfe +from tensorflow.python.eager import context as _context +from tensorflow.python.eager import core as _core +from tensorflow.python.eager import execute as _execute +from tensorflow.python.framework import dtypes as _dtypes +from tensorflow.security.fuzzing.py import annotation_types as _atypes + +from tensorflow.python.framework import op_def_registry as _op_def_registry +from tensorflow.python.framework import ops as _ops +from tensorflow.python.framework import op_def_library as _op_def_library +from tensorflow.python.util.deprecation import deprecated_endpoints +from tensorflow.python.util import dispatch as _dispatch +from tensorflow.python.util.tf_export import tf_export + +from typing import TypeVar, List, Any +from typing_extensions import Annotated + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('a') +def a(name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "A", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_a( + (name,), None) + if _result is not NotImplemented: + return _result + return a_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + a, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_a( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "A", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + a, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "A", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +A = tf_export("raw_ops.A")(_ops.to_raw_op(a)) +_dispatcher_for_a = a._tf_type_based_dispatcher.Dispatch + + +def a_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Float32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"A", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "A", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr') +def attr(a: int, name=None): + r"""TODO: add doc. + + Args: + a: An `int`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Attr", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_int(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Attr", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +Attr = tf_export("raw_ops.Attr")(_ops.to_raw_op(attr)) +_dispatcher_for_attr = attr._tf_type_based_dispatcher.Dispatch + + +def attr_eager_fallback(a: int, name, ctx): + a = _execute.make_int(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"Attr", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_bool') +def attr_bool(a: bool, name=None): + r"""TODO: add doc. + + Args: + a: A `bool`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrBool", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_bool( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_bool_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_bool, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_bool( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_bool(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrBool", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_bool, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrBool = tf_export("raw_ops.AttrBool")(_ops.to_raw_op(attr_bool)) +_dispatcher_for_attr_bool = attr_bool._tf_type_based_dispatcher.Dispatch + + +def attr_bool_eager_fallback(a: bool, name, ctx): + a = _execute.make_bool(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrBool", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_bool_list') +def attr_bool_list(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of `bools`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrBoolList", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_bool_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_bool_list_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_bool_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_bool_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_bool_list' Op, not %r." % a) + a = [_execute.make_bool(_b, "a") for _b in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrBoolList", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_bool_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrBoolList = tf_export("raw_ops.AttrBoolList")(_ops.to_raw_op(attr_bool_list)) +_dispatcher_for_attr_bool_list = attr_bool_list._tf_type_based_dispatcher.Dispatch + + +def attr_bool_list_eager_fallback(a, name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_bool_list' Op, not %r." % a) + a = [_execute.make_bool(_b, "a") for _b in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrBoolList", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_default') +def attr_default(a:str="banana", name=None): + r"""TODO: add doc. + + Args: + a: An optional `string`. Defaults to `"banana"`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrDefault", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_default_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if a is None: + a = "banana" + a = _execute.make_str(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrDefault", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrDefault = tf_export("raw_ops.AttrDefault")(_ops.to_raw_op(attr_default)) +_dispatcher_for_attr_default = attr_default._tf_type_based_dispatcher.Dispatch + + +def attr_default_eager_fallback(a: str, name, ctx): + if a is None: + a = "banana" + a = _execute.make_str(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrDefault", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_empty_list_default') +def attr_empty_list_default(a=[], name=None): + r"""TODO: add doc. + + Args: + a: An optional list of `floats`. Defaults to `[]`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrEmptyListDefault", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_empty_list_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_empty_list_default_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_empty_list_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_empty_list_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if a is None: + a = [] + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_empty_list_default' Op, not %r." % a) + a = [_execute.make_float(_f, "a") for _f in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrEmptyListDefault", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_empty_list_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrEmptyListDefault = tf_export("raw_ops.AttrEmptyListDefault")(_ops.to_raw_op(attr_empty_list_default)) +_dispatcher_for_attr_empty_list_default = attr_empty_list_default._tf_type_based_dispatcher.Dispatch + + +def attr_empty_list_default_eager_fallback(a, name, ctx): + if a is None: + a = [] + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_empty_list_default' Op, not %r." % a) + a = [_execute.make_float(_f, "a") for _f in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrEmptyListDefault", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_enum') +def attr_enum(a: str, name=None): + r"""TODO: add doc. + + Args: + a: A `string` from: `"apples", "oranges"`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrEnum", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_enum( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_enum_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_enum, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_enum( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_str(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrEnum", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_enum, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrEnum = tf_export("raw_ops.AttrEnum")(_ops.to_raw_op(attr_enum)) +_dispatcher_for_attr_enum = attr_enum._tf_type_based_dispatcher.Dispatch + + +def attr_enum_eager_fallback(a: str, name, ctx): + a = _execute.make_str(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrEnum", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_enum_list') +def attr_enum_list(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of `strings` from: `"apples", "oranges"`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrEnumList", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_enum_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_enum_list_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_enum_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_enum_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_enum_list' Op, not %r." % a) + a = [_execute.make_str(_s, "a") for _s in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrEnumList", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_enum_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrEnumList = tf_export("raw_ops.AttrEnumList")(_ops.to_raw_op(attr_enum_list)) +_dispatcher_for_attr_enum_list = attr_enum_list._tf_type_based_dispatcher.Dispatch + + +def attr_enum_list_eager_fallback(a, name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_enum_list' Op, not %r." % a) + a = [_execute.make_str(_s, "a") for _s in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrEnumList", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_float') +def attr_float(a: float, name=None): + r"""TODO: add doc. + + Args: + a: A `float`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrFloat", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_float( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_float_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_float, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_float( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_float(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrFloat", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_float, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrFloat = tf_export("raw_ops.AttrFloat")(_ops.to_raw_op(attr_float)) +_dispatcher_for_attr_float = attr_float._tf_type_based_dispatcher.Dispatch + + +def attr_float_eager_fallback(a: float, name, ctx): + a = _execute.make_float(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrFloat", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_list_default') +def attr_list_default(a=[5, 15], name=None): + r"""TODO: add doc. + + Args: + a: An optional list of `ints`. Defaults to `[5, 15]`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrListDefault", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_list_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_list_default_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_list_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_list_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if a is None: + a = [5, 15] + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_list_default' Op, not %r." % a) + a = [_execute.make_int(_i, "a") for _i in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrListDefault", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_list_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrListDefault = tf_export("raw_ops.AttrListDefault")(_ops.to_raw_op(attr_list_default)) +_dispatcher_for_attr_list_default = attr_list_default._tf_type_based_dispatcher.Dispatch + + +def attr_list_default_eager_fallback(a, name, ctx): + if a is None: + a = [5, 15] + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_list_default' Op, not %r." % a) + a = [_execute.make_int(_i, "a") for _i in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrListDefault", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_list_min') +def attr_list_min(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of `ints` that has length `>= 2`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrListMin", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_list_min( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_list_min_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_list_min, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_list_min( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_list_min' Op, not %r." % a) + a = [_execute.make_int(_i, "a") for _i in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrListMin", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_list_min, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrListMin = tf_export("raw_ops.AttrListMin")(_ops.to_raw_op(attr_list_min)) +_dispatcher_for_attr_list_min = attr_list_min._tf_type_based_dispatcher.Dispatch + + +def attr_list_min_eager_fallback(a, name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_list_min' Op, not %r." % a) + a = [_execute.make_int(_i, "a") for _i in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrListMin", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_AttrListTypeDefault_T = TypeVar("TV_AttrListTypeDefault_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_list_type_default') +def attr_list_type_default(a: Annotated[List[Any], TV_AttrListTypeDefault_T], b: Annotated[List[Any], TV_AttrListTypeDefault_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of at least 1 `Tensor` objects with the same type. + b: A list with the same length as `a` of `Tensor` objects with the same type as `a`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrListTypeDefault", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_list_type_default( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return attr_list_type_default_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_list_type_default, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_list_type_default( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_list_type_default' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'attr_list_type_default' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'attr_list_type_default' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrListTypeDefault", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_list_type_default, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrListTypeDefault = tf_export("raw_ops.AttrListTypeDefault")(_ops.to_raw_op(attr_list_type_default)) +_dispatcher_for_attr_list_type_default = attr_list_type_default._tf_type_based_dispatcher.Dispatch + + +def attr_list_type_default_eager_fallback(a: Annotated[List[Any], TV_AttrListTypeDefault_T], b: Annotated[List[Any], TV_AttrListTypeDefault_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_list_type_default' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'attr_list_type_default' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'attr_list_type_default' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + _attr_T, _inputs_T = _execute.args_to_matching_eager(list(a) + list(b), ctx, [], _dtypes.int32) + _inputs_T = [_inputs_T[:_attr_N]] + _inputs_T[_attr_N:] + _inputs_T = _inputs_T[:1] + [_inputs_T[1:]] + (a, b) = _inputs_T + _inputs_flat = list(a) + list(b) + _attrs = ("T", _attr_T, "N", _attr_N) + _result = _execute.execute(b"AttrListTypeDefault", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_min') +def attr_min(a: int, name=None): + r"""TODO: add doc. + + Args: + a: An `int` that is `>= 5`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrMin", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_min( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_min_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_min, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_min( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_int(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrMin", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_min, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrMin = tf_export("raw_ops.AttrMin")(_ops.to_raw_op(attr_min)) +_dispatcher_for_attr_min = attr_min._tf_type_based_dispatcher.Dispatch + + +def attr_min_eager_fallback(a: int, name, ctx): + a = _execute.make_int(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrMin", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_partial_shape') +def attr_partial_shape(a, name=None): + r"""TODO: add doc. + + Args: + a: A `tf.TensorShape` or list of `ints`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrPartialShape", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_partial_shape( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_partial_shape_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_partial_shape, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_partial_shape( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_shape(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrPartialShape", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_partial_shape, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrPartialShape = tf_export("raw_ops.AttrPartialShape")(_ops.to_raw_op(attr_partial_shape)) +_dispatcher_for_attr_partial_shape = attr_partial_shape._tf_type_based_dispatcher.Dispatch + + +def attr_partial_shape_eager_fallback(a, name, ctx): + a = _execute.make_shape(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrPartialShape", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_partial_shape_list') +def attr_partial_shape_list(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of shapes (each a `tf.TensorShape` or list of `ints`). + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrPartialShapeList", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_partial_shape_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_partial_shape_list_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_partial_shape_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_partial_shape_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_partial_shape_list' Op, not %r." % a) + a = [_execute.make_shape(_s, "a") for _s in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrPartialShapeList", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_partial_shape_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrPartialShapeList = tf_export("raw_ops.AttrPartialShapeList")(_ops.to_raw_op(attr_partial_shape_list)) +_dispatcher_for_attr_partial_shape_list = attr_partial_shape_list._tf_type_based_dispatcher.Dispatch + + +def attr_partial_shape_list_eager_fallback(a, name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_partial_shape_list' Op, not %r." % a) + a = [_execute.make_shape(_s, "a") for _s in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrPartialShapeList", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_shape') +def attr_shape(a, name=None): + r"""TODO: add doc. + + Args: + a: A `tf.TensorShape` or list of `ints`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrShape", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_shape( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_shape_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_shape, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_shape( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + a = _execute.make_shape(a, "a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrShape", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_shape, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrShape = tf_export("raw_ops.AttrShape")(_ops.to_raw_op(attr_shape)) +_dispatcher_for_attr_shape = attr_shape._tf_type_based_dispatcher.Dispatch + + +def attr_shape_eager_fallback(a, name, ctx): + a = _execute.make_shape(a, "a") + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrShape", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_shape_list') +def attr_shape_list(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of shapes (each a `tf.TensorShape` or list of `ints`). + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrShapeList", name, "a", a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_shape_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_shape_list_eager_fallback( + a=a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_shape_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_shape_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_shape_list' Op, not %r." % a) + a = [_execute.make_shape(_s, "a") for _s in a] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrShapeList", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_shape_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrShapeList = tf_export("raw_ops.AttrShapeList")(_ops.to_raw_op(attr_shape_list)) +_dispatcher_for_attr_shape_list = attr_shape_list._tf_type_based_dispatcher.Dispatch + + +def attr_shape_list_eager_fallback(a, name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'attr_shape_list' Op, not %r." % a) + a = [_execute.make_shape(_s, "a") for _s in a] + _inputs_flat = [] + _attrs = ("a", a) + _result = _execute.execute(b"AttrShapeList", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_AttrTypeDefault_T = TypeVar("TV_AttrTypeDefault_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('attr_type_default') +def attr_type_default(a: Annotated[Any, TV_AttrTypeDefault_T], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "AttrTypeDefault", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_attr_type_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + return attr_type_default_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_type_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_attr_type_default( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "AttrTypeDefault", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + attr_type_default, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +AttrTypeDefault = tf_export("raw_ops.AttrTypeDefault")(_ops.to_raw_op(attr_type_default)) +_dispatcher_for_attr_type_default = attr_type_default._tf_type_based_dispatcher.Dispatch + + +def attr_type_default_eager_fallback(a: Annotated[Any, TV_AttrTypeDefault_T], name, ctx): + _attr_T, (a,) = _execute.args_to_matching_eager([a], ctx, [], _dtypes.int32) + _inputs_flat = [a] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"AttrTypeDefault", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('b') +def b(name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "B", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_b( + (name,), None) + if _result is not NotImplemented: + return _result + return b_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + b, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_b( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "B", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + b, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "B", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +B = tf_export("raw_ops.B")(_ops.to_raw_op(b)) +_dispatcher_for_b = b._tf_type_based_dispatcher.Dispatch + + +def b_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Float32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"B", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "B", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_Binary_T = TypeVar("TV_Binary_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('binary') +def binary(a: Annotated[Any, TV_Binary_T], b: Annotated[Any, TV_Binary_T], name=None) -> Annotated[Any, TV_Binary_T]: + r"""TODO: add doc. + + Args: + a: A `Tensor`. + b: A `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Binary", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_binary( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return binary_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + binary, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_binary( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Binary", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + binary, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Binary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Binary = tf_export("raw_ops.Binary")(_ops.to_raw_op(binary)) +_dispatcher_for_binary = binary._tf_type_based_dispatcher.Dispatch + + +def binary_eager_fallback(a: Annotated[Any, TV_Binary_T], b: Annotated[Any, TV_Binary_T], name, ctx) -> Annotated[Any, TV_Binary_T]: + _attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], ctx, []) + (a, b) = _inputs_T + _inputs_flat = [a, b] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Binary", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Binary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_ComplexStructOutput = collections.namedtuple( + "ComplexStruct", + ["a", "b", "c"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('complex_struct') +def complex_struct(n_a: int, n_b: int, t_c, name=None): + r"""TODO: add doc. + + Args: + n_a: An `int` that is `>= 0`. + n_b: An `int` that is `>= 0`. + t_c: A list of `tf.DTypes`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b, c). + + a: A list of `n_a` `Tensor` objects with type `int32`. + b: A list of `n_b` `Tensor` objects with type `int64`. + c: A list of `Tensor` objects of type `t_c`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ComplexStruct", name, "n_a", n_a, "n_b", n_b, "t_c", t_c) + _result = _ComplexStructOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_complex_struct( + (n_a, n_b, t_c, name,), None) + if _result is not NotImplemented: + return _result + return complex_struct_eager_fallback( + n_a=n_a, n_b=n_b, t_c=t_c, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + complex_struct, (), dict(n_a=n_a, n_b=n_b, t_c=t_c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_complex_struct( + (n_a, n_b, t_c, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + n_a = _execute.make_int(n_a, "n_a") + n_b = _execute.make_int(n_b, "n_b") + if not isinstance(t_c, (list, tuple)): + raise TypeError( + "Expected list for 't_c' argument to " + "'complex_struct' Op, not %r." % t_c) + t_c = [_execute.make_type(_t, "t_c") for _t in t_c] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ComplexStruct", n_a=n_a, n_b=n_b, t_c=t_c, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + complex_struct, (), dict(n_a=n_a, n_b=n_b, t_c=t_c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("n_a", _op._get_attr_int("n_a"), "n_b", + _op._get_attr_int("n_b"), "t_c", _op.get_attr("t_c")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ComplexStruct", _inputs_flat, _attrs, _result) + _result = [_result[:n_a]] + _result[n_a:] + _result = _result[:1] + [_result[1:1 + n_b]] + _result[1 + n_b:] + _result = _result[:2] + [_result[2:]] + _result = _ComplexStructOutput._make(_result) + return _result + +ComplexStruct = tf_export("raw_ops.ComplexStruct")(_ops.to_raw_op(complex_struct)) +_dispatcher_for_complex_struct = complex_struct._tf_type_based_dispatcher.Dispatch + + +def complex_struct_eager_fallback(n_a: int, n_b: int, t_c, name, ctx): + n_a = _execute.make_int(n_a, "n_a") + n_b = _execute.make_int(n_b, "n_b") + if not isinstance(t_c, (list, tuple)): + raise TypeError( + "Expected list for 't_c' argument to " + "'complex_struct' Op, not %r." % t_c) + t_c = [_execute.make_type(_t, "t_c") for _t in t_c] + _inputs_flat = [] + _attrs = ("n_a", n_a, "n_b", n_b, "t_c", t_c) + _result = _execute.execute(b"ComplexStruct", n_a + n_b + len(t_c), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ComplexStruct", _inputs_flat, _attrs, _result) + _result = [_result[:n_a]] + _result[n_a:] + _result = _result[:1] + [_result[1:1 + n_b]] + _result[1 + n_b:] + _result = _result[:2] + [_result[2:]] + _result = _ComplexStructOutput._make(_result) + return _result + + +TV_CopyOp_T = TypeVar("TV_CopyOp_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('copy_op') +def copy_op(a: Annotated[Any, TV_CopyOp_T], name=None) -> Annotated[Any, TV_CopyOp_T]: + r"""TODO: add doc. + + Args: + a: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "CopyOp", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_copy_op( + (a, name,), None) + if _result is not NotImplemented: + return _result + return copy_op_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + copy_op, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_copy_op( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "CopyOp", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + copy_op, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "CopyOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +CopyOp = tf_export("raw_ops.CopyOp")(_ops.to_raw_op(copy_op)) +_dispatcher_for_copy_op = copy_op._tf_type_based_dispatcher.Dispatch + + +def copy_op_eager_fallback(a: Annotated[Any, TV_CopyOp_T], name, ctx) -> Annotated[Any, TV_CopyOp_T]: + _attr_T, (a,) = _execute.args_to_matching_eager([a], ctx, []) + _inputs_flat = [a] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"CopyOp", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "CopyOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DefaultAttrs_type_val = TypeVar("TV_DefaultAttrs_type_val", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('default_attrs') +def default_attrs(string_val:str="abc", string_list_val=["abc", ""], int_val:int=123, int_list_val=[1, 2, 3], float_val:float=10, float_list_val=[10], bool_val:bool=True, bool_list_val=[True, False], type_val:TV_DefaultAttrs_type_val=_dtypes.int32, type_list_val=[_dtypes.int32, _dtypes.float32], shape_val=[2, 1], shape_list_val=[[], [1]], tensor_val=_execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1 """, "tensor_val"), tensor_list_val=[_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1 """,)], name=None): + r"""TODO: add doc. + + Args: + string_val: An optional `string`. Defaults to `"abc"`. + string_list_val: An optional list of `strings`. Defaults to `["abc", ""]`. + int_val: An optional `int`. Defaults to `123`. + int_list_val: An optional list of `ints`. Defaults to `[1, 2, 3]`. + float_val: An optional `float`. Defaults to `10`. + float_list_val: An optional list of `floats`. Defaults to `[10]`. + bool_val: An optional `bool`. Defaults to `True`. + bool_list_val: An optional list of `bools`. Defaults to `[True, False]`. + type_val: An optional `tf.DType`. Defaults to `tf.int32`. + type_list_val: An optional list of `tf.DTypes`. Defaults to `[tf.int32, tf.float32]`. + shape_val: An optional `tf.TensorShape` or list of `ints`. Defaults to `[2, 1]`. + shape_list_val: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[[], [1]]`. + tensor_val: An optional `tf.TensorProto`. Defaults to `dtype: DT_INT32 tensor_shape { } int_val: 1`. + tensor_list_val: An optional list of `tf.TensorProto` objects. Defaults to `[dtype: DT_INT32 tensor_shape { } int_val: 1]`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DefaultAttrs", name, "string_val", string_val, + "string_list_val", string_list_val, "int_val", int_val, + "int_list_val", int_list_val, "float_val", float_val, + "float_list_val", float_list_val, "bool_val", bool_val, + "bool_list_val", bool_list_val, "type_val", type_val, "type_list_val", + type_list_val, "shape_val", shape_val, "shape_list_val", + shape_list_val, "tensor_val", tensor_val, "tensor_list_val", + tensor_list_val) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_default_attrs( + (string_val, string_list_val, int_val, int_list_val, float_val, + float_list_val, bool_val, bool_list_val, type_val, type_list_val, + shape_val, shape_list_val, tensor_val, tensor_list_val, name,), None) + if _result is not NotImplemented: + return _result + return default_attrs_eager_fallback( + string_val=string_val, string_list_val=string_list_val, + int_val=int_val, int_list_val=int_list_val, float_val=float_val, + float_list_val=float_list_val, bool_val=bool_val, + bool_list_val=bool_list_val, type_val=type_val, + type_list_val=type_list_val, shape_val=shape_val, + shape_list_val=shape_list_val, tensor_val=tensor_val, + tensor_list_val=tensor_list_val, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + default_attrs, (), dict(string_val=string_val, + string_list_val=string_list_val, + int_val=int_val, + int_list_val=int_list_val, + float_val=float_val, + float_list_val=float_list_val, + bool_val=bool_val, + bool_list_val=bool_list_val, + type_val=type_val, + type_list_val=type_list_val, + shape_val=shape_val, + shape_list_val=shape_list_val, + tensor_val=tensor_val, + tensor_list_val=tensor_list_val, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_default_attrs( + (string_val, string_list_val, int_val, int_list_val, float_val, + float_list_val, bool_val, bool_list_val, type_val, type_list_val, + shape_val, shape_list_val, tensor_val, tensor_list_val, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if string_val is None: + string_val = "abc" + string_val = _execute.make_str(string_val, "string_val") + if string_list_val is None: + string_list_val = ["abc", ""] + if not isinstance(string_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'string_list_val' argument to " + "'default_attrs' Op, not %r." % string_list_val) + string_list_val = [_execute.make_str(_s, "string_list_val") for _s in string_list_val] + if int_val is None: + int_val = 123 + int_val = _execute.make_int(int_val, "int_val") + if int_list_val is None: + int_list_val = [1, 2, 3] + if not isinstance(int_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'int_list_val' argument to " + "'default_attrs' Op, not %r." % int_list_val) + int_list_val = [_execute.make_int(_i, "int_list_val") for _i in int_list_val] + if float_val is None: + float_val = 10 + float_val = _execute.make_float(float_val, "float_val") + if float_list_val is None: + float_list_val = [10] + if not isinstance(float_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'float_list_val' argument to " + "'default_attrs' Op, not %r." % float_list_val) + float_list_val = [_execute.make_float(_f, "float_list_val") for _f in float_list_val] + if bool_val is None: + bool_val = True + bool_val = _execute.make_bool(bool_val, "bool_val") + if bool_list_val is None: + bool_list_val = [True, False] + if not isinstance(bool_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'bool_list_val' argument to " + "'default_attrs' Op, not %r." % bool_list_val) + bool_list_val = [_execute.make_bool(_b, "bool_list_val") for _b in bool_list_val] + if type_val is None: + type_val = _dtypes.int32 + type_val = _execute.make_type(type_val, "type_val") + if type_list_val is None: + type_list_val = [_dtypes.int32, _dtypes.float32] + if not isinstance(type_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'type_list_val' argument to " + "'default_attrs' Op, not %r." % type_list_val) + type_list_val = [_execute.make_type(_t, "type_list_val") for _t in type_list_val] + if shape_val is None: + shape_val = [2, 1] + shape_val = _execute.make_shape(shape_val, "shape_val") + if shape_list_val is None: + shape_list_val = [[], [1]] + if not isinstance(shape_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'shape_list_val' argument to " + "'default_attrs' Op, not %r." % shape_list_val) + shape_list_val = [_execute.make_shape(_s, "shape_list_val") for _s in shape_list_val] + if tensor_val is None: + tensor_val = _execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1 """, "tensor_val") + tensor_val = _execute.make_tensor(tensor_val, "tensor_val") + if tensor_list_val is None: + tensor_list_val = [_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1 """,)] + if not isinstance(tensor_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'tensor_list_val' argument to " + "'default_attrs' Op, not %r." % tensor_list_val) + tensor_list_val = [_execute.make_tensor(_t, "tensor_list_val") for _t in tensor_list_val] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DefaultAttrs", string_val=string_val, + string_list_val=string_list_val, int_val=int_val, + int_list_val=int_list_val, float_val=float_val, + float_list_val=float_list_val, bool_val=bool_val, + bool_list_val=bool_list_val, type_val=type_val, + type_list_val=type_list_val, shape_val=shape_val, + shape_list_val=shape_list_val, tensor_val=tensor_val, + tensor_list_val=tensor_list_val, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + default_attrs, (), dict(string_val=string_val, + string_list_val=string_list_val, + int_val=int_val, int_list_val=int_list_val, + float_val=float_val, + float_list_val=float_list_val, + bool_val=bool_val, + bool_list_val=bool_list_val, + type_val=type_val, + type_list_val=type_list_val, + shape_val=shape_val, + shape_list_val=shape_list_val, + tensor_val=tensor_val, + tensor_list_val=tensor_list_val, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +DefaultAttrs = tf_export("raw_ops.DefaultAttrs")(_ops.to_raw_op(default_attrs)) +_dispatcher_for_default_attrs = default_attrs._tf_type_based_dispatcher.Dispatch + + +def default_attrs_eager_fallback(string_val: str, string_list_val, int_val: int, int_list_val, float_val: float, float_list_val, bool_val: bool, bool_list_val, type_val: TV_DefaultAttrs_type_val, type_list_val, shape_val, shape_list_val, tensor_val, tensor_list_val, name, ctx): + if string_val is None: + string_val = "abc" + string_val = _execute.make_str(string_val, "string_val") + if string_list_val is None: + string_list_val = ["abc", ""] + if not isinstance(string_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'string_list_val' argument to " + "'default_attrs' Op, not %r." % string_list_val) + string_list_val = [_execute.make_str(_s, "string_list_val") for _s in string_list_val] + if int_val is None: + int_val = 123 + int_val = _execute.make_int(int_val, "int_val") + if int_list_val is None: + int_list_val = [1, 2, 3] + if not isinstance(int_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'int_list_val' argument to " + "'default_attrs' Op, not %r." % int_list_val) + int_list_val = [_execute.make_int(_i, "int_list_val") for _i in int_list_val] + if float_val is None: + float_val = 10 + float_val = _execute.make_float(float_val, "float_val") + if float_list_val is None: + float_list_val = [10] + if not isinstance(float_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'float_list_val' argument to " + "'default_attrs' Op, not %r." % float_list_val) + float_list_val = [_execute.make_float(_f, "float_list_val") for _f in float_list_val] + if bool_val is None: + bool_val = True + bool_val = _execute.make_bool(bool_val, "bool_val") + if bool_list_val is None: + bool_list_val = [True, False] + if not isinstance(bool_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'bool_list_val' argument to " + "'default_attrs' Op, not %r." % bool_list_val) + bool_list_val = [_execute.make_bool(_b, "bool_list_val") for _b in bool_list_val] + if type_val is None: + type_val = _dtypes.int32 + type_val = _execute.make_type(type_val, "type_val") + if type_list_val is None: + type_list_val = [_dtypes.int32, _dtypes.float32] + if not isinstance(type_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'type_list_val' argument to " + "'default_attrs' Op, not %r." % type_list_val) + type_list_val = [_execute.make_type(_t, "type_list_val") for _t in type_list_val] + if shape_val is None: + shape_val = [2, 1] + shape_val = _execute.make_shape(shape_val, "shape_val") + if shape_list_val is None: + shape_list_val = [[], [1]] + if not isinstance(shape_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'shape_list_val' argument to " + "'default_attrs' Op, not %r." % shape_list_val) + shape_list_val = [_execute.make_shape(_s, "shape_list_val") for _s in shape_list_val] + if tensor_val is None: + tensor_val = _execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1 """, "tensor_val") + tensor_val = _execute.make_tensor(tensor_val, "tensor_val") + if tensor_list_val is None: + tensor_list_val = [_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1 """,)] + if not isinstance(tensor_list_val, (list, tuple)): + raise TypeError( + "Expected list for 'tensor_list_val' argument to " + "'default_attrs' Op, not %r." % tensor_list_val) + tensor_list_val = [_execute.make_tensor(_t, "tensor_list_val") for _t in tensor_list_val] + _inputs_flat = [] + _attrs = ("string_val", string_val, "string_list_val", string_list_val, + "int_val", int_val, "int_list_val", int_list_val, "float_val", float_val, + "float_list_val", float_list_val, "bool_val", bool_val, "bool_list_val", + bool_list_val, "type_val", type_val, "type_list_val", type_list_val, + "shape_val", shape_val, "shape_list_val", shape_list_val, "tensor_val", + tensor_val, "tensor_list_val", tensor_list_val) + _result = _execute.execute(b"DefaultAttrs", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('device_placement_op') +def device_placement_op(name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DevicePlacementOp", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_device_placement_op( + (name,), None) + if _result is not NotImplemented: + return _result + return device_placement_op_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + device_placement_op, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_device_placement_op( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DevicePlacementOp", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + device_placement_op, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "DevicePlacementOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DevicePlacementOp = tf_export("raw_ops.DevicePlacementOp")(_ops.to_raw_op(device_placement_op)) +_dispatcher_for_device_placement_op = device_placement_op._tf_type_based_dispatcher.Dispatch + + +def device_placement_op_eager_fallback(name, ctx) -> Annotated[Any, _atypes.String]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"DevicePlacementOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DevicePlacementOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_DtypeWithDefaultOp_T = TypeVar("TV_DtypeWithDefaultOp_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('dtype_with_default_op') +def dtype_with_default_op(in_: Annotated[Any, TV_DtypeWithDefaultOp_T], name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + in_: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "DtypeWithDefaultOp", name, in_) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_dtype_with_default_op( + (in_, name,), None) + if _result is not NotImplemented: + return _result + return dtype_with_default_op_eager_fallback( + in_, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + dtype_with_default_op, (), dict(in_=in_, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_dtype_with_default_op( + (in_, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "DtypeWithDefaultOp", in_=in_, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + dtype_with_default_op, (), dict(in_=in_, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "DtypeWithDefaultOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +DtypeWithDefaultOp = tf_export("raw_ops.DtypeWithDefaultOp")(_ops.to_raw_op(dtype_with_default_op)) +_dispatcher_for_dtype_with_default_op = dtype_with_default_op._tf_type_based_dispatcher.Dispatch + + +def dtype_with_default_op_eager_fallback(in_: Annotated[Any, TV_DtypeWithDefaultOp_T], name, ctx) -> Annotated[Any, _atypes.String]: + _attr_T, (in_,) = _execute.args_to_matching_eager([in_], ctx, [], _dtypes.uint8) + _inputs_flat = [in_] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"DtypeWithDefaultOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "DtypeWithDefaultOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FiveFloatOutputsOutput = collections.namedtuple( + "FiveFloatOutputs", + ["a", "b", "c", "d", "e"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('five_float_outputs') +def five_float_outputs(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b, c, d, e). + + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `float32`. + c: A `Tensor` of type `float32`. + d: A `Tensor` of type `float32`. + e: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FiveFloatOutputs", name) + _result = _FiveFloatOutputsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_five_float_outputs( + (name,), None) + if _result is not NotImplemented: + return _result + return five_float_outputs_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + five_float_outputs, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_five_float_outputs( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FiveFloatOutputs", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + five_float_outputs, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "FiveFloatOutputs", _inputs_flat, _attrs, _result) + _result = _FiveFloatOutputsOutput._make(_result) + return _result + +FiveFloatOutputs = tf_export("raw_ops.FiveFloatOutputs")(_ops.to_raw_op(five_float_outputs)) +_dispatcher_for_five_float_outputs = five_float_outputs._tf_type_based_dispatcher.Dispatch + + +def five_float_outputs_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"FiveFloatOutputs", 5, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FiveFloatOutputs", _inputs_flat, _attrs, _result) + _result = _FiveFloatOutputsOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('float_input') +def float_input(a: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FloatInput", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_float_input( + (a, name,), None) + if _result is not NotImplemented: + return _result + return float_input_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + float_input, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_float_input( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FloatInput", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + float_input, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +FloatInput = tf_export("raw_ops.FloatInput")(_ops.to_raw_op(float_input)) +_dispatcher_for_float_input = float_input._tf_type_based_dispatcher.Dispatch + + +def float_input_eager_fallback(a: Annotated[Any, _atypes.Float32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.float32) + _inputs_flat = [a] + _attrs = None + _result = _execute.execute(b"FloatInput", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('float_output') +def float_output(name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FloatOutput", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_float_output( + (name,), None) + if _result is not NotImplemented: + return _result + return float_output_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + float_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_float_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FloatOutput", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + float_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "FloatOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +FloatOutput = tf_export("raw_ops.FloatOutput")(_ops.to_raw_op(float_output)) +_dispatcher_for_float_output = float_output._tf_type_based_dispatcher.Dispatch + + +def float_output_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Float32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"FloatOutput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FloatOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_FloatOutputStringOutputOutput = collections.namedtuple( + "FloatOutputStringOutput", + ["a", "b"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('float_output_string_output') +def float_output_string_output(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b). + + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FloatOutputStringOutput", name) + _result = _FloatOutputStringOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_float_output_string_output( + (name,), None) + if _result is not NotImplemented: + return _result + return float_output_string_output_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + float_output_string_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_float_output_string_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FloatOutputStringOutput", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + float_output_string_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "FloatOutputStringOutput", _inputs_flat, _attrs, _result) + _result = _FloatOutputStringOutputOutput._make(_result) + return _result + +FloatOutputStringOutput = tf_export("raw_ops.FloatOutputStringOutput")(_ops.to_raw_op(float_output_string_output)) +_dispatcher_for_float_output_string_output = float_output_string_output._tf_type_based_dispatcher.Dispatch + + +def float_output_string_output_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"FloatOutputStringOutput", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "FloatOutputStringOutput", _inputs_flat, _attrs, _result) + _result = _FloatOutputStringOutputOutput._make(_result) + return _result + +_Foo1Output = collections.namedtuple( + "Foo1", + ["d", "e"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('foo1') +def foo1(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Int32], c: Annotated[Any, _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `int32`. + c: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (d, e). + + d: A `Tensor` of type `float32`. + e: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Foo1", name, a, b, c) + _result = _Foo1Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_foo1( + (a, b, c, name,), None) + if _result is not NotImplemented: + return _result + return foo1_eager_fallback( + a, b, c, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + foo1, (), dict(a=a, b=b, c=c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_foo1( + (a, b, c, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Foo1", a=a, b=b, c=c, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + foo1, (), dict(a=a, b=b, c=c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Foo1", _inputs_flat, _attrs, _result) + _result = _Foo1Output._make(_result) + return _result + +Foo1 = tf_export("raw_ops.Foo1")(_ops.to_raw_op(foo1)) +_dispatcher_for_foo1 = foo1._tf_type_based_dispatcher.Dispatch + + +def foo1_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Int32], c: Annotated[Any, _atypes.Int32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.float32) + b = _ops.convert_to_tensor(b, _dtypes.int32) + c = _ops.convert_to_tensor(c, _dtypes.int32) + _inputs_flat = [a, b, c] + _attrs = None + _result = _execute.execute(b"Foo1", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Foo1", _inputs_flat, _attrs, _result) + _result = _Foo1Output._make(_result) + return _result + +_Foo2Output = collections.namedtuple( + "Foo2", + ["d", "e"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('foo2') +def foo2(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.String], c: Annotated[Any, _atypes.String], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `string`. + c: A `Tensor` of type `string`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (d, e). + + d: A `Tensor` of type `float32`. + e: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Foo2", name, a, b, c) + _result = _Foo2Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_foo2( + (a, b, c, name,), None) + if _result is not NotImplemented: + return _result + return foo2_eager_fallback( + a, b, c, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + foo2, (), dict(a=a, b=b, c=c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_foo2( + (a, b, c, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Foo2", a=a, b=b, c=c, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + foo2, (), dict(a=a, b=b, c=c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Foo2", _inputs_flat, _attrs, _result) + _result = _Foo2Output._make(_result) + return _result + +Foo2 = tf_export("raw_ops.Foo2")(_ops.to_raw_op(foo2)) +_dispatcher_for_foo2 = foo2._tf_type_based_dispatcher.Dispatch + + +def foo2_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.String], c: Annotated[Any, _atypes.String], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.float32) + b = _ops.convert_to_tensor(b, _dtypes.string) + c = _ops.convert_to_tensor(c, _dtypes.string) + _inputs_flat = [a, b, c] + _attrs = None + _result = _execute.execute(b"Foo2", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Foo2", _inputs_flat, _attrs, _result) + _result = _Foo2Output._make(_result) + return _result + +_Foo3Output = collections.namedtuple( + "Foo3", + ["d", "e"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('foo3') +def foo3(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.String], c: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `string`. + c: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (d, e). + + d: A `Tensor` of type `float32`. + e: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Foo3", name, a, b, c) + _result = _Foo3Output._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_foo3( + (a, b, c, name,), None) + if _result is not NotImplemented: + return _result + return foo3_eager_fallback( + a, b, c, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + foo3, (), dict(a=a, b=b, c=c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_foo3( + (a, b, c, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Foo3", a=a, b=b, c=c, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + foo3, (), dict(a=a, b=b, c=c, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Foo3", _inputs_flat, _attrs, _result) + _result = _Foo3Output._make(_result) + return _result + +Foo3 = tf_export("raw_ops.Foo3")(_ops.to_raw_op(foo3)) +_dispatcher_for_foo3 = foo3._tf_type_based_dispatcher.Dispatch + + +def foo3_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.String], c: Annotated[Any, _atypes.Float32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.float32) + b = _ops.convert_to_tensor(b, _dtypes.string) + c = _ops.convert_to_tensor(c, _dtypes.float32) + _inputs_flat = [a, b, c] + _attrs = None + _result = _execute.execute(b"Foo3", 2, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Foo3", _inputs_flat, _attrs, _result) + _result = _Foo3Output._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('func_attr') +def func_attr(f, name=None): + r"""TODO: add doc. + + Args: + f: A function decorated with @Defun. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FuncAttr", name, "f", f) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_func_attr( + (f, name,), None) + if _result is not NotImplemented: + return _result + return func_attr_eager_fallback( + f=f, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + func_attr, (), dict(f=f, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_func_attr( + (f, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FuncAttr", f=f, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + func_attr, (), dict(f=f, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +FuncAttr = tf_export("raw_ops.FuncAttr")(_ops.to_raw_op(func_attr)) +_dispatcher_for_func_attr = func_attr._tf_type_based_dispatcher.Dispatch + + +def func_attr_eager_fallback(f, name, ctx): + _inputs_flat = [] + _attrs = ("f", f) + _result = _execute.execute(b"FuncAttr", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('func_list_attr') +def func_list_attr(f, name=None): + r"""TODO: add doc. + + Args: + f: A list of functions decorated with @Defun. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "FuncListAttr", name, "f", f) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_func_list_attr( + (f, name,), None) + if _result is not NotImplemented: + return _result + return func_list_attr_eager_fallback( + f=f, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + func_list_attr, (), dict(f=f, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_func_list_attr( + (f, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(f, (list, tuple)): + raise TypeError( + "Expected list for 'f' argument to " + "'func_list_attr' Op, not %r." % f) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "FuncListAttr", f=f, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + func_list_attr, (), dict(f=f, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +FuncListAttr = tf_export("raw_ops.FuncListAttr")(_ops.to_raw_op(func_list_attr)) +_dispatcher_for_func_list_attr = func_list_attr._tf_type_based_dispatcher.Dispatch + + +def func_list_attr_eager_fallback(f, name, ctx): + if not isinstance(f, (list, tuple)): + raise TypeError( + "Expected list for 'f' argument to " + "'func_list_attr' Op, not %r." % f) + _inputs_flat = [] + _attrs = ("f", f) + _result = _execute.execute(b"FuncListAttr", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('get_deadline') +def get_deadline(name=None) -> Annotated[Any, _atypes.Int64]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GetDeadline", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_get_deadline( + (name,), None) + if _result is not NotImplemented: + return _result + return get_deadline_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + get_deadline, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_get_deadline( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GetDeadline", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + get_deadline, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "GetDeadline", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GetDeadline = tf_export("raw_ops.GetDeadline")(_ops.to_raw_op(get_deadline)) +_dispatcher_for_get_deadline = get_deadline._tf_type_based_dispatcher.Dispatch + + +def get_deadline_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int64]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"GetDeadline", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GetDeadline", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('graph_def_version') +def graph_def_version(name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "GraphDefVersion", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_graph_def_version( + (name,), None) + if _result is not NotImplemented: + return _result + return graph_def_version_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + graph_def_version, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_graph_def_version( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "GraphDefVersion", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + graph_def_version, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "GraphDefVersion", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +GraphDefVersion = tf_export("raw_ops.GraphDefVersion")(_ops.to_raw_op(graph_def_version)) +_dispatcher_for_graph_def_version = graph_def_version._tf_type_based_dispatcher.Dispatch + + +def graph_def_version_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"GraphDefVersion", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "GraphDefVersion", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_InPolymorphicTwice_T = TypeVar("TV_InPolymorphicTwice_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('in_polymorphic_twice') +def in_polymorphic_twice(a: Annotated[List[Any], TV_InPolymorphicTwice_T], b: Annotated[List[Any], TV_InPolymorphicTwice_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects with the same type. + b: A list of `Tensor` objects with the same type as `a`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "InPolymorphicTwice", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_in_polymorphic_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return in_polymorphic_twice_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + in_polymorphic_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_in_polymorphic_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'in_polymorphic_twice' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'in_polymorphic_twice' Op, not %r." % b) + _attr_M = len(b) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "InPolymorphicTwice", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + in_polymorphic_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +InPolymorphicTwice = tf_export("raw_ops.InPolymorphicTwice")(_ops.to_raw_op(in_polymorphic_twice)) +_dispatcher_for_in_polymorphic_twice = in_polymorphic_twice._tf_type_based_dispatcher.Dispatch + + +def in_polymorphic_twice_eager_fallback(a: Annotated[List[Any], TV_InPolymorphicTwice_T], b: Annotated[List[Any], TV_InPolymorphicTwice_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'in_polymorphic_twice' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'in_polymorphic_twice' Op, not %r." % b) + _attr_M = len(b) + _attr_T, _inputs_T = _execute.args_to_matching_eager(list(a) + list(b), ctx, [], _dtypes.int32) + _inputs_T = [_inputs_T[:_attr_N]] + _inputs_T[_attr_N:] + _inputs_T = _inputs_T[:1] + [_inputs_T[1:]] + (a, b) = _inputs_T + _inputs_flat = list(a) + list(b) + _attrs = ("T", _attr_T, "N", _attr_N, "M", _attr_M) + _result = _execute.execute(b"InPolymorphicTwice", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int64_output') +def int64_output(name=None) -> Annotated[Any, _atypes.Int64]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Int64Output", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int64_output( + (name,), None) + if _result is not NotImplemented: + return _result + return int64_output_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int64_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int64_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Int64Output", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int64_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Int64Output", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Int64Output = tf_export("raw_ops.Int64Output")(_ops.to_raw_op(int64_output)) +_dispatcher_for_int64_output = int64_output._tf_type_based_dispatcher.Dispatch + + +def int64_output_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int64]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"Int64Output", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Int64Output", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int_attr') +def int_attr(foo:int=1, name=None) -> Annotated[Any, _atypes.Int64]: + r"""TODO: add doc. + + Args: + foo: An optional `int`. Defaults to `1`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int64`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IntAttr", name, "foo", foo) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int_attr( + (foo, name,), None) + if _result is not NotImplemented: + return _result + return int_attr_eager_fallback( + foo=foo, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_attr, (), dict(foo=foo, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int_attr( + (foo, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if foo is None: + foo = 1 + foo = _execute.make_int(foo, "foo") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IntAttr", foo=foo, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_attr, (), dict(foo=foo, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("foo", _op._get_attr_int("foo")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "IntAttr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IntAttr = tf_export("raw_ops.IntAttr")(_ops.to_raw_op(int_attr)) +_dispatcher_for_int_attr = int_attr._tf_type_based_dispatcher.Dispatch + + +def int_attr_eager_fallback(foo: int, name, ctx) -> Annotated[Any, _atypes.Int64]: + if foo is None: + foo = 1 + foo = _execute.make_int(foo, "foo") + _inputs_flat = [] + _attrs = ("foo", foo) + _result = _execute.execute(b"IntAttr", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IntAttr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int_input') +def int_input(a: Annotated[Any, _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IntInput", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int_input( + (a, name,), None) + if _result is not NotImplemented: + return _result + return int_input_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_input, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int_input( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IntInput", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_input, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +IntInput = tf_export("raw_ops.IntInput")(_ops.to_raw_op(int_input)) +_dispatcher_for_int_input = int_input._tf_type_based_dispatcher.Dispatch + + +def int_input_eager_fallback(a: Annotated[Any, _atypes.Int32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.int32) + _inputs_flat = [a] + _attrs = None + _result = _execute.execute(b"IntInput", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int_input_float_input') +def int_input_float_input(a: Annotated[Any, _atypes.Int32], b: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `int32`. + b: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IntInputFloatInput", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int_input_float_input( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return int_input_float_input_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_input_float_input, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int_input_float_input( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IntInputFloatInput", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_input_float_input, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +IntInputFloatInput = tf_export("raw_ops.IntInputFloatInput")(_ops.to_raw_op(int_input_float_input)) +_dispatcher_for_int_input_float_input = int_input_float_input._tf_type_based_dispatcher.Dispatch + + +def int_input_float_input_eager_fallback(a: Annotated[Any, _atypes.Int32], b: Annotated[Any, _atypes.Float32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.int32) + b = _ops.convert_to_tensor(b, _dtypes.float32) + _inputs_flat = [a, b] + _attrs = None + _result = _execute.execute(b"IntInputFloatInput", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int_input_int_output') +def int_input_int_output(a: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IntInputIntOutput", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int_input_int_output( + (a, name,), None) + if _result is not NotImplemented: + return _result + return int_input_int_output_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_input_int_output, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int_input_int_output( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IntInputIntOutput", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_input_int_output, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IntInputIntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IntInputIntOutput = tf_export("raw_ops.IntInputIntOutput")(_ops.to_raw_op(int_input_int_output)) +_dispatcher_for_int_input_int_output = int_input_int_output._tf_type_based_dispatcher.Dispatch + + +def int_input_int_output_eager_fallback(a: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.Int32]: + a = _ops.convert_to_tensor(a, _dtypes.int32) + _inputs_flat = [a] + _attrs = None + _result = _execute.execute(b"IntInputIntOutput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IntInputIntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int_output') +def int_output(name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IntOutput", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int_output( + (name,), None) + if _result is not NotImplemented: + return _result + return int_output_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IntOutput", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IntOutput = tf_export("raw_ops.IntOutput")(_ops.to_raw_op(int_output)) +_dispatcher_for_int_output = int_output._tf_type_based_dispatcher.Dispatch + + +def int_output_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"IntOutput", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_IntOutputFloatOutputOutput = collections.namedtuple( + "IntOutputFloatOutput", + ["a", "b"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('int_output_float_output') +def int_output_float_output(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b). + + a: A `Tensor` of type `int32`. + b: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IntOutputFloatOutput", name) + _result = _IntOutputFloatOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_int_output_float_output( + (name,), None) + if _result is not NotImplemented: + return _result + return int_output_float_output_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_output_float_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_int_output_float_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IntOutputFloatOutput", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + int_output_float_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IntOutputFloatOutput", _inputs_flat, _attrs, _result) + _result = _IntOutputFloatOutputOutput._make(_result) + return _result + +IntOutputFloatOutput = tf_export("raw_ops.IntOutputFloatOutput")(_ops.to_raw_op(int_output_float_output)) +_dispatcher_for_int_output_float_output = int_output_float_output._tf_type_based_dispatcher.Dispatch + + +def int_output_float_output_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"IntOutputFloatOutput", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IntOutputFloatOutput", _inputs_flat, _attrs, _result) + _result = _IntOutputFloatOutputOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('is_resource_handle_ref_counting') +def is_resource_handle_ref_counting(handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Bool]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsResourceHandleRefCounting", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_is_resource_handle_ref_counting( + (handle, name,), None) + if _result is not NotImplemented: + return _result + return is_resource_handle_ref_counting_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_resource_handle_ref_counting, (), dict(handle=handle, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_is_resource_handle_ref_counting( + (handle, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsResourceHandleRefCounting", handle=handle, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_resource_handle_ref_counting, (), dict(handle=handle, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsResourceHandleRefCounting", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsResourceHandleRefCounting = tf_export("raw_ops.IsResourceHandleRefCounting")(_ops.to_raw_op(is_resource_handle_ref_counting)) +_dispatcher_for_is_resource_handle_ref_counting = is_resource_handle_ref_counting._tf_type_based_dispatcher.Dispatch + + +def is_resource_handle_ref_counting_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Bool]: + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"IsResourceHandleRefCounting", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsResourceHandleRefCounting", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('is_tensor_float32_enabled') +def is_tensor_float32_enabled(name=None) -> Annotated[Any, _atypes.Bool]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "IsTensorFloat32Enabled", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_is_tensor_float32_enabled( + (name,), None) + if _result is not NotImplemented: + return _result + return is_tensor_float32_enabled_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_tensor_float32_enabled, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_is_tensor_float32_enabled( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "IsTensorFloat32Enabled", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + is_tensor_float32_enabled, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "IsTensorFloat32Enabled", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +IsTensorFloat32Enabled = tf_export("raw_ops.IsTensorFloat32Enabled")(_ops.to_raw_op(is_tensor_float32_enabled)) +_dispatcher_for_is_tensor_float32_enabled = is_tensor_float32_enabled._tf_type_based_dispatcher.Dispatch + + +def is_tensor_float32_enabled_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Bool]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"IsTensorFloat32Enabled", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "IsTensorFloat32Enabled", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('kernel_label') +def kernel_label(name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "KernelLabel", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_kernel_label( + (name,), None) + if _result is not NotImplemented: + return _result + return kernel_label_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + kernel_label, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_kernel_label( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "KernelLabel", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + kernel_label, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "KernelLabel", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +KernelLabel = tf_export("raw_ops.KernelLabel")(_ops.to_raw_op(kernel_label)) +_dispatcher_for_kernel_label = kernel_label._tf_type_based_dispatcher.Dispatch + + +def kernel_label_eager_fallback(name, ctx) -> Annotated[Any, _atypes.String]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"KernelLabel", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "KernelLabel", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('kernel_label_required') +def kernel_label_required(input: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.String]: + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "KernelLabelRequired", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_kernel_label_required( + (input, name,), None) + if _result is not NotImplemented: + return _result + return kernel_label_required_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + kernel_label_required, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_kernel_label_required( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "KernelLabelRequired", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + kernel_label_required, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "KernelLabelRequired", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +KernelLabelRequired = tf_export("raw_ops.KernelLabelRequired")(_ops.to_raw_op(kernel_label_required)) +_dispatcher_for_kernel_label_required = kernel_label_required._tf_type_based_dispatcher.Dispatch + + +def kernel_label_required_eager_fallback(input: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.String]: + input = _ops.convert_to_tensor(input, _dtypes.int32) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"KernelLabelRequired", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "KernelLabelRequired", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_ListInput_T = TypeVar("TV_ListInput_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('list_input') +def list_input(a: Annotated[List[Any], TV_ListInput_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of at least 1 `Tensor` objects with the same type. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ListInput", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_list_input( + (a, name,), None) + if _result is not NotImplemented: + return _result + return list_input_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + list_input, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_list_input( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'list_input' Op, not %r." % a) + _attr_N = len(a) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ListInput", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + list_input, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +ListInput = tf_export("raw_ops.ListInput")(_ops.to_raw_op(list_input)) +_dispatcher_for_list_input = list_input._tf_type_based_dispatcher.Dispatch + + +def list_input_eager_fallback(a: Annotated[List[Any], TV_ListInput_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'list_input' Op, not %r." % a) + _attr_N = len(a) + _attr_T, a = _execute.args_to_matching_eager(list(a), ctx, []) + _inputs_flat = list(a) + _attrs = ("N", _attr_N, "T", _attr_T) + _result = _execute.execute(b"ListInput", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('list_output') +def list_output(T, name=None): + r"""TODO: add doc. + + Args: + T: A list of `tf.DTypes` that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ListOutput", name, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_list_output( + (T, name,), None) + if _result is not NotImplemented: + return _result + return list_output_eager_fallback( + T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + list_output, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_list_output( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(T, (list, tuple)): + raise TypeError( + "Expected list for 'T' argument to " + "'list_output' Op, not %r." % T) + T = [_execute.make_type(_t, "T") for _t in T] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ListOutput", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + list_output, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "ListOutput", _inputs_flat, _attrs, _result) + return _result + +ListOutput = tf_export("raw_ops.ListOutput")(_ops.to_raw_op(list_output)) +_dispatcher_for_list_output = list_output._tf_type_based_dispatcher.Dispatch + + +def list_output_eager_fallback(T, name, ctx): + if not isinstance(T, (list, tuple)): + raise TypeError( + "Expected list for 'T' argument to " + "'list_output' Op, not %r." % T) + T = [_execute.make_type(_t, "T") for _t in T] + _inputs_flat = [] + _attrs = ("T", T) + _result = _execute.execute(b"ListOutput", len(T), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ListOutput", _inputs_flat, _attrs, _result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('make_weak_resource_handle') +def make_weak_resource_handle(handle: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + handle: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MakeWeakResourceHandle", name, handle) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_make_weak_resource_handle( + (handle, name,), None) + if _result is not NotImplemented: + return _result + return make_weak_resource_handle_eager_fallback( + handle, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + make_weak_resource_handle, (), dict(handle=handle, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_make_weak_resource_handle( + (handle, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MakeWeakResourceHandle", handle=handle, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + make_weak_resource_handle, (), dict(handle=handle, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "MakeWeakResourceHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +MakeWeakResourceHandle = tf_export("raw_ops.MakeWeakResourceHandle")(_ops.to_raw_op(make_weak_resource_handle)) +_dispatcher_for_make_weak_resource_handle = make_weak_resource_handle._tf_type_based_dispatcher.Dispatch + + +def make_weak_resource_handle_eager_fallback(handle: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Resource]: + handle = _ops.convert_to_tensor(handle, _dtypes.resource) + _inputs_flat = [handle] + _attrs = None + _result = _execute.execute(b"MakeWeakResourceHandle", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MakeWeakResourceHandle", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_MixedStructOutput = collections.namedtuple( + "MixedStruct", + ["a", "b"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('mixed_struct') +def mixed_struct(n_a: int, name=None): + r"""TODO: add doc. + + Args: + n_a: An `int` that is `>= 0`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b). + + a: A list of `n_a` `Tensor` objects with type `int32`. + b: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "MixedStruct", name, "n_a", n_a) + _result = _MixedStructOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_mixed_struct( + (n_a, name,), None) + if _result is not NotImplemented: + return _result + return mixed_struct_eager_fallback( + n_a=n_a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + mixed_struct, (), dict(n_a=n_a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_mixed_struct( + (n_a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + n_a = _execute.make_int(n_a, "n_a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "MixedStruct", n_a=n_a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + mixed_struct, (), dict(n_a=n_a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("n_a", _op._get_attr_int("n_a")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "MixedStruct", _inputs_flat, _attrs, _result) + _result = [_result[:n_a]] + _result[n_a:] + _result = _MixedStructOutput._make(_result) + return _result + +MixedStruct = tf_export("raw_ops.MixedStruct")(_ops.to_raw_op(mixed_struct)) +_dispatcher_for_mixed_struct = mixed_struct._tf_type_based_dispatcher.Dispatch + + +def mixed_struct_eager_fallback(n_a: int, name, ctx): + n_a = _execute.make_int(n_a, "n_a") + _inputs_flat = [] + _attrs = ("n_a", n_a) + _result = _execute.execute(b"MixedStruct", n_a + 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "MixedStruct", _inputs_flat, _attrs, _result) + _result = [_result[:n_a]] + _result[n_a:] + _result = _MixedStructOutput._make(_result) + return _result + + +TV_NInPolymorphicTwice_T = TypeVar("TV_NInPolymorphicTwice_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_in_polymorphic_twice') +def n_in_polymorphic_twice(a: Annotated[List[Any], TV_NInPolymorphicTwice_T], b: Annotated[List[Any], TV_NInPolymorphicTwice_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects with the same type. + b: A list with the same length as `a` of `Tensor` objects with the same type as `a`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NInPolymorphicTwice", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_in_polymorphic_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return n_in_polymorphic_twice_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_in_polymorphic_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_in_polymorphic_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_in_polymorphic_twice' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'n_in_polymorphic_twice' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'n_in_polymorphic_twice' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NInPolymorphicTwice", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_in_polymorphic_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NInPolymorphicTwice = tf_export("raw_ops.NInPolymorphicTwice")(_ops.to_raw_op(n_in_polymorphic_twice)) +_dispatcher_for_n_in_polymorphic_twice = n_in_polymorphic_twice._tf_type_based_dispatcher.Dispatch + + +def n_in_polymorphic_twice_eager_fallback(a: Annotated[List[Any], TV_NInPolymorphicTwice_T], b: Annotated[List[Any], TV_NInPolymorphicTwice_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_in_polymorphic_twice' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'n_in_polymorphic_twice' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'n_in_polymorphic_twice' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + _attr_T, _inputs_T = _execute.args_to_matching_eager(list(a) + list(b), ctx, []) + _inputs_T = [_inputs_T[:_attr_N]] + _inputs_T[_attr_N:] + _inputs_T = _inputs_T[:1] + [_inputs_T[1:]] + (a, b) = _inputs_T + _inputs_flat = list(a) + list(b) + _attrs = ("T", _attr_T, "N", _attr_N) + _result = _execute.execute(b"NInPolymorphicTwice", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_in_twice') +def n_in_twice(a: Annotated[List[Any], _atypes.Int32], b: Annotated[List[Any], _atypes.String], name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects with type `int32`. + b: A list with the same length as `a` of `Tensor` objects with type `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NInTwice", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_in_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return n_in_twice_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_in_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_in_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_in_twice' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'n_in_twice' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'n_in_twice' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NInTwice", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_in_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NInTwice = tf_export("raw_ops.NInTwice")(_ops.to_raw_op(n_in_twice)) +_dispatcher_for_n_in_twice = n_in_twice._tf_type_based_dispatcher.Dispatch + + +def n_in_twice_eager_fallback(a: Annotated[List[Any], _atypes.Int32], b: Annotated[List[Any], _atypes.String], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_in_twice' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'n_in_twice' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'n_in_twice' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + a = _ops.convert_n_to_tensor(a, _dtypes.int32) + b = _ops.convert_n_to_tensor(b, _dtypes.string) + _inputs_flat = list(a) + list(b) + _attrs = ("N", _attr_N) + _result = _execute.execute(b"NInTwice", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_NInTwoTypeVariables_S = TypeVar("TV_NInTwoTypeVariables_S", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) +TV_NInTwoTypeVariables_T = TypeVar("TV_NInTwoTypeVariables_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_in_two_type_variables') +def n_in_two_type_variables(a: Annotated[List[Any], TV_NInTwoTypeVariables_S], b: Annotated[List[Any], TV_NInTwoTypeVariables_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects with the same type. + b: A list with the same length as `a` of `Tensor` objects with the same type. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NInTwoTypeVariables", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_in_two_type_variables( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return n_in_two_type_variables_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_in_two_type_variables, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_in_two_type_variables( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_in_two_type_variables' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'n_in_two_type_variables' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'n_in_two_type_variables' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NInTwoTypeVariables", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_in_two_type_variables, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NInTwoTypeVariables = tf_export("raw_ops.NInTwoTypeVariables")(_ops.to_raw_op(n_in_two_type_variables)) +_dispatcher_for_n_in_two_type_variables = n_in_two_type_variables._tf_type_based_dispatcher.Dispatch + + +def n_in_two_type_variables_eager_fallback(a: Annotated[List[Any], TV_NInTwoTypeVariables_S], b: Annotated[List[Any], TV_NInTwoTypeVariables_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_in_two_type_variables' Op, not %r." % a) + _attr_N = len(a) + if not isinstance(b, (list, tuple)): + raise TypeError( + "Expected list for 'b' argument to " + "'n_in_two_type_variables' Op, not %r." % b) + if len(b) != _attr_N: + raise ValueError( + "List argument 'b' to 'n_in_two_type_variables' Op with length %d " + "must match length %d of argument 'a'." % + (len(b), _attr_N)) + _attr_S, a = _execute.args_to_matching_eager(list(a), ctx, []) + _attr_T, b = _execute.args_to_matching_eager(list(b), ctx, []) + _inputs_flat = list(a) + list(b) + _attrs = ("S", _attr_S, "T", _attr_T, "N", _attr_N) + _result = _execute.execute(b"NInTwoTypeVariables", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_ints_in') +def n_ints_in(a: Annotated[List[Any], _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + a: A list of at least 2 `Tensor` objects with type `int32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NIntsIn", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_ints_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + return n_ints_in_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_ints_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_ints_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_ints_in' Op, not %r." % a) + _attr_N = len(a) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NIntsIn", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_ints_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NIntsIn = tf_export("raw_ops.NIntsIn")(_ops.to_raw_op(n_ints_in)) +_dispatcher_for_n_ints_in = n_ints_in._tf_type_based_dispatcher.Dispatch + + +def n_ints_in_eager_fallback(a: Annotated[List[Any], _atypes.Int32], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_ints_in' Op, not %r." % a) + _attr_N = len(a) + a = _ops.convert_n_to_tensor(a, _dtypes.int32) + _inputs_flat = list(a) + _attrs = ("N", _attr_N) + _result = _execute.execute(b"NIntsIn", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_ints_out') +def n_ints_out(N: int, name=None): + r"""TODO: add doc. + + Args: + N: An `int` that is `>= 2`. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NIntsOut", name, "N", N) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_ints_out( + (N, name,), None) + if _result is not NotImplemented: + return _result + return n_ints_out_eager_fallback( + N=N, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_ints_out, (), dict(N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_ints_out( + (N, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + N = _execute.make_int(N, "N") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NIntsOut", N=N, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_ints_out, (), dict(N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NIntsOut", _inputs_flat, _attrs, _result) + return _result + +NIntsOut = tf_export("raw_ops.NIntsOut")(_ops.to_raw_op(n_ints_out)) +_dispatcher_for_n_ints_out = n_ints_out._tf_type_based_dispatcher.Dispatch + + +def n_ints_out_eager_fallback(N: int, name, ctx): + N = _execute.make_int(N, "N") + _inputs_flat = [] + _attrs = ("N", N) + _result = _execute.execute(b"NIntsOut", N, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NIntsOut", _inputs_flat, _attrs, _result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_ints_out_default') +def n_ints_out_default(N:int=3, name=None): + r"""TODO: add doc. + + Args: + N: An optional `int` that is `>= 2`. Defaults to `3`. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NIntsOutDefault", name, "N", N) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_ints_out_default( + (N, name,), None) + if _result is not NotImplemented: + return _result + return n_ints_out_default_eager_fallback( + N=N, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_ints_out_default, (), dict(N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_ints_out_default( + (N, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if N is None: + N = 3 + N = _execute.make_int(N, "N") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NIntsOutDefault", N=N, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_ints_out_default, (), dict(N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NIntsOutDefault", _inputs_flat, _attrs, _result) + return _result + +NIntsOutDefault = tf_export("raw_ops.NIntsOutDefault")(_ops.to_raw_op(n_ints_out_default)) +_dispatcher_for_n_ints_out_default = n_ints_out_default._tf_type_based_dispatcher.Dispatch + + +def n_ints_out_default_eager_fallback(N: int, name, ctx): + if N is None: + N = 3 + N = _execute.make_int(N, "N") + _inputs_flat = [] + _attrs = ("N", N) + _result = _execute.execute(b"NIntsOutDefault", N, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NIntsOutDefault", _inputs_flat, _attrs, _result) + return _result + + +TV_NPolymorphicIn_T = TypeVar("TV_NPolymorphicIn_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_polymorphic_in') +def n_polymorphic_in(a: Annotated[List[Any], TV_NPolymorphicIn_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of at least 2 `Tensor` objects with the same type. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NPolymorphicIn", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_polymorphic_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + return n_polymorphic_in_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_polymorphic_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_polymorphic_in' Op, not %r." % a) + _attr_N = len(a) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NPolymorphicIn", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NPolymorphicIn = tf_export("raw_ops.NPolymorphicIn")(_ops.to_raw_op(n_polymorphic_in)) +_dispatcher_for_n_polymorphic_in = n_polymorphic_in._tf_type_based_dispatcher.Dispatch + + +def n_polymorphic_in_eager_fallback(a: Annotated[List[Any], TV_NPolymorphicIn_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_polymorphic_in' Op, not %r." % a) + _attr_N = len(a) + _attr_T, a = _execute.args_to_matching_eager(list(a), ctx, []) + _inputs_flat = list(a) + _attrs = ("T", _attr_T, "N", _attr_N) + _result = _execute.execute(b"NPolymorphicIn", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_NPolymorphicOut_T = TypeVar("TV_NPolymorphicOut_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_polymorphic_out') +def n_polymorphic_out(T: TV_NPolymorphicOut_T, N: int, name=None): + r"""TODO: add doc. + + Args: + T: A `tf.DType`. + N: An `int` that is `>= 2`. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NPolymorphicOut", name, "T", T, "N", N) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_polymorphic_out( + (T, N, name,), None) + if _result is not NotImplemented: + return _result + return n_polymorphic_out_eager_fallback( + T=T, N=N, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_out, (), dict(T=T, N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_polymorphic_out( + (T, N, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + N = _execute.make_int(N, "N") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NPolymorphicOut", T=T, N=N, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_out, (), dict(T=T, N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NPolymorphicOut", _inputs_flat, _attrs, _result) + return _result + +NPolymorphicOut = tf_export("raw_ops.NPolymorphicOut")(_ops.to_raw_op(n_polymorphic_out)) +_dispatcher_for_n_polymorphic_out = n_polymorphic_out._tf_type_based_dispatcher.Dispatch + + +def n_polymorphic_out_eager_fallback(T: TV_NPolymorphicOut_T, N: int, name, ctx): + T = _execute.make_type(T, "T") + N = _execute.make_int(N, "N") + _inputs_flat = [] + _attrs = ("T", T, "N", N) + _result = _execute.execute(b"NPolymorphicOut", N, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NPolymorphicOut", _inputs_flat, _attrs, _result) + return _result + + +TV_NPolymorphicOutDefault_T = TypeVar("TV_NPolymorphicOutDefault_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_polymorphic_out_default') +def n_polymorphic_out_default(T:TV_NPolymorphicOutDefault_T=_dtypes.bool, N:int=2, name=None): + r"""TODO: add doc. + + Args: + T: An optional `tf.DType`. Defaults to `tf.bool`. + N: An optional `int` that is `>= 2`. Defaults to `2`. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NPolymorphicOutDefault", name, "T", T, "N", N) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_polymorphic_out_default( + (T, N, name,), None) + if _result is not NotImplemented: + return _result + return n_polymorphic_out_default_eager_fallback( + T=T, N=N, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_out_default, (), dict(T=T, N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_polymorphic_out_default( + (T, N, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if T is None: + T = _dtypes.bool + T = _execute.make_type(T, "T") + if N is None: + N = 2 + N = _execute.make_int(N, "N") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NPolymorphicOutDefault", T=T, N=N, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_out_default, (), dict(T=T, N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NPolymorphicOutDefault", _inputs_flat, _attrs, _result) + return _result + +NPolymorphicOutDefault = tf_export("raw_ops.NPolymorphicOutDefault")(_ops.to_raw_op(n_polymorphic_out_default)) +_dispatcher_for_n_polymorphic_out_default = n_polymorphic_out_default._tf_type_based_dispatcher.Dispatch + + +def n_polymorphic_out_default_eager_fallback(T: TV_NPolymorphicOutDefault_T, N: int, name, ctx): + if T is None: + T = _dtypes.bool + T = _execute.make_type(T, "T") + if N is None: + N = 2 + N = _execute.make_int(N, "N") + _inputs_flat = [] + _attrs = ("T", T, "N", N) + _result = _execute.execute(b"NPolymorphicOutDefault", N, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NPolymorphicOutDefault", _inputs_flat, _attrs, _result) + return _result + + +TV_NPolymorphicRestrictIn_T = TypeVar("TV_NPolymorphicRestrictIn_T", _atypes.Bool, _atypes.String) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_polymorphic_restrict_in') +def n_polymorphic_restrict_in(a: Annotated[List[Any], TV_NPolymorphicRestrictIn_T], name=None): + r"""TODO: add doc. + + Args: + a: A list of at least 2 `Tensor` objects with the same type in: `string`, `bool`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NPolymorphicRestrictIn", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_polymorphic_restrict_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + return n_polymorphic_restrict_in_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_restrict_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_polymorphic_restrict_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_polymorphic_restrict_in' Op, not %r." % a) + _attr_N = len(a) + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NPolymorphicRestrictIn", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_restrict_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +NPolymorphicRestrictIn = tf_export("raw_ops.NPolymorphicRestrictIn")(_ops.to_raw_op(n_polymorphic_restrict_in)) +_dispatcher_for_n_polymorphic_restrict_in = n_polymorphic_restrict_in._tf_type_based_dispatcher.Dispatch + + +def n_polymorphic_restrict_in_eager_fallback(a: Annotated[List[Any], TV_NPolymorphicRestrictIn_T], name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'n_polymorphic_restrict_in' Op, not %r." % a) + _attr_N = len(a) + _attr_T, a = _execute.args_to_matching_eager(list(a), ctx, [_dtypes.string, _dtypes.bool, ]) + _inputs_flat = list(a) + _attrs = ("T", _attr_T, "N", _attr_N) + _result = _execute.execute(b"NPolymorphicRestrictIn", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_NPolymorphicRestrictOut_T = TypeVar("TV_NPolymorphicRestrictOut_T", _atypes.Bool, _atypes.String) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('n_polymorphic_restrict_out') +def n_polymorphic_restrict_out(T: TV_NPolymorphicRestrictOut_T, N: int, name=None): + r"""TODO: add doc. + + Args: + T: A `tf.DType` from: `tf.string, tf.bool`. + N: An `int` that is `>= 2`. + name: A name for the operation (optional). + + Returns: + A list of `N` `Tensor` objects with type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "NPolymorphicRestrictOut", name, "T", T, "N", N) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_n_polymorphic_restrict_out( + (T, N, name,), None) + if _result is not NotImplemented: + return _result + return n_polymorphic_restrict_out_eager_fallback( + T=T, N=N, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_restrict_out, (), dict(T=T, N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_n_polymorphic_restrict_out( + (T, N, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + N = _execute.make_int(N, "N") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "NPolymorphicRestrictOut", T=T, N=N, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + n_polymorphic_restrict_out, (), dict(T=T, N=N, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T"), "N", _op._get_attr_int("N")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "NPolymorphicRestrictOut", _inputs_flat, _attrs, _result) + return _result + +NPolymorphicRestrictOut = tf_export("raw_ops.NPolymorphicRestrictOut")(_ops.to_raw_op(n_polymorphic_restrict_out)) +_dispatcher_for_n_polymorphic_restrict_out = n_polymorphic_restrict_out._tf_type_based_dispatcher.Dispatch + + +def n_polymorphic_restrict_out_eager_fallback(T: TV_NPolymorphicRestrictOut_T, N: int, name, ctx): + T = _execute.make_type(T, "T") + N = _execute.make_int(N, "N") + _inputs_flat = [] + _attrs = ("T", T, "N", N) + _result = _execute.execute(b"NPolymorphicRestrictOut", N, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "NPolymorphicRestrictOut", _inputs_flat, _attrs, _result) + return _result + +_Namespace_TestStringOutputOutput = collections.namedtuple( + "Namespace_TestStringOutput", + ["output1", "output2"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('namespace_test_string_output') +def namespace_test_string_output(input: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output1, output2). + + output1: A `Tensor` of type `float32`. + output2: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Namespace>TestStringOutput", name, input) + _result = _Namespace_TestStringOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_namespace_test_string_output( + (input, name,), None) + if _result is not NotImplemented: + return _result + return namespace_test_string_output_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + namespace_test_string_output, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_namespace_test_string_output( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Namespace>TestStringOutput", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + namespace_test_string_output, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Namespace>TestStringOutput", _inputs_flat, _attrs, _result) + _result = _Namespace_TestStringOutputOutput._make(_result) + return _result + +Namespace_TestStringOutput = tf_export("raw_ops.Namespace_TestStringOutput")(_ops.to_raw_op(namespace_test_string_output)) +_dispatcher_for_namespace_test_string_output = namespace_test_string_output._tf_type_based_dispatcher.Dispatch + + +def namespace_test_string_output_eager_fallback(input: Annotated[Any, _atypes.Float32], name, ctx): + input = _ops.convert_to_tensor(input, _dtypes.float32) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"Namespace>TestStringOutput", 2, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Namespace>TestStringOutput", _inputs_flat, _attrs, _result) + _result = _Namespace_TestStringOutputOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('none') +def none(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "None", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_none( + (name,), None) + if _result is not NotImplemented: + return _result + return none_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + none, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_none( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "None", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + none, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +None_ = tf_export("raw_ops.None_")(_ops.to_raw_op(none)) +_dispatcher_for_none = none._tf_type_based_dispatcher.Dispatch + + +def none_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"None", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('old') +def old(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Old", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_old( + (name,), None) + if _result is not NotImplemented: + return _result + return old_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + old, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_old( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Old", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + old, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +Old = tf_export("raw_ops.Old")(_ops.to_raw_op(old)) +_dispatcher_for_old = old._tf_type_based_dispatcher.Dispatch + + +def old_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"Old", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('op_with_default_attr') +def op_with_default_attr(default_float:float=123, name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + default_float: An optional `float`. Defaults to `123`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OpWithDefaultAttr", name, "default_float", default_float) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_op_with_default_attr( + (default_float, name,), None) + if _result is not NotImplemented: + return _result + return op_with_default_attr_eager_fallback( + default_float=default_float, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + op_with_default_attr, (), dict(default_float=default_float, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_op_with_default_attr( + (default_float, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if default_float is None: + default_float = 123 + default_float = _execute.make_float(default_float, "default_float") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OpWithDefaultAttr", default_float=default_float, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + op_with_default_attr, (), dict(default_float=default_float, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("default_float", _op.get_attr("default_float")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OpWithDefaultAttr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OpWithDefaultAttr = tf_export("raw_ops.OpWithDefaultAttr")(_ops.to_raw_op(op_with_default_attr)) +_dispatcher_for_op_with_default_attr = op_with_default_attr._tf_type_based_dispatcher.Dispatch + + +def op_with_default_attr_eager_fallback(default_float: float, name, ctx) -> Annotated[Any, _atypes.Int32]: + if default_float is None: + default_float = 123 + default_float = _execute.make_float(default_float, "default_float") + _inputs_flat = [] + _attrs = ("default_float", default_float) + _result = _execute.execute(b"OpWithDefaultAttr", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OpWithDefaultAttr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('op_with_future_default_attr') +def op_with_future_default_attr(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OpWithFutureDefaultAttr", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_op_with_future_default_attr( + (name,), None) + if _result is not NotImplemented: + return _result + return op_with_future_default_attr_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + op_with_future_default_attr, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_op_with_future_default_attr( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OpWithFutureDefaultAttr", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + op_with_future_default_attr, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +OpWithFutureDefaultAttr = tf_export("raw_ops.OpWithFutureDefaultAttr")(_ops.to_raw_op(op_with_future_default_attr)) +_dispatcher_for_op_with_future_default_attr = op_with_future_default_attr._tf_type_based_dispatcher.Dispatch + + +def op_with_future_default_attr_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"OpWithFutureDefaultAttr", 0, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + _result = None + return _result + + +TV_OutT_T = TypeVar("TV_OutT_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('out_t') +def out_t(T: TV_OutT_T, name=None) -> Annotated[Any, TV_OutT_T]: + r"""TODO: add doc. + + Args: + T: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutT", name, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_out_t( + (T, name,), None) + if _result is not NotImplemented: + return _result + return out_t_eager_fallback( + T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + out_t, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_out_t( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutT", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + out_t, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +OutT = tf_export("raw_ops.OutT")(_ops.to_raw_op(out_t)) +_dispatcher_for_out_t = out_t._tf_type_based_dispatcher.Dispatch + + +def out_t_eager_fallback(T: TV_OutT_T, name, ctx) -> Annotated[Any, TV_OutT_T]: + T = _execute.make_type(T, "T") + _inputs_flat = [] + _attrs = ("T", T) + _result = _execute.execute(b"OutT", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutT", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('out_type_list') +def out_type_list(T, name=None): + r"""TODO: add doc. + + Args: + T: A list of `tf.DTypes`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutTypeList", name, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_out_type_list( + (T, name,), None) + if _result is not NotImplemented: + return _result + return out_type_list_eager_fallback( + T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + out_type_list, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_out_type_list( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(T, (list, tuple)): + raise TypeError( + "Expected list for 'T' argument to " + "'out_type_list' Op, not %r." % T) + T = [_execute.make_type(_t, "T") for _t in T] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutTypeList", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + out_type_list, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op.get_attr("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutTypeList", _inputs_flat, _attrs, _result) + return _result + +OutTypeList = tf_export("raw_ops.OutTypeList")(_ops.to_raw_op(out_type_list)) +_dispatcher_for_out_type_list = out_type_list._tf_type_based_dispatcher.Dispatch + + +def out_type_list_eager_fallback(T, name, ctx): + if not isinstance(T, (list, tuple)): + raise TypeError( + "Expected list for 'T' argument to " + "'out_type_list' Op, not %r." % T) + T = [_execute.make_type(_t, "T") for _t in T] + _inputs_flat = [] + _attrs = ("T", T) + _result = _execute.execute(b"OutTypeList", len(T), inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutTypeList", _inputs_flat, _attrs, _result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('out_type_list_restrict') +def out_type_list_restrict(t, name=None): + r"""TODO: add doc. + + Args: + t: A list of `tf.DTypes` from: `tf.string, tf.bool` that has length `>= 1`. + name: A name for the operation (optional). + + Returns: + A list of `Tensor` objects of type `t`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "OutTypeListRestrict", name, "t", t) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_out_type_list_restrict( + (t, name,), None) + if _result is not NotImplemented: + return _result + return out_type_list_restrict_eager_fallback( + t=t, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + out_type_list_restrict, (), dict(t=t, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_out_type_list_restrict( + (t, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(t, (list, tuple)): + raise TypeError( + "Expected list for 't' argument to " + "'out_type_list_restrict' Op, not %r." % t) + t = [_execute.make_type(_t, "t") for _t in t] + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "OutTypeListRestrict", t=t, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + out_type_list_restrict, (), dict(t=t, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("t", _op.get_attr("t")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "OutTypeListRestrict", _inputs_flat, _attrs, _result) + return _result + +OutTypeListRestrict = tf_export("raw_ops.OutTypeListRestrict")(_ops.to_raw_op(out_type_list_restrict)) +_dispatcher_for_out_type_list_restrict = out_type_list_restrict._tf_type_based_dispatcher.Dispatch + + +def out_type_list_restrict_eager_fallback(t, name, ctx): + if not isinstance(t, (list, tuple)): + raise TypeError( + "Expected list for 't' argument to " + "'out_type_list_restrict' Op, not %r." % t) + t = [_execute.make_type(_t, "t") for _t in t] + _inputs_flat = [] + _attrs = ("t", t) + _result = _execute.execute(b"OutTypeListRestrict", len(t), + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "OutTypeListRestrict", _inputs_flat, _attrs, _result) + return _result + + +TV_Polymorphic_T = TypeVar("TV_Polymorphic_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('polymorphic') +def polymorphic(a: Annotated[Any, TV_Polymorphic_T], name=None) -> Annotated[Any, TV_Polymorphic_T]: + r"""TODO: add doc. + + Args: + a: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Polymorphic", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_polymorphic( + (a, name,), None) + if _result is not NotImplemented: + return _result + return polymorphic_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polymorphic, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_polymorphic( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Polymorphic", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polymorphic, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Polymorphic", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Polymorphic = tf_export("raw_ops.Polymorphic")(_ops.to_raw_op(polymorphic)) +_dispatcher_for_polymorphic = polymorphic._tf_type_based_dispatcher.Dispatch + + +def polymorphic_eager_fallback(a: Annotated[Any, TV_Polymorphic_T], name, ctx) -> Annotated[Any, TV_Polymorphic_T]: + _attr_T, (a,) = _execute.args_to_matching_eager([a], ctx, []) + _inputs_flat = [a] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Polymorphic", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Polymorphic", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PolymorphicDefaultOut_T = TypeVar("TV_PolymorphicDefaultOut_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('polymorphic_default_out') +def polymorphic_default_out(T:TV_PolymorphicDefaultOut_T=_dtypes.string, name=None) -> Annotated[Any, TV_PolymorphicDefaultOut_T]: + r"""TODO: add doc. + + Args: + T: An optional `tf.DType`. Defaults to `tf.string`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PolymorphicDefaultOut", name, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_polymorphic_default_out( + (T, name,), None) + if _result is not NotImplemented: + return _result + return polymorphic_default_out_eager_fallback( + T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polymorphic_default_out, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_polymorphic_default_out( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if T is None: + T = _dtypes.string + T = _execute.make_type(T, "T") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PolymorphicDefaultOut", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polymorphic_default_out, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PolymorphicDefaultOut", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PolymorphicDefaultOut = tf_export("raw_ops.PolymorphicDefaultOut")(_ops.to_raw_op(polymorphic_default_out)) +_dispatcher_for_polymorphic_default_out = polymorphic_default_out._tf_type_based_dispatcher.Dispatch + + +def polymorphic_default_out_eager_fallback(T: TV_PolymorphicDefaultOut_T, name, ctx) -> Annotated[Any, TV_PolymorphicDefaultOut_T]: + if T is None: + T = _dtypes.string + T = _execute.make_type(T, "T") + _inputs_flat = [] + _attrs = ("T", T) + _result = _execute.execute(b"PolymorphicDefaultOut", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PolymorphicDefaultOut", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_PolymorphicOut_T = TypeVar("TV_PolymorphicOut_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('polymorphic_out') +def polymorphic_out(T: TV_PolymorphicOut_T, name=None) -> Annotated[Any, TV_PolymorphicOut_T]: + r"""TODO: add doc. + + Args: + T: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "PolymorphicOut", name, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_polymorphic_out( + (T, name,), None) + if _result is not NotImplemented: + return _result + return polymorphic_out_eager_fallback( + T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polymorphic_out, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_polymorphic_out( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "PolymorphicOut", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + polymorphic_out, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "PolymorphicOut", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +PolymorphicOut = tf_export("raw_ops.PolymorphicOut")(_ops.to_raw_op(polymorphic_out)) +_dispatcher_for_polymorphic_out = polymorphic_out._tf_type_based_dispatcher.Dispatch + + +def polymorphic_out_eager_fallback(T: TV_PolymorphicOut_T, name, ctx) -> Annotated[Any, TV_PolymorphicOut_T]: + T = _execute.make_type(T, "T") + _inputs_flat = [] + _attrs = ("T", T) + _result = _execute.execute(b"PolymorphicOut", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "PolymorphicOut", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_RefIn_T = TypeVar("TV_RefIn_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_in') +def ref_in(a: Annotated[Any, TV_RefIn_T], name=None): + r"""TODO: add doc. + + Args: + a: A mutable `Tensor`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_in op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_in( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefIn", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_in, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +RefIn = tf_export("raw_ops.RefIn")(_ops.to_raw_op(ref_in)) +_dispatcher_for_ref_in = ref_in._tf_type_based_dispatcher.Dispatch + + +def ref_in_eager_fallback(a: Annotated[Any, TV_RefIn_T], name, ctx): + raise RuntimeError("ref_in op does not support eager execution. Arg 'a' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_input_float_input') +def ref_input_float_input(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type mutable `float32`. + b: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_input_float_input op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_input_float_input( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefInputFloatInput", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_input_float_input, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +RefInputFloatInput = tf_export("raw_ops.RefInputFloatInput")(_ops.to_raw_op(ref_input_float_input)) +_dispatcher_for_ref_input_float_input = ref_input_float_input._tf_type_based_dispatcher.Dispatch + + +def ref_input_float_input_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name, ctx): + raise RuntimeError("ref_input_float_input op does not support eager execution. Arg 'a' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_input_float_input_int_output') +def ref_input_float_input_int_output(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + a: A `Tensor` of type mutable `float32`. + b: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_input_float_input_int_output op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_input_float_input_int_output( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefInputFloatInputIntOutput", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_input_float_input_int_output, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefInputFloatInputIntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefInputFloatInputIntOutput = tf_export("raw_ops.RefInputFloatInputIntOutput")(_ops.to_raw_op(ref_input_float_input_int_output)) +_dispatcher_for_ref_input_float_input_int_output = ref_input_float_input_int_output._tf_type_based_dispatcher.Dispatch + + +def ref_input_float_input_int_output_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("ref_input_float_input_int_output op does not support eager execution. Arg 'a' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_input_int_input') +def ref_input_int_input(a: Annotated[Any, _atypes.Int32], b: Annotated[Any, _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type mutable `int32`. + b: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_input_int_input op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_input_int_input( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefInputIntInput", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_input_int_input, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +RefInputIntInput = tf_export("raw_ops.RefInputIntInput")(_ops.to_raw_op(ref_input_int_input)) +_dispatcher_for_ref_input_int_input = ref_input_int_input._tf_type_based_dispatcher.Dispatch + + +def ref_input_int_input_eager_fallback(a: Annotated[Any, _atypes.Int32], b: Annotated[Any, _atypes.Int32], name, ctx): + raise RuntimeError("ref_input_int_input op does not support eager execution. Arg 'a' is a ref.") + +TV_RefOut_T = TypeVar("TV_RefOut_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_out') +def ref_out(T: TV_RefOut_T, name=None) -> Annotated[Any, TV_RefOut_T]: + r"""TODO: add doc. + + Args: + T: A `tf.DType`. + name: A name for the operation (optional). + + Returns: + A mutable `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_out op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_out( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefOut", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_out, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefOut", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefOut = tf_export("raw_ops.RefOut")(_ops.to_raw_op(ref_out)) +_dispatcher_for_ref_out = ref_out._tf_type_based_dispatcher.Dispatch + + +def ref_out_eager_fallback(T: TV_RefOut_T, name, ctx) -> Annotated[Any, TV_RefOut_T]: + raise RuntimeError("ref_out op does not support eager execution. Arg 'a' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_output') +def ref_output(name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type mutable `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_output op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefOutput", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RefOutput = tf_export("raw_ops.RefOutput")(_ops.to_raw_op(ref_output)) +_dispatcher_for_ref_output = ref_output._tf_type_based_dispatcher.Dispatch + + +def ref_output_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int32]: + raise RuntimeError("ref_output op does not support eager execution. Arg 'a' is a ref.") +_RefOutputFloatOutputOutput = collections.namedtuple( + "RefOutputFloatOutput", + ["a", "b"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('ref_output_float_output') +def ref_output_float_output(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b). + + a: A `Tensor` of type mutable `float32`. + b: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("ref_output_float_output op does not support eager execution. Arg 'a' is a ref.") + else: + _result = _dispatcher_for_ref_output_float_output( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RefOutputFloatOutput", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + ref_output_float_output, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "RefOutputFloatOutput", _inputs_flat, _attrs, _result) + _result = _RefOutputFloatOutputOutput._make(_result) + return _result + +RefOutputFloatOutput = tf_export("raw_ops.RefOutputFloatOutput")(_ops.to_raw_op(ref_output_float_output)) +_dispatcher_for_ref_output_float_output = ref_output_float_output._tf_type_based_dispatcher.Dispatch + + +def ref_output_float_output_eager_fallback(name, ctx): + raise RuntimeError("ref_output_float_output op does not support eager execution. Arg 'a' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('requires_older_graph_version') +def requires_older_graph_version(name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "RequiresOlderGraphVersion", name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_requires_older_graph_version( + (name,), None) + if _result is not NotImplemented: + return _result + return requires_older_graph_version_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + requires_older_graph_version, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_requires_older_graph_version( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "RequiresOlderGraphVersion", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + requires_older_graph_version, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "RequiresOlderGraphVersion", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +RequiresOlderGraphVersion = tf_export("raw_ops.RequiresOlderGraphVersion")(_ops.to_raw_op(requires_older_graph_version)) +_dispatcher_for_requires_older_graph_version = requires_older_graph_version._tf_type_based_dispatcher.Dispatch + + +def requires_older_graph_version_eager_fallback(name, ctx) -> Annotated[Any, _atypes.Int32]: + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"RequiresOlderGraphVersion", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "RequiresOlderGraphVersion", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('reserved_attr') +def reserved_attr(range: int, name=None): + r"""TODO: add doc. + + Args: + range: An `int`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReservedAttr", name, "range", range) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_reserved_attr( + (range, name,), None) + if _result is not NotImplemented: + return _result + return reserved_attr_eager_fallback( + range=range, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reserved_attr, (), dict(range=range, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_reserved_attr( + (range, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + range = _execute.make_int(range, "range") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReservedAttr", range=range, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reserved_attr, (), dict(range=range, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +ReservedAttr = tf_export("raw_ops.ReservedAttr")(_ops.to_raw_op(reserved_attr)) +_dispatcher_for_reserved_attr = reserved_attr._tf_type_based_dispatcher.Dispatch + + +def reserved_attr_eager_fallback(range: int, name, ctx): + range = _execute.make_int(range, "range") + _inputs_flat = [] + _attrs = ("range", range) + _result = _execute.execute(b"ReservedAttr", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('reserved_input') +def reserved_input(input: Annotated[Any, _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ReservedInput", name, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_reserved_input( + (input, name,), None) + if _result is not NotImplemented: + return _result + return reserved_input_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reserved_input, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_reserved_input( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ReservedInput", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + reserved_input, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +ReservedInput = tf_export("raw_ops.ReservedInput")(_ops.to_raw_op(reserved_input)) +_dispatcher_for_reserved_input = reserved_input._tf_type_based_dispatcher.Dispatch + + +def reserved_input_eager_fallback(input: Annotated[Any, _atypes.Int32], name, ctx): + input = _ops.convert_to_tensor(input, _dtypes.int32) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"ReservedInput", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('resource_create_op') +def resource_create_op(resource: Annotated[Any, _atypes.Resource], name=None): + r"""TODO: add doc. + + Args: + resource: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceCreateOp", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_resource_create_op( + (resource, name,), None) + if _result is not NotImplemented: + return _result + return resource_create_op_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + resource_create_op, (), dict(resource=resource, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_resource_create_op( + (resource, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceCreateOp", resource=resource, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + resource_create_op, (), dict(resource=resource, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +ResourceCreateOp = tf_export("raw_ops.ResourceCreateOp")(_ops.to_raw_op(resource_create_op)) +_dispatcher_for_resource_create_op = resource_create_op._tf_type_based_dispatcher.Dispatch + + +def resource_create_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx): + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"ResourceCreateOp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('resource_initialized_op') +def resource_initialized_op(resource: Annotated[Any, _atypes.Resource], name=None) -> Annotated[Any, _atypes.Bool]: + r"""TODO: add doc. + + Args: + resource: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `bool`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceInitializedOp", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_resource_initialized_op( + (resource, name,), None) + if _result is not NotImplemented: + return _result + return resource_initialized_op_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + resource_initialized_op, (), dict(resource=resource, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_resource_initialized_op( + (resource, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceInitializedOp", resource=resource, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + resource_initialized_op, (), dict(resource=resource, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "ResourceInitializedOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +ResourceInitializedOp = tf_export("raw_ops.ResourceInitializedOp")(_ops.to_raw_op(resource_initialized_op)) +_dispatcher_for_resource_initialized_op = resource_initialized_op._tf_type_based_dispatcher.Dispatch + + +def resource_initialized_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx) -> Annotated[Any, _atypes.Bool]: + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"ResourceInitializedOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "ResourceInitializedOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('resource_using_op') +def resource_using_op(resource: Annotated[Any, _atypes.Resource], name=None): + r"""TODO: add doc. + + Args: + resource: A `Tensor` of type `resource`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "ResourceUsingOp", name, resource) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_resource_using_op( + (resource, name,), None) + if _result is not NotImplemented: + return _result + return resource_using_op_eager_fallback( + resource, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + resource_using_op, (), dict(resource=resource, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_resource_using_op( + (resource, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "ResourceUsingOp", resource=resource, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + resource_using_op, (), dict(resource=resource, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +ResourceUsingOp = tf_export("raw_ops.ResourceUsingOp")(_ops.to_raw_op(resource_using_op)) +_dispatcher_for_resource_using_op = resource_using_op._tf_type_based_dispatcher.Dispatch + + +def resource_using_op_eager_fallback(resource: Annotated[Any, _atypes.Resource], name, ctx): + resource = _ops.convert_to_tensor(resource, _dtypes.resource) + _inputs_flat = [resource] + _attrs = None + _result = _execute.execute(b"ResourceUsingOp", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_Restrict_T = TypeVar("TV_Restrict_T", _atypes.Bool, _atypes.String) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('restrict') +def restrict(a: Annotated[Any, TV_Restrict_T], name=None) -> Annotated[Any, TV_Restrict_T]: + r"""TODO: add doc. + + Args: + a: A `Tensor`. Must be one of the following types: `string`, `bool`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Restrict", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_restrict( + (a, name,), None) + if _result is not NotImplemented: + return _result + return restrict_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + restrict, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_restrict( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Restrict", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + restrict, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Restrict", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Restrict = tf_export("raw_ops.Restrict")(_ops.to_raw_op(restrict)) +_dispatcher_for_restrict = restrict._tf_type_based_dispatcher.Dispatch + + +def restrict_eager_fallback(a: Annotated[Any, TV_Restrict_T], name, ctx) -> Annotated[Any, TV_Restrict_T]: + _attr_T, (a,) = _execute.args_to_matching_eager([a], ctx, [_dtypes.string, _dtypes.bool, ]) + _inputs_flat = [a] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Restrict", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Restrict", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('simple') +def simple(a: Annotated[Any, _atypes.Int32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Simple", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_simple( + (a, name,), None) + if _result is not NotImplemented: + return _result + return simple_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + simple, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_simple( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Simple", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + simple, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "Simple", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Simple = tf_export("raw_ops.Simple")(_ops.to_raw_op(simple)) +_dispatcher_for_simple = simple._tf_type_based_dispatcher.Dispatch + + +def simple_eager_fallback(a: Annotated[Any, _atypes.Int32], name, ctx) -> Annotated[Any, _atypes.Float32]: + a = _ops.convert_to_tensor(a, _dtypes.int32) + _inputs_flat = [a] + _attrs = None + _result = _execute.execute(b"Simple", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Simple", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('simple_struct') +def simple_struct(n_a: int, name=None): + r"""TODO: add doc. + + Args: + n_a: An `int` that is `>= 0`. + name: A name for the operation (optional). + + Returns: + A list of `n_a` `Tensor` objects with type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SimpleStruct", name, "n_a", n_a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_simple_struct( + (n_a, name,), None) + if _result is not NotImplemented: + return _result + return simple_struct_eager_fallback( + n_a=n_a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + simple_struct, (), dict(n_a=n_a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_simple_struct( + (n_a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + n_a = _execute.make_int(n_a, "n_a") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SimpleStruct", n_a=n_a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + simple_struct, (), dict(n_a=n_a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("n_a", _op._get_attr_int("n_a")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SimpleStruct", _inputs_flat, _attrs, _result) + return _result + +SimpleStruct = tf_export("raw_ops.SimpleStruct")(_ops.to_raw_op(simple_struct)) +_dispatcher_for_simple_struct = simple_struct._tf_type_based_dispatcher.Dispatch + + +def simple_struct_eager_fallback(n_a: int, name, ctx): + n_a = _execute.make_int(n_a, "n_a") + _inputs_flat = [] + _attrs = ("n_a", n_a) + _result = _execute.execute(b"SimpleStruct", n_a, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SimpleStruct", _inputs_flat, _attrs, _result) + return _result + + +TV_SleepIdentityOp_T = TypeVar("TV_SleepIdentityOp_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('sleep_identity_op') +def sleep_identity_op(sleep_seconds: Annotated[Any, _atypes.Int32], input: Annotated[Any, TV_SleepIdentityOp_T], name=None) -> Annotated[Any, TV_SleepIdentityOp_T]: + r"""TODO: add doc. + + Args: + sleep_seconds: A `Tensor` of type `int32`. + input: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `input`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SleepIdentityOp", name, sleep_seconds, input) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_sleep_identity_op( + (sleep_seconds, input, name,), None) + if _result is not NotImplemented: + return _result + return sleep_identity_op_eager_fallback( + sleep_seconds, input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sleep_identity_op, (), dict(sleep_seconds=sleep_seconds, + input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_sleep_identity_op( + (sleep_seconds, input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SleepIdentityOp", sleep_seconds=sleep_seconds, input=input, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sleep_identity_op, (), dict(sleep_seconds=sleep_seconds, + input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "SleepIdentityOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +SleepIdentityOp = tf_export("raw_ops.SleepIdentityOp")(_ops.to_raw_op(sleep_identity_op)) +_dispatcher_for_sleep_identity_op = sleep_identity_op._tf_type_based_dispatcher.Dispatch + + +def sleep_identity_op_eager_fallback(sleep_seconds: Annotated[Any, _atypes.Int32], input: Annotated[Any, TV_SleepIdentityOp_T], name, ctx) -> Annotated[Any, TV_SleepIdentityOp_T]: + _attr_T, (input,) = _execute.args_to_matching_eager([input], ctx, []) + sleep_seconds = _ops.convert_to_tensor(sleep_seconds, _dtypes.int32) + _inputs_flat = [sleep_seconds, input] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"SleepIdentityOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "SleepIdentityOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('sleep_op') +def sleep_op(sleep_seconds: Annotated[Any, _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + sleep_seconds: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "SleepOp", name, sleep_seconds) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_sleep_op( + (sleep_seconds, name,), None) + if _result is not NotImplemented: + return _result + return sleep_op_eager_fallback( + sleep_seconds, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sleep_op, (), dict(sleep_seconds=sleep_seconds, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_sleep_op( + (sleep_seconds, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "SleepOp", sleep_seconds=sleep_seconds, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + sleep_op, (), dict(sleep_seconds=sleep_seconds, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +SleepOp = tf_export("raw_ops.SleepOp")(_ops.to_raw_op(sleep_op)) +_dispatcher_for_sleep_op = sleep_op._tf_type_based_dispatcher.Dispatch + + +def sleep_op_eager_fallback(sleep_seconds: Annotated[Any, _atypes.Int32], name, ctx): + sleep_seconds = _ops.convert_to_tensor(sleep_seconds, _dtypes.int32) + _inputs_flat = [sleep_seconds] + _attrs = None + _result = _execute.execute(b"SleepOp", 0, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('string_list_attr') +def string_list_attr(a, b: str, name=None): + r"""TODO: add doc. + + Args: + a: A list of `strings`. + b: A `string`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StringListAttr", name, "a", a, "b", b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_string_list_attr( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return string_list_attr_eager_fallback( + a=a, b=b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_list_attr, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_string_list_attr( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'string_list_attr' Op, not %r." % a) + a = [_execute.make_str(_s, "a") for _s in a] + b = _execute.make_str(b, "b") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StringListAttr", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + string_list_attr, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +StringListAttr = tf_export("raw_ops.StringListAttr")(_ops.to_raw_op(string_list_attr)) +_dispatcher_for_string_list_attr = string_list_attr._tf_type_based_dispatcher.Dispatch + + +def string_list_attr_eager_fallback(a, b: str, name, ctx): + if not isinstance(a, (list, tuple)): + raise TypeError( + "Expected list for 'a' argument to " + "'string_list_attr' Op, not %r." % a) + a = [_execute.make_str(_s, "a") for _s in a] + b = _execute.make_str(b, "b") + _inputs_flat = [] + _attrs = ("a", a, "b", b) + _result = _execute.execute(b"StringListAttr", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('stub_resource_handle_op') +def stub_resource_handle_op(container:str="", shared_name:str="", name=None) -> Annotated[Any, _atypes.Resource]: + r"""TODO: add doc. + + Args: + container: An optional `string`. Defaults to `""`. + shared_name: An optional `string`. Defaults to `""`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `resource`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "StubResourceHandleOp", name, "container", container, + "shared_name", shared_name) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_stub_resource_handle_op( + (container, shared_name, name,), None) + if _result is not NotImplemented: + return _result + return stub_resource_handle_op_eager_fallback( + container=container, shared_name=shared_name, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + stub_resource_handle_op, (), dict(container=container, + shared_name=shared_name, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_stub_resource_handle_op( + (container, shared_name, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "StubResourceHandleOp", container=container, shared_name=shared_name, + name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + stub_resource_handle_op, (), dict(container=container, + shared_name=shared_name, + name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("container", _op.get_attr("container"), "shared_name", + _op.get_attr("shared_name")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "StubResourceHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +StubResourceHandleOp = tf_export("raw_ops.StubResourceHandleOp")(_ops.to_raw_op(stub_resource_handle_op)) +_dispatcher_for_stub_resource_handle_op = stub_resource_handle_op._tf_type_based_dispatcher.Dispatch + + +def stub_resource_handle_op_eager_fallback(container: str, shared_name: str, name, ctx) -> Annotated[Any, _atypes.Resource]: + if container is None: + container = "" + container = _execute.make_str(container, "container") + if shared_name is None: + shared_name = "" + shared_name = _execute.make_str(shared_name, "shared_name") + _inputs_flat = [] + _attrs = ("container", container, "shared_name", shared_name) + _result = _execute.execute(b"StubResourceHandleOp", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "StubResourceHandleOp", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +TV_TestAttr_T = TypeVar("TV_TestAttr_T", _atypes.Float32, _atypes.Float64) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('test_attr') +def test_attr(T: TV_TestAttr_T, name=None) -> Annotated[Any, TV_TestAttr_T]: + r"""TODO: add doc. + + Args: + T: A `tf.DType` from: `tf.float32, tf.float64`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `T`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TestAttr", name, "T", T) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_test_attr( + (T, name,), None) + if _result is not NotImplemented: + return _result + return test_attr_eager_fallback( + T=T, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + test_attr, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_test_attr( + (T, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + T = _execute.make_type(T, "T") + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TestAttr", T=T, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + test_attr, (), dict(T=T, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "TestAttr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TestAttr = tf_export("raw_ops.TestAttr")(_ops.to_raw_op(test_attr)) +_dispatcher_for_test_attr = test_attr._tf_type_based_dispatcher.Dispatch + + +def test_attr_eager_fallback(T: TV_TestAttr_T, name, ctx) -> Annotated[Any, TV_TestAttr_T]: + T = _execute.make_type(T, "T") + _inputs_flat = [] + _attrs = ("T", T) + _result = _execute.execute(b"TestAttr", 1, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TestAttr", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TestStringOutputOutput = collections.namedtuple( + "TestStringOutput", + ["output1", "output2"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('test_string_output') +def test_string_output(input: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + input: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (output1, output2). + + output1: A `Tensor` of type `float32`. + output2: A `Tensor` of type `string`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TestStringOutput", name, input) + _result = _TestStringOutputOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_test_string_output( + (input, name,), None) + if _result is not NotImplemented: + return _result + return test_string_output_eager_fallback( + input, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + test_string_output, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_test_string_output( + (input, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TestStringOutput", input=input, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + test_string_output, (), dict(input=input, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TestStringOutput", _inputs_flat, _attrs, _result) + _result = _TestStringOutputOutput._make(_result) + return _result + +TestStringOutput = tf_export("raw_ops.TestStringOutput")(_ops.to_raw_op(test_string_output)) +_dispatcher_for_test_string_output = test_string_output._tf_type_based_dispatcher.Dispatch + + +def test_string_output_eager_fallback(input: Annotated[Any, _atypes.Float32], name, ctx): + input = _ops.convert_to_tensor(input, _dtypes.float32) + _inputs_flat = [input] + _attrs = None + _result = _execute.execute(b"TestStringOutput", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TestStringOutput", _inputs_flat, _attrs, _result) + _result = _TestStringOutputOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_float_inputs') +def two_float_inputs(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TwoFloatInputs", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_two_float_inputs( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return two_float_inputs_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_inputs, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_two_float_inputs( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoFloatInputs", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_inputs, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +TwoFloatInputs = tf_export("raw_ops.TwoFloatInputs")(_ops.to_raw_op(two_float_inputs)) +_dispatcher_for_two_float_inputs = two_float_inputs._tf_type_based_dispatcher.Dispatch + + +def two_float_inputs_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.float32) + b = _ops.convert_to_tensor(b, _dtypes.float32) + _inputs_flat = [a, b] + _attrs = None + _result = _execute.execute(b"TwoFloatInputs", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_float_inputs_float_output') +def two_float_inputs_float_output(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Float32]: + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TwoFloatInputsFloatOutput", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_two_float_inputs_float_output( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return two_float_inputs_float_output_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_inputs_float_output, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_two_float_inputs_float_output( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoFloatInputsFloatOutput", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_inputs_float_output, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TwoFloatInputsFloatOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TwoFloatInputsFloatOutput = tf_export("raw_ops.TwoFloatInputsFloatOutput")(_ops.to_raw_op(two_float_inputs_float_output)) +_dispatcher_for_two_float_inputs_float_output = two_float_inputs_float_output._tf_type_based_dispatcher.Dispatch + + +def two_float_inputs_float_output_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Float32]: + a = _ops.convert_to_tensor(a, _dtypes.float32) + b = _ops.convert_to_tensor(b, _dtypes.float32) + _inputs_flat = [a, b] + _attrs = None + _result = _execute.execute(b"TwoFloatInputsFloatOutput", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TwoFloatInputsFloatOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_float_inputs_int_output') +def two_float_inputs_int_output(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name=None) -> Annotated[Any, _atypes.Int32]: + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `float32`. + name: A name for the operation (optional). + + Returns: + A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TwoFloatInputsIntOutput", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_two_float_inputs_int_output( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return two_float_inputs_int_output_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_inputs_int_output, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_two_float_inputs_int_output( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoFloatInputsIntOutput", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_inputs_int_output, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TwoFloatInputsIntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +TwoFloatInputsIntOutput = tf_export("raw_ops.TwoFloatInputsIntOutput")(_ops.to_raw_op(two_float_inputs_int_output)) +_dispatcher_for_two_float_inputs_int_output = two_float_inputs_int_output._tf_type_based_dispatcher.Dispatch + + +def two_float_inputs_int_output_eager_fallback(a: Annotated[Any, _atypes.Float32], b: Annotated[Any, _atypes.Float32], name, ctx) -> Annotated[Any, _atypes.Int32]: + a = _ops.convert_to_tensor(a, _dtypes.float32) + b = _ops.convert_to_tensor(b, _dtypes.float32) + _inputs_flat = [a, b] + _attrs = None + _result = _execute.execute(b"TwoFloatInputsIntOutput", 1, + inputs=_inputs_flat, attrs=_attrs, ctx=ctx, + name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TwoFloatInputsIntOutput", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +_TwoFloatOutputsOutput = collections.namedtuple( + "TwoFloatOutputs", + ["a", "b"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_float_outputs') +def two_float_outputs(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b). + + a: A `Tensor` of type `float32`. + b: A `Tensor` of type `float32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TwoFloatOutputs", name) + _result = _TwoFloatOutputsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_two_float_outputs( + (name,), None) + if _result is not NotImplemented: + return _result + return two_float_outputs_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_outputs, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_two_float_outputs( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoFloatOutputs", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_float_outputs, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TwoFloatOutputs", _inputs_flat, _attrs, _result) + _result = _TwoFloatOutputsOutput._make(_result) + return _result + +TwoFloatOutputs = tf_export("raw_ops.TwoFloatOutputs")(_ops.to_raw_op(two_float_outputs)) +_dispatcher_for_two_float_outputs = two_float_outputs._tf_type_based_dispatcher.Dispatch + + +def two_float_outputs_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"TwoFloatOutputs", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TwoFloatOutputs", _inputs_flat, _attrs, _result) + _result = _TwoFloatOutputsOutput._make(_result) + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_int_inputs') +def two_int_inputs(a: Annotated[Any, _atypes.Int32], b: Annotated[Any, _atypes.Int32], name=None): + r"""TODO: add doc. + + Args: + a: A `Tensor` of type `int32`. + b: A `Tensor` of type `int32`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TwoIntInputs", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_two_int_inputs( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return two_int_inputs_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_int_inputs, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_two_int_inputs( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoIntInputs", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_int_inputs, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +TwoIntInputs = tf_export("raw_ops.TwoIntInputs")(_ops.to_raw_op(two_int_inputs)) +_dispatcher_for_two_int_inputs = two_int_inputs._tf_type_based_dispatcher.Dispatch + + +def two_int_inputs_eager_fallback(a: Annotated[Any, _atypes.Int32], b: Annotated[Any, _atypes.Int32], name, ctx): + a = _ops.convert_to_tensor(a, _dtypes.int32) + b = _ops.convert_to_tensor(b, _dtypes.int32) + _inputs_flat = [a, b] + _attrs = None + _result = _execute.execute(b"TwoIntInputs", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + +_TwoIntOutputsOutput = collections.namedtuple( + "TwoIntOutputs", + ["a", "b"]) + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_int_outputs') +def two_int_outputs(name=None): + r"""TODO: add doc. + + Args: + name: A name for the operation (optional). + + Returns: + A tuple of `Tensor` objects (a, b). + + a: A `Tensor` of type `int32`. + b: A `Tensor` of type `int32`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TwoIntOutputs", name) + _result = _TwoIntOutputsOutput._make(_result) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_two_int_outputs( + (name,), None) + if _result is not NotImplemented: + return _result + return two_int_outputs_eager_fallback( + name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_int_outputs, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_two_int_outputs( + (name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoIntOutputs", name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_int_outputs, (), dict(name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = () + _inputs_flat = _op.inputs + _execute.record_gradient( + "TwoIntOutputs", _inputs_flat, _attrs, _result) + _result = _TwoIntOutputsOutput._make(_result) + return _result + +TwoIntOutputs = tf_export("raw_ops.TwoIntOutputs")(_ops.to_raw_op(two_int_outputs)) +_dispatcher_for_two_int_outputs = two_int_outputs._tf_type_based_dispatcher.Dispatch + + +def two_int_outputs_eager_fallback(name, ctx): + _inputs_flat = [] + _attrs = None + _result = _execute.execute(b"TwoIntOutputs", 2, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "TwoIntOutputs", _inputs_flat, _attrs, _result) + _result = _TwoIntOutputsOutput._make(_result) + return _result + + +TV_TwoRefsIn_T = TypeVar("TV_TwoRefsIn_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('two_refs_in') +def two_refs_in(a: Annotated[Any, TV_TwoRefsIn_T], b: Annotated[Any, TV_TwoRefsIn_T], name=None): + r"""TODO: add doc. + + Args: + a: A mutable `Tensor`. + b: A mutable `Tensor`. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + raise RuntimeError("two_refs_in op does not support eager execution. Arg 'b' is a ref.") + else: + _result = _dispatcher_for_two_refs_in( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TwoRefsIn", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + two_refs_in, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +TwoRefsIn = tf_export("raw_ops.TwoRefsIn")(_ops.to_raw_op(two_refs_in)) +_dispatcher_for_two_refs_in = two_refs_in._tf_type_based_dispatcher.Dispatch + + +def two_refs_in_eager_fallback(a: Annotated[Any, TV_TwoRefsIn_T], b: Annotated[Any, TV_TwoRefsIn_T], name, ctx): + raise RuntimeError("two_refs_in op does not support eager execution. Arg 'b' is a ref.") + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('type_list') +def type_list(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TypeList", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_type_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + return type_list_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + type_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_type_list( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TypeList", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + type_list, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +TypeList = tf_export("raw_ops.TypeList")(_ops.to_raw_op(type_list)) +_dispatcher_for_type_list = type_list._tf_type_based_dispatcher.Dispatch + + +def type_list_eager_fallback(a, name, ctx): + _attr_T, a = _execute.convert_to_mixed_eager_tensors(a, ctx) + _inputs_flat = list(a) + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TypeList", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('type_list_restrict') +def type_list_restrict(a, name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects with types from: `string`, `bool`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TypeListRestrict", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_type_list_restrict( + (a, name,), None) + if _result is not NotImplemented: + return _result + return type_list_restrict_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + type_list_restrict, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_type_list_restrict( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TypeListRestrict", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + type_list_restrict, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +TypeListRestrict = tf_export("raw_ops.TypeListRestrict")(_ops.to_raw_op(type_list_restrict)) +_dispatcher_for_type_list_restrict = type_list_restrict._tf_type_based_dispatcher.Dispatch + + +def type_list_restrict_eager_fallback(a, name, ctx): + _attr_T, a = _execute.convert_to_mixed_eager_tensors(a, ctx) + _inputs_flat = list(a) + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TypeListRestrict", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('type_list_twice') +def type_list_twice(a, b, name=None): + r"""TODO: add doc. + + Args: + a: A list of `Tensor` objects. + b: A list of `Tensor` objects. Must have the same type as `a`. + name: A name for the operation (optional). + + Returns: + The created Operation. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "TypeListTwice", name, a, b) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_type_list_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + return type_list_twice_eager_fallback( + a, b, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + type_list_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_type_list_twice( + (a, b, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "TypeListTwice", a=a, b=b, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + type_list_twice, (), dict(a=a, b=b, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + return _op +TypeListTwice = tf_export("raw_ops.TypeListTwice")(_ops.to_raw_op(type_list_twice)) +_dispatcher_for_type_list_twice = type_list_twice._tf_type_based_dispatcher.Dispatch + + +def type_list_twice_eager_fallback(a, b, name, ctx): + _attr_T, (a, b) = _execute.args_to_mixed_eager_tensors((a, b), ctx) + _inputs_flat = list(a) + list(b) + _attrs = ("T", _attr_T) + _result = _execute.execute(b"TypeListTwice", 0, inputs=_inputs_flat, + attrs=_attrs, ctx=ctx, name=name) + _result = None + return _result + + +TV_Unary_T = TypeVar("TV_Unary_T", _atypes.BFloat16, _atypes.Bool, _atypes.Complex128, _atypes.Complex64, _atypes.Float16, _atypes.Float32, _atypes.Float64, _atypes.Float8e4m3fn, _atypes.Float8e5m2, _atypes.Half, _atypes.Int16, _atypes.Int32, _atypes.Int4, _atypes.Int64, _atypes.Int8, _atypes.QInt16, _atypes.QInt32, _atypes.QInt8, _atypes.QUInt16, _atypes.QUInt8, _atypes.Resource, _atypes.String, _atypes.UInt16, _atypes.UInt32, _atypes.UInt4, _atypes.UInt64, _atypes.UInt8, _atypes.Variant) + +@_dispatch.add_fallback_dispatch_list +@_dispatch.add_type_based_api_dispatcher +@tf_export('unary') +def unary(a: Annotated[Any, TV_Unary_T], name=None) -> Annotated[Any, TV_Unary_T]: + r"""TODO: add doc. + + Args: + a: A `Tensor`. + name: A name for the operation (optional). + + Returns: + A `Tensor`. Has the same type as `a`. + """ + _ctx = _context._context or _context.context() + tld = _ctx._thread_local_data + if tld.is_eager: + try: + _result = pywrap_tfe.TFE_Py_FastPathExecute( + _ctx, "Unary", name, a) + return _result + except _core._NotOkStatusException as e: + _ops.raise_from_not_ok_status(e, name) + except _core._FallbackException: + pass + try: + _result = _dispatcher_for_unary( + (a, name,), None) + if _result is not NotImplemented: + return _result + return unary_eager_fallback( + a, name=name, ctx=_ctx) + except _core._SymbolicException: + pass # Add nodes to the TensorFlow graph. + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unary, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + else: + _result = _dispatcher_for_unary( + (a, name,), None) + if _result is not NotImplemented: + return _result + # Add nodes to the TensorFlow graph. + try: + _, _, _op, _outputs = _op_def_library._apply_op_helper( + "Unary", a=a, name=name) + except (TypeError, ValueError): + _result = _dispatch.dispatch( + unary, (), dict(a=a, name=name) + ) + if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED: + return _result + raise + _result = _outputs[:] + if _execute.must_record_gradient(): + _attrs = ("T", _op._get_attr_type("T")) + _inputs_flat = _op.inputs + _execute.record_gradient( + "Unary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + +Unary = tf_export("raw_ops.Unary")(_ops.to_raw_op(unary)) +_dispatcher_for_unary = unary._tf_type_based_dispatcher.Dispatch + + +def unary_eager_fallback(a: Annotated[Any, TV_Unary_T], name, ctx) -> Annotated[Any, TV_Unary_T]: + _attr_T, (a,) = _execute.args_to_matching_eager([a], ctx, []) + _inputs_flat = [a] + _attrs = ("T", _attr_T) + _result = _execute.execute(b"Unary", 1, inputs=_inputs_flat, attrs=_attrs, + ctx=ctx, name=name) + if _execute.must_record_gradient(): + _execute.record_gradient( + "Unary", _inputs_flat, _attrs, _result) + _result, = _result + return _result + diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_util.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..74099bd600173475b05739150f73a8346a332d2f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/test_util.py @@ -0,0 +1,4199 @@ +# 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. +# ============================================================================== + +# pylint: disable=invalid-name +"""Test utils for tensorflow.""" + +import collections +from collections import OrderedDict +from collections.abc import Iterator +import contextlib +import functools +import gc +import itertools +import math +import os +import random +import re +import tempfile +import threading +import time +from typing import Union +import unittest + +from absl.testing import parameterized +import numpy as np + +from google.protobuf import descriptor_pool +from google.protobuf import text_format +from tensorflow.core.config import flags +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python import pywrap_sanitizers +from tensorflow.python import tf2 +from tensorflow.python.client import device_lib +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.client import session as s +from tensorflow.python.compat import v2_compat +from tensorflow.python.compat.compat import forward_compatibility_horizon +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import _test_metrics_util +from tensorflow.python.framework import config +from tensorflow.python.framework import device as pydev +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import gpu_util +from tensorflow.python.framework import importer +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.framework import tfrt_utils +from tensorflow.python.framework import versions +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import control_flow_util_v2 +from tensorflow.python.ops import gen_sparse_ops +from tensorflow.python.ops import gen_sync_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import script_ops +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.ops import variables + + +from tensorflow.python.ops.ragged import ragged_ops # pylint: disable=unused-import +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_tensor_value +from tensorflow.python.platform import _pywrap_stacktrace_handler +from tensorflow.python.platform import googletest +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import server_lib +from tensorflow.python.util import _pywrap_util_port +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util import tf_inspect +from tensorflow.python.util import traceback_utils +from tensorflow.python.util.compat import collections_abc +from tensorflow.python.util.protobuf import compare +from tensorflow.python.util.tf_export import tf_export + + +# If the below import is made available through the BUILD rule, then this +# function is overridden and will instead return True and cause Tensorflow +# graphs to be compiled with XLA. +def is_xla_enabled(): + return False + + +try: + from tensorflow.python.framework.is_xla_test_true import is_xla_enabled # pylint: disable=g-import-not-at-top, unused-import +except Exception: # pylint: disable=broad-except + pass + + +# Uses the same mechanism as above to selectively enable/disable MLIR +# compilation. +def is_mlir_bridge_enabled(): + return None + + +try: + from tensorflow.python.framework.is_mlir_bridge_test_false import is_mlir_bridge_enabled # pylint: disable=g-import-not-at-top, unused-import +except ImportError: + try: + from tensorflow.python.framework.is_mlir_bridge_test_true import is_mlir_bridge_enabled # pylint: disable=g-import-not-at-top, unused-import + except ImportError: + pass + + +def is_asan_enabled(): + """Check if ASAN is enabled.""" + return pywrap_sanitizers.is_asan_enabled() + + +def is_msan_enabled(): + """Check if MSAN is enabled.""" + return pywrap_sanitizers.is_msan_enabled() + + +def is_tsan_enabled(): + """Check if TSAN is enabled.""" + return pywrap_sanitizers.is_tsan_enabled() + + +def is_ubsan_enabled(): + """Check if UBSAN is enabled.""" + return pywrap_sanitizers.is_ubsan_enabled() + + +def _get_object_count_by_type(exclude=()): + return ( + collections.Counter([type(obj).__name__ for obj in gc.get_objects()]) - + collections.Counter([type(obj).__name__ for obj in exclude])) + + +@tf_export("test.gpu_device_name") +def gpu_device_name(): + """Returns the name of a GPU device if available or a empty string. + + This method should only be used in tests written with `tf.test.TestCase`. + + >>> class MyTest(tf.test.TestCase): + ... + ... def test_add_on_gpu(self): + ... if not tf.test.is_built_with_gpu_support(): + ... self.skipTest("test is only applicable on GPU") + ... + ... with tf.device(tf.test.gpu_device_name()): + ... self.assertEqual(tf.math.add(1.0, 2.0), 3.0) + + """ + for x in device_lib.list_local_devices(): + if x.device_type == "GPU": + return compat.as_str(x.name) + return "" + + +def assert_ops_in_graph(expected_ops, graph): + """Assert all expected operations are found. + + Args: + expected_ops: `dict` of op name to op type. + graph: Graph to check. + + Returns: + `dict` of node name to node. + + Raises: + ValueError: If the expected ops are not present in the graph. + """ + actual_ops = {} + gd = graph.as_graph_def() + for node in gd.node: + if node.name in expected_ops: + if expected_ops[node.name] != node.op: + raise ValueError("Expected op for node %s is different. %s vs %s" % + (node.name, expected_ops[node.name], node.op)) + actual_ops[node.name] = node + if set(expected_ops.keys()) != set(actual_ops.keys()): + raise ValueError("Not all expected ops are present. Expected %s, found %s" % + (expected_ops.keys(), actual_ops.keys())) + return actual_ops + + +@tf_export("test.assert_equal_graph_def", v1=[]) +def assert_equal_graph_def_v2(expected, actual): + """Asserts that two `GraphDef`s are (mostly) the same. + + Compares two `GraphDef` protos for equality, ignoring versions and ordering of + nodes, attrs, and control inputs. Node names are used to match up nodes + between the graphs, so the naming of nodes must be consistent. This function + ignores randomized attribute values that may appear in V2 checkpoints. + + Args: + expected: The `GraphDef` we expected. + actual: The `GraphDef` we have. + + Raises: + AssertionError: If the `GraphDef`s do not match. + TypeError: If either argument is not a `GraphDef`. + """ + assert_equal_graph_def(actual, expected, checkpoint_v2=True, + hash_table_shared_name=True) + + +@tf_export(v1=["test.assert_equal_graph_def"]) +def assert_equal_graph_def_v1(actual, expected, checkpoint_v2=False, + hash_table_shared_name=False): + """Asserts that two `GraphDef`s are (mostly) the same. + + Compares two `GraphDef` protos for equality, ignoring versions and ordering of + nodes, attrs, and control inputs. Node names are used to match up nodes + between the graphs, so the naming of nodes must be consistent. + + Args: + actual: The `GraphDef` we have. + expected: The `GraphDef` we expected. + checkpoint_v2: boolean determining whether to ignore randomized attribute + values that appear in V2 checkpoints. + hash_table_shared_name: boolean determining whether to ignore randomized + shared_names that appear in HashTableV2 op defs. + + Raises: + AssertionError: If the `GraphDef`s do not match. + TypeError: If either argument is not a `GraphDef`. + """ + assert_equal_graph_def(actual, expected, checkpoint_v2, + hash_table_shared_name) + + +def assert_equal_graph_def(actual, expected, checkpoint_v2=False, + hash_table_shared_name=False): + if not isinstance(actual, graph_pb2.GraphDef): + raise TypeError("Expected tf.GraphDef for actual, got %s" % + type(actual).__name__) + if not isinstance(expected, graph_pb2.GraphDef): + raise TypeError("Expected tf.GraphDef for expected, got %s" % + type(expected).__name__) + + if checkpoint_v2: + _strip_checkpoint_v2_randomized(actual) + _strip_checkpoint_v2_randomized(expected) + + if hash_table_shared_name: + _strip_hash_table_shared_name(actual) + _strip_hash_table_shared_name(expected) + + diff = pywrap_tf_session.EqualGraphDefWrapper(actual.SerializeToString(), + expected.SerializeToString()) + if diff: + raise AssertionError(compat.as_str(diff)) + + +def assert_meta_graph_protos_equal(tester, a, b): + """Compares MetaGraphDefs `a` and `b` in unit test class `tester`.""" + # Carefully check the collection_defs + tester.assertEqual(set(a.collection_def), set(b.collection_def)) + collection_keys = a.collection_def.keys() + for k in collection_keys: + a_value = a.collection_def[k] + b_value = b.collection_def[k] + proto_type = ops.get_collection_proto_type(k) + if proto_type: + a_proto = proto_type() + b_proto = proto_type() + # Number of entries in the collections is the same + tester.assertEqual( + len(a_value.bytes_list.value), len(b_value.bytes_list.value)) + for (a_value_item, b_value_item) in zip(a_value.bytes_list.value, + b_value.bytes_list.value): + a_proto.ParseFromString(a_value_item) + b_proto.ParseFromString(b_value_item) + tester.assertProtoEquals(a_proto, b_proto) + else: + tester.assertEquals(a_value, b_value) + # Compared the fields directly, remove their raw values from the + # proto comparison below. + a.ClearField("collection_def") + b.ClearField("collection_def") + + # Check the graph_defs. + assert_equal_graph_def(a.graph_def, b.graph_def, checkpoint_v2=True) + # Check graph_def versions (ignored by assert_equal_graph_def). + tester.assertProtoEquals(a.graph_def.versions, b.graph_def.versions) + # Compared the fields directly, remove their raw values from the + # proto comparison below. + a.ClearField("graph_def") + b.ClearField("graph_def") + + tester.assertProtoEquals(a, b) + + +# Matches attributes named via _SHARDED_SUFFIX in +# tensorflow/python/training/saver.py +_SHARDED_SAVE_OP_PATTERN = "_temp_[0-9a-z]{32}/part" + + +def _strip_checkpoint_v2_randomized(graph_def): + for node in graph_def.node: + delete_keys = [] + for attr_key in node.attr: + attr_tensor_value = node.attr[attr_key].tensor + if attr_tensor_value and len(attr_tensor_value.string_val) == 1: + attr_tensor_string_value = attr_tensor_value.string_val[0] + if (attr_tensor_string_value and + re.match(compat.as_bytes(_SHARDED_SAVE_OP_PATTERN), + attr_tensor_string_value)): + delete_keys.append(attr_key) + for attr_key in delete_keys: + del node.attr[attr_key] + + +_TABLE_SHARED_NAME_PATTERN = r"hash_table_[0-9a-z\-]+" + + +def _strip_hash_table_shared_name(graph_def): + for node in graph_def.node: + delete_keys = [] + if node.op == "HashTableV2" and "shared_name" in node.attr: + if re.match(compat.as_bytes(_TABLE_SHARED_NAME_PATTERN), + node.attr["shared_name"].s): + delete_keys.append("shared_name") + for attr_key in delete_keys: + del node.attr[attr_key] + + +def IsGoogleCudaEnabled(): + return _pywrap_util_port.IsGoogleCudaEnabled() + + +def IsBuiltWithROCm(): + return _pywrap_util_port.IsBuiltWithROCm() + + +def IsBuiltWithXLA(): + return _pywrap_util_port.IsBuiltWithXLA() + + +def IsBuiltWithNvcc(): + return _pywrap_util_port.IsBuiltWithNvcc() + + +def GpuSupportsHalfMatMulAndConv(): + return _pywrap_util_port.GpuSupportsHalfMatMulAndConv() + + +def IsMklEnabled(): + return _pywrap_util_port.IsMklEnabled() + + +def InstallStackTraceHandler(): + _pywrap_stacktrace_handler.InstallStacktraceHandler() + + +def NHWCToNCHW(input_tensor): + """Converts the input from the NHWC format to NCHW. + + Args: + input_tensor: a 3-, 4-, or 5-D tensor, or an array representing shape + + Returns: + converted tensor or shape array + """ + # tensor dim -> new axis order + new_axes = {3: [0, 2, 1], 4: [0, 3, 1, 2], 5: [0, 4, 1, 2, 3]} + if isinstance(input_tensor, tensor_lib.Tensor): + ndims = input_tensor.shape.ndims + return array_ops.transpose(input_tensor, new_axes[ndims]) + else: + ndims = len(input_tensor) + return [input_tensor[a] for a in new_axes[ndims]] + + +def NHWCToNCHW_VECT_C(input_shape_or_tensor): + """Transforms the input from the NHWC layout to NCHW_VECT_C layout. + + Note: Does not include quantization or type conversion steps, which should + be applied afterwards. + + Args: + input_shape_or_tensor: a 4- or 5-D tensor, or an array representing shape + + Returns: + tensor or shape array transformed into NCHW_VECT_C + + Raises: + ValueError: if last dimension of `input_shape_or_tensor` is not evenly + divisible by 4. + """ + permutations = {5: [0, 3, 1, 2, 4], 6: [0, 4, 1, 2, 3, 5]} + is_tensor = isinstance(input_shape_or_tensor, tensor_lib.Tensor) + temp_shape = ( + input_shape_or_tensor.shape.as_list() + if is_tensor else input_shape_or_tensor) + if temp_shape[-1] % 4 != 0: + raise ValueError( + "Last dimension of input must be evenly divisible by 4 to convert to " + "NCHW_VECT_C.") + temp_shape[-1] //= 4 + temp_shape.append(4) + permutation = permutations[len(temp_shape)] + if is_tensor: + t = array_ops.reshape(input_shape_or_tensor, temp_shape) + return array_ops.transpose(t, permutation) + else: + return [temp_shape[a] for a in permutation] + + +def NCHW_VECT_CToNHWC(input_shape_or_tensor): + """Transforms the input from the NCHW_VECT_C layout to NHWC layout. + + Note: Does not include de-quantization or type conversion steps, which should + be applied beforehand. + + Args: + input_shape_or_tensor: a 5- or 6-D tensor, or an array representing shape + + Returns: + tensor or shape array transformed into NHWC + + Raises: + ValueError: if last dimension of `input_shape_or_tensor` is not 4. + """ + permutations = {5: [0, 2, 3, 1, 4], 6: [0, 2, 3, 4, 1, 5]} + is_tensor = isinstance(input_shape_or_tensor, tensor_lib.Tensor) + input_shape = ( + input_shape_or_tensor.shape.as_list() + if is_tensor else input_shape_or_tensor) + if input_shape[-1] != 4: + raise ValueError("Last dimension of NCHW_VECT_C must be 4.") + permutation = permutations[len(input_shape)] + nhwc_shape = [input_shape[a] for a in permutation[:-1]] + nhwc_shape[-1] *= input_shape[-1] + if is_tensor: + t = array_ops.transpose(input_shape_or_tensor, permutation) + return array_ops.reshape(t, nhwc_shape) + else: + return nhwc_shape + + +def NCHWToNHWC(input_tensor): + """Converts the input from the NCHW format to NHWC. + + Args: + input_tensor: a 4- or 5-D tensor, or an array representing shape + + Returns: + converted tensor or shape array + """ + # tensor dim -> new axis order + new_axes = {4: [0, 2, 3, 1], 5: [0, 2, 3, 4, 1]} + if isinstance(input_tensor, tensor_lib.Tensor): + ndims = input_tensor.shape.ndims + return array_ops.transpose(input_tensor, new_axes[ndims]) + else: + ndims = len(input_tensor) + return [input_tensor[a] for a in new_axes[ndims]] + + +def skip_if(condition): + """Skips the decorated function if condition is or evaluates to True. + + Args: + condition: Either an expression that can be used in "if not condition" + statement, or a callable whose result should be a boolean. + + Returns: + The wrapped function + """ + + def real_skip_if(fn): + + def wrapper(*args, **kwargs): + if callable(condition): + skip = condition() + else: + skip = condition + if not skip: + return fn(*args, **kwargs) + + return wrapper + + return real_skip_if + + +@contextlib.contextmanager +def skip_if_error(test_obj, error_type, messages=None): + """Context manager to skip cases not considered failures by the tests. + + Note that this does not work if used in setUpClass/tearDownClass. + Usage in setUp/tearDown works fine just like regular test methods. + + Args: + test_obj: A test object provided as `self` in the test methods; this object + is usually an instance of `unittest.TestCase`'s subclass and should have + `skipTest` method. + error_type: The error type to skip. Note that if `messages` are given, both + `error_type` and `messages` need to match for the test to be skipped. + messages: Optional, a string or list of strings. If `None`, the test will be + skipped if `error_type` matches what is raised; otherwise, the test is + skipped if any of the `messages` is contained in the message of the error + raised, and `error_type` matches the error raised. + + Yields: + Nothing. + """ + if messages: + messages = nest.flatten(messages) + try: + yield + except error_type as e: + if not messages or any(message in str(e) for message in messages): + test_obj.skipTest("Skipping error: {}: {}".format(type(e), str(e))) + else: + raise + + +def enable_c_shapes(fn): + """No-op. TODO(b/74620627): Remove this.""" + return fn + + +def with_c_shapes(cls): + """No-op. TODO(b/74620627): Remove this.""" + return cls + + +def enable_control_flow_v2(fn): + """Decorator for enabling CondV2 and WhileV2 on a test. + + Note this enables using CondV2 and WhileV2 after running the test class's + setup/teardown methods. + + In addition to this, callers must import the while_v2 module in order to set + the _while_v2 module in control_flow_ops. + + Args: + fn: the function to be wrapped + + Returns: + The wrapped function + """ + + def wrapper(*args, **kwargs): + enable_control_flow_v2_old = control_flow_util.ENABLE_CONTROL_FLOW_V2 + control_flow_util.ENABLE_CONTROL_FLOW_V2 = True + try: + return fn(*args, **kwargs) + finally: + control_flow_util.ENABLE_CONTROL_FLOW_V2 = enable_control_flow_v2_old + + return wrapper + + +def with_control_flow_v2(cls): + """Adds methods that call original methods with WhileV2 and CondV2 enabled. + + Note this enables CondV2 and WhileV2 in new methods after running the test + class's setup method. + + In addition to this, callers must import the while_v2 module in order to set + the _while_v2 module in control_flow_ops. + + If a test function has _disable_control_flow_v2 attr set to True (using the + @disable_control_flow_v2 decorator), the v2 function is not generated for it. + + Example: + + @test_util.with_control_flow_v2 + class ControlFlowTest(test.TestCase): + + def testEnabledForV2(self): + ... + + @test_util.disable_control_flow_v2("b/xyzabc") + def testDisabledForV2(self): + ... + + Generated class: + class ControlFlowTest(test.TestCase): + + def testEnabledForV2(self): + ... + + def testEnabledForV2WithControlFlowV2(self): + // Enable V2 flags. + testEnabledForV2(self) + // Restore V2 flags. + + def testDisabledForV2(self): + ... + + Args: + cls: class to decorate + + Returns: + cls with new test methods added + """ + if control_flow_util.ENABLE_CONTROL_FLOW_V2: + return cls + + for name, value in cls.__dict__.copy().items(): + if (callable(value) and + name.startswith(unittest.TestLoader.testMethodPrefix) and + not getattr(value, "_disable_control_flow_v2", False)): + setattr(cls, name + "WithControlFlowV2", enable_control_flow_v2(value)) + return cls + + +def disable_control_flow_v2(unused_msg): + """Decorator for a function in a with_control_flow_v2 enabled test class. + + Blocks the function from being run with v2 control flow ops. + + Args: + unused_msg: Reason for disabling. + + Returns: + The wrapped function with _disable_control_flow_v2 attr set to True. + """ + + def wrapper(func): + func._disable_control_flow_v2 = True + return func + + return wrapper + + +def enable_output_all_intermediates(fn): + """Force-enable outputing all intermediates from functional control flow ops. + + Args: + fn: the function to be wrapped + + Returns: + The wrapped function + """ + + def wrapper(*args, **kwargs): + output_all_intermediates_old = \ + control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE + control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = True + try: + return fn(*args, **kwargs) + finally: + control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = \ + output_all_intermediates_old + + return wrapper + + +def assert_no_new_pyobjects_executing_eagerly(func=None, warmup_iters=2): + """Decorator for asserting that no new Python objects persist after a test. + + Runs the test multiple times executing eagerly, first as a warmup and then to + let objects accumulate. The warmup helps ignore caches which do not grow as + the test is run repeatedly. + + Useful for checking that there are no missing Py_DECREFs in the C exercised by + a bit of Python. + + Args: + func: The function to test. + warmup_iters: The numer of warmup iterations, excluded from measuring. + + Returns: + The wrapped function performing the test. + """ + + def wrap_f(f): + def decorator(self, *args, **kwargs): + """Warms up, gets object counts, runs the test, checks for new objects.""" + with context.eager_mode(): + gc.disable() + # Python 3.11 removed "errors" and "skipped" as members of + # unittest.case._Outcome so get them from the test result object + # instead. + test_errors = None + test_skipped = None + if hasattr(self._outcome, "errors"): + test_errors = self._outcome.errors + test_skipped = self._outcome.skipped + else: + test_errors = self._outcome.result.errors + test_skipped = self._outcome.result.skipped + # Run the test 2 times as warmup, in an attempt to fill up caches, which + # should not grow as the test is run repeatedly below. + # + # TODO(b/117156879): Running warmup twice is black magic; we have seen + # tests that fail with 1 warmup run, and pass with 2, on various + # versions of python2.7.x. + for _ in range(warmup_iters): + f(self, *args, **kwargs) + # Since we aren't in the normal test lifecycle, we need to manually run + # cleanups to clear out their object references. + self.doCleanups() + + # Some objects are newly created by _get_object_count_by_type(). So + # create and save as a dummy variable to include it as a baseline. + obj_count_by_type = _get_object_count_by_type() + gc.collect() + + # Make sure any registered functions are cleaned up in the C++ runtime. + registered_function_names = context.context().list_function_names() + + # unittest.doCleanups adds to self._outcome with each unwound call. + # These objects are retained across gc collections so we exclude them + # from the object count calculation. + obj_count_by_type = _get_object_count_by_type( + exclude=gc.get_referents(test_errors, test_skipped)) + + if ops.has_default_graph(): + collection_sizes_before = { + collection: len(ops.get_collection(collection)) + for collection in ops.get_default_graph().collections + } + for _ in range(3): + f(self, *args, **kwargs) + # Since we aren't in the normal test lifecycle, we need to manually run + # cleanups to clear out their object references. + self.doCleanups() + # Note that gc.get_objects misses anything that isn't subject to garbage + # collection (C types). Collections are a common source of leaks, so we + # test for collection sizes explicitly. + if ops.has_default_graph(): + for collection_key in ops.get_default_graph().collections: + collection = ops.get_collection(collection_key) + size_before = collection_sizes_before.get(collection_key, 0) + if len(collection) > size_before: + raise AssertionError( + ("Collection %s increased in size from " + "%d to %d (current items %s).") % + (collection_key, size_before, len(collection), collection)) + # Make sure our collection checks don't show up as leaked memory by + # removing references to temporary variables. + del collection + del collection_key + del size_before + del collection_sizes_before + gc.collect() + + # There should be no new Python objects hanging around. + obj_count_by_type = ( + _get_object_count_by_type( + exclude=gc.get_referents(test_errors, test_skipped)) - + obj_count_by_type) + + # There should be no newly registered functions hanging around. + leftover_functions = ( + context.context().list_function_names() - registered_function_names) + assert not leftover_functions, ( + "The following functions were newly created: %s" % + leftover_functions) + + # In some cases (specifically on MacOS), new_count is somehow + # smaller than previous_count. + # Using plain assert because not all classes using this decorator + # have assertLessEqual + assert not obj_count_by_type, ( + "The following objects were newly created: %s" % + str(obj_count_by_type)) + gc.enable() + return decorator + + if func is None: + return wrap_f + else: + return wrap_f(func) + + +def assert_no_new_tensors(f): + """Decorator for asserting that no new Tensors persist after a test. + + Mainly useful for checking that code using the Python C API has correctly + manipulated reference counts. + + Clears the caches that it knows about, runs the garbage collector, then checks + that there are no Tensor or Tensor-like objects still around. This includes + Tensors to which something still has a reference (e.g. from missing + Py_DECREFs) and uncollectable cycles (i.e. Python reference cycles where one + of the objects has __del__ defined). + + Args: + f: The test case to run. + + Returns: + The decorated test case. + """ + + def decorator(self, **kwargs): + """Finds existing Tensors, runs the test, checks for new Tensors.""" + + def _is_tensorflow_object(obj): + try: + return isinstance(obj, + (tensor_lib.Tensor, variables.Variable, + tensor_shape.Dimension, tensor_shape.TensorShape)) + except (ReferenceError, AttributeError): + # If the object no longer exists, we don't care about it. + return False + + tensors_before = set( + id(obj) for obj in gc.get_objects() if _is_tensorflow_object(obj)) + outside_executed_eagerly = context.executing_eagerly() + # Run the test in a new graph so that collections get cleared when it's + # done, but inherit the graph key so optimizers behave. + outside_graph_key = ops.get_default_graph()._graph_key + with ops.Graph().as_default(): + ops.get_default_graph()._graph_key = outside_graph_key + if outside_executed_eagerly: + with context.eager_mode(): + result = f(self, **kwargs) + else: + result = f(self, **kwargs) + # Make an effort to clear caches, which would otherwise look like leaked + # Tensors. + context.context()._clear_caches() # pylint: disable=protected-access + gc.collect() + tensors_after = [ + obj for obj in gc.get_objects() + if _is_tensorflow_object(obj) and id(obj) not in tensors_before + ] + if tensors_after: + raise AssertionError(("%d Tensors not deallocated after test: %s" % ( + len(tensors_after), + str(tensors_after), + ))) + return result + + return decorator + + +def _find_reference_cycle(objects, idx): + + def get_ignore_reason(obj, denylist): + """Tests whether an object should be omitted from the dependency graph.""" + if len(denylist) > 100: + return "" + if tf_inspect.isframe(obj): + if "test_util.py" in tf_inspect.getframeinfo(obj)[0]: + return "" + for b in denylist: + if b is obj: + return "" + if obj is denylist: + return "" + return None + + # Note: this function is meant to help with diagnostics. Its output is purely + # a human-readable representation, so you may freely modify it to suit your + # needs. + def describe(obj, denylist, leaves_only=False): + """Returns a custom human-readable summary of obj. + + Args: + obj: the value to describe. + denylist: same as denylist in get_ignore_reason. + leaves_only: boolean flag used when calling describe recursively. Useful + for summarizing collections. + """ + if get_ignore_reason(obj, denylist): + return "{}{}".format(get_ignore_reason(obj, denylist), type(obj)) + if tf_inspect.isframe(obj): + return "frame: {}".format(tf_inspect.getframeinfo(obj)) + elif tf_inspect.ismodule(obj): + return "module: {}".format(obj.__name__) + else: + if leaves_only: + return "{}, {}".format(type(obj), id(obj)) + elif isinstance(obj, list): + return "list({}): {}".format( + id(obj), [describe(e, denylist, leaves_only=True) for e in obj]) + elif isinstance(obj, tuple): + return "tuple({}): {}".format( + id(obj), [describe(e, denylist, leaves_only=True) for e in obj]) + elif isinstance(obj, dict): + return "dict({}): {} keys".format(id(obj), len(obj.keys())) + elif tf_inspect.isfunction(obj): + return "function({}) {}; globals ID: {}".format( + id(obj), obj.__name__, id(obj.__globals__)) + else: + return "{}, {}".format(type(obj), id(obj)) + + def build_ref_graph(obj, graph, reprs, denylist): + """Builds a reference graph as -> . + + Args: + obj: The object to start from. The graph will be built by recursively + adding its referrers. + graph: Dict holding the graph to be built. To avoid creating extra + references, the graph holds object IDs rather than actual objects. + reprs: Auxiliary structure that maps object IDs to their human-readable + description. + denylist: List of objects to ignore. + """ + referrers = gc.get_referrers(obj) + denylist = denylist + (referrers,) + + obj_id = id(obj) + for r in referrers: + if get_ignore_reason(r, denylist) is None: + r_id = id(r) + if r_id not in graph: + graph[r_id] = [] + if obj_id not in graph[r_id]: + graph[r_id].append(obj_id) + build_ref_graph(r, graph, reprs, denylist) + reprs[r_id] = describe(r, denylist) + + def find_cycle(el, graph, reprs, path): + """Finds and prints a single cycle in the dependency graph.""" + if el not in graph: + return + for r in graph[el]: + if r in path: + logging.error("Reference cycle sample:") + for p in path + (r,): + logging.error(reprs.get(p, "unknown object " + str(p))) + return True + else: + if find_cycle(r, graph, reprs, path + (r,)): + return True + return False + + obj = objects[idx] + graph = {} # referrer ID -> object ID + reprs = {} # object ID -> description + build_ref_graph(obj, graph, reprs, (objects, graph, reprs, get_ignore_reason, + describe, build_ref_graph, find_cycle)) + for k in graph: + if find_cycle(k, graph, reprs, ()): + return True + return False + + +def assert_no_garbage_created(f): + """Test method decorator to assert that no garbage has been created. + + Note that this decorator sets DEBUG_SAVEALL, which in some Python interpreters + cannot be un-set (i.e. will disable garbage collection for any other unit + tests in the same file/shard). + + Args: + f: The function to decorate. + + Returns: + The decorated function. + """ + + # FIXME(power) -- Update documentation, we no longer care if garbage is + # created, we only want to verify we don't have memory leaks. + def decorator(self, **kwargs): + """Sets DEBUG_SAVEALL, runs the test, and checks for new garbage.""" + gc.disable() + previous_debug_flags = gc.get_debug() + gc.set_debug(gc.DEBUG_UNCOLLECTABLE) + gc.collect() + previous_garbage = len(gc.garbage) + result = f(self, **kwargs) + gc.collect() + new_garbage = len(gc.garbage) + if new_garbage > previous_garbage: + + for i, obj in enumerate(gc.garbage[previous_garbage:]): + # Known false positive for ast.fix_missing_locations. + if getattr(obj, "__module__", "") == "ast": + new_garbage -= 3 + + if new_garbage > previous_garbage: + logging.error( + "The decorated test created work for Python's garbage collector, " + "likely due to a reference cycle. New objects in cycle(s):") + for i, obj in enumerate(gc.garbage[previous_garbage:]): + try: + logging.error("Object %d of %d", i, + len(gc.garbage) - previous_garbage) + + def _safe_object_str(obj): + return "<%s %d>" % (obj.__class__.__name__, id(obj)) + + logging.error(" Object type: %s", _safe_object_str(obj)) + logging.error( + " Referrer types: %s", ", ".join( + [_safe_object_str(ref) for ref in gc.get_referrers(obj)])) + logging.error( + " Referent types: %s", ", ".join( + [_safe_object_str(ref) for ref in gc.get_referents(obj)])) + logging.error(" Object attribute names: %s", dir(obj)) + logging.error(" Object __str__:") + logging.error(obj) + logging.error(" Object __repr__:") + logging.error(repr(obj)) + except Exception: # pylint: disable=broad-except + logging.error("(Exception while printing object)") + + # When garbage is created, this call can help identify reference cycles, + # which are typically the cause of such garbage. + if new_garbage > previous_garbage: + for i in range(previous_garbage, new_garbage): + if _find_reference_cycle(gc.garbage, i): + break + + # This will fail if any garbage has been created, typically because of a + # reference cycle. + self.assertEqual(previous_garbage, new_garbage) + # TODO(allenl): Figure out why this debug flag reset doesn't work. It would + # be nice to be able to decorate arbitrary tests in a large test suite and + # not hold on to every object in other tests. + gc.set_debug(previous_debug_flags) + gc.enable() + return result + + return decorator + + +def _combine_named_parameters(**kwargs): + """Generate combinations based on its keyword arguments. + + Two sets of returned combinations can be concatenated using +. Their product + can be computed using `times()`. + + Args: + **kwargs: keyword arguments of form `option=[possibilities, ...]` or + `option=the_only_possibility`. + + Returns: + a list of dictionaries for each combination. Keys in the dictionaries are + the keyword argument names. Each key has one value - one of the + corresponding keyword argument values. + """ + sort_by_key = lambda k: k[0] + combinations = [] + for key, values in sorted(kwargs.items(), key=sort_by_key): + if not isinstance(values, list): + values = [values] + combinations.append([(key, value) for value in values]) + + return [OrderedDict(result) for result in itertools.product(*combinations)] + + +def generate_combinations_with_testcase_name(**kwargs): + """Generate combinations based on its keyword arguments using combine(). + + This function calls combine() and appends a testcase name to the list of + dictionaries returned. The 'testcase_name' key is a required for named + parameterized tests. + + Args: + **kwargs: keyword arguments of form `option=[possibilities, ...]` or + `option=the_only_possibility`. + + Returns: + a list of dictionaries for each combination. Keys in the dictionaries are + the keyword argument names. Each key has one value - one of the + corresponding keyword argument values. + """ + combinations = _combine_named_parameters(**kwargs) + named_combinations = [] + for combination in combinations: + assert isinstance(combination, OrderedDict) + name = "".join([ + "_{}_{}".format("".join(filter(str.isalnum, key)), + "".join(filter(str.isalnum, str(value)))) + for key, value in combination.items() + ]) + named_combinations.append( + OrderedDict( + list(combination.items()) + + [("testcase_name", "_test{}".format(name))])) + + return named_combinations + + +def run_all_in_graph_and_eager_modes(cls): + """Execute all test methods in the given class with and without eager.""" + base_decorator = run_in_graph_and_eager_modes + for name in dir(cls): + if (not name.startswith(unittest.TestLoader.testMethodPrefix) or + name.startswith("testSkipEager") or + name.startswith("test_skip_eager") or + name == "test_session" or + name == "test_scope"): + continue + value = getattr(cls, name, None) + if callable(value): + setattr(cls, name, base_decorator(value)) + return cls + + +def run_class_in_v1_v2(cls): + """Execute all test methods in a given class in v1 and v2 modes.""" + base_decorator = run_in_v1_v2 + for name in dir(cls): + if (not name.startswith(unittest.TestLoader.testMethodPrefix) or + name.startswith("testSkipEager") or + name.startswith("test_skip_eager") or + name == "test_session" or + name == "test_scope"): + continue + + attr = getattr(cls, name, None) + if not callable(attr): + continue + + setattr(cls, name, base_decorator(attr)) + return cls + + +def enable_nested_function_shape_inference(fn): + """Decorator for enabling nested_function_shape_inference on a test. + + This function returns a decorator intended to be applied to test methods in + a `tf.test.TestCase` class. Doing so will set nested_function_shape_inference, + reset the context, execute the test, then reset the context to the state + it was in prior to this test. + + Example: + + class MyTest(test.TestCase): + + @enable_nested_function_shape_inference + def testFoo(self): + ... + + Args: + fn: the function to be wrapped. + + Returns: + The wrapped function. + """ + + def wrapper(*args, **kwargs): + # If `nested_function_shape_inference` is already enabled do nothing. + if flags.config().enable_nested_function_shape_inference.value(): + return fn(*args, **kwargs) + + flags.config().enable_nested_function_shape_inference.reset(True) + try: + return fn(*args, **kwargs) + finally: + flags.config().enable_nested_function_shape_inference.reset(False) + + return wrapper + + +def enable_quantized_dtypes_training(fn): + """Decorator for enabling quantized_dtypes_training on a test. + + This function returns a decorator intended to be applied to test methods in + a `tf.test.TestCase` class. Doing so will set quantized_dtypes_training, + reset the context, execute the test, then reset the context to the state + it was in prior to this test. + + Example: + + class MyTest(test.TestCase): + + @enable_quantized_dtypes_training + def testFoo(self): + ... + + Args: + fn: the function to be wrapped. + + Returns: + The wrapped function. + """ + + def wrapper(*args, **kwargs): + # If `enable_quantized_dtypes_training` is already enabled do nothing. + if flags.config().enable_quantized_dtypes_training.value(): + return fn(*args, **kwargs) + + flags.config().enable_quantized_dtypes_training.reset(True) + try: + return fn(*args, **kwargs) + finally: + flags.config().enable_quantized_dtypes_training.reset(False) + + return wrapper + + +def enable_eager_op_as_function(fn): + """Returns the same fn. This will be removed once all usages are removed. + + Args: + fn: the function to be wrapped. + + Returns: + The wrapped function. + """ + + def wrapper(*args, **kwargs): + return fn(*args, **kwargs) + + return wrapper + + +@tf_export("test.with_eager_op_as_function") +def with_eager_op_as_function(cls=None, only_as_function=False): # pylint: disable=unused-argument + """Returns the same class. This will be removed once all usages are removed. + + Args: + cls: class to decorate. + only_as_function: unused argument. + + Returns: + cls + """ + + def decorator(cls): + return cls + + if cls is not None: + return decorator(cls) + + return decorator + + +def enable_graph_building_optimization(fn): + """Decorator for enabling graph_building_optimization on a test. + + This function returns a decorator intended to be applied to test methods in + a `tf.test.TestCase` class. Doing so will enable graph_building_optimization, + execute the test, then reset the feature flag to its default value. + + Example: + + class MyTest(test.TestCase): + + @enable_graph_building_optimization + def testFoo(self): + ... + + Args: + fn: the function to be wrapped. + + Returns: + The wrapped function. + """ + + def wrapper(*args, **kwargs): + # If `graph_building_optimization` is already enabled do nothing. + if flags.config().graph_building_optimization.value(): + return fn(*args, **kwargs) + + flags.config().graph_building_optimization.reset(True) + try: + return fn(*args, **kwargs) + finally: + flags.config().graph_building_optimization.reset(False) + + return wrapper + + +def add_graph_building_optimization_tests(cls=None): + """Adds methods with graph_building_optimization enabled to the test suite. + + Example: + + @test_util.add_graph_building_optimization_tests + class FooTest(test.TestCase): + + def testBar(self): + ... + + Generated class: + class FooTest(test.TestCase): + + def testBar(self): + ... + + def testBarWithGraphBuildingOptimization(self): + // Enable graph_building_optimization + testBar(self) + // Disable graph_building_optimization + + Args: + cls: class to decorate. + + Returns: + cls with new test methods added. + """ + + def decorator(cls): + if flags.config().graph_building_optimization.value(): + return cls + + for name, value in cls.__dict__.copy().items(): + if (callable(value) and + (name.startswith(unittest.TestLoader.testMethodPrefix) or + name.startswith("benchmark"))): + setattr(cls, name + "WithGraphBuildingOptimization", + enable_graph_building_optimization(value)) + return cls + + if cls is not None: + return decorator(cls) + + return decorator + + +def disable_eager_op_as_function(unused_msg): + """Decorator for a function in a with_eager_op_as_function enabled test class. + + Blocks the function from being run with eager_op_as_function enabled. + + Args: + unused_msg: Reason for disabling. + + Returns: + The wrapped function with _disable_eager_op_as_function attr set to True. + """ + return _disable_test(execute_func=False) + + +def set_xla_env_flag(func=None, flag=""): + """Decorator for setting XLA_FLAGS prior to running a test. + + This function returns a decorator intended to be applied to test methods in + a `tf.test.TestCase` class. Doing so will allow users to set any xla flags + exposed via the XLA_FLAGS environment variable, execute the test, then reset + the XLA_FLAGS to the state it was in prior to this test. + + Example: + + class MyTest(test.TestCase): + + @set_xla_env_flag(flag='--xla_gpu_enable_fast_min_max=false') + def testFoo(self): + ... + + Args: + func: The function to be wrapped. + flag: The xla flag to be set in the XLA_FLAGS env variable. + + Returns: + The wrapped function. + """ + + def decorator(f): + + @functools.wraps(f) + def decorated(*args, **kwargs): + original_xla_flags = os.environ.get("XLA_FLAGS") + new_xla_flags = flag + if original_xla_flags: + new_xla_flags = new_xla_flags + " " + original_xla_flags + os.environ["XLA_FLAGS"] = new_xla_flags + try: + return f(*args, **kwargs) + finally: + if original_xla_flags is None: + del os.environ["XLA_FLAGS"] + else: + os.environ["XLA_FLAGS"] = original_xla_flags + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + +def build_as_function_and_v1_graph(func=None): + """Run a test case in v1 graph mode and inside tf.function in eager mode. + + WARNING: This decorator can only be used in test cases that statically checks + generated graph. Attempting to evaluate graph or function results via. + session.run() or self.evaluate() will fail. + + WARNING: This decorator can only be used for test cases that inherit from + absl.testing.parameterized.TestCase. + + Args: + func: Test case function to be decorated. + + Returns: + Decorated test case function. + """ + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError( + "`run_in_graph_mode_and_function` only supports test methods.") + + @parameterized.named_parameters(("_v1_graph", "v1_graph"), + ("_function", "function")) + @functools.wraps(f) + def decorated(self, run_mode, *args, **kwargs): + if run_mode == "v1_graph": + with ops.Graph().as_default(): + f(self, *args, **kwargs) + elif run_mode == "function": + + @def_function.function + def function_in_eager(): + f(self, *args, **kwargs) + + # Create a new graph for the eagerly executed version of this test for + # better isolation. + graph_for_eager_test = ops.Graph() + with graph_for_eager_test.as_default(), context.eager_mode(): + function_in_eager() + ops.dismantle_graph(graph_for_eager_test) + else: + raise ValueError("Unknown run mode %s" % run_mode) + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + +def run_in_async_and_sync_mode(f): + """Execute the test in async mode and sync mode.""" + + @parameterized.named_parameters([("Async", True), ("", False)]) + @functools.wraps(f) + def decorator(self, async_mode, *args, **kwargs): + if async_mode: + with context.execution_mode(context.ASYNC): + f(self, *args, **kwargs) + else: + with context.execution_mode(context.SYNC): + f(self, *args, **kwargs) + return decorator + + +def run_in_graph_and_eager_modes(func=None, + config=None, + use_gpu=True, + assert_no_eager_garbage=False): + """Execute the decorated test with and without enabling eager execution. + + This function returns a decorator intended to be applied to test methods in + a `tf.test.TestCase` class. Doing so will cause the contents of the test + method to be executed twice - once normally, and once with eager execution + enabled. This allows unittests to confirm the equivalence between eager + and graph execution (see `tf.compat.v1.enable_eager_execution`). + + For example, consider the following unittest: + + ```python + class MyTests(tf.test.TestCase): + + @run_in_graph_and_eager_modes + def test_foo(self): + x = tf.constant([1, 2]) + y = tf.constant([3, 4]) + z = tf.add(x, y) + self.assertAllEqual([4, 6], self.evaluate(z)) + + if __name__ == "__main__": + tf.test.main() + ``` + + This test validates that `tf.add()` has the same behavior when computed with + eager execution enabled as it does when constructing a TensorFlow graph and + executing the `z` tensor in a session. + + `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and + `run_in_graph_and_eager_modes` are available decorators for different + v1/v2/eager/graph combinations. + + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + config: An optional config_pb2.ConfigProto to use to configure the session + when executing graphs. + use_gpu: If True, attempt to run as many operations as possible on GPU. + assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage + collector and asserts that no extra garbage has been created when running + the test with eager execution enabled. This will fail if there are + reference cycles (e.g. a = []; a.append(a)). Off by default because some + tests may create garbage for legitimate reasons (e.g. they define a class + which inherits from `object`), and because DEBUG_SAVEALL is sticky in some + Python interpreters (meaning that tests which rely on objects being + collected elsewhere in the unit test file will not work). Additionally, + checks that nothing still has a reference to Tensors that the test + allocated. + + Returns: + Returns a decorator that will run the decorated test method twice: + once by constructing and executing a graph in a session and once with + eager execution enabled. + """ + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError( + "`run_in_graph_and_eager_modes` only supports test methods. " + "Did you mean to use `run_all_in_graph_and_eager_modes`?") + + def decorated(self, *args, **kwargs): + logging.info("Running %s in GRAPH mode.", f.__name__) + try: + with context.graph_mode(), self.subTest("graph_mode"): + # XLATestCase uses `session`, which also doesn't take any args, + # instead of `test_session` + for class_ in self.__class__.mro(): + if class_.__name__ == "XLATestCase": + session_func = self.session + session_kwargs = {} + break + else: + session_func = self.test_session + session_kwargs = dict(use_gpu=use_gpu, config=config) + with session_func(**session_kwargs): + f(self, *args, **kwargs) + except unittest.case.SkipTest: + pass + + def run_eagerly(self, **kwargs): + logging.info("Running %s in EAGER mode.", f.__name__) + if not use_gpu: + with ops.device("/device:CPU:0"): + f(self, *args, **kwargs) + else: + f(self, *args, **kwargs) + + if assert_no_eager_garbage: + ops.reset_default_graph() + run_eagerly = assert_no_new_tensors( + assert_no_garbage_created(run_eagerly)) + + # This decorator runs the wrapped test twice. + # Reset the test environment between runs. + self.tearDown() + self._tempdir = None + # Create a new graph for the eagerly executed version of this test for + # better isolation. + graph_for_eager_test = ops.Graph() + with ( + graph_for_eager_test.as_default(), + context.eager_mode(), + self.subTest("eager_mode"), + ): + self.setUp() + run_eagerly(self, **kwargs) + ops.dismantle_graph(graph_for_eager_test) + + return tf_decorator.make_decorator(f, decorated) + + if func is not None: + return decorator(func) + + return decorator + + +def run_in_v1_v2(func=None, + device_to_use: str = None, + assert_no_eager_garbage: bool = False): + """Execute the decorated test in v1 and v2 modes. + + The overall execution is similar to that of `run_in_graph_and_eager_mode`. + + Args: + func: A test function/method to be decorated. If `func` is None, this method + returns a decorator the can be applied to a function. Otherwise, an + already applied decorator is returned. + device_to_use: A string in the following format: "/device:CPU:0". + assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage + collector and asserts that no extra garbage has been created when running + the test with eager execution enabled. This will fail if there are + reference cycles (e.g. a = []; a.append(a)). Off by default because some + tests may create garbage for legitimate reasons (e.g. they define a class + which inherits from `object`), and because DEBUG_SAVEALL is sticky in some + Python interpreters (meaning that tests which rely on objects being + collected elsewhere in the unit test file will not work). Additionally, + checks that nothing still has a reference to Tensors that the test + allocated. + + Returns: + A decorator that runs a given test in v1 and v2 modes. + """ + + decorator_tag = "wrapped_with_v1_v2_decorator" + if hasattr(func, decorator_tag): + # Already decorated with this very same decorator + return func + + def decorator(f): + + def decorated(self, *args, **kwargs): + logging.info("Running %s in V1 mode.", f.__name__) + try: + with self.subTest("V1_mode"): + v2_compat.disable_v2_behavior() + f(self, *args, **kwargs) + except unittest.case.SkipTest: + pass + + def run_v2(self, **kwargs): + logging.info("Running %s in V2 mode.", f.__name__) + if device_to_use: + with ops.device(device_to_use): + f(self, *args, **kwargs) + else: + f(self, *args, **kwargs) + + if assert_no_eager_garbage: + ops.reset_default_graph() + run_v2 = assert_no_new_tensors( + assert_no_garbage_created(run_v2)) + + # This decorator runs the wrapped test twice. + # Reset the test environment between runs. + self.tearDown() + self._tempdir = None # pylint:disable=protected-access + + ops.reset_default_graph() + v2_compat.enable_v2_behavior() + with self.subTest("V2_mode"): + self.setUp() + run_v2(self, **kwargs) + + tf_decorated = tf_decorator.make_decorator(f, decorated) + tf_decorated.__dict__[decorator_tag] = True + return tf_decorated + + if func is not None: + return decorator(func) + + return decorator + + +def py_func_if_in_function(f): + + def decorated(*args, **kwds): + if not ops.inside_function(): + return f(*args, **kwds) + + tensor_args = [] + tensor_indices = [] + for i, arg in enumerate(args): + if isinstance(arg, (tensor_lib.Tensor, variables.Variable)): + tensor_args.append(arg) + tensor_indices.append(i) + + def inner_f(*inner_tensor_args): + my_args = list(args) + for i, n in zip(tensor_indices, inner_tensor_args): + my_args[i] = n + return f(*my_args, **kwds) + + return script_ops.py_func(inner_f, tensor_args, []) + + return tf_decorator.make_decorator(f, decorated) + + +def also_run_as_tf_function(f): + """Runs the decorated test twice--once as is, once inside a tf.function. + + This allows you to run a test both in eager execution and inside a + tf.function, exercising the two execution modes supported in tf 2.0. The test + assertions are automatically done inside tf.py_funcs, and tf.function ensures + that they run in the proper order and with the proper side effects. + + Currently variable creation is not supported in tests annotated with this + decorator since it's tricky to ensure the variable doesn't get repeatedly + created when retracing the tf.function. + + Args: + f: the test method to be decorated + + Returns: + The decorated test method, which will run both in eager and inside a + tf.function. + """ + + def decorated(*args, **kwds): + + def bound_f(): + f(*args, **kwds) + + with context.eager_mode(): + # Running in eager mode + bound_f() + # Running as TF function + # TODO(b/121143941): Remove the autograph override. + def_function.function(bound_f, autograph=False)() + + return decorated + + +def deprecated_graph_mode_only(func=None): + """Execute the decorated test in graph mode. + + This function returns a decorator intended to be applied to tests that are not + compatible with eager mode. When this decorator is applied, the test body will + be run in an environment where API calls construct graphs instead of executing + eagerly. + + `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and + `run_in_graph_and_eager_modes` are available decorators for different + v1/v2/eager/graph combinations. + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + + Returns: + Returns a decorator that will run the decorated test method in graph mode. + """ + + def decorator(f): + if tf_inspect.isclass(f): + setup = f.__dict__.get("setUp") + if setup is not None: + setattr(f, "setUp", decorator(setup)) + + for name, value in f.__dict__.copy().items(): + if (callable(value) and + name.startswith(unittest.TestLoader.testMethodPrefix)): + setattr(f, name, decorator(value)) + + return f + + def decorated(self, *args, **kwargs): + if context.executing_eagerly(): + with context.graph_mode(): + return f(self, *args, **kwargs) + else: + return f(self, *args, **kwargs) + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + +run_deprecated_v1 = deprecated_graph_mode_only + + +def run_all_in_deprecated_graph_mode_only(cls): + """Execute all tests in a class in graph mode.""" + base_decorator = deprecated_graph_mode_only + for name in dir(cls): + if (not name.startswith(unittest.TestLoader.testMethodPrefix) or + name == "test_session"): + continue + value = getattr(cls, name, None) + if callable(value): + setattr(cls, name, base_decorator(value)) + return cls + + +def _run_vn_only(func=None, v2=True, reason=None): + """Execute the decorated test only if running in the specified mode. + + This function is intended to be applied to tests that exercise functionality + that belongs to either only v2, or v1. + If the test is run in the mode opposite of the specified one, it will simply + be skipped. + + It shouldn't be used directly, instead, use the `run_v1_only` or + `run_v2_only` wrappers that call it. + + `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and + `run_in_graph_and_eager_modes` are available decorators for different + v1/v2/eager/graph combinations. + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + v2: a boolean value indicating whether the test should be skipped in v2, + or v1. + reason: string giving a reason for limiting the test to a particular mode. + + Returns: + A decorator that will skip the test method in the specified version. + """ + if not reason: + reason = f"Test is only compatible with {'v2 ' if v2 else 'v1'}" + + def decorator(f): + if tf_inspect.isclass(f): + # To skip an entire test suite class, we only decorate the setUp method + # to skip all tests. There are cases when setUp is not defined (not + # overridden in subclasses of TestCase, so not available in f.__dict__ + # below). For those cases, we walk the method resolution order list and + # pick the first setUp method we find (usually this should be the one in + # the parent class since that's the TestCase class). + for cls in type.mro(f): + setup = cls.__dict__.get("setUp") + if setup is not None: + setattr(f, "setUp", decorator(setup)) + break + + return f + else: + # If f is just a function, just create a decorator for it and return it + def decorated(self, *args, **kwargs): + tf2_enabled = tf2.enabled() + # Skip if TF is in v2 mode, but the test is expected to only be run + # in v1, and vice versa + if (tf2_enabled and not v2) or (not tf2_enabled and v2): + self.skipTest(reason) + + return f(self, *args, **kwargs) + + return tf_decorator.make_decorator(f, decorated) + + if func is not None: + return decorator(func) + + return decorator + + +def run_v1_only(reason=None, func=None): + """Only execute the test if Tensorflow is in v1 mode.""" + return _run_vn_only(func=func, v2=False, reason=reason) + + +def run_v2_only(func=None, reason=None): + """Only execute the test if Tensorflow is in v2 mode.""" + return _run_vn_only(func=func, v2=True, reason=reason) + + +def run_gpu_only(func=None): + """Execute the decorated test only if a GPU is available. + + This function is intended to be applied to tests that require the presence + of a GPU. If a GPU is absent, it will simply be skipped. + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + + Returns: + Returns a decorator that will conditionally skip the decorated test method. + """ + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError("`run_gpu_only` only supports test methods.") + + def decorated(self, *args, **kwargs): + if not is_gpu_available(): + self.skipTest("Test requires GPU") + + return f(self, *args, **kwargs) + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + +def run_cuda_only(func=None): + """Execute the decorated test only if a GPU is available. + + This function is intended to be applied to tests that require the presence + of a CUDA GPU. If a CUDA GPU is absent, it will simply be skipped. + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + + Returns: + Returns a decorator that will conditionally skip the decorated test method. + """ + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError("`run_cuda_only` only supports test methods.") + + def decorated(self, *args, **kwargs): + if not is_gpu_available(cuda_only=True): + self.skipTest("Test requires CUDA GPU") + + return f(self, *args, **kwargs) + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + +def run_gpu_or_tpu(func=None): + """Execute the decorated test only if a physical GPU or TPU is available. + + This function is intended to be applied to tests that require the presence + of a physical GPU or TPU. It complies with the following rules: + - If a GPU is available, the test will run on the GPU. + - If a GPU is absent and a TPU is available, the test will run on the TPU. + - If both GPU and TPU are absent, the test will be skipped. + + Args: + func: function to be annotated. If `func` is None, this method returns a + decorator the can be applied to a function. If `func` is not None this + returns the decorator applied to `func`. + + Returns: + Returns a decorator that will conditionally skip the decorated test method. + """ + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError("`run_gpu_or_tpu` only supports test methods.") + + def decorated(self, *args, **kwargs): + if config.list_physical_devices("GPU"): + return f(self, "GPU", *args, **kwargs) + + if config.list_physical_devices("TPU"): + return f(self, "TPU", *args, **kwargs) + + self.skipTest("Test requires GPU or TPU") + + return decorated + + return decorator if func is None else decorator(func) + + +def with_forward_compatibility_horizons(*horizons): + """Executes the decorated test with the specified forward-compat horizons. + + Args: + *horizons: A list of (year, month, day) tuples. If the list includes + `None`, then the test will also be run with no forward-compatibility + horizon set. + + Returns: + A decorator that will execute the test with the specified horizons. + """ + if not horizons: + raise ValueError("Expected at least one horizon.") + for horizon in horizons: + if not ((horizon is None) or + (len(horizon) == 3 and all(isinstance(x, int) for x in horizon))): + raise ValueError("Bad horizon value: %r" % horizon) + + def decorator(f): + if tf_inspect.isclass(f): + raise ValueError("`with_forward_compatibility_horizons` only " + "supports test methods.") + def decorated(self, *args, **kwargs): + for horizon in horizons: + if horizon is None: + f(self, *args, **kwargs) + else: + (year, month, day) = horizon + with forward_compatibility_horizon(year, month, day): + f(self, *args, **kwargs) + return decorated + + return decorator + + +@deprecation.deprecated(None, + "Use `tf.config.list_physical_devices('GPU')` instead.") +@tf_export("test.is_gpu_available") +def is_gpu_available(cuda_only=False, min_cuda_compute_capability=None): + """Returns whether TensorFlow can access a GPU. + + Warning: if a non-GPU version of the package is installed, the function would + also return False. Use `tf.test.is_built_with_cuda` to validate if TensorFlow + was build with CUDA support. + + For example, + >>> gpu_available = tf.test.is_gpu_available() + >>> is_cuda_gpu_available = tf.test.is_gpu_available(cuda_only=True) + >>> is_cuda_gpu_min_3 = tf.test.is_gpu_available(True, (3,0)) + + Args: + cuda_only: limit the search to CUDA GPUs. + min_cuda_compute_capability: a (major,minor) pair that indicates the minimum + CUDA compute capability required, or None if no requirement. + + Note that the keyword arg name "cuda_only" is misleading (since routine will + return true when a GPU device is available irrespective of whether TF was + built with CUDA support or ROCm support. However no changes here because + + ++ Changing the name "cuda_only" to something more generic would break + backward compatibility + + ++ Adding an equivalent "rocm_only" would require the implementation check + the build type. This in turn would require doing the same for CUDA and thus + potentially break backward compatibility + + ++ Adding a new "cuda_or_rocm_only" would not break backward compatibility, + but would require most (if not all) callers to update the call to use + "cuda_or_rocm_only" instead of "cuda_only" + + Returns: + True if a GPU device of the requested kind is available. + """ + + # This was needed earlier when we had support for SYCL in TensorFlow. + del cuda_only + + try: + for local_device in device_lib.list_local_devices(): + if local_device.device_type == "GPU": + gpu_info = gpu_util.compute_capability_from_device_desc(local_device) + cc = gpu_info.compute_capability or (0, 0) + if not min_cuda_compute_capability or cc >= min_cuda_compute_capability: + return True + return False + except errors_impl.NotFoundError as e: + if not all(x in str(e) for x in ["CUDA", "not find"]): + raise e + else: + logging.error(str(e)) + return False + + +@contextlib.contextmanager +def device(use_gpu): + """Uses gpu when requested and available.""" + if use_gpu and is_gpu_available(): + dev = "/device:GPU:0" + else: + dev = "/device:CPU:0" + with ops.device(dev): + yield + + +@contextlib.contextmanager +def use_gpu(): + """Uses gpu when requested and available.""" + with device(use_gpu=True): + yield + + +@contextlib.contextmanager +def force_gpu(): + """Force the gpu to be used.""" + with ops.device("/device:GPU:0"): + yield + + +@contextlib.contextmanager +def force_cpu(): + """Force the cpu to be used.""" + with ops.device("/device:CPU:0"): + yield + + +@contextlib.contextmanager +def deterministic_ops(): + """Enables deterministic ops.""" + try: + config.enable_op_determinism() + yield + finally: + config.disable_op_determinism() + + +class CapturedWrites: + """A utility class to load the captured writes made to a stream.""" + + def __init__(self, capture_location): + self.capture_location = capture_location + + def contents(self): + """Get the captured writes as a single string.""" + with open(self.capture_location) as tmp_file: + output_data = "".join(tmp_file.readlines()) + return output_data + + +class FakeEagerSession: + """Fake session so tests that conditionally use placeholders can use eager. + + There are a number of tests that conditionally use placeholders for shape + inference. The pattern is demonstrated here: + + ```python + with self.cached_session() as sess: + if static_shape: + y = math_ops.matmul(x, ...) + feed_dict = {} + else: + x_ph = array_ops.placeholder(...) + y = math_ops.matmul(x_ph, ...) + feed_dict = {x_ph: x} + val = sess.run(y, feed_dict=feed_dict) + ``` + + Since the feed_dict is empty when not using placeholders we should be able to + call self.evaluate(), however this requires rewriting the test case. + This class should be considered a stop-gap solution to get tests running with + eager with minimal changes to the actual test. + """ + + def __init__(self, test_case): + self._test_case = test_case + + def run(self, fetches, *args, **kwargs): + """Evaluate `fetches`. + + Fail if additional args are specified. + + Args: + fetches: A Tensor or a nested list/tuple of Tensors. + *args: Positional arguments + **kwargs: Keyword arguments + + Raises: + RuntimeError: If args or kwargs are specified. + + Returns: + Tensors as numpy values. + """ + feed_dict = kwargs.pop("feed_dict", {}) + if feed_dict: + raise RuntimeError( + "feed_dict is not supported when eager execution is enabled " + "(in this case, sess.run(t) is shorthand for t.numpy()") + + if args or kwargs: + raise RuntimeError( + "Optional args are not supported when eager execution is enabled " + "(in this case, sess.run(t) is shorthand for t.numpy()") + + return self._test_case.evaluate(fetches) + + +class ErrorLoggingSession(s.Session): + """Wrapper around a Session that logs errors in run().""" + + def run(self, *args, **kwargs): + try: + return super().run(*args, **kwargs) + except Exception as e: # pylint: disable=broad-except + # Note: disable the logging for OutOfRangeError, which makes the output + # of tf.data tests hard to read, because OutOfRangeError is used as the + # signal completion + if not isinstance(e, errors.OutOfRangeError): + logging.error(str(e)) + raise + + +def disable_cudnn_autotune(func): + """Disable autotuning during the call to this function. + + Some tests want to base assertions on a graph being isomorphic with a copy. + To ensure this, this decorator disables autotuning. + + Args: + func: Function to run with CuDNN autotuning turned off. + + Returns: + Decorated function. + """ + + def decorator(f): + + def decorated(self, *args, **kwargs): + original_tf_cudnn_use_autotune = os.environ.get("TF_CUDNN_USE_AUTOTUNE") + os.environ["TF_CUDNN_USE_AUTOTUNE"] = "false" + original_xla_flags = os.environ.get("XLA_FLAGS") + new_xla_flags = "--xla_gpu_autotune_level=0" + if original_xla_flags: + new_xla_flags = original_xla_flags + " " + new_xla_flags + os.environ["XLA_FLAGS"] = new_xla_flags + + result = f(self, *args, **kwargs) + + if (original_tf_cudnn_use_autotune is None): + del os.environ["TF_CUDNN_USE_AUTOTUNE"] + else: + os.environ["TF_CUDNN_USE_AUTOTUNE"] = original_tf_cudnn_use_autotune + if (original_xla_flags is None): + del os.environ["XLA_FLAGS"] + else: + os.environ["XLA_FLAGS"] = original_xla_flags + + return result + + return tf_decorator.make_decorator(func, decorated) + + if func is not None: + return decorator(func) + + return decorator + + +# The description is just for documentation purposes. +def enable_tf_xla_constant_folding(description): + + if not isinstance(description, str): + raise ValueError("'description' should be string, got {}".format( + type(description))) + + def enable_tf_xla_constant_folding_impl(func): + """Enable constant folding during the call to this function. + + Some tests fail without constant folding. + + Args: + func: Function to run with constant folding turned on. + + Returns: + Decorated function. + """ + + def decorator(f): + + def decorated(self, *args, **kwargs): + original_var = pywrap_tf_session.TF_GetXlaConstantFoldingDisabled() + pywrap_tf_session.TF_SetXlaConstantFoldingDisabled(False) + result = f(self, *args, **kwargs) + pywrap_tf_session.TF_SetXlaConstantFoldingDisabled(original_var) + return result + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + return enable_tf_xla_constant_folding_impl + + +# Updates test function by selectively disabling it. +def _disable_test(execute_func): + + def disable_test_impl(func): + + def decorator(func): + + def decorated(self, *args, **kwargs): + if execute_func: + return func(self, *args, **kwargs) + + return tf_decorator.make_decorator(func, decorated) + + if func is not None: + return decorator(func) + + return decorator + + return disable_test_impl + + +# The description is just for documentation purposes. +def disable_xla(description): # pylint: disable=unused-argument + """Execute the test method only if xla is not enabled.""" + execute_func = not is_xla_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def disable_mlir_bridge(description): # pylint: disable=unused-argument + """Execute the test method only if MLIR bridge is not enabled.""" + execute_func = not is_mlir_bridge_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def disable_asan(description): # pylint: disable=unused-argument + """Execute the test method only if ASAN is not enabled.""" + execute_func = not is_asan_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def disable_msan(description): # pylint: disable=unused-argument + """Execute the test method only if MSAN is not enabled.""" + execute_func = not is_msan_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def disable_tsan(description): # pylint: disable=unused-argument + """Execute the test method only if TSAN is not enabled.""" + execute_func = not is_tsan_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def disable_ubsan(description): # pylint: disable=unused-argument + """Execute the test method only if UBSAN is not enabled.""" + execute_func = not is_ubsan_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def disable_tfrt(unused_description): + + def disable_tfrt_impl(cls_or_func): + """Execute the test only if tfrt is not enabled.""" + + if tf_inspect.isclass(cls_or_func): + if tfrt_utils.enabled(): + return None + else: + return cls_or_func + else: + def decorator(func): + + def decorated(self, *args, **kwargs): + if tfrt_utils.enabled(): + return + else: + return func(self, *args, **kwargs) + + return decorated + + if cls_or_func is not None: + return decorator(cls_or_func) + + return decorator + + return disable_tfrt_impl + + +def for_all_test_methods(decorator, *args, **kwargs): + """Generate class-level decorator from given method-level decorator. + + It is expected for the given decorator to take some arguments and return + a method that is then called on the test method to produce a decorated + method. + + Args: + decorator: The decorator to apply. + *args: Positional arguments + **kwargs: Keyword arguments + Returns: Function that will decorate a given classes test methods with the + decorator. + """ + + def all_test_methods_impl(cls): + """Apply decorator to all test methods in class.""" + for name in dir(cls): + value = getattr(cls, name) + if callable(value) and name.startswith( + "test") and (name != "test_session"): + setattr(cls, name, decorator(*args, **kwargs)(value)) + return cls + + return all_test_methods_impl + + +# The description is just for documentation purposes. +def no_xla_auto_jit(description): # pylint: disable=unused-argument + """This test is not intended to be run with XLA auto jit enabled.""" + execute_func = not is_xla_enabled() + return _disable_test(execute_func) + + +# The description is just for documentation purposes. +def xla_allow_fallback(description): # pylint: disable=unused-argument + + def xla_allow_fallback_impl(func): + """Allow fallback to TF even though testing xla.""" + + def decorator(func): + + def decorated(self, *args, **kwargs): + if is_xla_enabled(): + # Update the global XLABuildOpsPassFlags to enable lazy compilation, + # which allows the compiler to fall back to TF classic. Remember the + # old value so that we can reset it. + old_value = pywrap_tf_session.TF_SetXlaEnableLazyCompilation(True) + result = func(self, *args, **kwargs) + pywrap_tf_session.TF_SetXlaEnableLazyCompilation(old_value) + return result + else: + return func(self, *args, **kwargs) + + return decorated + + if func is not None: + return decorator(func) + + return decorator + + return xla_allow_fallback_impl + + +# The description is just for documentation purposes. +def run_without_tensor_float_32(description): # pylint: disable=unused-argument + """Execute test with TensorFloat-32 disabled. + + While almost every real-world deep learning model runs fine with + TensorFloat-32, many tests use assertAllClose or similar methods. + TensorFloat-32 matmuls typically will cause such methods to fail with the + default tolerances. + + Args: + description: A description used for documentation purposes, describing why + the test requires TensorFloat-32 to be disabled. + + Returns: + Decorator which runs a test with TensorFloat-32 disabled. + """ + + def decorator(f): + + @functools.wraps(f) + def decorated(self, *args, **kwargs): + allowed = config.tensor_float_32_execution_enabled() + try: + config.enable_tensor_float_32_execution(False) + f(self, *args, **kwargs) + finally: + config.enable_tensor_float_32_execution(allowed) + + return decorated + + return decorator + + +# The description is just for documentation purposes. +def run_all_without_tensor_float_32(description): # pylint: disable=unused-argument + """Execute all tests in a class with TensorFloat-32 disabled.""" + return for_all_test_methods(run_without_tensor_float_32, description) + + +def matmul_without_tf32(a, b, *args, **kwargs): + """Run matmul but cast float32 inputs to float64 if TensorFloat-32 is enabled. + + This effectively runs matmul without TensorFloat-32. It should only be used in + tests when verifying some other op or functions works correctly, e.g. to test + `tf.linalg.sqrtm` by matrix multiplying the output of the op by itself. In + such cases, the matmul itself is not being tested so it's OK to run it with + higher precision. + + If a matmul itself is being tested, or some other op which uses matmul, use + `run_without_tensor_float_32` instead. + + This also casts complex64 inputs to complex128, since TensorFloat-32 can also + be used with complex64 + + Args: + a: First input to tf.linalg.matmul + b: Second input to tf.linalg.matmul + args: Other positional arguments to tf.linalg.matmul + **kwargs: Other keyword arguments to tf.linalg.matmul + + Returns: + A tensor with the same type as `a`. + """ + if config.tensor_float_32_execution_enabled() and a.dtype == "float32": + a = math_ops.cast(a, "float64") + b = math_ops.cast(b, "float64") + ret = math_ops.matmul(a, b, *args, **kwargs) + return math_ops.cast(ret, a.dtype) + elif config.tensor_float_32_execution_enabled() and a.dtype == "complex64": + a = math_ops.cast(a, "complex128") + b = math_ops.cast(b, "complex128") + ret = math_ops.matmul(a, b, *args, **kwargs) + return math_ops.cast(ret, a.dtype) + else: + return math_ops.matmul(a, b, *args, **kwargs) + + +class EagerSessionWarner: + + def __getattr__(self, attr): + raise AttributeError( + "Trying to access properties or call methods on the result of " + "self.session(), self.cached_session(), etc while eager execution " + "is enabled. If you're porting this test case to TF 2.0, either " + "adapt the test to work with eager execution or insert a call to " + "tf.disable_eager_execution() in the main() function of this test " + "file.") + +# TODO(b/286583977): Set it to True and remove. +_ENABLE_AUTO_BOTH_MODES = False + + +@tf_export("test.TestCase") +class TensorFlowTestCase(googletest.TestCase): + """Base class for tests that need to test TensorFlow.""" + + def __init__(self, methodName="runTest"): # pylint: disable=invalid-name + super().__init__(methodName) + # Make sure we get unfiltered stack traces during the test + traceback_utils.disable_traceback_filtering() + if is_xla_enabled(): + pywrap_tf_session.TF_SetXlaAutoJitMode("2") + pywrap_tf_session.TF_SetXlaMinClusterSize(1) + pywrap_tf_session.TF_SetXlaEnableLazyCompilation(False) + pywrap_tf_session.TF_SetTfXlaCpuGlobalJit(True) + # Constant folding secretly runs code on TF:Classic CPU, so we also + # disable it here. + pywrap_tf_session.TF_SetXlaConstantFoldingDisabled(True) + + # Check if the mlir bridge has been explicitly enabled or disabled. If + # is_mlir_bridge_enabled() returns None, the user did not explictly enable + # or disable the bridge so do not update enable_mlir_bridge. + if is_mlir_bridge_enabled(): + context.context().enable_mlir_bridge = True + elif is_mlir_bridge_enabled() is not None: + context.context().enable_mlir_bridge = False + + self._threads = [] + self._tempdir = None + self._cached_session = None + self._test_start_time = None + # This flag provides the ability to control whether the graph mode gets + # initialized for TF1 or not. Initializing for TF1, which is what was + # happening earlier, was preventing enablement of 'eager mode' in the test. + self._set_default_seed = True + + def setUp(self): + super().setUp() + self._ClearCachedSession() + random.seed(random_seed.DEFAULT_GRAPH_SEED) + np.random.seed(random_seed.DEFAULT_GRAPH_SEED) + # Note: The following line is necessary because some test methods may error + # out from within nested graph contexts (e.g., via assertRaises and + # assertRaisesRegexp), which may leave ops._default_graph_stack non-empty + # under certain versions of Python. That would cause + # ops.reset_default_graph() to throw an exception if the stack were not + # cleared first. + ops._default_graph_stack.reset() # pylint: disable=protected-access + ops.reset_default_graph() + if self._set_default_seed: + random_seed.set_random_seed(random_seed.DEFAULT_GRAPH_SEED) + # Reset summary writer in case another test used set_as_default() with their + # summary writer. + summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access + summary_state.writer = None + + # Avoiding calling setUp() for the poorly named test_session method. + if self.id().endswith(".test_session"): + self.skipTest("Not a test.") + + self._test_start_time = time.time() + + @classmethod + def setUpClass(cls): + super().setUpClass() + if _ENABLE_AUTO_BOTH_MODES: + run_all_in_graph_and_eager_modes(cls) + + def tearDown(self): + # If a subclass overrides setUp and doesn't call the parent class's setUp, + # then we may not have set the start time. + if self._test_start_time is not None: + logging.info("time(%s): %ss", self.id(), + round(time.time() - self._test_start_time, 2)) + + for thread in self._threads: + thread.check_termination() + + self._ClearCachedSession() + super().tearDown() + + def _ClearCachedSession(self): + if self._cached_session is not None: + self._cached_session.close() + self._cached_session = None + + def get_temp_dir(self): + """Returns a unique temporary directory for the test to use. + + If you call this method multiple times during in a test, it will return the + same folder. However, across different runs the directories will be + different. This will ensure that across different runs tests will not be + able to pollute each others environment. + If you need multiple unique directories within a single test, you should + use tempfile.mkdtemp as follows: + tempfile.mkdtemp(dir=self.get_temp_dir()): + + Returns: + string, the path to the unique temporary directory created for this test. + """ + if not self._tempdir: + self._tempdir = tempfile.mkdtemp(dir=googletest.GetTempDir()) + return self._tempdir + + @contextlib.contextmanager + def captureWritesToStream(self, stream) -> Iterator[CapturedWrites]: + """A context manager that captures the writes to a given stream. + + This context manager captures all writes to a given stream inside of a + `CapturedWrites` object. When this context manager is created, it yields + the `CapturedWrites` object. The captured contents can be accessed by + calling `.contents()` on the `CapturedWrites`. + + For this function to work, the stream must have a file descriptor that + can be modified using `os.dup` and `os.dup2`, and the stream must support + a `.flush()` method. The default python sys.stdout and sys.stderr are + examples of this. Note that this does not work in Colab or Jupyter + notebooks, because those use alternate stdout streams. + + Example: + ```python + class MyOperatorTest(test_util.TensorFlowTestCase): + def testMyOperator(self): + input = [1.0, 2.0, 3.0, 4.0, 5.0] + with self.captureWritesToStream(sys.stdout) as captured: + result = MyOperator(input).eval() + self.assertStartsWith(captured.contents(), "This was printed.") + ``` + + Args: + stream: The stream whose writes should be captured. This stream must have + a file descriptor, support writing via using that file descriptor, and + must have a `.flush()` method. + + Yields: + A `CapturedWrites` object that contains all writes to the specified stream + made during this context. + """ + stream.flush() + fd = stream.fileno() + tmp_file, tmp_file_path = tempfile.mkstemp(dir=self.get_temp_dir()) + orig_fd = os.dup(fd) + os.dup2(tmp_file, fd) + try: + yield CapturedWrites(tmp_file_path) + finally: + os.close(tmp_file) + os.dup2(orig_fd, fd) + + def _AssertProtoEquals(self, a, b, msg=None, relative_tolerance=None): + """Asserts that a and b are the same proto. + + Uses ProtoEq() first, as it returns correct results + for floating point attributes, and then use assertProtoEqual() + in case of failure as it provides good error messages. + + Args: + a: a proto. + b: another proto. + msg: Optional message to report on failure. + relative_tolerance: float. The allowable difference between the two values + being compared is determined by multiplying the relative tolerance by + the maximum of the two values. If this is not provided, then all floats + are compared using string comparison. + """ + if not compare.ProtoEq(a, b): + compare.assertProtoEqual( + self, + a, + b, + normalize_numbers=True, + msg=msg, + relative_tolerance=relative_tolerance, + ) + + def assertProtoEquals( + self, + expected_message_maybe_ascii, + message, + msg=None, + relative_tolerance=None, + ): + """Asserts that message is same as parsed expected_message_ascii. + + Creates another prototype of message, reads the ascii message into it and + then compares them using self._AssertProtoEqual(). + + Args: + expected_message_maybe_ascii: proto message in original or ascii form. + message: the message to validate. + msg: Optional message to report on failure. + relative_tolerance: float. The allowable difference between the two values + being compared is determined by multiplying the relative tolerance by + the maximum of the two values. If this is not provided, then all floats + are compared using string comparison. + """ + if isinstance(expected_message_maybe_ascii, type(message)): + expected_message = expected_message_maybe_ascii + self._AssertProtoEquals( + expected_message, + message, + msg=msg, + relative_tolerance=relative_tolerance, + ) + elif isinstance(expected_message_maybe_ascii, (str, bytes)): + expected_message = type(message)() + text_format.Merge( + expected_message_maybe_ascii, + expected_message, + descriptor_pool=descriptor_pool.Default()) + self._AssertProtoEquals( + expected_message, + message, + msg=msg, + relative_tolerance=relative_tolerance, + ) + else: + assert False, ("Can't compare protos of type %s and %s." % + (type(expected_message_maybe_ascii), type(message))) + + def assertProtoEqualsVersion( + self, + expected, + actual, + producer=versions.GRAPH_DEF_VERSION, + min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER, + msg=None): + expected = "versions { producer: %d min_consumer: %d };\n%s" % ( + producer, min_consumer, expected) + self.assertProtoEquals(expected, actual, msg=msg) + + def assertStartsWith(self, actual, expected_start, msg=None): + """Assert that actual.startswith(expected_start) is True. + + Args: + actual: str + expected_start: str + msg: Optional message to report on failure. + """ + if not actual.startswith(expected_start): + fail_msg = "%r does not start with %r" % (actual, expected_start) + fail_msg += " : %r" % (msg) if msg else "" + self.fail(fail_msg) + + def _eval_tensor(self, tensor): + if tensor is None: + return None + elif callable(tensor): + return self._eval_helper(tensor()) + else: + try: + # for compatibility with TF1 test cases + if sparse_tensor.is_sparse(tensor): + return sparse_tensor.SparseTensorValue(tensor.indices.numpy(), + tensor.values.numpy(), + tensor.dense_shape.numpy()) + elif ragged_tensor.is_ragged(tensor): + return ragged_tensor_value.RaggedTensorValue( + self._eval_tensor(tensor.values), + self._eval_tensor(tensor.row_splits)) + elif isinstance(tensor, indexed_slices.IndexedSlices): + return indexed_slices.IndexedSlicesValue( + values=tensor.values.numpy(), + indices=tensor.indices.numpy(), + dense_shape=None + if tensor.dense_shape is None else tensor.dense_shape.numpy()) + else: + if hasattr(tensor, "numpy") and callable(tensor.numpy): + return tensor.numpy() + else: + # Try our best to convert CompositeTensor components to NumPy + # arrays. Officially, we don't support NumPy arrays as + # CompositeTensor components. So don't be surprised if this doesn't + # work. + return nest.map_structure(lambda t: t.numpy(), tensor, + expand_composites=True) + except AttributeError as e: + raise ValueError(f"Unsupported type {type(tensor).__name__!r}.") from e + + def _eval_helper(self, tensors): + if tensors is None: + return None + return nest.map_structure(self._eval_tensor, tensors) + + def evaluate( + self, tensors + ) -> Union[ + ragged_tensor_value.RaggedTensorValue, + sparse_tensor.SparseTensorValue, + None + ]: + """Evaluates tensors and returns numpy values. + + Args: + tensors: A Tensor or a nested list/tuple of Tensors. + + Returns: + tensors numpy values. + """ + if context.executing_eagerly(): + return self._eval_helper(tensors) + else: + sess = ops.get_default_session() + flattened_tensors = nest.flatten(tensors) + if sess is None: + with self.test_session() as sess: + flattened_results = sess.run(flattened_tensors) + else: + flattened_results = sess.run(flattened_tensors) + return nest.pack_sequence_as(tensors, flattened_results) + + # pylint: disable=g-doc-return-or-yield + # pylint: disable=redefined-outer-name + @contextlib.contextmanager + def session( + self, graph=None, config=None, use_gpu=True, force_gpu=False + ) -> Iterator[s.Session]: + """A context manager for a TensorFlow Session for use in executing tests. + + Note that this will set this session and the graph as global defaults. + + Use the `use_gpu` and `force_gpu` options to control where ops are run. If + `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if + `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as + possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to + the CPU. + + Example: + + ``` python + class MyOperatorTest(test_util.TensorFlowTestCase): + def testMyOperator(self): + with self.session(): + valid_input = [1.0, 2.0, 3.0, 4.0, 5.0] + result = MyOperator(valid_input).eval() + self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0] + invalid_input = [-1.0, 2.0, 7.0] + with self.assertRaisesOpError("negative input not supported"): + MyOperator(invalid_input).eval() + ``` + + Args: + graph: Optional graph to use during the returned session. + config: An optional config_pb2.ConfigProto to use to configure the + session. + use_gpu: If True, attempt to run as many ops as possible on GPU. + force_gpu: If True, pin all ops to `/device:GPU:0`. + + Yields: + A Session object that should be used as a context manager to surround + the graph building and execution code in a test case. + """ + if context.executing_eagerly(): + yield EagerSessionWarner() + else: + with self._create_session(graph, config, force_gpu) as sess: + with self._constrain_devices_and_set_default(sess, use_gpu, force_gpu): + yield sess + + @contextlib.contextmanager + def cached_session(self, + graph=None, + config=None, + use_gpu=True, + force_gpu=False) -> Iterator[s.Session]: + """Returns a TensorFlow Session for use in executing tests. + + This method behaves differently than self.session(): for performance reasons + `cached_session` will by default reuse the same session within the same + test. The session returned by this function will only be closed at the end + of the test (in the TearDown function). + + Use the `use_gpu` and `force_gpu` options to control where ops are run. If + `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if + `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as + possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to + the CPU. + + Example: + ```python + class MyOperatorTest(test_util.TensorFlowTestCase): + def testMyOperator(self): + with self.cached_session() as sess: + valid_input = [1.0, 2.0, 3.0, 4.0, 5.0] + result = MyOperator(valid_input).eval() + self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0] + invalid_input = [-1.0, 2.0, 7.0] + with self.assertRaisesOpError("negative input not supported"): + MyOperator(invalid_input).eval() + ``` + + Args: + graph: Optional graph to use during the returned session. + config: An optional config_pb2.ConfigProto to use to configure the + session. + use_gpu: If True, attempt to run as many ops as possible on GPU. + force_gpu: If True, pin all ops to `/device:GPU:0`. + + Yields: + A Session object that should be used as a context manager to surround + the graph building and execution code in a test case. + """ + if context.executing_eagerly(): + yield FakeEagerSession(self) + else: + sess = self._get_cached_session( + graph, config, force_gpu, crash_if_inconsistent_args=True) + with self._constrain_devices_and_set_default(sess, use_gpu, + force_gpu) as cached: + yield cached + + @contextlib.contextmanager + @deprecation.deprecated(None, "Use `self.session()` or " + "`self.cached_session()` instead.") + def test_session(self, + graph=None, + config=None, + use_gpu=True, + force_gpu=False): + """Use cached_session instead.""" + if self.id().endswith(".test_session"): + self.skipTest( + "Tests that have the name \"test_session\" are automatically skipped " + "by TensorFlow test fixture, as the name is reserved for creating " + "sessions within tests. Please rename your test if you have a test " + "with this name.") + if context.executing_eagerly(): + yield None + else: + if graph is None: + sess = self._get_cached_session( + graph, config, force_gpu, crash_if_inconsistent_args=False) + with self._constrain_devices_and_set_default(sess, use_gpu, + force_gpu) as cached: + yield cached + else: + with self.session(graph, config, use_gpu, force_gpu) as sess: + yield sess + + # pylint: enable=g-doc-return-or-yield + + class _CheckedThread(object): + """A wrapper class for Thread that asserts successful completion. + + This class should be created using the TensorFlowTestCase.checkedThread() + method. + """ + + def __init__(self, testcase, target, args=None, kwargs=None): + """Constructs a new instance of _CheckedThread. + + Args: + testcase: The TensorFlowTestCase for which this thread is being created. + target: A callable object representing the code to be executed in the + thread. + args: A tuple of positional arguments that will be passed to target. + kwargs: A dictionary of keyword arguments that will be passed to target. + """ + self._testcase = testcase + self._target = target + self._args = () if args is None else args + self._kwargs = {} if kwargs is None else kwargs + self._thread = threading.Thread(target=self._protected_run) + self._exception = None + + self._is_thread_joined = False + + def _protected_run(self): + """Target for the wrapper thread. Sets self._exception on failure.""" + try: + self._target(*self._args, **self._kwargs) + except Exception as e: # pylint: disable=broad-except + self._exception = e + + def start(self): + """Starts the thread's activity. + + This must be called at most once per _CheckedThread object. It arranges + for the object's target to be invoked in a separate thread of control. + """ + self._thread.start() + + def join(self): + """Blocks until the thread terminates. + + Raises: + self._testcase.failureException: If the thread terminates with due to + an exception. + """ + self._is_thread_joined = True + self._thread.join() + if self._exception is not None: + self._testcase.fail("Error in checkedThread: %s" % str(self._exception)) + + def is_alive(self): + """Returns whether the thread is alive. + + This method returns True just before the run() method starts + until just after the run() method terminates. + + Returns: + True if the thread is alive, otherwise False. + """ + return self._thread.is_alive() + + def check_termination(self): + """Returns whether the checked thread was properly used and did terminate. + + Every checked thread should be "join"ed after starting, and before the + test tears down. If it is not joined, it is possible the thread will hang + and cause flaky failures in tests. + + Raises: + self._testcase.failureException: If check_termination was called before + thread was joined. + + RuntimeError: If the thread is not terminated. This means thread was not + joined with the main thread. + """ + if self._is_thread_joined: + if self.is_alive(): + raise RuntimeError( + "Thread was not joined with main thread, and is still running " + "when the test finished.") + else: + self._testcase.fail("A checked thread was not joined.") + + def checkedThread(self, target, args=None, kwargs=None): + """Returns a Thread wrapper that asserts 'target' completes successfully. + + This method should be used to create all threads in test cases, as + otherwise there is a risk that a thread will silently fail, and/or + assertions made in the thread will not be respected. + + Args: + target: A callable object to be executed in the thread. + args: The argument tuple for the target invocation. Defaults to (). + kwargs: A dictionary of keyword arguments for the target invocation. + Defaults to {}. + + Returns: + A wrapper for threading.Thread that supports start() and join() methods. + """ + ret = TensorFlowTestCase._CheckedThread(self, target, args, kwargs) + self._threads.append(ret) + return ret + + # pylint: enable=invalid-name + @py_func_if_in_function + def assertNear(self, f1, f2, err, msg=None): + """Asserts that two floats are near each other. + + Checks that |f1 - f2| < err and asserts a test failure + if not. + + Args: + f1: A float value. + f2: A float value. + err: A float value. + msg: An optional string message to append to the failure message. + """ + # f1 == f2 is needed here as we might have: f1, f2 = inf, inf + self.assertTrue( + f1 == f2 or math.fabs(f1 - f2) <= err, "%f != %f +/- %f%s" % + (f1, f2, err, " (%s)" % msg if msg is not None else "")) + + @py_func_if_in_function + def assertArrayNear(self, farray1, farray2, err, msg=None): + """Asserts that two float arrays are near each other. + + Checks that for all elements of farray1 and farray2 + |f1 - f2| < err. Asserts a test failure if not. + + Args: + farray1: a list of float values. + farray2: a list of float values. + err: a float value. + msg: Optional message to report on failure. + """ + self.assertEqual(len(farray1), len(farray2), msg=msg) + for f1, f2 in zip(farray1, farray2): + self.assertNear(float(f1), float(f2), err, msg=msg) + + def _NDArrayNear(self, ndarray1, ndarray2, err): + return np.linalg.norm(ndarray1 - ndarray2) < err + + @py_func_if_in_function + def assertNDArrayNear(self, ndarray1, ndarray2, err, msg=None): + """Asserts that two numpy arrays have near values. + + Args: + ndarray1: a numpy ndarray. + ndarray2: a numpy ndarray. + err: a float. The maximum absolute difference allowed. + msg: Optional message to report on failure. + """ + self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err), msg=msg) + + def _GetNdArray(self, a): + # If a is tensor-like then convert it to ndarray + if tensor_util.is_tf_type(a): + if isinstance(a, ops._EagerTensorBase): + a = a.numpy() + else: + a = self.evaluate(a) + if not isinstance(a, np.ndarray): + try: + return np.array(a) + except ValueError as e: + # TODO(b/264461299): NumPy 1.24 no longer infers dtype=object from + # ragged sequences. + # See: + # https://numpy.org/neps/nep-0034-infer-dtype-is-object.html + # Fixing this correctly requires clarifying the API contract of this + # function with respect to ragged sequences and possibly updating all + # users. As a backwards compatibility measure, if array + # creation fails with an "inhomogeneous shape" error, try again with + # an explicit dtype=object, which should restore the previous behavior. + if "inhomogeneous shape" in str(e): + return np.array(a, dtype=object) + else: + raise + return a + + def evaluate_if_both_tensors(self, a, b): + if (tensor_util.is_tf_type(a) and tensor_util.is_tf_type(b) and + not isinstance(a, ops._EagerTensorBase) and + not isinstance(b, ops._EagerTensorBase)): + return self.evaluate((a, b)) + else: + return (a, b) + + def _assertArrayLikeAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None): + (a, b) = self.evaluate_if_both_tensors(a, b) + a = self._GetNdArray(a) + b = self._GetNdArray(b) + # When the array rank is small, print its contents. Numpy array printing is + # implemented using inefficient recursion so prints can cause tests to + # time out. + if a.shape != b.shape and (b.ndim <= 3 or b.size < 500): + shape_mismatch_msg = ("Shape mismatch: expected %s, got %s with contents " + "%s.") % (a.shape, b.shape, b) + else: + shape_mismatch_msg = "Shape mismatch: expected %s, got %s." % (a.shape, + b.shape) + self.assertEqual(a.shape, b.shape, shape_mismatch_msg) + + msgs = [msg] + # np.allclose does not always work for our custom bfloat16 and float8 + # extension types when type promotions are involved, so we first cast any + # arrays of such types to float32. + a_dtype = a.dtype + custom_dtypes = (dtypes.bfloat16.as_numpy_dtype, + dtypes.float8_e5m2.as_numpy_dtype, + dtypes.float8_e4m3fn.as_numpy_dtype) + a = a.astype(np.float32) if a.dtype in custom_dtypes else a + b = b.astype(np.float32) if b.dtype in custom_dtypes else b + if not np.allclose(a, b, rtol=rtol, atol=atol): + # Adds more details to np.testing.assert_allclose. + # + # NOTE: numpy.allclose (and numpy.testing.assert_allclose) + # checks whether two arrays are element-wise equal within a + # tolerance. The relative difference (rtol * abs(b)) and the + # absolute difference atol are added together to compare against + # the absolute difference between a and b. Here, we want to + # tell user which elements violate such conditions. + cond = np.logical_or( + np.abs(a - b) > atol + rtol * np.abs(b), + np.isnan(a) != np.isnan(b)) + if a.ndim: + x = a[np.where(cond)] + y = b[np.where(cond)] + msgs.append("not close where = {}".format(np.where(cond))) + else: + # np.where is broken for scalars + x, y = a, b + msgs.append("not close lhs = {}".format(x)) + msgs.append("not close rhs = {}".format(y)) + msgs.append("not close dif = {}".format(np.abs(x - y))) + msgs.append("not close tol = {}".format(atol + rtol * np.abs(y))) + msgs.append("dtype = {}, shape = {}".format(a_dtype, a.shape)) + # TODO(xpan): There seems to be a bug: + # tensorflow/compiler/tests:binary_ops_test pass with float32 + # nan even though the equal_nan is False by default internally. + np.testing.assert_allclose( + a, b, rtol=rtol, atol=atol, err_msg="\n".join(msgs), equal_nan=True) + + def _assertAllCloseRecursive(self, + a, + b, + rtol=1e-6, + atol=1e-6, + path=None, + msg=None): + if ragged_tensor.is_ragged(a) or ragged_tensor.is_ragged(b): + return self._assertRaggedClose(a, b, rtol, atol, msg) + path = path or [] + path_str = (("[" + "][".join(str(p) for p in path) + "]") if path else "") + msg = msg if msg else "" + + # Check if a and/or b are namedtuples. + if hasattr(a, "_asdict"): + a = a._asdict() + if hasattr(b, "_asdict"): + b = b._asdict() + a_is_dict = isinstance(a, collections_abc.Mapping) + if a_is_dict != isinstance(b, collections_abc.Mapping): + raise ValueError("Can't compare dict to non-dict, a%s vs b%s. %s" % + (path_str, path_str, msg)) + if a_is_dict: + self.assertItemsEqual( + a.keys(), + b.keys(), + msg="mismatched keys: a%s has keys %s, but b%s has keys %s. %s" % + (path_str, a.keys(), path_str, b.keys(), msg)) + for k in a: + path.append(k) + self._assertAllCloseRecursive( + a[k], b[k], rtol=rtol, atol=atol, path=path, msg=msg) + del path[-1] + elif isinstance(a, (list, tuple)): + # Try to directly compare a, b as ndarrays; if not work, then traverse + # through the sequence, which is more expensive. + try: + (a, b) = self.evaluate_if_both_tensors(a, b) + a_as_ndarray = self._GetNdArray(a) + b_as_ndarray = self._GetNdArray(b) + self._assertArrayLikeAllClose( + a_as_ndarray, + b_as_ndarray, + rtol=rtol, + atol=atol, + msg="Mismatched value: a%s is different from b%s. %s" % + (path_str, path_str, msg)) + except (ValueError, TypeError, NotImplementedError) as e: + if len(a) != len(b): + raise ValueError( + "Mismatched length: a%s has %d items, but b%s has %d items. %s" % + (path_str, len(a), path_str, len(b), msg)) + for idx, (a_ele, b_ele) in enumerate(zip(a, b)): + path.append(str(idx)) + self._assertAllCloseRecursive( + a_ele, b_ele, rtol=rtol, atol=atol, path=path, msg=msg) + del path[-1] + # a and b are ndarray like objects + else: + try: + self._assertArrayLikeAllClose( + a, + b, + rtol=rtol, + atol=atol, + msg=("Mismatched value: a%s is different from b%s. %s" % + (path_str, path_str, msg))) + except TypeError as e: + msg = ("Error: a%s has %s, but b%s has %s. %s" % + (path_str, type(a), path_str, type(b), msg)) + e.args = ((e.args[0] + " : " + msg,) + e.args[1:]) + raise + + @py_func_if_in_function + def assertAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None): + """Asserts that two structures of numpy arrays or Tensors, have near values. + + `a` and `b` can be arbitrarily nested structures. A layer of a nested + structure can be a `dict`, `namedtuple`, `tuple` or `list`. + + Note: the implementation follows + [`numpy.allclose`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html) + (and numpy.testing.assert_allclose). It checks whether two arrays are + element-wise equal within a tolerance. The relative difference + (`rtol * abs(b)`) and the absolute difference `atol` are added together + to compare against the absolute difference between `a` and `b`. + + Args: + a: The expected numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor), or any arbitrarily nested of + structure of these. + b: The actual numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor), or any arbitrarily nested of + structure of these. + rtol: relative tolerance. + atol: absolute tolerance. + msg: Optional message to report on failure. + + Raises: + ValueError: if only one of `a[p]` and `b[p]` is a dict or + `a[p]` and `b[p]` have different length, where `[p]` denotes a path + to the nested structure, e.g. given `a = [(1, 1), {'d': (6, 7)}]` and + `[p] = [1]['d']`, then `a[p] = (6, 7)`. + """ + self._assertAllCloseRecursive(a, b, rtol=rtol, atol=atol, msg=msg) + + @py_func_if_in_function + def assertAllCloseAccordingToType(self, + a, + b, + rtol=1e-6, + atol=1e-6, + float_rtol=1e-6, + float_atol=1e-6, + half_rtol=1e-3, + half_atol=1e-3, + bfloat16_rtol=1e-2, + bfloat16_atol=1e-2, + msg=None): + """Like assertAllClose, but also suitable for comparing fp16 arrays. + + In particular, the tolerance is reduced to 1e-3 if at least + one of the arguments is of type float16. + + Args: + a: the expected numpy ndarray or anything can be converted to one. + b: the actual numpy ndarray or anything can be converted to one. + rtol: relative tolerance. + atol: absolute tolerance. + float_rtol: relative tolerance for float32. + float_atol: absolute tolerance for float32. + half_rtol: relative tolerance for float16. + half_atol: absolute tolerance for float16. + bfloat16_rtol: relative tolerance for bfloat16. + bfloat16_atol: absolute tolerance for bfloat16. + msg: Optional message to report on failure. + """ + (a, b) = self.evaluate_if_both_tensors(a, b) + a = self._GetNdArray(a) + b = self._GetNdArray(b) + # types with lower tol are put later to overwrite previous ones. + if (a.dtype == np.float32 or b.dtype == np.float32 or + a.dtype == np.complex64 or b.dtype == np.complex64): + rtol = max(rtol, float_rtol) + atol = max(atol, float_atol) + if a.dtype == np.float16 or b.dtype == np.float16: + rtol = max(rtol, half_rtol) + atol = max(atol, half_atol) + if (a.dtype == dtypes.bfloat16.as_numpy_dtype or + b.dtype == dtypes.bfloat16.as_numpy_dtype): + rtol = max(rtol, bfloat16_rtol) + atol = max(atol, bfloat16_atol) + + self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg) + + @py_func_if_in_function + def assertNotAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None): + """Assert that two numpy arrays, or Tensors, do not have near values. + + Args: + a: The expected numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor), or any arbitrarily nested of + structure of these. + b: The actual numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor), or any arbitrarily nested of + structure of these. + rtol: relative tolerance. + atol: absolute tolerance. + msg: Optional message to report on failure. + + Raises: + AssertionError: If `a` and `b` are unexpectedly close at all elements. + """ + try: + self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg) + except AssertionError: + return + msg = msg or "" + raise AssertionError("The two values are close at all elements. %s" % msg) + + @py_func_if_in_function + def assertAllEqual(self, a, b, msg=None): + """Asserts that two numpy arrays or Tensors have the same values. + + Args: + a: the expected numpy ndarray or anything can be converted to one. + b: the actual numpy ndarray or anything can be converted to one. + msg: Optional message to report on failure. + """ + if (ragged_tensor.is_ragged(a) or ragged_tensor.is_ragged(b)): + return self._assertRaggedEqual(a, b, msg) + msg = msg if msg else "" + (a, b) = self.evaluate_if_both_tensors(a, b) + a = self._GetNdArray(a) + b = self._GetNdArray(b) + # Arbitrary bounds so that we don't print giant tensors. + if (b.ndim <= 3 or b.size < 500): + self.assertEqual( + a.shape, b.shape, "Shape mismatch: expected %s, got %s." + " Contents: %r. \n%s." % (a.shape, b.shape, b, msg)) + else: + self.assertEqual( + a.shape, b.shape, "Shape mismatch: expected %s, got %s." + " %s" % (a.shape, b.shape, msg)) + + same = (a == b) + + if dtypes.as_dtype(a.dtype).is_floating: + same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b))) + msgs = [msg] + if not np.all(same): + # Adds more details to np.testing.assert_array_equal. + diff = np.logical_not(same) + if a.ndim: + x = a[np.where(diff)] + y = b[np.where(diff)] + msgs.append("not equal where = {}".format(np.where(diff))) + else: + # np.where is broken for scalars + x, y = a, b + msgs.append("not equal lhs = %r" % x) + msgs.append("not equal rhs = %r" % y) + + if (a.dtype.kind != b.dtype.kind and + {a.dtype.kind, b.dtype.kind}.issubset({"U", "S", "O"})): + a_list = [] + b_list = [] + # OK to flatten `a` and `b` because they are guaranteed to have the + # same shape. + for out_list, flat_arr in [(a_list, a.flat), (b_list, b.flat)]: + for item in flat_arr: + if isinstance(item, str): + out_list.append(item.encode("utf-8")) + else: + out_list.append(item) + a = np.array(a_list) + b = np.array(b_list) + + np.testing.assert_array_equal(a, b, err_msg="\n".join(msgs)) + + @py_func_if_in_function + def assertNotAllEqual(self, a, b, msg=None): + """Asserts that two numpy arrays or Tensors do not have the same values. + + Args: + a: the expected numpy ndarray or anything can be converted to one. + b: the actual numpy ndarray or anything can be converted to one. + msg: Optional message to report on failure. + """ + try: + self.assertAllEqual(a, b) + except AssertionError: + return + msg = msg or "" + raise AssertionError("The two values are equal at all elements. %s" % msg) + + @py_func_if_in_function + def assertAllGreater(self, a, comparison_target): + """Assert element values are all greater than a target value. + + Args: + a: The numpy `ndarray`, or anything that can be converted into a numpy + `ndarray` (including Tensor). + comparison_target: The target value of comparison. + """ + (a, comparison_target) = self.evaluate_if_both_tensors(a, comparison_target) + a = self._GetNdArray(a) + self.assertGreater(np.min(a), comparison_target) + + @py_func_if_in_function + def assertAllLess(self, a, comparison_target): + """Assert element values are all less than a target value. + + Args: + a: The numpy `ndarray`, or anything that can be converted into a numpy + `ndarray` (including Tensor). + comparison_target: The target value of comparison. + """ + (a, comparison_target) = self.evaluate_if_both_tensors(a, comparison_target) + a = self._GetNdArray(a) + self.assertLess(np.max(a), comparison_target) + + @py_func_if_in_function + def assertAllGreaterEqual(self, a, comparison_target): + """Assert element values are all greater than or equal to a target value. + + Args: + a: The numpy `ndarray`, or anything that can be converted into a numpy + `ndarray` (including Tensor). + comparison_target: The target value of comparison. + """ + (a, comparison_target) = self.evaluate_if_both_tensors(a, comparison_target) + a = self._GetNdArray(a) + self.assertGreaterEqual(np.min(a), comparison_target) + + @py_func_if_in_function + def assertAllLessEqual(self, a, comparison_target): + """Assert element values are all less than or equal to a target value. + + Args: + a: The numpy `ndarray`, or anything that can be converted into a numpy + `ndarray` (including Tensor). + comparison_target: The target value of comparison. + """ + (a, comparison_target) = self.evaluate_if_both_tensors(a, comparison_target) + a = self._GetNdArray(a) + self.assertLessEqual(np.max(a), comparison_target) + + def _format_subscripts(self, subscripts, value, limit=10, indent=2): + """Generate a summary of ndarray subscripts as a list of str. + + If limit == N, this method will print up to the first N subscripts on + separate + lines. A line of ellipses (...) will be appended at the end if the number of + subscripts exceeds N. + + Args: + subscripts: The tensor (np.ndarray) subscripts, of the same format as + np.where()'s return value, i.e., a tuple of arrays with each array + corresponding to a dimension. E.g., (array([1, 1]), array([0, 1])). + value: (np.ndarray) value of the tensor. + limit: (int) The maximum number of indices to print. + indent: (int) Number of characters to indent at the beginning of each + line. + + Returns: + (list of str) the multi-line representation of the subscripts and values, + potentially with omission at the end. + """ + lines = [] + subscripts = np.transpose(subscripts) + prefix = " " * indent + if np.ndim(value) == 0: + return [prefix + "[0] : " + str(value)] + for subscript in itertools.islice(subscripts, limit): + lines.append(prefix + str(subscript) + " : " + + str(value[tuple(subscript)])) + if len(subscripts) > limit: + lines.append(prefix + "...") + return lines + + @py_func_if_in_function + def assertAllInRange(self, + target, + lower_bound, + upper_bound, + open_lower_bound=False, + open_upper_bound=False): + """Assert that elements in a Tensor are all in a given range. + + Args: + target: The numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor). + lower_bound: lower bound of the range + upper_bound: upper bound of the range + open_lower_bound: (`bool`) whether the lower bound is open (i.e., > rather + than the default >=) + open_upper_bound: (`bool`) whether the upper bound is open (i.e., < rather + than the default <=) + + Raises: + AssertionError: + if the value tensor does not have an ordered numeric type (float* or + int*), or + if there are nan values, or + if any of the elements do not fall in the specified range. + """ + target = self._GetNdArray(target) + if not (np.issubdtype(target.dtype, np.floating) or + np.issubdtype(target.dtype, np.integer)): + raise AssertionError( + "The value of %s does not have an ordered numeric type, instead it " + "has type: %s" % (target, target.dtype)) + + nan_subscripts = np.where(np.isnan(target)) + if np.size(nan_subscripts): + raise AssertionError( + "%d of the %d element(s) are NaN. " + "Subscripts(s) and value(s) of the NaN element(s):\n" % + (len(nan_subscripts[0]), np.size(target)) + + "\n".join(self._format_subscripts(nan_subscripts, target))) + + range_str = (("(" if open_lower_bound else "[") + str(lower_bound) + ", " + + str(upper_bound) + (")" if open_upper_bound else "]")) + + violations = ( + np.less_equal(target, lower_bound) if open_lower_bound else np.less( + target, lower_bound)) + violations = np.logical_or( + violations, + np.greater_equal(target, upper_bound) + if open_upper_bound else np.greater(target, upper_bound)) + violation_subscripts = np.where(violations) + if np.size(violation_subscripts): + raise AssertionError( + "%d of the %d element(s) are outside the range %s. " % + (len(violation_subscripts[0]), np.size(target), range_str) + + "Subscript(s) and value(s) of the offending elements:\n" + + "\n".join(self._format_subscripts(violation_subscripts, target))) + + @py_func_if_in_function + def assertAllInSet(self, target, expected_set): + """Assert that elements of a Tensor are all in a given closed set. + + Args: + target: The numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor). + expected_set: (`list`, `tuple` or `set`) The closed set that the elements + of the value of `target` are expected to fall into. + + Raises: + AssertionError: + if any of the elements do not fall into `expected_set`. + """ + target = self._GetNdArray(target) + + # Elements in target that are not in expected_set. + diff = np.setdiff1d(target.flatten(), list(expected_set)) + if np.size(diff): + raise AssertionError("%d unique element(s) are not in the set %s: %s" % + (np.size(diff), expected_set, diff)) + + @py_func_if_in_function + def assertDTypeEqual(self, target, expected_dtype): + """Assert ndarray data type is equal to expected. + + Args: + target: The numpy `ndarray`, or anything that can be converted into a + numpy `ndarray` (including Tensor). + expected_dtype: Expected data type. + """ + target = self._GetNdArray(target) + if not isinstance(target, list): + arrays = [target] + for arr in arrays: + self.assertEqual(arr.dtype, expected_dtype) + + # pylint: disable=g-doc-return-or-yield + @contextlib.contextmanager + def assertRaisesWithPredicateMatch(self, exception_type, + expected_err_re_or_predicate): + """Returns a context manager to enclose code expected to raise an exception. + + If the exception is an OpError, the op stack is also included in the message + predicate search. + + Args: + exception_type: The expected type of exception that should be raised. + expected_err_re_or_predicate: If this is callable, it should be a function + of one argument that inspects the passed-in exception and returns True + (success) or False (please fail the test). Otherwise, the error message + is expected to match this regular expression partially. + + Returns: + A context manager to surround code that is expected to raise an + exception. + """ + if callable(expected_err_re_or_predicate): + predicate = expected_err_re_or_predicate + else: + + def predicate(e): + err_str = e.message if isinstance(e, errors.OpError) else str(e) + op = e.op if isinstance(e, errors.OpError) else None + while op is not None: + err_str += "\nCaused by: " + op.name + op = op._original_op # pylint: disable=protected-access + logging.info("Searching within error strings: '%s' within '%s'", + expected_err_re_or_predicate, err_str) + return re.search(expected_err_re_or_predicate, err_str) + + try: + yield + self.fail(exception_type.__name__ + " not raised") + except Exception as e: # pylint: disable=broad-except + if not isinstance(e, exception_type) or not predicate(e): + raise AssertionError("Exception of type %s: %s" % + (str(type(e)), str(e))) + + # pylint: enable=g-doc-return-or-yield + + def assertRaisesOpError(self, expected_err_re_or_predicate): + return self.assertRaisesWithPredicateMatch(errors.OpError, + expected_err_re_or_predicate) + + def assertRaisesIncompatibleShapesError( + self, exception_type=errors.InvalidArgumentError): + return self.assertRaisesWithPredicateMatch( + exception_type, r"Incompatible shapes|Dimensions must be equal|" + r"required broadcastable shapes") + + def assertShapeEqual(self, input_a, input_b, msg=None): + """Asserts that two Numpy or TensorFlow objects have the same shape. + + For Tensors, this compares statically known shapes at compile time, not + dynamic shapes at runtime. + + Args: + input_a: A Numpy ndarray, Numpy scalar, or a Tensor. + input_b: A Numpy ndarray, Numpy scalar, or a Tensor. + msg: Optional message to report on failure. + + Raises: + TypeError: If the arguments have the wrong type. + """ + if not isinstance(input_a, (np.ndarray, np.generic, tensor_lib.Tensor)): + raise TypeError( + "input_a must be a Numpy ndarray, Numpy scalar, or a Tensor." + f"Instead received {type(input_a)}") + if not isinstance(input_b, (np.ndarray, np.generic, tensor_lib.Tensor)): + raise TypeError( + "input_b must be a Numpy ndarray, Numpy scalar, or a Tensor." + f"Instead received {type(input_b)}") + shape_a = input_a.get_shape().as_list() if isinstance( + input_a, tensor_lib.Tensor) else input_a.shape + shape_b = input_b.get_shape().as_list() if isinstance( + input_b, tensor_lib.Tensor) else input_b.shape + self.assertAllEqual(shape_a, shape_b, msg=msg) + + def assertDeviceEqual(self, device1, device2, msg=None): + """Asserts that the two given devices are the same. + + Args: + device1: A string device name or TensorFlow `DeviceSpec` object. + device2: A string device name or TensorFlow `DeviceSpec` object. + msg: Optional message to report on failure. + """ + device1 = pydev.canonical_name(device1) + device2 = pydev.canonical_name(device2) + self.assertEqual( + device1, device2, + "Devices %s and %s are not equal. %s" % (device1, device2, msg)) + + @py_func_if_in_function + def assertDictEqual(self, a, b, msg=None): + """Assert that two given dictionary of tensors are the same. + + Args: + a: Expected dictionary with numpy ndarray or anything else that can be + converted to one as values. + b: Actual dictionary with numpy ndarray or anything else that can be + converted to one as values. + msg: Optional message to report on failure. + """ + # To keep backwards compatibility, we first try the base class + # assertDictEqual. If that fails we try the tensorflow one. + try: + super().assertDictEqual(a, b, msg) + except Exception: # pylint: disable=broad-except + self.assertSameElements(a.keys(), b.keys()) # pylint: disable=g-assert-in-except + for k, v in a.items(): + (a_k, b_k) = self.evaluate_if_both_tensors(v, b[k]) + a_k = self._GetNdArray(a_k) + b_k = self._GetNdArray(b_k) + if np.issubdtype(a_k.dtype, np.floating): + self.assertAllClose(v, b[k], msg=k) + else: + self.assertAllEqual(v, b[k], msg=k) + + def _GetPyList(self, a): + """Converts `a` to a nested python list.""" + if isinstance(a, ragged_tensor.RaggedTensor): + return self.evaluate(a).to_list() + elif isinstance(a, tensor_lib.Tensor): + a = self.evaluate(a) + return a.tolist() if isinstance(a, np.ndarray) else a + elif isinstance(a, np.ndarray): + return a.tolist() + elif isinstance(a, ragged_tensor_value.RaggedTensorValue): + return a.to_list() + else: + return np.array(a, dtype=object).tolist() + + def _assertRaggedEqual(self, a, b, msg): + """Asserts that two ragged tensors are equal.""" + a_list = self._GetPyList(a) + b_list = self._GetPyList(b) + self.assertEqual(a_list, b_list, msg) + + if not (isinstance(a, (list, tuple)) or isinstance(b, (list, tuple))): + a_ragged_rank = a.ragged_rank if ragged_tensor.is_ragged(a) else 0 + b_ragged_rank = b.ragged_rank if ragged_tensor.is_ragged(b) else 0 + self.assertEqual(a_ragged_rank, b_ragged_rank, msg) + + def _assertRaggedClose(self, a, b, rtol, atol, msg=None): + a_list = self._GetPyList(a) + b_list = self._GetPyList(b) + self._assertListCloseRecursive(a_list, b_list, rtol, atol, msg) + + if not (isinstance(a, (list, tuple)) or isinstance(b, (list, tuple))): + a_ragged_rank = a.ragged_rank if ragged_tensor.is_ragged(a) else 0 + b_ragged_rank = b.ragged_rank if ragged_tensor.is_ragged(b) else 0 + self.assertEqual(a_ragged_rank, b_ragged_rank, msg) + + def _assertListCloseRecursive(self, a, b, rtol, atol, msg, path="value"): + self.assertEqual(type(a), type(b)) + if isinstance(a, (list, tuple)): + self.assertLen(a, len(b), "Length differs for %s" % path) + for i in range(len(a)): + self._assertListCloseRecursive(a[i], b[i], rtol, atol, msg, + "%s[%s]" % (path, i)) + else: + self._assertAllCloseRecursive(a, b, rtol, atol, path, msg) + + # Fix Python 3+ compatibility issues + # pylint: disable=invalid-name + + # Silence a deprecation warning + assertRaisesRegexp = googletest.TestCase.assertRaisesRegex + + # assertItemsEqual is assertCountEqual as of 3.2. + assertItemsEqual = googletest.TestCase.assertCountEqual + + # pylint: enable=invalid-name + + @contextlib.contextmanager + def _constrain_devices_and_set_default(self, sess, use_gpu, force_gpu): + """Set the session and its graph to global default and constrain devices.""" + if context.executing_eagerly(): + yield None + else: + with sess.graph.as_default(), sess.as_default(): + if force_gpu: + # Use the name of an actual device if one is detected, or + # '/device:GPU:0' otherwise + gpu_name = gpu_device_name() + if not gpu_name: + gpu_name = "/device:GPU:0" + with sess.graph.device(gpu_name): + yield sess + elif use_gpu: + yield sess + else: + with sess.graph.device("/device:CPU:0"): + yield sess + + def _create_session(self, graph, config, force_gpu): + """See session() for details.""" + + def prepare_config(config): + """Returns a config for sessions. + + Args: + config: An optional config_pb2.ConfigProto to use to configure the + session. + + Returns: + A config_pb2.ConfigProto object. + """ + # TODO(b/114333779): Enforce allow_soft_placement=False when + # use_gpu=False. Currently many tests rely on the fact that any device + # will be used even when a specific device is supposed to be used. + allow_soft_placement = not force_gpu + if config is None: + config = context.context().config + config.allow_soft_placement = allow_soft_placement + elif not allow_soft_placement and config.allow_soft_placement: + config_copy = context.context().config + config = config_copy + config.allow_soft_placement = False + # Don't perform optimizations for tests so we don't inadvertently run + # gpu ops on cpu + config.graph_options.optimizer_options.opt_level = -1 + # Disable Grappler constant folding since some tests & benchmarks + # use constant input and become meaningless after constant folding. + # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE + # GRAPPLER TEAM. + config.graph_options.rewrite_options.constant_folding = ( + rewriter_config_pb2.RewriterConfig.OFF) + config.graph_options.rewrite_options.pin_to_host_optimization = ( + rewriter_config_pb2.RewriterConfig.OFF) + return config + + return ErrorLoggingSession(graph=graph, config=prepare_config(config)) + + def _get_cached_session(self, + graph=None, + config=None, + force_gpu=False, + crash_if_inconsistent_args=True): + """See cached_session() for documentation.""" + if self._cached_session is None: + sess = self._create_session( + graph=graph, config=config, force_gpu=force_gpu) + self._cached_session = sess + self._cached_graph = graph + self._cached_config = config + self._cached_force_gpu = force_gpu + return sess + else: + if crash_if_inconsistent_args and self._cached_graph is not graph: + raise ValueError("The graph used to get the cached session is " + "different than the one that was used to create the " + "session. Maybe create a new session with " + "self.session()") + if crash_if_inconsistent_args and self._cached_config is not config: + raise ValueError("The config used to get the cached session is " + "different than the one that was used to create the " + "session. Maybe create a new session with " + "self.session()") + if crash_if_inconsistent_args and (self._cached_force_gpu is + not force_gpu): + raise ValueError( + "The force_gpu value used to get the cached session is " + "different than the one that was used to create the " + "session. Maybe create a new session with " + "self.session()") + return self._cached_session + + +ASSIGNED_PORTS = set() +lock = threading.Lock() + + +def pick_unused_port(): + """Returns an unused and unassigned local port.""" + import portpicker # pylint: disable=g-import-not-at-top + + global ASSIGNED_PORTS + with lock: + while True: + try: + port = portpicker.pick_unused_port() + except portpicker.NoFreePortFoundError as porterror: + raise unittest.SkipTest("Flakes in portpicker library do not represent" + " TensorFlow errors.") from porterror + if port > 10000 and port not in ASSIGNED_PORTS: + ASSIGNED_PORTS.add(port) + logging.info("Using local port %r", port) + return port + + +@tf_export("test.create_local_cluster") +def create_local_cluster(num_workers, + num_ps, + protocol="grpc", + worker_config=None, + ps_config=None): + """Create and start local servers and return the associated `Server` objects. + + "PS" stands for "parameter server": a task responsible for storing and + updating the model's parameters. Other tasks send updates to these parameters + as they work on optimizing the parameters. This particular division of labor + between tasks is not required, but is common for distributed training. + + Read more at https://www.tensorflow.org/guide/extend/architecture + + ![components](https://www.tensorflow.org/images/diag1.svg "components") + + + Figure illustrates the interaction of these components. + "/job:worker/task:0" and "/job:ps/task:0" are both tasks with worker services. + + + Example: + ```python + workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2) + + worker_sessions = [tf.compat.v1.Session(w.target) for w in workers] + + with tf.device("/job:ps/task:0"): + ... + with tf.device("/job:ps/task:1"): + ... + with tf.device("/job:worker/task:0"): + ... + with tf.device("/job:worker/task:1"): + ... + + worker_sessions[0].run(...) + ``` + + Args: + num_workers: Number of worker servers to start. + num_ps: Number of PS servers to start. + protocol: Communication protocol. Allowed values are documented in the + documentation of `tf.distribute.Server`. + worker_config: (optional) `tf.ConfigProto` to initialize workers. Can be + used to instantiate multiple devices etc. + ps_config: (optional) `tf.ConfigProto` to initialize PS servers. + + Returns: + A tuple `(worker_servers, ps_servers)`. `worker_servers` is a list + of `num_workers` objects of type `tf.distribute.Server` (all running + locally); + and `ps_servers` is a list of `num_ps` objects of similar type. + + Raises: + ImportError: if portpicker module was not found at load time + """ + worker_ports = [pick_unused_port() for _ in range(num_workers)] + ps_ports = [pick_unused_port() for _ in range(num_ps)] + cluster_dict = { + "worker": ["localhost:%s" % port for port in worker_ports], + "ps": ["localhost:%s" % port for port in ps_ports] + } + cs = server_lib.ClusterSpec(cluster_dict) + + workers = [ + server_lib.Server( + cs, + job_name="worker", + protocol=protocol, + task_index=ix, + config=worker_config, + start=True) for ix in range(num_workers) + ] + ps_servers = [ + server_lib.Server( + cs, + job_name="ps", + protocol=protocol, + task_index=ix, + config=ps_config, + start=True) for ix in range(num_ps) + ] + + return workers, ps_servers + + +def get_node_def_from_graph(node_name, graph_def): + """Returns the `NodeDef` instance for given node name in the graph def. + + This method explores only the NodeDefs in `graph_def.node`. + + Args: + node_name: Name of the NodeDef to search for. + graph_def: An instance of `GraphDef` proto. + + Returns: + the `NodeDef` instance whose name field matches the given node_name or None. + """ + for node_def in graph_def.node: + if node_def.name == node_name: + return node_def + return None + + +def set_producer_version(graph, producer_version): + """Sets graph.graph_def_versions.producer to `producer_version`.""" + # The C API doesn't expose altering GraphDefVersions. We can indirectly set + # it via import_graph_def though. + graph_def = graph_pb2.GraphDef() + graph_def.versions.producer = producer_version + with graph.as_default(): + importer.import_graph_def(graph_def) + assert graph.graph_def_versions.producer, producer_version + + +@contextlib.contextmanager +def _fake_gradient_tape_context_manager(): + """tf.gradients(...) implemented as tf.GradientTape context manager interface. + + This is useful to test tf.gradients() in tests that uses tf.GradientTape(). + + Yields: + gradient tape instance that's implemented by tf.gradients() underneath. + """ + try: + class FakeGradientTape: + + def watch(self, x): + pass + + def gradient(self, y, x, grad_ys=None): + result = gradients_impl.gradients(y, x, grad_ys) + + # Unlike `tape.gradient()`, `tf.gradients()` returns a list for a single + # element. So unpack if needed to match `tape.gradient()` behavior. + if not isinstance(x, (list, tuple)): + assert len(result) == 1 + return result[0] + + return result + + yield FakeGradientTape() + finally: + pass + + +class AbstractGradientTape: + """Abstract GradientTape context manager that has multiple implementations. + + This is useful to test both tf.GradientTape() and tf.gradients() without + duplicating tests. + """ + + def __init__(self, use_tape, persistent=False): + self._use_tape = use_tape + self._persistent = persistent + + def __enter__(self) -> backprop.GradientTape: + if self._use_tape: + self._tape_impl = backprop.GradientTape(persistent=self._persistent) + else: + self._tape_impl = _fake_gradient_tape_context_manager() + return self._tape_impl.__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + self._tape_impl.__exit__(exc_type, exc_val, exc_tb) + + +@contextlib.contextmanager +def run_functions_eagerly(run_eagerly): + """Runs functions eagerly if `run_eagerly` is true. + + WARNING: Setting `run_eagerly` to True in tests running in V1 graph mode + *WILL NOT* make the tf.function to run eagerly because eager is disabled by + default in V1. Instead, tf.function will run as a traced graph function. + + Ensures that the state (for running functions eagerly) is back to the initial + `def_function.RUN_FUNCTIONS_EAGERLY` state. + + Args: + run_eagerly: Boolean determining whether to run the function eagerly or not. + + Raises: + ValueError if `run_eagerly` is not a boolean. + + Yields: + Nothing. + """ + if not isinstance(run_eagerly, bool): + raise ValueError( + "Expected bool for `run_eagerly` but got {}".format(run_eagerly)) + + is_eager = context.executing_eagerly() + if not is_eager and run_eagerly: + logging.warning( + "Running tf.function eagerly in V1 graph mode is not supported. " + "tf.function will be run as a traced graph function.") + + initial_state = def_function.functions_run_eagerly() + def_function.run_functions_eagerly(run_eagerly) + try: + yield + finally: + def_function.run_functions_eagerly(initial_state) + + +class TestDelta: + """A utility class to track increments to test counters.""" + + def __init__(self, name, label): + self.name = name + self.label = label + self.Reset() + + def Reset(self): + self.last_value = _test_metrics_util.test_counter_value( + self.name, self.label) + + def Get(self): + value = _test_metrics_util.test_counter_value(self.name, self.label) + return value - self.last_value + + +@tf_export("test.experimental.sync_devices") +def sync_devices(): + """Synchronizes all devices. + + By default, GPUs run asynchronously. This means that when you run an op on the + GPU, like `tf.linalg.matmul`, the op may still be running on the GPU when the + function returns. Non-GPU devices can also be made to run asynchronously by + calling `tf.config.experimental.set_synchronous_execution(False)`. Calling + `sync_devices()` blocks until pending ops have finished executing. This is + primarily useful for measuring performance during a benchmark. + + For example, here is how you can measure how long `tf.linalg.matmul` runs: + + >>> import time + >>> x = tf.random.normal((4096, 4096)) + >>> tf.linalg.matmul(x, x) # Warmup. + >>> tf.test.experimental.sync_devices() # Block until warmup has completed. + >>> + >>> start = time.time() + >>> y = tf.linalg.matmul(x, x) + >>> tf.test.experimental.sync_devices() # Block until matmul has completed. + >>> end = time.time() + >>> print(f'Time taken: {end - start}') + + If the call to `sync_devices()` was omitted, the time printed could be too + small. This is because the op could still be running asynchronously when + the line `end = time.time()` is executed. + + Raises: + RuntimeError: If run outside Eager mode. This must be called in Eager mode, + outside any `tf.function`s. + """ + if not context.executing_eagerly(): + raise RuntimeError( + "sync_devices() must only be called in Eager mode, outside tf.functions" + ) + + # There are two sources of asynchrony in TensorFlow: + # + # 1. On GPUs, kernels are run on a CUDA stream, which is inherently + # asynchronous. + # 2. Calling `tf.config.experimental.set_synchronous_execution(False)` makes + # all ops asynchronous, in which case TensorFlow maintains internal queues + # of pending ops. + # + # Calling SyncDevice addresses source (1). Calling async_await addresses + # source (2). It is important that SyncDevice() is called before async_wait(), + # otherwise the SyncDevice op itself may still be pending on an internal + # TensorFlow queue when the sync_devices() Python function returns. + devices = config.list_logical_devices() + for dev in devices: + with ops.device(dev.name): + gen_sync_ops.SyncDevice() + context.async_wait() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tfrt_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tfrt_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..83bc10e73a52dbd45e40918bf493f337fa1d9f5b --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/tfrt_utils.py @@ -0,0 +1,20 @@ +# 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. +# ============================================================================== +"""Utilities for TFRT migration.""" + + +def enabled(): + """Returns true if TFRT should be enabled.""" + return False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/traceable_stack.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/traceable_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..bce16048a24983ce5ea46f0ba393ffaccab29b8f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/traceable_stack.py @@ -0,0 +1,129 @@ +# 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 simple stack that associates filename and line numbers with each object.""" + +import inspect + + +class TraceableObject(object): + """Wrap an object together with its the code definition location.""" + + # Return codes for the set_filename_and_line_from_caller() method. + SUCCESS, HEURISTIC_USED, FAILURE = (0, 1, 2) + + def __init__(self, obj, filename=None, lineno=None): + self.obj = obj + self.filename = filename + self.lineno = lineno + + def set_filename_and_line_from_caller(self, offset=0): + """Set filename and line using the caller's stack frame. + + If the requested stack information is not available, a heuristic may + be applied and self.HEURISTIC USED will be returned. If the heuristic + fails then no change will be made to the filename and lineno members + (None by default) and self.FAILURE will be returned. + + Args: + offset: Integer. If 0, the caller's stack frame is used. If 1, + the caller's caller's stack frame is used. Larger values are + permissible but if out-of-range (larger than the number of stack + frames available) the outermost stack frame will be used. + + Returns: + TraceableObject.SUCCESS if appropriate stack information was found, + TraceableObject.HEURISTIC_USED if the offset was larger than the stack, + and TraceableObject.FAILURE if the stack was empty. + """ + retcode = self.SUCCESS + frame = inspect.currentframe() + # Offset is defined in "Args" as relative to the caller. We are one frame + # beyond the caller. + for _ in range(offset + 1): + parent = frame.f_back + if parent is None: + # If the offset is too large then we use the largest offset possible. + retcode = self.HEURISTIC_USED + break + frame = parent + self.filename = frame.f_code.co_filename + self.lineno = frame.f_lineno + return retcode + + def copy_metadata(self): + """Return a TraceableObject like this one, but without the object.""" + return self.__class__(None, filename=self.filename, lineno=self.lineno) + + +class TraceableStack(object): + """A stack of TraceableObjects.""" + + def __init__(self, existing_stack=None): + """Constructor. + + Args: + existing_stack: [TraceableObject, ...] If provided, this object will + set its new stack to a SHALLOW COPY of existing_stack. + """ + self._stack = existing_stack[:] if existing_stack else [] + + def push_obj(self, obj, offset=0): + """Add object to the stack and record its filename and line information. + + Args: + obj: An object to store on the stack. + offset: Integer. If 0, the caller's stack frame is used. If 1, + the caller's caller's stack frame is used. + + Returns: + TraceableObject.SUCCESS if appropriate stack information was found, + TraceableObject.HEURISTIC_USED if the stack was smaller than expected, + and TraceableObject.FAILURE if the stack was empty. + """ + traceable_obj = TraceableObject(obj) + self._stack.append(traceable_obj) + # Offset is defined in "Args" as relative to the caller. We are 1 frame + # beyond the caller and need to compensate. + return traceable_obj.set_filename_and_line_from_caller(offset + 1) + + def pop_obj(self): + """Remove last-inserted object and return it, without filename/line info.""" + return self._stack.pop().obj + + def peek_top_obj(self): + """Return the most recent stored object.""" + return self._stack[-1].obj + + def peek_objs(self): + """Return iterator over stored objects ordered newest to oldest.""" + return (t_obj.obj for t_obj in reversed(self._stack)) + + def peek_traceable_objs(self): + """Return iterator over stored TraceableObjects ordered newest to oldest.""" + return reversed(self._stack) + + def __len__(self): + """Return number of items on the stack, and used for truth-value testing.""" + return len(self._stack) + + def copy(self): + """Return a copy of self referencing the same objects but in a new list. + + This method is implemented to support thread-local stacks. + + Returns: + TraceableStack with a new list that holds existing objects. + """ + return TraceableStack(self._stack) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_spec.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..26911cdd97bc80808501ec741897bcfc7edaa2cd --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_spec.py @@ -0,0 +1,1062 @@ +# 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. +# ============================================================================== +"""Type specifications for TensorFlow APIs.""" + +import abc +import functools +from typing import Any, List, Optional, Sequence, Type +import warnings + +import numpy as np + +from tensorflow.core.function import trace_type +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.framework import tensor_shape +from tensorflow.python.platform import tf_logging as logging +# TODO(b/238903802): Remove dependency on nested_structure_coder. +from tensorflow.python.saved_model import nested_structure_coder +from tensorflow.python.types import core as core_types +from tensorflow.python.types import internal +from tensorflow.python.types import trace +from tensorflow.python.util import _pywrap_utils +from tensorflow.python.util import compat +from tensorflow.python.util import deprecation +from tensorflow.python.util import nest +from tensorflow.python.util import tf_decorator +from tensorflow.python.util.tf_export import tf_export +from tensorflow.tools.docs import doc_controls + + +_CACHED_CMP_KEY = "_cached_cmp_key" # Used by hashing and equality. +# Cache fixed, derived TypeSpec properties to avoid expensive recompute. +CACHED_FIXED_PROPERTIES = [_CACHED_CMP_KEY] + + +@tf_export("TypeSpec", v1=["TypeSpec", "data.experimental.Structure"]) +class TypeSpec( + internal.TypeSpec, + trace.TraceType, + trace_type.Serializable, + metaclass=abc.ABCMeta, +): + """Specifies a TensorFlow value type. + + A `tf.TypeSpec` provides metadata describing an object accepted or returned + by TensorFlow APIs. Concrete subclasses, such as `tf.TensorSpec` and + `tf.RaggedTensorSpec`, are used to describe different value types. + + For example, `tf.function`'s `input_signature` argument accepts a list + (or nested structure) of `TypeSpec`s. + + Creating new subclasses of `TypeSpec` (outside of TensorFlow core) is not + currently supported. In particular, we may make breaking changes to the + private methods and properties defined by this base class. + + Example: + + >>> spec = tf.TensorSpec(shape=[None, None], dtype=tf.int32) + >>> @tf.function(input_signature=[spec]) + ... def double(x): + ... return x * 2 + >>> double(tf.constant([[1, 2], [3, 4]])) + + """ + # === Subclassing === + # + # Each `TypeSpec` subclass must define: + # + # * A "component encoding" for values. + # * A "serialization" for types. + # + # The component encoding for a value is a nested structure of `tf.Tensor` + # or `CompositeTensor` that can be used by the `TypeSpec` to reconstruct + # the value. Each individual `TypeSpec` must use the same nested structure + # for all values -- this structure is defined by the `component_specs` + # attribute. Decomposing values into components, and reconstructing them + # from those components, should be inexpensive. In particular, it should + # *not* require any TensorFlow ops. + # + # The serialization for a `TypeSpec` is a nested tuple of values that can + # be used to reconstruct the `TypeSpec`. See the documentation for + # `_serialize()` for more information. + + __slots__ = CACHED_FIXED_PROPERTIES + + @abc.abstractproperty + def value_type(self): + """The Python type for values that are compatible with this TypeSpec. + + In particular, all values that are compatible with this TypeSpec must be an + instance of this type. + """ + raise NotImplementedError("%s.value_type" % type(self).__name__) + + def is_subtype_of(self, other: trace.TraceType) -> bool: + """Returns True if `self` is a subtype of `other`. + + Implements the tf.types.experimental.func.TraceType interface. + + If not overridden by a subclass, the default behavior is to assume the + TypeSpec is covariant upon attributes that implement TraceType and + invariant upon rest of the attributes as well as the structure and type + of the TypeSpec. + + Args: + other: A TraceType object. + """ + if type(self) is not type(other): + return False + + is_subtype = True + + def check_attribute(attribute_self, attribute_other): + nonlocal is_subtype + if not is_subtype: + return + + if isinstance(attribute_self, trace.TraceType): + if not attribute_self.is_subtype_of(attribute_other): + is_subtype = False + return + else: + if attribute_self != attribute_other: + is_subtype = False + + try: + # TODO(b/217959193): Replace _serialize with parameter decomposition. + nest.map_structure(check_attribute, self._serialize(), other._serialize()) # pylint: disable=protected-access + except (ValueError, TypeError): + return False + + return is_subtype + + def most_specific_common_supertype( + self, others: Sequence[trace.TraceType]) -> Optional["TypeSpec"]: + """Returns the most specific supertype TypeSpec of `self` and `others`. + + Implements the tf.types.experimental.func.TraceType interface. + + If not overridden by a subclass, the default behavior is to assume the + TypeSpec is covariant upon attributes that implement TraceType and + invariant upon rest of the attributes as well as the structure and type + of the TypeSpec. + + Args: + others: A sequence of TraceTypes. + """ + if any(type(self) is not type(other) for other in others): + return None + + has_supertype = True + + def make_supertype_attribute(attribute_self, *attribute_others): + nonlocal has_supertype + if not has_supertype: + return + + if isinstance(attribute_self, trace.TraceType): + attribute_supertype = attribute_self.most_specific_common_supertype( + attribute_others) + if attribute_supertype is None: + has_supertype = False + return + return attribute_supertype + else: + if not all(attribute_self == attribute_other + for attribute_other in attribute_others): + has_supertype = False + return + return attribute_self + + try: + # TODO(b/217959193): Replace _serialize with parameter decomposition. + serialized_supertype = nest.map_structure( + make_supertype_attribute, self._serialize(), + *(o._serialize() for o in others)) # pylint: disable=protected-access + except (ValueError, TypeError): + return None + + return self._deserialize(serialized_supertype) if has_supertype else None + + @classmethod + def experimental_type_proto(cls) -> Type[struct_pb2.TypeSpecProto]: + """Returns the type of proto associated with TypeSpec serialization. + + Do NOT override for custom non-TF types. + """ + return struct_pb2.TypeSpecProto + + @classmethod + def experimental_from_proto(cls, + proto: struct_pb2.TypeSpecProto) -> "TypeSpec": + """Returns a TypeSpec instance based on the serialized proto. + + Do NOT override for custom non-TF types. + + Args: + proto: Proto generated using 'experimental_as_proto'. + """ + return nested_structure_coder.decode_proto( + struct_pb2.StructuredValue(type_spec_value=proto)) + + def experimental_as_proto(self) -> struct_pb2.TypeSpecProto: + """Returns a proto representation of the TypeSpec instance. + + Do NOT override for custom non-TF types. + """ + return nested_structure_coder.encode_structure(self).type_spec_value + + @doc_controls.do_not_doc_inheritable + def placeholder_value(self, placeholder_context): + """Value used for tracing a function signature with this TraceType. + + WARNING: Do not override. + + Args: + placeholder_context: A class container for context information when + creating a placeholder value. + + Returns: + A `CompositeTensor` placeholder whose components are recursively composed + of placeholders themselves. + """ + if placeholder_context.unnest_only: + return self + + component_placeholders = nest.map_structure( + lambda x: x.placeholder_value(placeholder_context), + self._component_specs) + return self._from_components(component_placeholders) + + @doc_controls.do_not_doc_inheritable + def to_tensors(self, value): + """See TraceType base class for details. Do not override.""" + + tensors = [] + nest.map_structure( + lambda spec, v: tensors.extend(spec.to_tensors(v)), + self._component_specs, + self._to_components(value)) + return tensors + + @doc_controls.do_not_doc_inheritable + def from_tensors(self, tensors): + """See TraceType base class for details. Do not override.""" + components = nest.map_structure( + lambda spec: spec.from_tensors(tensors), + self._component_specs + ) + return self._from_components(components) + + @doc_controls.do_not_doc_inheritable + def flatten(self): + """See TraceType base class for details. Do not override.""" + flat = [] + nest.map_structure( + lambda spec: flat.extend(spec.flatten()), + self._component_specs) + return flat + + @doc_controls.do_not_doc_inheritable + def cast(self, value, casting_context): + """See TraceType base class for details. Do not override.""" + if casting_context.allow_specs and isinstance(value, TypeSpec): + assert value.is_subtype_of(self), f"Can not cast {value!r} to {self!r}" + return self + + did_cast = False + def cast_fn(spec, v): + casted_v = spec.cast(v, casting_context) + if casted_v is not v: + nonlocal did_cast + did_cast = True + return casted_v + + cast_components = nest.map_structure( + cast_fn, self._component_specs, self._to_components(value) + ) + + if did_cast: + return self._from_components(cast_components) + else: + return value + + # TODO(b/225058047): Reconsider semantics. + def is_compatible_with(self, spec_or_value): + """Returns true if `spec_or_value` is compatible with this TypeSpec. + + Prefer using "is_subtype_of" and "most_specific_common_supertype" wherever + possible. + + Args: + spec_or_value: A TypeSpec or TypeSpec associated value to compare against. + """ + # === Subclassing === + # If not overridden by subclasses, the default behavior is to convert + # `spec_or_value` to a `TypeSpec` (if it isn't already); and then to + # consider two `TypeSpec`s compatible if they have the same type, and + # the values returned by `_serialize` are compatible (where + # `tf.TensorShape`, `tf.TensorSpec`, and `tf.DType` are checked for + # compatibility using their `is_compatible_with` method; and all other + # types are considered compatible if they are equal). + if not isinstance(spec_or_value, TypeSpec): + spec_or_value = type_spec_from_value(spec_or_value) + if type(self) is not type(spec_or_value): + return False + return self.__is_compatible(self._serialize(), spec_or_value._serialize()) # pylint: disable=protected-access + + @deprecation.deprecated(None, "Use most_specific_common_supertype instead.") + def most_specific_compatible_type(self, other: "TypeSpec") -> "TypeSpec": + """Returns the most specific TypeSpec compatible with `self` and `other`. + + Deprecated. Please use `most_specific_common_supertype` instead. + Do not override this function. + + Args: + other: A `TypeSpec`. + + Raises: + ValueError: If there is no TypeSpec that is compatible with both `self` + and `other`. + """ + result = self.most_specific_common_supertype([other]) + if result is None: + raise ValueError("No TypeSpec is compatible with both %s and %s" % + (self, other)) + return result + + # TODO(b/226395276): Delete after removing usages. + def _with_tensor_ranks_only(self) -> "TypeSpec": + """Returns a TypeSpec compatible with `self`, with tensor shapes relaxed. + + Returns: + A `TypeSpec` that is compatible with `self`, where any `TensorShape` + information has been relaxed to include only tensor rank (and not + the dimension sizes for individual axes). + """ + + # === Subclassing === + # If not overridden by a subclass, the default behavior is to serialize + # this TypeSpec, relax any TensorSpec or TensorShape values, and + # deserialize the result. + + def relax(value): + if isinstance(value, TypeSpec): + return value._with_tensor_ranks_only() # pylint: disable=protected-access + elif (isinstance(value, tensor_shape.TensorShape) and + value.rank is not None): + return tensor_shape.TensorShape([None] * value.rank) + else: + return value + + return self._deserialize(nest.map_structure(relax, self._serialize())) + + # TODO(b/206014848): Helper function to support logic that does not consider + # Tensor name. Will be removed once load-bearing usages of Tensor name are + # fixed. + def _without_tensor_names(self) -> "TypeSpec": + """Returns a TypeSpec compatible with `self`, with tensor names removed. + + Returns: + A `TypeSpec` that is compatible with `self`, where the name of any + `TensorSpec` is set to `None`. + """ + + # === Subclassing === + # If not overridden by a subclass, the default behavior is to serialize + # this TypeSpec, set the TensorSpecs' names to None, and deserialize the + # result. + + def rename(value): + if isinstance(value, TypeSpec): + return value._without_tensor_names() # pylint: disable=protected-access + return value + + return self._deserialize(nest.map_structure(rename, self._serialize())) + + # === Component encoding for values === + + @abc.abstractmethod + def _to_components(self, value): + """Encodes `value` as a nested structure of `Tensor` or `CompositeTensor`. + + Args: + value: A value compatible with this `TypeSpec`. (Caller is responsible + for ensuring compatibility.) + + Returns: + A nested structure of `tf.Tensor` or `tf.CompositeTensor` compatible with + `self._component_specs`, which can be used to reconstruct `value`. + """ + # === Subclassing === + # This method must be inexpensive (do not call TF ops). + raise NotImplementedError("%s._to_components()" % type(self).__name__) + + @abc.abstractmethod + def _from_components(self, components): + """Reconstructs a value from a nested structure of Tensor/CompositeTensor. + + Args: + components: A nested structure of `tf.Tensor` or `tf.CompositeTensor`, + compatible with `self._component_specs`. (Caller is responsible for + ensuring compatibility.) + + Returns: + A value that is compatible with this `TypeSpec`. + """ + # === Subclassing === + # This method must be inexpensive (do not call TF ops). + raise NotImplementedError("%s._from_components()" % type(self).__name__) + + @abc.abstractproperty + def _component_specs(self): + """A nested structure of TypeSpecs for this type's components. + + Returns: + A nested structure describing the component encodings that are returned + by this TypeSpec's `_to_components` method. In particular, for a + TypeSpec `spec` and a compatible value `value`: + + ``` + nest.map_structure(lambda t, c: assert t.is_compatible_with(c), + spec._component_specs, spec._to_components(value)) + ``` + """ + raise NotImplementedError("%s._component_specs()" % type(self).__name__) + + # === Tensor list encoding for values === + + def _to_tensor_list(self, value) -> List["core_types.Symbol"]: + """Encodes `value` as a flat list of `tf.Tensor`. + + By default, this just flattens `self._to_components(value)` using + `nest.flatten`. However, subclasses may override this to return a + different tensor encoding for values. In particular, some subclasses + of `BatchableTypeSpec` override this method to return a "boxed" encoding + for values, which then can be batched or unbatched. See + `BatchableTypeSpec` for more details. + + Args: + value: A value with compatible this `TypeSpec`. (Caller is responsible + for ensuring compatibility.) + + Returns: + A list of `tf.Tensor`, compatible with `self._flat_tensor_specs`, which + can be used to reconstruct `value`. + """ + return nest.flatten(self._to_components(value), expand_composites=True) + + def _from_tensor_list(self, tensor_list: List["core_types.Symbol"]) -> Any: + """Reconstructs a value from a flat list of `tf.Tensor`. + + Args: + tensor_list: A flat list of `tf.Tensor`, compatible with + `self._flat_tensor_specs`. + + Returns: + A value that is compatible with this `TypeSpec`. + + Raises: + ValueError: If `tensor_list` is not compatible with + `self._flat_tensor_specs`. + """ + self.__check_tensor_list(tensor_list) + return self._from_compatible_tensor_list(tensor_list) + + def _from_compatible_tensor_list( + self, tensor_list: List["core_types.Symbol"]) -> Any: + """Reconstructs a value from a compatible flat list of `tf.Tensor`. + + Args: + tensor_list: A flat list of `tf.Tensor`, compatible with + `self._flat_tensor_specs`. (Caller is responsible for ensuring + compatibility.) + + Returns: + A value that is compatible with this `TypeSpec`. + """ + return self._from_components( + nest.pack_sequence_as( + self._component_specs, tensor_list, expand_composites=True)) + + @property + def _flat_tensor_specs(self): + """A list of TensorSpecs compatible with self._to_tensor_list(v).""" + return nest.flatten(self._component_specs, expand_composites=True) + + # === Serialization for types === + + @abc.abstractmethod + def _serialize(self): + """Returns a nested tuple containing the state of this TypeSpec. + + The serialization may contain the following value types: boolean, + integer, string, float, None, `TensorSpec`, `tf.TensorShape`, `tf.DType`, + `np.ndarray`, `TypeSpec`, and nested tuples, namedtuples, dicts, and + OrderedDicts of any of the above. + + This method is used to provide default definitions for: equality + testing (__eq__, __ne__), hashing (__hash__), pickling (__reduce__), + string representation (__repr__), `self.is_compatible_with()`, + `self.most_specific_compatible_type()`, and protobuf serialization + (e.g. TensorInfo and StructuredValue). + """ + raise NotImplementedError("%s._serialize()" % type(self).__name__) + + @classmethod + def _deserialize(cls, serialization): + """Reconstructs a TypeSpec from a value returned by `serialize`. + + Args: + serialization: A value returned by _serialize. In some contexts, + `namedtuple`s in `serialization` may not have the identical type that + was returned by `_serialize` (but its type will still be a `namedtuple` + type with the same type name and field names). For example, the code + that loads a SavedModel does not have access to the original + `namedtuple` type, so it dynamically creates a new `namedtuple` type + with the same type name and field names as the original one. If + necessary, you can check `serialization` for these duck-typed + `nametuple` types, and restore them to the original type. (E.g., this + would be necessary if you rely on type checks such as `isinstance` for + this `TypeSpec`'s member variables). + + Returns: + A `TypeSpec` of type `cls`. + """ + return cls(*serialization) # pytype: disable=not-instantiable # trace-all-classes + + # === Operators === + + def __eq__(self, other) -> bool: + # pylint: disable=protected-access + return (type(other) is type(self) and + self.__get_cmp_key() == other.__get_cmp_key()) + + def __ne__(self, other) -> bool: + return not self == other + + def __hash__(self) -> int: + return hash(self.__get_cmp_key()) + + def __reduce__(self): + return type(self), self._serialize() + + def __repr__(self) -> str: + return "%s%r" % (type(self).__name__, self._serialize()) + + # === Legacy Output === + # TODO(b/133606651) Document and/or deprecate the legacy_output methods. + # (These are used by tf.data.) + + def _to_legacy_output_types(self): + raise NotImplementedError("%s._to_legacy_output_types()" % + type(self).__name__) + + def _to_legacy_output_shapes(self): + raise NotImplementedError("%s._to_legacy_output_shapes()" % + type(self).__name__) + + def _to_legacy_output_classes(self): + return self.value_type + + # === Private Helper Methods === + + # TODO(b/154541175): Currently this usage is used to represent a Tensor + # argument not a TensorSpec argument as it should be. + def __tf_tracing_type__(self, + context: trace.TracingContext) -> trace.TraceType: + return self + + def __check_tensor_list(self, tensor_list): + """Raises an exception if tensor_list incompatible w/ flat_tensor_specs.""" + expected = self._flat_tensor_specs + specs = [type_spec_from_value(t) for t in tensor_list] + if len(specs) != len(expected): + raise ValueError(f"Cannot create a {self.value_type.__name__} from the " + f"tensor list because the TypeSpec expects " + f"{len(expected)} items, but the provided tensor list " + f"has {len(specs)} items.") + for i, (s1, s2) in enumerate(zip(specs, expected)): + if not s1.is_compatible_with(s2): + raise ValueError(f"Cannot create a {self.value_type.__name__} from the " + f"tensor list because item {i} ({tensor_list[i]!r}) " + f"is incompatible with the expected TypeSpec {s2}.") + + def __get_cmp_key(self): + """Returns a hashable eq-comparable key for `self`.""" + if not hasattr(self, _CACHED_CMP_KEY): + setattr(self, _CACHED_CMP_KEY, ( + type(self), + self.__make_cmp_key(self._serialize()), + )) + return getattr(self, _CACHED_CMP_KEY) + + def __make_cmp_key(self, value): + """Converts `value` to a hashable key.""" + if isinstance(value, (int, float, bool, np.generic, dtypes.DType, TypeSpec, + tensor_shape.TensorShape)): + return value + if isinstance(value, compat.bytes_or_text_types): + return value + if value is None: + return value + if isinstance(value, dict): + return tuple([ + tuple([self.__make_cmp_key(key), + self.__make_cmp_key(value[key])]) + for key in sorted(value.keys()) + ]) + if isinstance(value, tuple): + return tuple([self.__make_cmp_key(v) for v in value]) + if isinstance(value, list): + return (list, tuple([self.__make_cmp_key(v) for v in value])) + if isinstance(value, np.ndarray): + return (np.ndarray, value.shape, + TypeSpec.__nested_list_to_tuple(value.tolist())) + raise ValueError(f"Cannot generate a hashable key for {self} because " + f"the _serialize() method " + f"returned an unsupproted value of type {type(value)}") + + @staticmethod + def __nested_list_to_tuple(value): + """Converts a nested list to a corresponding nested tuple.""" + if isinstance(value, list): + return tuple(TypeSpec.__nested_list_to_tuple(v) for v in value) + return value + + @staticmethod + def __same_types(a, b): + """Returns whether a and b have the same type, up to namedtuple equivalence. + + Consistent with tf.nest.assert_same_structure(), two namedtuple types + are considered the same iff they agree in their class name (without + qualification by module name) and in their sequence of field names. + This makes namedtuples recreated by nested_structure_coder compatible with + their original Python definition. + + Args: + a: a Python object. + b: a Python object. + + Returns: + A boolean that is true iff type(a) and type(b) are the same object + or equivalent namedtuple types. + """ + if nest.is_namedtuple(a) and nest.is_namedtuple(b): + return nest.same_namedtuples(a, b) + else: + return type(a) is type(b) + + @staticmethod + def __is_compatible(a, b): + """Returns true if the given type serializations compatible.""" + if isinstance(a, TypeSpec): + return a.is_compatible_with(b) + if not TypeSpec.__same_types(a, b): + return False + if isinstance(a, (list, tuple)): + return (len(a) == len(b) and + all(TypeSpec.__is_compatible(x, y) for (x, y) in zip(a, b))) + if isinstance(a, dict): + return (len(a) == len(b) and sorted(a.keys()) == sorted(b.keys()) and + all(TypeSpec.__is_compatible(a[k], b[k]) for k in a.keys())) + if isinstance(a, (tensor_shape.TensorShape, dtypes.DType)): + return a.is_compatible_with(b) + return a == b + +trace_type.register_serializable(TypeSpec) + + +class TypeSpecBatchEncoder(object, metaclass=abc.ABCMeta): + """Class used to encode and decode composite tensor values for batching. + + In order to be batched and unbatched by APIs such as `tf.data.Dataset` and + `tf.map_fn`, composite tensors must be encoded using flat tensors that can + themselves be batched or unbatched. `TypeSpecBatchEncoder`s are + responsible for implementing this encoding. + + If a composite tensor's shape is a prefix of the shape of all of its + component tensors, then this encoding can usually be performed by just + returning those component tensors as a list. But if the composite tensor + has components whose shape has a more complex relationship to the shape + of the composite tensor, then a custom `TypeSpecBatchEncoder` may + need to be implemented. + """ + + @abc.abstractmethod + def batch(self, spec, batch_size): + """Returns the TypeSpec representing a batch of values described by `spec`. + + Args: + spec: The `TypeSpec` for an individual value. + batch_size: An `int` indicating the number of values that are batched + together, or `None` if the batch size is not known. + + Returns: + A `TypeSpec` for a batch of values. + """ + raise NotImplementedError(f"{type(self).__name__}.batch") + + @abc.abstractmethod + def unbatch(self, spec): + """Returns the TypeSpec for a single unbatched element in `spec`. + + Args: + spec: The `TypeSpec` for a batch of values. + + Returns: + A `TypeSpec` for an individual value. + """ + raise NotImplementedError(f"{type(self).__name__}.unbatch") + + @abc.abstractmethod + def encode(self, spec, value, minimum_rank=0): + """Encodes `value` as a nest of batchable `Tensor` or `CompositeTensor`. + + Args: + spec: The TypeSpec of the value to encode. + value: A value compatible with `spec`. + minimum_rank: The minimum rank for the returned Tensors, CompositeTensors, + and ExtensionType values. This can be used to ensure that the encoded + values can be unbatched this number of times. If `minimum_rank>0`, + then `t.shape[:minimum_rank]` must be compatible for all values `t` + returned by `encode`. + + Returns: + A nest (as defined by `tf.nest`) of `tf.Tensor`s, batchable + `tf.CompositeTensor`s, or `tf.ExtensionType`s. Stacking, unstacking, or + concatenating these encoded values and then decoding the result must be + equivalent to stacking, unstacking, or concatenating the original values. + """ + raise NotImplementedError(f"{type(self).__name__}.encode") + + @abc.abstractmethod + def decode(self, spec, encoded_value): + """Decodes `value` from a batchable tensor encoding. + + Args: + spec: The TypeSpec for the result value. If encoded values with spec `s` + were batched, then `spec` should be `s.batch(batch_size)`; or if encoded + values with spec `s` were unbatched, then `spec` should be + `s.unbatch()`. + encoded_value: A nest of values returned by `encode`; or a nest of values + that was formed by stacking, unstacking, or concatenating the + corresponding elements of values returned by `encode`. + + Returns: + A value compatible with `type_spec`. + """ + raise NotImplementedError(f"{type(self).__name__}.decode") + + @abc.abstractmethod + def encoding_specs(self, spec): + """Returns a nest of `TypeSpec`(s) describing the encoding for `spec`. + + Args: + spec: The TypeSpec whose encoding should be described. + + Returns: + A nest (as defined by `tf.nest) of `tf.TypeSpec`, describing the values + that are returned by `self.encode(spec, ...)`. All TypeSpecs in this + nest must be batchable. + """ + raise NotImplementedError(f"{type(self).__name__}.encoding_specs") + + +class LegacyTypeSpecBatchEncoder(TypeSpecBatchEncoder): + """TypeSpecBatchEncoder for legacy composite tensor classes. + + TODO(edloper): Update existing composite tensors to use non-legacy + CompositTensorBatchEncoders. + """ + + def batch(self, type_spec, batch_size): + return type_spec._batch(batch_size) # pylint: disable=protected-access + + def unbatch(self, type_spec): + return type_spec._unbatch() # pylint: disable=protected-access + + def encode(self, type_spec, value, minimum_rank=0): + if minimum_rank == 0: + return type_spec._to_tensor_list(value) # pylint: disable=protected-access + elif minimum_rank == 1: + if not isinstance(type_spec, BatchableTypeSpec): + raise ValueError(f"{type_spec.__name__}.encode does not support " + "minimum_rank>0.") + return type_spec._to_batched_tensor_list(value) # pylint: disable=protected-access + else: + raise ValueError(f"{type_spec.__name__}.encode does not support " + "minimum_rank>1.") + + def decode(self, type_spec, encoded_value): + return type_spec._from_tensor_list(encoded_value) # pylint: disable=protected-access + + def encoding_specs(self, spec): + return spec._flat_tensor_specs # pylint: disable=protected-access + + +class BatchableTypeSpec(TypeSpec, metaclass=abc.ABCMeta): + """TypeSpec with a batchable tensor encoding. + + The batchable tensor encoding is a list of `tf.Tensor`s that supports + batching and unbatching. In particular, stacking (or unstacking) + values with the same `TypeSpec` must be equivalent to stacking (or + unstacking) each of their tensor lists. Unlike the component encoding + (returned by `self._to_components)`, the batchable tensor encoding + may require using encoding/decoding ops. + + If a subclass's batchable tensor encoding is not simply a flattened version + of the component encoding, then the subclass must override `_to_tensor_list`, + `_from_tensor_list`, and _flat_tensor_specs`. + """ + + __slots__ = [] + + __batch_encoder__ = LegacyTypeSpecBatchEncoder() + + @abc.abstractmethod + def _batch(self, batch_size) -> TypeSpec: + """Returns a TypeSpec representing a batch of objects with this TypeSpec. + + Args: + batch_size: An `int` representing the number of elements in a batch, or + `None` if the batch size may vary. + + Returns: + A `TypeSpec` representing a batch of objects with this TypeSpec. + """ + raise NotImplementedError(f"{type(self).__name__}._batch") + + @abc.abstractmethod + def _unbatch(self) -> TypeSpec: + """Returns a TypeSpec representing a single element this TypeSpec. + + Returns: + A `TypeSpec` representing a single element of objects with this TypeSpec. + """ + raise NotImplementedError(f"{type(self).__name__}._unbatch") + +# LINT.IfChange + @property + def _flat_tensor_specs(self) -> List[TypeSpec]: + """A list of TensorSpecs compatible with self._to_tensor_list(v).""" + component_flat_tensor_specs = nest.map_structure( + functools.partial(get_batchable_flat_tensor_specs, context_spec=self), + self._component_specs) + return nest.flatten(component_flat_tensor_specs) +# LINT.ThenChange(//tensorflow/python/framework/type_utils.py:_specs_for_flat_tensors) +# Note that _specs_for_flat_tensors in type_utils.py must correspond +# _flat_tensor_specs in this class and any derived classes. + + def _to_tensor_list( + self, value: composite_tensor.CompositeTensor + ) -> List["core_types.Symbol"]: + """Encodes `value` as a flat list of `core.Symbol`.""" + component_tensor_lists = nest.map_structure(batchable_to_tensor_list, + self._component_specs, + self._to_components(value)) + return nest.flatten(component_tensor_lists) + + def _to_batched_tensor_list( + self, value: composite_tensor.CompositeTensor + ) -> List["core_types.Symbol"]: + """Encodes `value` as a flat list of `core.Symbol` each with rank>0.""" + get_spec_tensor_list = lambda spec, v: ( # pylint: disable=g-long-lambda + batchable_to_tensor_list(spec, v, minimum_rank=1) + if isinstance(spec, BatchableTypeSpec) else spec._to_tensor_list(v)) # pylint: disable=protected-access + component_batched_tensor_lists = nest.map_structure( + get_spec_tensor_list, self._component_specs, self._to_components(value)) + tensor_list = nest.flatten(component_batched_tensor_lists) + if any(t.shape.ndims == 0 for t in tensor_list): + raise ValueError( + f"While converting {value} to a list of tensors for batching, " + f"found a scalar item which cannot be batched.") + return tensor_list + + def _from_compatible_tensor_list( + self, + tensor_list: List["core_types.Symbol"] + ) -> composite_tensor.CompositeTensor: + """Reconstructs a value from a compatible flat list of `core.Symbol`.""" + flat_specs = nest.map_structure( + functools.partial(get_batchable_flat_tensor_specs, context_spec=self), + self._component_specs) + nested_tensor_list = nest.pack_sequence_as(flat_specs, tensor_list) + components = nest.map_structure_up_to(self._component_specs, + batchable_from_tensor_list, + self._component_specs, + nested_tensor_list) + return self._from_components(components) + + +def get_batchable_flat_tensor_specs(spec, context_spec=None): + """Returns the flat tensor specs for `spec`.""" + if isinstance(spec, internal.TensorSpec): + return [spec] + elif hasattr(spec, "__batch_encoder__"): + encoding_specs = nest.map_structure( + functools.partial( + get_batchable_flat_tensor_specs, context_spec=context_spec), + spec.__batch_encoder__.encoding_specs(spec)) + return nest.flatten(encoding_specs) + else: + # TODO(edloper) Fix existing CompositeTensors that permit this, and + # then turn this warning into an error. + warnings.warn(f"Batchable type {context_spec} contains non-batchable " + f"field or component with type {spec}.") + return spec._flat_tensor_specs # pylint: disable=protected-access + + +def batchable_to_tensor_list(spec, value, minimum_rank=0): + """Returns a list of tensors encoding `value`, whose type is `spec`.""" + if isinstance(spec, internal.TensorSpec): + return [value] + elif hasattr(spec, "__batch_encoder__"): + encoded_value = spec.__batch_encoder__.encode(spec, value, minimum_rank) + encoded_specs = spec.__batch_encoder__.encoding_specs(spec) + encoded_flats = nest.map_structure( + functools.partial(batchable_to_tensor_list, minimum_rank=minimum_rank), + encoded_specs, encoded_value) + return nest.flatten(encoded_flats) + else: + return spec._to_tensor_list(value) # pylint: disable=protected-access + + +def batchable_from_tensor_list(spec, tensor_list): + """Returns a value with type `spec` decoded from `tensor_list`.""" + if isinstance(spec, internal.TensorSpec): + assert len(tensor_list) == 1 + return tensor_list[0] + elif hasattr(spec, "__batch_encoder__"): + encoded_specs = spec.__batch_encoder__.encoding_specs(spec) + flat_specs = nest.map_structure(get_batchable_flat_tensor_specs, + encoded_specs) + encoded_flats = nest.pack_sequence_as(flat_specs, tensor_list) + encoded_value = nest.map_structure_up_to(encoded_specs, + batchable_from_tensor_list, + encoded_specs, encoded_flats) + return spec.__batch_encoder__.decode(spec, encoded_value) + else: + return spec._from_compatible_tensor_list(tensor_list) # pylint: disable=protected-access + + +@tf_export("type_spec_from_value") +def type_spec_from_value(value) -> TypeSpec: + """Returns a `tf.TypeSpec` that represents the given `value`. + + Examples: + + >>> tf.type_spec_from_value(tf.constant([1, 2, 3])) + TensorSpec(shape=(3,), dtype=tf.int32, name=None) + >>> tf.type_spec_from_value(np.array([4.0, 5.0], np.float64)) + TensorSpec(shape=(2,), dtype=tf.float64, name=None) + >>> tf.type_spec_from_value(tf.ragged.constant([[1, 2], [3, 4, 5]])) + RaggedTensorSpec(TensorShape([2, None]), tf.int32, 1, tf.int64) + + >>> example_input = tf.ragged.constant([[1, 2], [3]]) + >>> @tf.function(input_signature=[tf.type_spec_from_value(example_input)]) + ... def f(x): + ... return tf.reduce_sum(x, axis=1) + + Args: + value: A value that can be accepted or returned by TensorFlow APIs. Accepted + types for `value` include `tf.Tensor`, any value that can be converted to + `tf.Tensor` using `tf.convert_to_tensor`, and any subclass of + `CompositeTensor` (such as `tf.RaggedTensor`). + + Returns: + A `TypeSpec` that is compatible with `value`. + + Raises: + TypeError: If a TypeSpec cannot be built for `value`, because its type + is not supported. + """ + spec = _type_spec_from_value(value) + if spec is not None: + return spec + + # Fallback: try converting value to a tensor. + try: + tensor = tensor_conversion_registry.convert(value) + spec = _type_spec_from_value(tensor) + if spec is not None: + return spec + except (ValueError, TypeError) as e: + logging.vlog( + 3, "Failed to convert %r to tensor: %s" % (type(value).__name__, e)) + + raise TypeError(f"Could not build a TypeSpec for {value} of " + f"unsupported type {type(value)}.") + + +def _type_spec_from_value(value) -> TypeSpec: + """Returns a `TypeSpec` that represents the given `value`.""" + if isinstance(value, core_types.Symbol): + # Note: we do not include Tensor names when constructing TypeSpecs. + return trace_type.from_value(value) + + if isinstance(value, composite_tensor.CompositeTensor): + return value._type_spec # pylint: disable=protected-access + + # If `value` is a list and all of its elements can be represented by the same + # batchable type spec, then we can represent the entire list using a single + # type spec that captures the type accurately (unlike the `convert_to_tensor` + # fallback). + if isinstance(value, list) and value: + subspecs = [_type_spec_from_value(v) for v in value] + if isinstance(subspecs[0], BatchableTypeSpec): + merged_subspec = subspecs[0].most_specific_common_supertype(subspecs[1:]) + if merged_subspec is not None: + return merged_subspec._batch(len(subspecs)) # pylint: disable=protected-access + + for entry in reversed(_TYPE_CONVERSION_FUNCTION_REGISTRY): + type_object, converter_fn, allow_subclass = entry + if ((type(value) is type_object) or # pylint: disable=unidiomatic-typecheck + (allow_subclass and isinstance(value, type_object))): + return converter_fn(value) + + return None + + +_TYPE_CONVERSION_FUNCTION_REGISTRY = [] + + +def register_type_spec_from_value_converter(type_object, + converter_fn, + allow_subclass=False): + """Registers a function for converting values with a given type to TypeSpecs. + + If multiple registered `type_object`s match a value, then the most recent + registration takes precedence. Custom converters should not be defined for + `CompositeTensor`s; use `CompositeTensor._type_spec` instead. + + Args: + type_object: A Python `type` object representing the type of values accepted + by `converter_fn`. + converter_fn: A function that takes one argument (an instance of the type + represented by `type_object`) and returns a `TypeSpec`. + allow_subclass: If true, then use `isinstance(value, type_object)` to check + for matches. If false, then use `type(value) is type_object`. + """ + _, type_object = tf_decorator.unwrap(type_object) + _TYPE_CONVERSION_FUNCTION_REGISTRY.append( + (type_object, converter_fn, allow_subclass)) + + +_pywrap_utils.RegisterType("TypeSpec", TypeSpec) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_spec_registry.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_spec_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..e67a5b7b0178034c9e5d46f5bea6e165e19a884f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_spec_registry.py @@ -0,0 +1,87 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Registry for custom TypeSpecs.""" + +import re + +from tensorflow.python.types import internal + + +_TYPE_SPEC_TO_NAME = {} +_NAME_TO_TYPE_SPEC = {} + +# Regular expression for valid TypeSpec names. +_REGISTERED_NAME_RE = re.compile(r"^(\w+\.)+\w+$") + + +# TODO(b/173744905) tf_export this as "tf.register_type_spec". (And add a +# usage example to the docstring, once the API is public.) +# +# TODO(b/173744905) Update this decorator to apply to ExtensionType rather than +# TypeSpec (once we do refactoring to move to_components/from_components from +# TypeSpec to ExtensionType). +def register(name): + """Decorator used to register a globally unique name for a TypeSpec subclass. + + Args: + name: The name of the type spec. Must be globally unique. Must have the + form `"{project_name}.{type_name}"`. E.g. `"my_project.MyTypeSpec"`. + + Returns: + A class decorator that registers the decorated class with the given name. + """ + if not isinstance(name, str): + raise TypeError("Expected `name` to be a string; got %r" % (name,)) + if not _REGISTERED_NAME_RE.match(name): + raise ValueError( + "Registered name must have the form '{project_name}.{type_name}' " + "(e.g. 'my_project.MyTypeSpec'); got %r." % name) + + def decorator_fn(cls): + if not (isinstance(cls, type) and issubclass(cls, internal.TypeSpec)): + raise TypeError("Expected `cls` to be a TypeSpec; got %r" % (cls,)) + if cls in _TYPE_SPEC_TO_NAME: + raise ValueError("Class %s.%s has already been registered with name %s." % + (cls.__module__, cls.__name__, _TYPE_SPEC_TO_NAME[cls])) + if name in _NAME_TO_TYPE_SPEC: + raise ValueError("Name %s has already been registered for class %s.%s." % + (name, _NAME_TO_TYPE_SPEC[name].__module__, + _NAME_TO_TYPE_SPEC[name].__name__)) + _TYPE_SPEC_TO_NAME[cls] = name + _NAME_TO_TYPE_SPEC[name] = cls + return cls + + return decorator_fn + + +# TODO(edloper) tf_export this as "tf.get_type_spec_name" (or some similar name) +def get_name(cls): + """Returns the registered name for TypeSpec `cls`.""" + if not (isinstance(cls, type) and issubclass(cls, internal.TypeSpec)): + raise TypeError("Expected `cls` to be a TypeSpec; got %r" % (cls,)) + if cls not in _TYPE_SPEC_TO_NAME: + raise ValueError("TypeSpec %s.%s has not been registered." % + (cls.__module__, cls.__name__)) + return _TYPE_SPEC_TO_NAME[cls] + + +# TODO(edloper) tf_export this as "tf.lookup_type_spec" (or some similar name) +def lookup(name): + """Returns the TypeSpec that has been registered with name `name`.""" + if not isinstance(name, str): + raise TypeError("Expected `name` to be a string; got %r" % (name,)) + if name not in _NAME_TO_TYPE_SPEC: + raise ValueError("No TypeSpec has been registered with name %r" % (name,)) + return _NAME_TO_TYPE_SPEC[name] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_utils.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0eebdae2be9800651bd6478c98f1fc1e88888bc3 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/type_utils.py @@ -0,0 +1,194 @@ +# 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. +# ============================================================================== +"""Utility functions for types information, incuding full type information.""" + +from typing import List + +from tensorflow.core.framework import full_type_pb2 +from tensorflow.core.framework import types_pb2 +from tensorflow.python.framework import type_spec +from tensorflow.python.ops.ragged.ragged_tensor import RaggedTensorSpec +from tensorflow.python.ops.structured.structured_tensor import StructuredTensor +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest + +# TODO(b/226455884) A python binding for DT_TO_FT or map_dtype_to_tensor() from +# tensorflow/core/framework/types.cc to avoid duplication here +_DT_TO_FT = { + types_pb2.DT_FLOAT: full_type_pb2.TFT_FLOAT, + types_pb2.DT_DOUBLE: full_type_pb2.TFT_DOUBLE, + types_pb2.DT_INT32: full_type_pb2.TFT_INT32, + types_pb2.DT_UINT8: full_type_pb2.TFT_UINT8, + types_pb2.DT_INT16: full_type_pb2.TFT_INT16, + types_pb2.DT_INT8: full_type_pb2.TFT_INT8, + types_pb2.DT_STRING: full_type_pb2.TFT_STRING, + types_pb2.DT_COMPLEX64: full_type_pb2.TFT_COMPLEX64, + types_pb2.DT_INT64: full_type_pb2.TFT_INT64, + types_pb2.DT_BOOL: full_type_pb2.TFT_BOOL, + types_pb2.DT_UINT16: full_type_pb2.TFT_UINT16, + types_pb2.DT_COMPLEX128: full_type_pb2.TFT_COMPLEX128, + types_pb2.DT_HALF: full_type_pb2.TFT_HALF, + types_pb2.DT_UINT32: full_type_pb2.TFT_UINT32, + types_pb2.DT_UINT64: full_type_pb2.TFT_UINT64, + types_pb2.DT_VARIANT: full_type_pb2.TFT_LEGACY_VARIANT, +} + + +def _translate_to_fulltype_for_flat_tensors( + spec: type_spec.TypeSpec) -> List[full_type_pb2.FullTypeDef]: + """Convert a TypeSec to a list of FullTypeDef. + + The FullTypeDef created corresponds to the encoding used with datasets + (and map_fn) that uses variants (and not FullTypeDef corresponding to the + default "component" encoding). + + Currently, the only use of this is for information about the contents of + ragged tensors, so only ragged tensors return useful full type information + and other types return TFT_UNSET. While this could be improved in the future, + this function is intended for temporary use and expected to be removed + when type inference support is sufficient. + + Args: + spec: A TypeSpec for one element of a dataset or map_fn. + + Returns: + A list of FullTypeDef corresponding to SPEC. The length of this list + is always the same as the length of spec._flat_tensor_specs. + """ + if isinstance(spec, RaggedTensorSpec): + dt = spec.dtype + elem_t = _DT_TO_FT.get(dt) + if elem_t is None: + logging.vlog(1, "dtype %s that has no conversion to fulltype.", dt) + elif elem_t == full_type_pb2.TFT_LEGACY_VARIANT: + logging.vlog(1, "Ragged tensors containing variants are not supported.", + dt) + else: + assert len(spec._flat_tensor_specs) == 1 # pylint: disable=protected-access + return [ + full_type_pb2.FullTypeDef( + type_id=full_type_pb2.TFT_RAGGED, + args=[full_type_pb2.FullTypeDef(type_id=elem_t)]) + ] + return [ + full_type_pb2.FullTypeDef(type_id=full_type_pb2.TFT_UNSET) + for t in spec._flat_tensor_specs # pylint: disable=protected-access + ] + + +# LINT.IfChange(_specs_for_flat_tensors) +def _specs_for_flat_tensors(element_spec): + """Return a flat list of type specs for element_spec. + + Note that "flat" in this function and in `_flat_tensor_specs` is a nickname + for the "batchable tensor list" encoding used by datasets and map_fn + internally (in C++/graphs). The ability to batch, unbatch and change + batch size is one important characteristic of this encoding. A second + important characteristic is that it represets a ragged tensor or sparse + tensor as a single tensor of type variant (and this encoding uses special + ops to encode/decode to/from variants). + + (In constrast, the more typical encoding, e.g. the C++/graph + representation when calling a tf.function, is "component encoding" which + represents sparse and ragged tensors as multiple dense tensors and does + not use variants or special ops for encoding/decoding.) + + Args: + element_spec: A nest of TypeSpec describing the elements of a dataset (or + map_fn). + + Returns: + A non-nested list of TypeSpec used by the encoding of tensors by + datasets and map_fn for ELEMENT_SPEC. The items + in this list correspond to the items in `_flat_tensor_specs`. + """ + if isinstance(element_spec, StructuredTensor.Spec): + specs = [] + for _, field_spec in sorted( + element_spec._field_specs.items(), key=lambda t: t[0]): # pylint: disable=protected-access + specs.extend(_specs_for_flat_tensors(field_spec)) + elif isinstance(element_spec, type_spec.BatchableTypeSpec) and ( + element_spec.__class__._flat_tensor_specs is # pylint: disable=protected-access + type_spec.BatchableTypeSpec._flat_tensor_specs): # pylint: disable=protected-access + # Classes which use the default `_flat_tensor_specs` from + # `BatchableTypeSpec` case (i.e. a derived class does not override + # `_flat_tensor_specs`.) are encoded using `component_specs`. + specs = nest.flatten( + element_spec._component_specs, # pylint: disable=protected-access + expand_composites=False) + else: + # In addition flatting any nesting in Python, + # this default case covers things that are encoded by one tensor, + # such as dense tensors which are unchanged by encoding and + # ragged tensors and sparse tensors which are encoded by a variant tensor. + specs = nest.flatten(element_spec, expand_composites=False) + return specs +# LINT.ThenChange() +# Note that _specs_for_flat_tensors must correspond to _flat_tensor_specs + + +def fulltypes_for_flat_tensors(element_spec): + """Convert the element_spec for a dataset to a list of FullType Def. + + Note that "flat" in this function and in `_flat_tensor_specs` is a nickname + for the "batchable tensor list" encoding used by datasets and map_fn. + The FullTypeDef created corresponds to this encoding (e.g. that uses variants + and not the FullTypeDef corresponding to the default "component" encoding). + + This is intended for temporary internal use and expected to be removed + when type inference support is sufficient. See limitations of + `_translate_to_fulltype_for_flat_tensors`. + + Args: + element_spec: A nest of TypeSpec describing the elements of a dataset (or + map_fn). + + Returns: + A list of FullTypeDef correspoinding to ELEMENT_SPEC. The items + in this list correspond to the items in `_flat_tensor_specs`. + """ + specs = _specs_for_flat_tensors(element_spec) + full_types_lists = [_translate_to_fulltype_for_flat_tensors(s) for s in specs] + rval = nest.flatten(full_types_lists) # flattens list-of-list to flat list. + return rval + + +def fulltype_list_to_product(fulltype_list): + """Convert a list of FullType Def into a single FullType Def.""" + return full_type_pb2.FullTypeDef( + type_id=full_type_pb2.TFT_PRODUCT, args=fulltype_list) + + +def iterator_full_type_from_spec(element_spec): + """Returns a FullTypeDef for an iterator for the elements. + + Args: + element_spec: A nested structure of `tf.TypeSpec` objects representing the + element type specification. + + Returns: + A FullTypeDef for an iterator for the element tensor representation. + """ + args = fulltypes_for_flat_tensors(element_spec) + return full_type_pb2.FullTypeDef( + type_id=full_type_pb2.TFT_PRODUCT, + args=[ + full_type_pb2.FullTypeDef( + type_id=full_type_pb2.TFT_ITERATOR, + args=[ + full_type_pb2.FullTypeDef( + type_id=full_type_pb2.TFT_PRODUCT, args=args) + ]) + ]) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/versions.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/versions.py new file mode 100644 index 0000000000000000000000000000000000000000..498090ef4fabe8035e7ac871373f4da409c7c1e0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/versions.py @@ -0,0 +1,103 @@ +# Copyright 2015 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""TensorFlow versions.""" + +from tensorflow.python.client import pywrap_tf_session +from tensorflow.python.util.tf_export import tf_export + +__version__ = pywrap_tf_session.__version__ +__git_version__ = pywrap_tf_session.__git_version__ +__compiler_version__ = pywrap_tf_session.__compiler_version__ +__cxx11_abi_flag__ = pywrap_tf_session.__cxx11_abi_flag__ +__monolithic_build__ = pywrap_tf_session.__monolithic_build__ +__cxx_version__ = pywrap_tf_session.__cxx_version__ + +VERSION = __version__ +tf_export( + "version.VERSION", + "__version__", + v1=["version.VERSION", "VERSION", "__version__"]).export_constant( + __name__, "VERSION") +GIT_VERSION = __git_version__ +tf_export( + "version.GIT_VERSION", + "__git_version__", + v1=["version.GIT_VERSION", "GIT_VERSION", + "__git_version__"]).export_constant(__name__, "GIT_VERSION") +COMPILER_VERSION = __compiler_version__ +tf_export( + "version.COMPILER_VERSION", + "__compiler_version__", + v1=["version.COMPILER_VERSION", "COMPILER_VERSION", + "__compiler_version__"]).export_constant(__name__, "COMPILER_VERSION") + +CXX11_ABI_FLAG = __cxx11_abi_flag__ +tf_export( + "sysconfig.CXX11_ABI_FLAG", + "__cxx11_abi_flag__", + v1=["sysconfig.CXX11_ABI_FLAG", "CXX11_ABI_FLAG", + "__cxx11_abi_flag__"]).export_constant(__name__, "CXX11_ABI_FLAG") +CXX_VERSION = __cxx_version__ +tf_export( + "sysconfig.CXX_VERSION", + "__cxx_version__", + v1=["sysconfig.CXX_VERSION", "CXX_VERSION", + "__cxx_version__"]).export_constant(__name__, "CXX_VERSION") +MONOLITHIC_BUILD = __monolithic_build__ +tf_export( + "sysconfig.MONOLITHIC_BUILD", + "__monolithic_build__", + v1=[ + "sysconfig.MONOLITHIC_BUILD", "MONOLITHIC_BUILD", "__monolithic_build__" + ]).export_constant(__name__, "MONOLITHIC_BUILD") + +GRAPH_DEF_VERSION = pywrap_tf_session.GRAPH_DEF_VERSION +tf_export( + "version.GRAPH_DEF_VERSION", + v1=["version.GRAPH_DEF_VERSION", "GRAPH_DEF_VERSION"]).export_constant( + __name__, "GRAPH_DEF_VERSION") +GRAPH_DEF_VERSION_MIN_CONSUMER = ( + pywrap_tf_session.GRAPH_DEF_VERSION_MIN_CONSUMER) +tf_export( + "version.GRAPH_DEF_VERSION_MIN_CONSUMER", + v1=[ + "version.GRAPH_DEF_VERSION_MIN_CONSUMER", + "GRAPH_DEF_VERSION_MIN_CONSUMER" + ]).export_constant(__name__, "GRAPH_DEF_VERSION_MIN_CONSUMER") +GRAPH_DEF_VERSION_MIN_PRODUCER = ( + pywrap_tf_session.GRAPH_DEF_VERSION_MIN_PRODUCER) +tf_export( + "version.GRAPH_DEF_VERSION_MIN_PRODUCER", + v1=[ + "version.GRAPH_DEF_VERSION_MIN_PRODUCER", + "GRAPH_DEF_VERSION_MIN_PRODUCER" + ]).export_constant(__name__, "GRAPH_DEF_VERSION_MIN_PRODUCER") + +__all__ = [ + "__version__", + "__git_version__", + "__compiler_version__", + "__cxx11_abi_flag__", + "__monolithic_build__", + "COMPILER_VERSION", + "CXX11_ABI_FLAG", + "GIT_VERSION", + "GRAPH_DEF_VERSION", + "GRAPH_DEF_VERSION_MIN_CONSUMER", + "GRAPH_DEF_VERSION_MIN_PRODUCER", + "VERSION", + "MONOLITHIC_BUILD", +] diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/weak_tensor.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/weak_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..e89a07d7f04284a3b37b12aca9149d93be16854e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/framework/weak_tensor.py @@ -0,0 +1,275 @@ +# 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. +# ============================================================================= +"""An extension type that represents WeakTensor.""" + +from typing import Optional + +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import composite_tensor_gradient +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import extension_type +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion_registry +from tensorflow.python.types import core + + +_ALLOWED_WEAK_DTYPES = ( + dtypes.int32, + dtypes.int64, + dtypes.float32, + dtypes.float64, + dtypes.complex128, +) + + +class WeakTensorGradient(composite_tensor_gradient.CompositeTensorGradient): + """CompositeTensorGradient for WeakTensor.""" + + def get_gradient_components(self, weak_tensor): + return weak_tensor.tensor + + def replace_gradient_components(self, weak_tensor, component_grads): + return weak_tensor._type_spec._from_components([component_grads]) # pylint: disable=protected-access + + +class WeakTensor(extension_type.BatchableExtensionType, core.Tensor): + """A weakly typed Tensor. + + A simple wrapper class that contains a normal Tensor. + + A "weak" type means that its dtype is temporarily inferred by the system, + and could defer to other dtypes. + + i.g. weak f64 + f16 => f16 + + This information is used for auto dtype conversion. + """ + + # __name__ is required for serialization in SavedModel. + __name__ = "tf.WeakTensor" + tensor: tensor_lib.Tensor + + def __validate__(self): + if self.tensor.dtype not in _ALLOWED_WEAK_DTYPES: + raise TypeError( + f"{self.tensor.dtype} not allowed " + f"as a weak type. The allowed types are {_ALLOWED_WEAK_DTYPES}." + ) + + def __str__(self): + return self._format_weak_tensor(is_repr=False) + + def __repr__(self): + return self._format_weak_tensor(is_repr=True) + + def _format_weak_tensor(self, is_repr): + tensor_str = self.tensor.__repr__() if is_repr else self.tensor.__str__() + closing_char = tensor_str[len(tensor_str) - 1] + last_index = tensor_str.rfind(closing_char) + return tensor_str[:last_index] + ", weak=True" + closing_char + + def __getattr__(self, *args, **kwargs): + # Fallback to `__getattr__` if `__getattribute__` fails, so that we can + # directly expose Tensor's methods. + return getattr(self.tensor, *args, **kwargs) + + def _disallow(self, task): + raise errors.OperatorNotAllowedInGraphError( + f"{task} is not allowed. You can attempt the following resolutions to" + " the problem: If you are running in Graph mode, use Eager execution" + " mode or decorate this function with @tf.function. If you are using" + " AutoGraph, you can try decorating this function with @tf.function." + " If that does not work, then you may be using an unsupported feature" + " or your source code may not be visible to AutoGraph. See" + " https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/limitations.md#access-to-source-code" + " for more information." + ) + + def _disallow_iteration(self): + self._disallow("Iterating over a symbolic `tf.WeakTensor`") + + def _shape_as_list(self): + if self.shape.ndims is not None: + return [dim.value for dim in self.shape.dims] + else: + return None + + def __iter__(self): + if not context.executing_eagerly(): + self._disallow_iteration() + first_dim = self.tensor._get_first_dim() + return _WeakTensorIterator(self, first_dim) + + def __hash__(self): + return self.tensor.__hash__() + + def __copy__(self): + # Weak Tensors are immutable so it's safe to return themselves as a copy. + return self + + def __len__(self): + return self.tensor.__len__() + + def __bool__(self): + return self.tensor.__bool__() + + def __tf_tensor__( + self, dtype: Optional[dtypes.DType] = None, name: Optional[str] = None + ): + return self.tensor.__tf_tensor__(dtype=dtype, name=name) + + def __deepcopy__(self, memo): + # Eager Tensors are immutable so it's safe to return themselves as a copy. + del memo + return self + + def to_tensor(self): + """Converts this 'WeakTensor' into a 'tf.Tensor'.""" + return self.tensor + + def _as_graph_element(self): + """Convert `self` to a graph element.""" + return self.tensor + + @classmethod + def from_tensor(cls, tensor): + """Converts a 'tf.Tensor' into a 'WeakTensor'. + + This should be the standard way of creating a WeakTensor instead + of directly calling the WeakTensor constructor. + + Args: + tensor: The `tf.Tensor` that should be converted into a 'WeakTensor'. + + Returns: + A `EagerWeakTensor` or 'GraphWeakTensor' that holds the `tensor`. + """ + if isinstance(tensor, core.Value): + return EagerWeakTensor(tensor) + if isinstance(tensor, core.Symbol): + return GraphWeakTensor(tensor) + raise errors.InvalidArgumentError( + None, + None, + "WeakTensor can only be constructed from tf.Tensor or tf.WeakTensor," + f" but {type(tensor)} was given.", + ) + + # Redefine `shape` and `dtype` rather than relying on `getattr` because the + # class derives from core.Tensor which returns None in the two methods. + @property + def dtype(self): + return self.tensor.dtype + + @property + def shape(self): + return self.tensor.shape + + @property + def is_tensor_like(self): + return True + + __composite_gradient__ = WeakTensorGradient() + + +# EagerWeakTensor and GraphWeakTensor are wrapper classes that are +# introduced for WeakTensor to pass instance checks for core.Value or +# core.Symbol. +class EagerWeakTensor(core.Value, WeakTensor): + """A weakly typed Eager Tensor.""" + + __name__ = "tf.EagerWeakTensor" + + # Methods that are only avilable for EagerTensor. + def numpy(self): + """Copy of the contents of this EagerWeakTensor into a NumPy array or scalar.""" + if not isinstance(self.tensor, ops.EagerTensor): + raise ValueError("WeakTensor.numpy() is only supported in eager mode.") + return self.tensor.numpy() + + def __complex__(self): + return self.tensor.__complex__() + + def __int__(self): + return self.tensor.__int__() + + def __float__(self): + return self.tensor.__float__() + + def __index__(self): + return self.tensor.__index__() + + def __format__(self, format_spec): + return f"{self.tensor.__format__(format_spec)} weakly typed" + + def __array__(self, dtype=None): + # We need to explicitly call np.array() because + # self_tensor.__array__() for scalars raise: + # ValueError: object __array__ method not producing an array + # resource_variable_ops also follows the same pattern. + return np.array(self.tensor.__array__(dtype)) + + +class GraphWeakTensor(core.Symbol, WeakTensor): + """A weakly typed Graph Tensor.""" + + __name__ = "tf.GraphWeakTensor" + + +class _WeakTensorIterator(object): + """Iterates over the leading dim of a WeakTensor. Performs no error checks.""" + + __slots__ = ["_weak_tensor", "_index", "_limit"] + + def __init__(self, weak_tensor, dim0): + self._weak_tensor = weak_tensor + self._index = 0 + self._limit = dim0 + + def __iter__(self): + return self + + def __next__(self): + if self._index == self._limit: + raise StopIteration + result = WeakTensor.from_tensor((self._weak_tensor.tensor[self._index])) + self._index += 1 + return result + + +def convert_to_weak_tensor_or_tensor(t, to_weak): + if to_weak: + return WeakTensor.from_tensor(t) + # We should return a normal Tensor because is_weak = False. + if isinstance(t, WeakTensor): + return t.tensor + return t + + +# convert_to_tensor(WeakTensor) should return a Tensor because convert_to_tensor +# is mostly used internally and we want to limit the scope of WeakTensor +# creation to tf.constant and WeakTensor patched ops. +def weak_tensor_conversion_function(t): + if isinstance(t, WeakTensor): + return t.tensor + + +tensor_conversion_registry.register_tensor_conversion_function( + WeakTensor, weak_tensor_conversion_function +) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_cluster.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_cluster.pyi new file mode 100644 index 0000000000000000000000000000000000000000..fa2a1086cac2526c0751f090625210d87d1c1b6e --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_cluster.pyi @@ -0,0 +1,27 @@ +# 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. +# ============================================================================== + +class Cluster: + def __init__(self, *args, **kwargs) -> None: ... + +def TF_DeterminePeakMemoryUsage(arg0, arg1: Cluster) -> dict[str,tuple[int,list[tuple[str,int,int,int,int]]]]: ... +def TF_EstimatePerformance(arg0: bytes) -> float: ... +def TF_GetSupportedDevices(arg0: Cluster, arg1) -> dict[str,list[str]]: ... +def TF_ListAvailableOps() -> list[str]: ... +def TF_ListDevices(arg0: Cluster) -> list[bytes]: ... +def TF_MeasureCosts(arg0, arg1: Cluster, arg2: bool) -> tuple[list[bytes],float,bytes]: ... +def TF_NewCluster(arg0: bool, arg1: bool) -> Cluster: ... +def TF_NewVirtualCluster(arg0: list[bytes]) -> Cluster: ... +def TF_ShutdownCluster(arg0: Cluster) -> None: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_item.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_item.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a087325eb642c0fbc9f2d6353d5c578a3856b2d0 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_item.pyi @@ -0,0 +1,22 @@ +# 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. +# ============================================================================== + +class GrapplerItem: + def __init__(self, *args, **kwargs) -> None: ... + +def TF_GetColocationGroups(arg0: GrapplerItem) -> list[list[str]]: ... +def TF_GetOpProperties(arg0: GrapplerItem) -> dict[str,list[bytes]]: ... +def TF_IdentifyImportantOps(arg0: GrapplerItem, arg1: bool) -> list[str]: ... +def TF_NewItem(arg0: bytes, arg1: bool, arg2: bool) -> GrapplerItem: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_optimizer.pyi b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_optimizer.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9eb2d0e7393c6f4d5e84e7d24b9a85c4e243b387 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/_pywrap_tf_optimizer.pyi @@ -0,0 +1,19 @@ +# 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. +# ============================================================================== + +from typing import Any + +def TF_OptimizeGraph(*args, **kwargs) -> Any: ... +def TF_OptimizeGraphSerialized(arg0, arg1: str, arg2: str, arg3: bool, arg4: str, arg5: bool) -> bytes: ... diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/cluster.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3c2eaad9fc2dc001810e279a917b4c5afa21d5 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/cluster.py @@ -0,0 +1,118 @@ +# 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 python interface for Grappler clusters.""" + +import contextlib + +from tensorflow.core.framework import step_stats_pb2 +from tensorflow.core.grappler.costs import op_performance_data_pb2 +from tensorflow.core.protobuf import device_properties_pb2 +from tensorflow.python.grappler import _pywrap_tf_cluster as tf_cluster + + +class Cluster(object): + """Grappler Clusters.""" + + def __init__(self, + allow_soft_placement=True, + disable_detailed_stats=True, + disable_timeline=True, + devices=None): + """Creates a Cluster. + + Args: + allow_soft_placement: If True, TF will automatically fix illegal + placements instead of erroring out if the placement isn't legal. + disable_detailed_stats: If True, detailed statistics will not be + available. + disable_timeline: If True, the timeline information will not be reported. + devices: A list of devices of type device_properties_pb2.NamedDevice. + If None, a device list will be created based on the spec of + the local machine. + """ + self._tf_cluster = None + self._generate_timeline = not disable_timeline + + if devices is None: + self._tf_cluster = tf_cluster.TF_NewCluster(allow_soft_placement, + disable_detailed_stats) + else: + devices_serialized = [device.SerializeToString() for device in devices] + self._tf_cluster = tf_cluster.TF_NewVirtualCluster(devices_serialized) + + def Shutdown(self): + if self._tf_cluster is not None: + tf_cluster.TF_ShutdownCluster(self._tf_cluster) + self._tf_cluster = None + + def __del__(self): + self.Shutdown() + + @property + def tf_cluster(self): + return self._tf_cluster + + def ListDevices(self): + """Returns a list of available hardware devices.""" + if self._tf_cluster is None: + return [] + return [device_properties_pb2.NamedDevice.FromString(device) + for device in tf_cluster.TF_ListDevices(self._tf_cluster)] + + def ListAvailableOps(self): + """Returns a list of all available operations (sorted alphabetically).""" + return tf_cluster.TF_ListAvailableOps() + + def GetSupportedDevices(self, item): + return tf_cluster.TF_GetSupportedDevices(self._tf_cluster, item.tf_item) + + def EstimatePerformance(self, device): + return tf_cluster.TF_EstimatePerformance(device.SerializeToString()) + + def MeasureCosts(self, item): + """Returns the cost of running the specified item. + + Args: + item: The item for which to measure the costs. + Returns: The triplet op_perfs, runtime, step_stats. + """ + op_perf_bytes_list, run_time, step_stats_bytes = tf_cluster.TF_MeasureCosts( + item.tf_item, self._tf_cluster, self._generate_timeline) + + op_perfs = [op_performance_data_pb2.OpPerformance.FromString(op_perf_bytes) + for op_perf_bytes in op_perf_bytes_list] + return (op_perfs, run_time, + step_stats_pb2.StepStats.FromString(step_stats_bytes)) + + def DeterminePeakMemoryUsage(self, item): + """Returns a snapshot of the peak memory usage. + + Args: + item: The item for which to measure the costs. + Returns: A hashtable indexed by device name. + """ + return tf_cluster.TF_DeterminePeakMemoryUsage(item.tf_item, + self._tf_cluster) + + +@contextlib.contextmanager +def Provision(allow_soft_placement=True, + disable_detailed_stats=True, + disable_timeline=True, + devices=None): + cluster = Cluster(allow_soft_placement, disable_detailed_stats, + disable_timeline, devices) + yield cluster + cluster.Shutdown() diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/item.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/item.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f29606b8cd824c88ab9ebe2f167b96b96cf0fc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/item.py @@ -0,0 +1,90 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""A python interface for Grappler items.""" + +from tensorflow.core.grappler.costs import op_performance_data_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.python.grappler import _pywrap_tf_item as tf_item + + +class Item(object): + """GrapplerItem.""" + + def __init__(self, + metagraph, + ignore_colocation=True, + ignore_user_placement=False): + """Creates an Item. + + Args: + metagraph: a TensorFlow metagraph. + ignore_colocation: if set, the tool will ignore all the colocation + constraints generated by TensorFlow. + ignore_user_placement: if set, all the placement annotations annotated in + the metagraph will be ignored. + Raises: + ValueError: the metagraph is incomplete or invalid. + """ + self._metagraph = metagraph + self._item_graph = meta_graph_pb2.MetaGraphDef() + self._item_graph.CopyFrom(metagraph) + self._ignore_colocation = ignore_colocation + self._ignore_user_placement = ignore_user_placement + self._tf_item = None + self._BuildTFItem() + + def IdentifyImportantOps(self, sort_topologically=False): + return tf_item.TF_IdentifyImportantOps(self.tf_item, sort_topologically) + + def GetOpProperties(self): + """Get Op properties.""" + props = tf_item.TF_GetOpProperties(self.tf_item) + properties = {} + for key, values in props.items(): + prop = [] + for value in values: + # TODO(petebu): Make this conversion to a dictionary be done in the C++ + # wrapper for performance. + prop.append( + op_performance_data_pb2.OpInfo.TensorProperties.FromString(value)) + properties[key] = prop + return properties + + def GetColocationGroups(self): + """Return a list of hard colocation constraints. + + All the nodes in a colocation tuple must be placed on the same device for + the model to work. + + Returns: + A list of colocation tuples. + """ + return tf_item.TF_GetColocationGroups(self.tf_item) + + @property + def metagraph(self): + return self._metagraph + + @property + def tf_item(self): + if self._item_graph != self._metagraph: + self._BuildTFItem() + self._item_graph.CopyFrom(self._metagraph) + return self._tf_item + + def _BuildTFItem(self): + self._tf_item = tf_item.TF_NewItem(self._metagraph.SerializeToString(), + self._ignore_colocation, + self._ignore_user_placement) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/tf_optimizer.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/tf_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0b07cb5abc3ee2b9dbaaad1010e143b0c9d6e66f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/grappler/tf_optimizer.py @@ -0,0 +1,91 @@ +# Copyright 2017 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================= +"""Provides a proper python API for the symbols exported through swig.""" + +import threading + +from tensorflow.core.framework import graph_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.grappler import _pywrap_tf_optimizer as tf_opt +from tensorflow.python.grappler import cluster as gcluster + +_OPTIMIZE_GRAPH_CLUSTER_LOCK = threading.Lock() +is_oss = True # Updated by copybara. + + +def OptimizeGraph(config_proto, + metagraph, + verbose=True, + graph_id=b'graph_to_optimize', + cluster=None, + strip_default_attributes=False): + """Optimize the provided metagraph. + + For best results, the signature_def field in `metagraph` should be populated + with information about input (feed) and output (fetch) tensors. + + Args: + config_proto: a ConfigProto protobuf. + metagraph: a MetagraphDef protobuf. + verbose: whether to log optimization results. + graph_id: a string identifying this graph. + cluster: a grappler cluster object representing hardware resources + available to run this graph. + strip_default_attributes: whether graph node attributes having default + values should be removed after all the optimization passes. This + option is useful if the resulting graph will be executed by an older + process that might not know some of the recently added attributes. + """ + if not isinstance(config_proto, config_pb2.ConfigProto): + raise TypeError('Argument `config_proto` should be a tf.ConfigProto, ' + f'received type: {type(config_proto).__name__}') + if is_oss: + optimize_method = tf_opt.TF_OptimizeGraphSerialized + metagraph = metagraph.SerializeToString() + else: + optimize_method = tf_opt.TF_OptimizeGraph + + if cluster is not None: + out_graph = optimize_method( + cluster.tf_cluster, + config_proto.SerializeToString(), + metagraph, + verbose, + graph_id, + strip_default_attributes, + ) + else: + # Currently Grappler assumes no more than 1 sessions alive globally. + # See comments on SingleMachine::Provision(), hence we use the following + # lock to prevent concurrent access to the following code. + with _OPTIMIZE_GRAPH_CLUSTER_LOCK: + cluster = gcluster.Cluster() + try: + out_graph = optimize_method( + cluster.tf_cluster, + config_proto.SerializeToString(), + metagraph, + verbose, + graph_id, + strip_default_attributes, + ) + finally: + # Force the cleanup instead of waiting on python GC to cleanup the + # temporary cluster we've created. Otherwise subsequent calls might + # not have a clean slate because GC may not have run yet. + cluster.Shutdown() + if is_oss: + out_graph = graph_pb2.GraphDef.FromString(out_graph) + return out_graph diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/__init__.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a8a380d7e08a500cc7a96fe853b1479e8ffc50 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/__init__.py @@ -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. +# ============================================================================== +"""Implementation of the Keras API, the high-level API of TensorFlow. + +Detailed documentation and user guides are available at +[keras.io](https://keras.io). +""" +# pylint: disable=unused-import +from tensorflow.python import tf2 +from tensorflow.python.keras import distribute + +# See b/110718070#comment18 for more details about this import. +from tensorflow.python.keras import models + +from tensorflow.python.keras.engine.input_layer import Input +from tensorflow.python.keras.engine.sequential import Sequential +from tensorflow.python.keras.engine.training import Model diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/activations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/activations.py new file mode 100644 index 0000000000000000000000000000000000000000..623c8e365cb9ef254e5b374bc076cdfa0f247cf9 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/activations.py @@ -0,0 +1,588 @@ +# 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. +# ============================================================================== +"""Built-in activation functions.""" + +from tensorflow.python.keras import backend +from tensorflow.python.keras.layers import advanced_activations +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.util import dispatch + +# b/123041942 +# In TF 2.x, if the `tf.nn.softmax` is used as an activation function in Keras +# layers, it gets serialized as 'softmax_v2' instead of 'softmax' as the +# internal method name is returned in serialization. This results in errors in +# model exporting and loading as Keras can't find any activation function with +# the name of `softmax_v2`. +# This dict maps the activation function name from its v2 version to its +# canonical name. +_TF_ACTIVATIONS_V2 = { + 'softmax_v2': 'softmax', +} + + +@dispatch.add_dispatch_support +def softmax(x, axis=-1): + """Softmax converts a vector of values to a probability distribution. + + The elements of the output vector are in range (0, 1) and sum to 1. + + Each vector is handled independently. The `axis` argument sets which axis + of the input the function is applied along. + + Softmax is often used as the activation for the last + layer of a classification network because the result could be interpreted as + a probability distribution. + + The softmax of each vector x is computed as + `exp(x) / tf.reduce_sum(exp(x))`. + + The input values in are the log-odds of the resulting probability. + + Args: + x : Input tensor. + axis: Integer, axis along which the softmax normalization is applied. + + Returns: + Tensor, output of softmax transformation (all values are non-negative + and sum to 1). + + Examples: + + **Example 1: standalone usage** + + >>> inputs = tf.random.normal(shape=(32, 10)) + >>> outputs = tf.keras.activations.softmax(inputs) + >>> tf.reduce_sum(outputs[0, :]) # Each sample in the batch now sums to 1 + + + **Example 2: usage in a `Dense` layer** + + >>> layer = tf.keras.layers.Dense(32, activation=tf.keras.activations.softmax) + """ + if x.shape.rank > 1: + if isinstance(axis, int): + output = nn.softmax(x, axis=axis) + else: + # nn.softmax does not support tuple axis. + e = math_ops.exp(x - math_ops.reduce_max(x, axis=axis, keepdims=True)) + s = math_ops.reduce_sum(e, axis=axis, keepdims=True) + output = e / s + else: + raise ValueError('Cannot apply softmax to a tensor that is 1D. ' + 'Received input: %s' % (x,)) + + # Cache the logits to use for crossentropy loss. + output._keras_logits = x # pylint: disable=protected-access + return output + + +@dispatch.add_dispatch_support +def elu(x, alpha=1.0): + """Exponential Linear Unit. + + The exponential linear unit (ELU) with `alpha > 0` is: + `x` if `x > 0` and + `alpha * (exp(x) - 1)` if `x < 0` + The ELU hyperparameter `alpha` controls the value to which an + ELU saturates for negative net inputs. ELUs diminish the + vanishing gradient effect. + + ELUs have negative values which pushes the mean of the activations + closer to zero. + Mean activations that are closer to zero enable faster learning as they + bring the gradient closer to the natural gradient. + ELUs saturate to a negative value when the argument gets smaller. + Saturation means a small derivative which decreases the variation + and the information that is propagated to the next layer. + + Example Usage: + + >>> import tensorflow as tf + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Conv2D(32, (3, 3), activation='elu', + ... input_shape=(28, 28, 1))) + >>> model.add(tf.keras.layers.MaxPooling2D((2, 2))) + >>> model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='elu')) + >>> model.add(tf.keras.layers.MaxPooling2D((2, 2))) + >>> model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='elu')) + + + + Args: + x: Input tensor. + alpha: A scalar, slope of negative section. `alpha` controls the value to + which an ELU saturates for negative net inputs. + + Returns: + The exponential linear unit (ELU) activation function: `x` if `x > 0` and + `alpha * (exp(x) - 1)` if `x < 0`. + + + Reference: + [Fast and Accurate Deep Network Learning by Exponential Linear Units + (ELUs) (Clevert et al, 2016)](https://arxiv.org/abs/1511.07289) + """ + return backend.elu(x, alpha) + + +@dispatch.add_dispatch_support +def selu(x): + """Scaled Exponential Linear Unit (SELU). + + The Scaled Exponential Linear Unit (SELU) activation function is defined as: + + - `if x > 0: return scale * x` + - `if x < 0: return scale * alpha * (exp(x) - 1)` + + where `alpha` and `scale` are pre-defined constants + (`alpha=1.67326324` and `scale=1.05070098`). + + Basically, the SELU activation function multiplies `scale` (> 1) with the + output of the `tf.keras.activations.elu` function to ensure a slope larger + than one for positive inputs. + + The values of `alpha` and `scale` are + chosen so that the mean and variance of the inputs are preserved + between two consecutive layers as long as the weights are initialized + correctly (see `tf.keras.initializers.LecunNormal` initializer) + and the number of input units is "large enough" + (see reference paper for more information). + + Example Usage: + + >>> num_classes = 10 # 10-class problem + >>> model = tf.keras.Sequential() + >>> model.add(tf.keras.layers.Dense(64, kernel_initializer='lecun_normal', + ... activation='selu')) + >>> model.add(tf.keras.layers.Dense(32, kernel_initializer='lecun_normal', + ... activation='selu')) + >>> model.add(tf.keras.layers.Dense(16, kernel_initializer='lecun_normal', + ... activation='selu')) + >>> model.add(tf.keras.layers.Dense(num_classes, activation='softmax')) + + Args: + x: A tensor or variable to compute the activation function for. + + Returns: + The scaled exponential unit activation: `scale * elu(x, alpha)`. + + Notes: + - To be used together with the + `tf.keras.initializers.LecunNormal` initializer. + - To be used together with the dropout variant + `tf.keras.layers.AlphaDropout` (not regular dropout). + + References: + - [Klambauer et al., 2017](https://arxiv.org/abs/1706.02515) + """ + return nn.selu(x) + + +@dispatch.add_dispatch_support +def softplus(x): + """Softplus activation function, `softplus(x) = log(exp(x) + 1)`. + + Example Usage: + + >>> a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32) + >>> b = tf.keras.activations.softplus(a) + >>> b.numpy() + array([2.0611537e-09, 3.1326166e-01, 6.9314718e-01, 1.3132616e+00, + 2.0000000e+01], dtype=float32) + + Args: + x: Input tensor. + + Returns: + The softplus activation: `log(exp(x) + 1)`. + """ + return math_ops.softplus(x) + + +@dispatch.add_dispatch_support +def softsign(x): + """Softsign activation function, `softsign(x) = x / (abs(x) + 1)`. + + Example Usage: + + >>> a = tf.constant([-1.0, 0.0, 1.0], dtype = tf.float32) + >>> b = tf.keras.activations.softsign(a) + >>> b.numpy() + array([-0.5, 0. , 0.5], dtype=float32) + + Args: + x: Input tensor. + + Returns: + The softsign activation: `x / (abs(x) + 1)`. + """ + return nn.softsign(x) + + +@dispatch.add_dispatch_support +def swish(x): + """Swish activation function, `swish(x) = x * sigmoid(x)`. + + Swish activation function which returns `x*sigmoid(x)`. + It is a smooth, non-monotonic function that consistently matches + or outperforms ReLU on deep networks, it is unbounded above and + bounded below. + + + Example Usage: + + >>> a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32) + >>> b = tf.keras.activations.swish(a) + >>> b.numpy() + array([-4.1223075e-08, -2.6894143e-01, 0.0000000e+00, 7.3105860e-01, + 2.0000000e+01], dtype=float32) + + Args: + x: Input tensor. + + Returns: + The swish activation applied to `x` (see reference paper for details). + + Reference: + - [Ramachandran et al., 2017](https://arxiv.org/abs/1710.05941) + """ + return nn.swish(x) + + +@dispatch.add_dispatch_support +def relu(x, alpha=0., max_value=None, threshold=0): + """Applies the rectified linear unit activation function. + + With default values, this returns the standard ReLU activation: + `max(x, 0)`, the element-wise maximum of 0 and the input tensor. + + Modifying default parameters allows you to use non-zero thresholds, + change the max value of the activation, + and to use a non-zero multiple of the input for values below the threshold. + + For example: + + >>> foo = tf.constant([-10, -5, 0.0, 5, 10], dtype = tf.float32) + >>> tf.keras.activations.relu(foo).numpy() + array([ 0., 0., 0., 5., 10.], dtype=float32) + >>> tf.keras.activations.relu(foo, alpha=0.5).numpy() + array([-5. , -2.5, 0. , 5. , 10. ], dtype=float32) + >>> tf.keras.activations.relu(foo, max_value=5).numpy() + array([0., 0., 0., 5., 5.], dtype=float32) + >>> tf.keras.activations.relu(foo, threshold=5).numpy() + array([-0., -0., 0., 0., 10.], dtype=float32) + + Args: + x: Input `tensor` or `variable`. + alpha: A `float` that governs the slope for values lower than the + threshold. + max_value: A `float` that sets the saturation threshold (the largest value + the function will return). + threshold: A `float` giving the threshold value of the activation function + below which values will be damped or set to zero. + + Returns: + A `Tensor` representing the input tensor, + transformed by the relu activation function. + Tensor will be of the same shape and dtype of input `x`. + """ + return backend.relu(x, alpha=alpha, max_value=max_value, threshold=threshold) + + +@dispatch.add_dispatch_support +def gelu(x, approximate=False): + """Applies the Gaussian error linear unit (GELU) activation function. + + Gaussian error linear unit (GELU) computes + `x * P(X <= x)`, where `P(X) ~ N(0, 1)`. + The (GELU) nonlinearity weights inputs by their value, rather than gates + inputs by their sign as in ReLU. + + For example: + + >>> x = tf.constant([-3.0, -1.0, 0.0, 1.0, 3.0], dtype=tf.float32) + >>> y = tf.keras.activations.gelu(x) + >>> y.numpy() + array([-0.00404951, -0.15865529, 0. , 0.8413447 , 2.9959507 ], + dtype=float32) + >>> y = tf.keras.activations.gelu(x, approximate=True) + >>> y.numpy() + array([-0.00363752, -0.15880796, 0. , 0.841192 , 2.9963627 ], + dtype=float32) + + Args: + x: Input tensor. + approximate: A `bool`, whether to enable approximation. + + Returns: + The gaussian error linear activation: + `0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * x^3)))` + if `approximate` is `True` or + `x * P(X <= x) = 0.5 * x * (1 + erf(x / sqrt(2)))`, + where `P(X) ~ N(0, 1)`, + if `approximate` is `False`. + + Reference: + - [Gaussian Error Linear Units (GELUs)](https://arxiv.org/abs/1606.08415) + """ + return nn.gelu(x, approximate) + + +@dispatch.add_dispatch_support +def tanh(x): + """Hyperbolic tangent activation function. + + For example: + + >>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32) + >>> b = tf.keras.activations.tanh(a) + >>> b.numpy() + array([-0.9950547, -0.7615942, 0., 0.7615942, 0.9950547], dtype=float32) + + Args: + x: Input tensor. + + Returns: + Tensor of same shape and dtype of input `x`, with tanh activation: + `tanh(x) = sinh(x)/cosh(x) = ((exp(x) - exp(-x))/(exp(x) + exp(-x)))`. + """ + return nn.tanh(x) + + +@dispatch.add_dispatch_support +def sigmoid(x): + """Sigmoid activation function, `sigmoid(x) = 1 / (1 + exp(-x))`. + + Applies the sigmoid activation function. For small values (<-5), + `sigmoid` returns a value close to zero, and for large values (>5) + the result of the function gets close to 1. + + Sigmoid is equivalent to a 2-element Softmax, where the second element is + assumed to be zero. The sigmoid function always returns a value between + 0 and 1. + + For example: + + >>> a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32) + >>> b = tf.keras.activations.sigmoid(a) + >>> b.numpy() + array([2.0611537e-09, 2.6894143e-01, 5.0000000e-01, 7.3105860e-01, + 1.0000000e+00], dtype=float32) + + Args: + x: Input tensor. + + Returns: + Tensor with the sigmoid activation: `1 / (1 + exp(-x))`. + """ + output = nn.sigmoid(x) + # Cache the logits to use for crossentropy loss. + output._keras_logits = x # pylint: disable=protected-access + return output + + +@dispatch.add_dispatch_support +def exponential(x): + """Exponential activation function. + + For example: + + >>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32) + >>> b = tf.keras.activations.exponential(a) + >>> b.numpy() + array([0.04978707, 0.36787945, 1., 2.7182817 , 20.085537], dtype=float32) + + Args: + x: Input tensor. + + Returns: + Tensor with exponential activation: `exp(x)`. + """ + return math_ops.exp(x) + + +@dispatch.add_dispatch_support +def hard_sigmoid(x): + """Hard sigmoid activation function. + + A faster approximation of the sigmoid activation. + Piecewise linear approximation of the sigmoid function. + Ref: 'https://en.wikipedia.org/wiki/Hard_sigmoid' + + For example: + + >>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32) + >>> b = tf.keras.activations.hard_sigmoid(a) + >>> b.numpy() + array([0. , 0.3, 0.5, 0.7, 1. ], dtype=float32) + + Args: + x: Input tensor. + + Returns: + The hard sigmoid activation, defined as: + + - `if x < -2.5: return 0` + - `if x > 2.5: return 1` + - `if -2.5 <= x <= 2.5: return 0.2 * x + 0.5` + """ + return backend.hard_sigmoid(x) + + +@dispatch.add_dispatch_support +def linear(x): + """Linear activation function (pass-through). + + For example: + + >>> a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32) + >>> b = tf.keras.activations.linear(a) + >>> b.numpy() + array([-3., -1., 0., 1., 3.], dtype=float32) + + Args: + x: Input tensor. + + Returns: + The input, unmodified. + """ + return x + + +@dispatch.add_dispatch_support +def serialize(activation): + """Returns the string identifier of an activation function. + + Args: + activation : Function object. + + Returns: + String denoting the name attribute of the input function + + For example: + + >>> tf.keras.activations.serialize(tf.keras.activations.tanh) + 'tanh' + >>> tf.keras.activations.serialize(tf.keras.activations.sigmoid) + 'sigmoid' + >>> tf.keras.activations.serialize('abcd') + Traceback (most recent call last): + ... + ValueError: ('Cannot serialize', 'abcd') + + Raises: + ValueError: The input function is not a valid one. + """ + if (hasattr(activation, '__name__') and + activation.__name__ in _TF_ACTIVATIONS_V2): + return _TF_ACTIVATIONS_V2[activation.__name__] + return serialize_keras_object(activation) + + +# Add additional globals so that deserialize can find these common activation +# functions +leaky_relu = nn.leaky_relu +log_softmax = nn.log_softmax +relu6 = nn.relu6 +silu = nn.swish + + +@dispatch.add_dispatch_support +def deserialize(name, custom_objects=None): + """Returns activation function given a string identifier. + + Args: + name: The name of the activation function. + custom_objects: Optional `{function_name: function_obj}` + dictionary listing user-provided activation functions. + + Returns: + Corresponding activation function. + + For example: + + >>> tf.keras.activations.deserialize('linear') + + >>> tf.keras.activations.deserialize('sigmoid') + + >>> tf.keras.activations.deserialize('abcd') + Traceback (most recent call last): + ... + ValueError: Unknown activation function:abcd + + Raises: + ValueError: `Unknown activation function` if the input string does not + denote any defined Tensorflow activation function. + """ + globs = globals() + + # only replace missing activations + advanced_activations_globs = advanced_activations.get_globals() + for key, val in advanced_activations_globs.items(): + if key not in globs: + globs[key] = val + + return deserialize_keras_object( + name, + module_objects=globs, + custom_objects=custom_objects, + printable_module_name='activation function') + + +@dispatch.add_dispatch_support +def get(identifier): + """Returns function. + + Args: + identifier: Function or string + + Returns: + Function corresponding to the input string or input function. + + For example: + + >>> tf.keras.activations.get('softmax') + + >>> tf.keras.activations.get(tf.keras.activations.softmax) + + >>> tf.keras.activations.get(None) + + >>> tf.keras.activations.get(abs) + + >>> tf.keras.activations.get('abcd') + Traceback (most recent call last): + ... + ValueError: Unknown activation function:abcd + + Raises: + ValueError: Input is an unknown function or string, i.e., the input does + not denote any defined function. + """ + if identifier is None: + return linear + if isinstance(identifier, str): + identifier = str(identifier) + return deserialize(identifier) + elif isinstance(identifier, dict): + return deserialize(identifier) + elif callable(identifier): + return identifier + else: + raise TypeError( + 'Could not interpret activation function identifier: {}'.format( + identifier)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/backend.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..7d491e3e23e0aae834df62446c4b7e708432eb38 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/backend.py @@ -0,0 +1,6503 @@ +# 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. +# ============================================================================== +# pylint: disable=protected-access +# pylint: disable=redefined-outer-name +# pylint: disable=redefined-builtin +# pylint: disable=g-classes-have-attributes +"""Keras backend API.""" + +import collections +import itertools +import json +import os +import sys +import threading +import warnings +import weakref + +import numpy as np + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python import tf2 +from tensorflow.python.client import session as session_module +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.eager.context import get_config +from tensorflow.python.framework import composite_tensor +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import device_spec +from tensorflow.python.framework import dtypes as dtypes_module +from tensorflow.python.framework import func_graph +from tensorflow.python.framework import ops +from tensorflow.python.framework import sparse_tensor +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend_config +from tensorflow.python.keras.distribute import distribute_coordinator_utils as dc +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.keras.utils import control_flow_util +from tensorflow.python.keras.utils import object_identity +from tensorflow.python.keras.utils import tf_contextlib +from tensorflow.python.keras.utils import tf_inspect +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import ctc_ops as ctc +from tensorflow.python.ops import functional_ops +from tensorflow.python.ops import gradients as gradients_module +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import logging_ops +from tensorflow.python.ops import map_fn as map_fn_lib +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import tensor_array_grad # pylint: disable=unused-import +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import variable_v1 +from tensorflow.python.ops import variables as variables_module +from tensorflow.python.ops import while_loop +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.training import moving_averages +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.tools.docs import doc_controls + +py_all = all +py_sum = sum +py_any = any + +# INTERNAL UTILS + +# The internal graph maintained by Keras and used by the symbolic Keras APIs +# while executing eagerly (such as the functional API for model-building). +# This is thread-local to allow building separate models in different threads +# concurrently, but comes at the cost of not being able to build one model +# across threads. +_GRAPH = threading.local() + +# A graph which is used for constructing functions in eager mode. +_CURRENT_SCRATCH_GRAPH = threading.local() + +# This is a thread local object that will hold the default internal TF session +# used by Keras. It can be set manually via `set_session(sess)`. +_SESSION = threading.local() + + +# A global dictionary mapping graph objects to an index of counters used +# for various layer/optimizer names in each graph. +# Allows to give unique autogenerated names to layers, in a graph-specific way. +PER_GRAPH_OBJECT_NAME_UIDS = weakref.WeakKeyDictionary() + + +# A global set tracking what object names have been seen so far. +# Optionally used as an avoid-list when generating names +OBSERVED_NAMES = set() + + +# _DUMMY_EAGER_GRAPH.key is used as a key in _GRAPH_LEARNING_PHASES. +# We keep a separate reference to it to make sure it does not get removed from +# _GRAPH_LEARNING_PHASES. +# _DummyEagerGraph inherits from threading.local to make its `key` attribute +# thread local. This is needed to make set_learning_phase affect only the +# current thread during eager execution (see b/123096885 for more details). +class _DummyEagerGraph(threading.local): + """_DummyEagerGraph provides a thread local `key` attribute. + + We can't use threading.local directly, i.e. without subclassing, because + gevent monkey patches threading.local and its version does not support + weak references. + """ + + class _WeakReferencableClass: + """This dummy class is needed for two reasons. + + - We need something that supports weak references. Basic types like string + and ints don't. + - We need something whose hash and equality are based on object identity + to make sure they are treated as different keys to _GRAPH_LEARNING_PHASES. + + An empty Python class satisfies both of these requirements. + """ + pass + + def __init__(self): + # Constructors for classes subclassing threading.local run once + # per thread accessing something in the class. Thus, each thread will + # get a different key. + super(_DummyEagerGraph, self).__init__() + self.key = _DummyEagerGraph._WeakReferencableClass() + self.learning_phase_is_set = False + + +_DUMMY_EAGER_GRAPH = _DummyEagerGraph() + +# This boolean flag can be set to True to leave variable initialization +# up to the user. +# Change its value via `manual_variable_initialization(value)`. +_MANUAL_VAR_INIT = False + +# This list holds the available devices. +# It is populated when `_get_available_gpus()` is called for the first time. +# We assume our devices don't change henceforth. +_LOCAL_DEVICES = None + +# The below functions are kept accessible from backend for compatibility. +epsilon = backend_config.epsilon +floatx = backend_config.floatx +image_data_format = backend_config.image_data_format +set_epsilon = backend_config.set_epsilon +set_floatx = backend_config.set_floatx +set_image_data_format = backend_config.set_image_data_format + + +@doc_controls.do_not_generate_docs +def backend(): + """Publicly accessible method for determining the current backend. + + Only exists for API compatibility with multi-backend Keras. + + Returns: + The string "tensorflow". + """ + return 'tensorflow' + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def cast_to_floatx(x): + """Cast a Numpy array to the default Keras float type. + + Args: + x: Numpy array or TensorFlow tensor. + + Returns: + The same array (Numpy array if `x` was a Numpy array, or TensorFlow tensor + if `x` was a tensor), cast to its new type. + + Example: + + >>> tf.keras.backend.floatx() + 'float32' + >>> arr = np.array([1.0, 2.0], dtype='float64') + >>> arr.dtype + dtype('float64') + >>> new_arr = cast_to_floatx(arr) + >>> new_arr + array([1., 2.], dtype=float32) + >>> new_arr.dtype + dtype('float32') + + """ + if isinstance(x, (tensor_lib.Tensor, + variables_module.Variable, + sparse_tensor.SparseTensor)): + return math_ops.cast(x, dtype=floatx()) + return np.asarray(x, dtype=floatx()) + + +def get_uid(prefix=''): + """Associates a string prefix with an integer counter in a TensorFlow graph. + + Args: + prefix: String prefix to index. + + Returns: + Unique integer ID. + + Example: + + >>> get_uid('dense') + 1 + >>> get_uid('dense') + 2 + + """ + graph = get_graph() + if graph not in PER_GRAPH_OBJECT_NAME_UIDS: + PER_GRAPH_OBJECT_NAME_UIDS[graph] = collections.defaultdict(int) + layer_name_uids = PER_GRAPH_OBJECT_NAME_UIDS[graph] + layer_name_uids[prefix] += 1 + return layer_name_uids[prefix] + + +def reset_uids(): + """Resets graph identifiers. + """ + + PER_GRAPH_OBJECT_NAME_UIDS.clear() + OBSERVED_NAMES.clear() + + +def clear_session(): + """Resets all state generated by Keras. + + Keras manages a global state, which it uses to implement the Functional + model-building API and to uniquify autogenerated layer names. + + If you are creating many models in a loop, this global state will consume + an increasing amount of memory over time, and you may want to clear it. + Calling `clear_session()` releases the global state: this helps avoid clutter + from old models and layers, especially when memory is limited. + + Example 1: calling `clear_session()` when creating models in a loop + + ```python + for _ in range(100): + # Without `clear_session()`, each iteration of this loop will + # slightly increase the size of the global state managed by Keras + model = tf.keras.Sequential([tf.keras.layers.Dense(10) for _ in range(10)]) + + for _ in range(100): + # With `clear_session()` called at the beginning, + # Keras starts with a blank state at each iteration + # and memory consumption is constant over time. + tf.keras.backend.clear_session() + model = tf.keras.Sequential([tf.keras.layers.Dense(10) for _ in range(10)]) + ``` + + Example 2: resetting the layer name generation counter + + >>> import tensorflow as tf + >>> layers = [tf.keras.layers.Dense(10) for _ in range(10)] + >>> new_layer = tf.keras.layers.Dense(10) + >>> print(new_layer.name) + dense_10 + >>> tf.keras.backend.set_learning_phase(1) + >>> print(tf.keras.backend.learning_phase()) + 1 + >>> tf.keras.backend.clear_session() + >>> new_layer = tf.keras.layers.Dense(10) + >>> print(new_layer.name) + dense + """ + global _SESSION + global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned + global _GRAPH_VARIABLES # pylint: disable=global-variable-not-assigned + global _GRAPH_TF_OPTIMIZERS # pylint: disable=global-variable-not-assigned + global _GRAPH + _GRAPH.graph = None + ops.reset_default_graph() + reset_uids() + _SESSION.session = None + graph = get_graph() + with graph.as_default(): + _DUMMY_EAGER_GRAPH.learning_phase_is_set = False + _GRAPH_LEARNING_PHASES.clear() + # Create the learning phase placeholder in graph using the default factory. + _GRAPH_LEARNING_PHASES.setdefault(graph) + _GRAPH_VARIABLES.pop(graph, None) + _GRAPH_TF_OPTIMIZERS.pop(graph, None) + if context.executing_eagerly(): + # Clear pending nodes in eager executors, kernel caches and step_containers. + context.context().clear_kernel_cache() + + +@doc_controls.do_not_generate_docs +def manual_variable_initialization(value): + """Sets the manual variable initialization flag. + + This boolean flag determines whether + variables should be initialized + as they are instantiated (default), or if + the user should handle the initialization + (e.g. via `tf.compat.v1.initialize_all_variables()`). + + Args: + value: Python boolean. + """ + global _MANUAL_VAR_INIT + _MANUAL_VAR_INIT = value + + +@doc_controls.do_not_generate_docs +def learning_phase(): + """Returns the learning phase flag. + + The learning phase flag is a bool tensor (0 = test, 1 = train) + to be passed as input to any Keras function + that uses a different behavior at train time and test time. + + Returns: + Learning phase (scalar integer tensor or Python integer). + """ + graph = ops.get_default_graph() + if graph is getattr(_GRAPH, 'graph', None): + # Don't enter an init_scope for the learning phase if eager execution + # is enabled but we're inside the Keras workspace graph. + learning_phase = symbolic_learning_phase() + else: + with ops.init_scope(): + # We always check & set the learning phase inside the init_scope, + # otherwise the wrong default_graph will be used to look up the learning + # phase inside of functions & defuns. + # + # This is because functions & defuns (both in graph & in eager mode) + # will always execute non-eagerly using a function-specific default + # subgraph. + learning_phase = _GRAPH_LEARNING_PHASES[None] + _mark_func_graph_as_unsaveable(graph, learning_phase) + return learning_phase + + +def global_learning_phase_is_set(): + return _DUMMY_EAGER_GRAPH.learning_phase_is_set + + +def _mark_func_graph_as_unsaveable(graph, learning_phase): + """Mark func graph as unsaveable due to use of symbolic keras learning phase. + + Functions that capture the symbolic learning phase cannot be exported to + SavedModel. Mark the funcgraph as unsaveable, so that an error will be raised + if it is exported. + + Args: + graph: Graph or FuncGraph object. + learning_phase: Learning phase placeholder or int defined in the graph. + """ + if graph.building_function and is_placeholder(learning_phase): + graph.mark_as_unsaveable( + 'The keras learning phase placeholder was used inside a function. ' + 'Exporting placeholders is not supported when saving out a SavedModel. ' + 'Please call `tf.keras.backend.set_learning_phase(0)` in the function ' + 'to set the learning phase to a constant value.') + + +def symbolic_learning_phase(): + graph = get_graph() + with graph.as_default(): + return _GRAPH_LEARNING_PHASES[graph] + + +def _default_learning_phase(): + if context.executing_eagerly(): + return 0 + else: + with name_scope(''): + return array_ops.placeholder_with_default( + False, shape=(), name='keras_learning_phase') + + +@doc_controls.do_not_generate_docs +def set_learning_phase(value): + """Sets the learning phase to a fixed value. + + The backend learning phase affects any code that calls + `backend.learning_phase()` + In particular, all Keras built-in layers use the learning phase as the default + for the `training` arg to `Layer.__call__`. + + User-written layers and models can achieve the same behavior with code that + looks like: + + ```python + def call(self, inputs, training=None): + if training is None: + training = backend.learning_phase() + ``` + + Args: + value: Learning phase value, either 0 or 1 (integers). + 0 = test, 1 = train + + Raises: + ValueError: if `value` is neither `0` nor `1`. + """ + warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and ' + 'will be removed after 2020-10-11. To update it, simply ' + 'pass a True/False value to the `training` argument of the ' + '`__call__` method of your layer or model.') + deprecated_internal_set_learning_phase(value) + + +def deprecated_internal_set_learning_phase(value): + """A deprecated internal implementation of set_learning_phase. + + This method is an internal-only version of `set_learning_phase` that + does not raise a deprecation error. It is required because + saved_model needs to keep working with user code that uses the deprecated + learning phase methods until those APIs are fully removed from the public API. + + Specifically SavedModel saving needs to make sure the learning phase is 0 + during tracing even if users overwrote it to a different value. + + But, we don't want to raise deprecation warnings for users when savedmodel + sets learning phase just for compatibility with code that relied on + explicitly setting the learning phase for other values. + + Args: + value: Learning phase value, either 0 or 1 (integers). 0 = test, 1 = train + + Raises: + ValueError: if `value` is neither `0` nor `1`. + """ + global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned + if value not in {0, 1}: + raise ValueError('Expected learning phase to be 0 or 1.') + with ops.init_scope(): + if context.executing_eagerly(): + # In an eager context, the learning phase values applies to both the eager + # context and the internal Keras graph. + _DUMMY_EAGER_GRAPH.learning_phase_is_set = True + _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = value + _GRAPH_LEARNING_PHASES[get_graph()] = value + + +@tf_contextlib.contextmanager +@doc_controls.do_not_generate_docs +def learning_phase_scope(value): + """Provides a scope within which the learning phase is equal to `value`. + + The learning phase gets restored to its original value upon exiting the scope. + + Args: + value: Learning phase value, either 0 or 1 (integers). + 0 = test, 1 = train + + Yields: + None. + + Raises: + ValueError: if `value` is neither `0` nor `1`. + """ + warnings.warn('`tf.keras.backend.learning_phase_scope` is deprecated and ' + 'will be removed after 2020-10-11. To update it, simply ' + 'pass a True/False value to the `training` argument of the ' + '`__call__` method of your layer or model.') + with deprecated_internal_learning_phase_scope(value): + try: + yield + finally: + pass + + +@tf_contextlib.contextmanager +def deprecated_internal_learning_phase_scope(value): + """An internal-only version of `learning_phase_scope`. + + Unlike the public method, this method does not raise a deprecation warning. + This is needed because saved model saving needs to set learning phase + to maintain compatibility + with code that sets/gets the learning phase, but saved model + saving itself shouldn't raise a deprecation warning. + + We can get rid of this method and its usages when the public API is + removed. + + Args: + value: Learning phase value, either 0 or 1 (integers). 0 = test, 1 = train + + Yields: + None. + + Raises: + ValueError: if `value` is neither `0` nor `1`. + """ + global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned + if value not in {0, 1}: + raise ValueError('Expected learning phase to be 0 or 1.') + + with ops.init_scope(): + if context.executing_eagerly(): + previous_eager_value = _GRAPH_LEARNING_PHASES.get( + _DUMMY_EAGER_GRAPH.key, None) + previous_graph_value = _GRAPH_LEARNING_PHASES.get(get_graph(), None) + + learning_phase_previously_set = _DUMMY_EAGER_GRAPH.learning_phase_is_set + try: + deprecated_internal_set_learning_phase(value) + yield + finally: + # Restore learning phase to initial value. + if not learning_phase_previously_set: + _DUMMY_EAGER_GRAPH.learning_phase_is_set = False + with ops.init_scope(): + if context.executing_eagerly(): + if previous_eager_value is not None: + _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = previous_eager_value + elif _DUMMY_EAGER_GRAPH.key in _GRAPH_LEARNING_PHASES: + del _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] + + graph = get_graph() + if previous_graph_value is not None: + _GRAPH_LEARNING_PHASES[graph] = previous_graph_value + elif graph in _GRAPH_LEARNING_PHASES: + del _GRAPH_LEARNING_PHASES[graph] + + +@tf_contextlib.contextmanager +def eager_learning_phase_scope(value): + """Internal scope that sets the learning phase in eager / tf.function only. + + Args: + value: Learning phase value, either 0 or 1 (integers). + 0 = test, 1 = train + + Yields: + None. + + Raises: + ValueError: if `value` is neither `0` nor `1`. + """ + global _GRAPH_LEARNING_PHASES # pylint: disable=global-variable-not-assigned + assert value in {0, 1} + assert ops.executing_eagerly_outside_functions() + global_learning_phase_was_set = global_learning_phase_is_set() + if global_learning_phase_was_set: + previous_value = learning_phase() + try: + _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = value + yield + finally: + # Restore learning phase to initial value or unset. + if global_learning_phase_was_set: + _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] = previous_value + else: + del _GRAPH_LEARNING_PHASES[_DUMMY_EAGER_GRAPH.key] + + +def _as_graph_element(obj): + """Convert `obj` to a graph element if possible, otherwise return `None`. + + Args: + obj: Object to convert. + + Returns: + The result of `obj._as_graph_element()` if that method is available; + otherwise `None`. + """ + conv_fn = getattr(obj, '_as_graph_element', None) + if conv_fn and callable(conv_fn): + return conv_fn() + return None + + +def _assert_same_graph(original_item, item): + """Fail if the 2 items are from different graphs. + + Args: + original_item: Original item to check against. + item: Item to check. + + Raises: + ValueError: if graphs do not match. + """ + original_graph = getattr(original_item, 'graph', None) + graph = getattr(item, 'graph', None) + if original_graph and graph and original_graph is not graph: + raise ValueError( + '%s must be from the same graph as %s (graphs are %s and %s).' % + (item, original_item, graph, original_graph)) + + +def _current_graph(op_input_list, graph=None): + """Returns the appropriate graph to use for the given inputs. + + This library method provides a consistent algorithm for choosing the graph + in which an Operation should be constructed: + + 1. If the default graph is being used to construct a function, we + use the default graph. + 2. If the "graph" is specified explicitly, we validate that all of the inputs + in "op_input_list" are compatible with that graph. + 3. Otherwise, we attempt to select a graph from the first Operation- + or Tensor-valued input in "op_input_list", and validate that all other + such inputs are in the same graph. + 4. If the graph was not specified and it could not be inferred from + "op_input_list", we attempt to use the default graph. + + Args: + op_input_list: A list of inputs to an operation, which may include `Tensor`, + `Operation`, and other objects that may be converted to a graph element. + graph: (Optional) The explicit graph to use. + + Raises: + TypeError: If op_input_list is not a list or tuple, or if graph is not a + Graph. + ValueError: If a graph is explicitly passed and not all inputs are from it, + or if the inputs are from multiple graphs, or we could not find a graph + and there was no default graph. + + Returns: + The appropriate graph to use for the given inputs. + + """ + current_default_graph = ops.get_default_graph() + if current_default_graph.building_function: + return current_default_graph + + op_input_list = tuple(op_input_list) # Handle generators correctly + if graph and not isinstance(graph, ops.Graph): + raise TypeError('Input graph needs to be a Graph: %s' % (graph,)) + + # 1. We validate that all of the inputs are from the same graph. This is + # either the supplied graph parameter, or the first one selected from one + # the graph-element-valued inputs. In the latter case, we hold onto + # that input in original_graph_element so we can provide a more + # informative error if a mismatch is found. + original_graph_element = None + for op_input in op_input_list: + # Determine if this is a valid graph_element. + # TODO(josh11b): Note that we exclude subclasses of Tensor. Need to clean this + # up. + if (isinstance(op_input, ( + ops.Operation, tensor_lib.Tensor, composite_tensor.CompositeTensor)) and + ((not isinstance(op_input, tensor_lib.Tensor)) + or type(op_input) == tensor_lib.Tensor)): # pylint: disable=unidiomatic-typecheck + graph_element = op_input + else: + graph_element = _as_graph_element(op_input) + + if graph_element is not None: + if not graph: + original_graph_element = graph_element + graph = getattr(graph_element, 'graph', None) + elif original_graph_element is not None: + _assert_same_graph(original_graph_element, graph_element) + elif graph_element.graph is not graph: + raise ValueError('%s is not from the passed-in graph.' % graph_element) + + # 2. If all else fails, we use the default graph, which is always there. + return graph or current_default_graph + + +def _get_session(op_input_list=()): + """Returns the session object for the current thread.""" + global _SESSION + default_session = ops.get_default_session() + if default_session is not None: + session = default_session + else: + if ops.inside_function(): + raise RuntimeError('Cannot get session inside Tensorflow graph function.') + # If we don't have a session, or that session does not match the current + # graph, create and cache a new session. + if (getattr(_SESSION, 'session', None) is None or + _SESSION.session.graph is not _current_graph(op_input_list)): + # If we are creating the Session inside a tf.distribute.Strategy scope, + # we ask the strategy for the right session options to use. + if distribute_lib.has_strategy(): + configure_and_create_distributed_session( + distribute_lib.get_strategy()) + else: + _SESSION.session = session_module.Session( + config=get_default_session_config()) + session = _SESSION.session + return session + + +def get_session(op_input_list=()): + """Returns the TF session to be used by the backend. + + If a default TensorFlow session is available, we will return it. + + Else, we will return the global Keras session assuming it matches + the current graph. + + If no global Keras session exists at this point: + we will create a new global session. + + Note that you can manually set the global session + via `K.set_session(sess)`. + + Args: + op_input_list: An option sequence of tensors or ops, which will be used + to determine the current graph. Otherwise the default graph will be + used. + + Returns: + A TensorFlow session. + """ + session = _get_session(op_input_list) + if not _MANUAL_VAR_INIT: + with session.graph.as_default(): + _initialize_variables(session) + return session + + +def get_graph(): + if context.executing_eagerly(): + global _GRAPH + if not getattr(_GRAPH, 'graph', None): + _GRAPH.graph = func_graph.FuncGraph('keras_graph') + return _GRAPH.graph + else: + return ops.get_default_graph() + + +@tf_contextlib.contextmanager +def _scratch_graph(graph=None): + """Retrieve a shared and temporary func graph. + + The eager execution path lifts a subgraph from the keras global graph into + a scratch graph in order to create a function. DistributionStrategies, in + turn, constructs multiple functions as well as a final combined function. In + order for that logic to work correctly, all of the functions need to be + created on the same scratch FuncGraph. + + Args: + graph: A graph to be used as the current scratch graph. If not set then + a scratch graph will either be retrieved or created: + + Yields: + The current scratch graph. + """ + global _CURRENT_SCRATCH_GRAPH + scratch_graph = getattr(_CURRENT_SCRATCH_GRAPH, 'graph', None) + # If scratch graph and `graph` are both configured, they must match. + if (scratch_graph is not None and graph is not None and + scratch_graph is not graph): + raise ValueError('Multiple scratch graphs specified.') + + if scratch_graph: + yield scratch_graph + return + + graph = graph or func_graph.FuncGraph('keras_scratch_graph') + try: + _CURRENT_SCRATCH_GRAPH.graph = graph + yield graph + finally: + _CURRENT_SCRATCH_GRAPH.graph = None + + +def set_session(session): + """Sets the global TensorFlow session. + + Args: + session: A TF Session. + """ + global _SESSION + _SESSION.session = session + + +def get_default_session_config(): + if os.environ.get('OMP_NUM_THREADS'): + logging.warning( + 'OMP_NUM_THREADS is no longer used by the default Keras config. ' + 'To configure the number of threads, use tf.config.threading APIs.') + + config = get_config() + config.allow_soft_placement = True + + return config + + +def get_default_graph_uid_map(): + graph = ops.get_default_graph() + name_uid_map = PER_GRAPH_OBJECT_NAME_UIDS.get(graph, None) + if name_uid_map is None: + name_uid_map = collections.defaultdict(int) + PER_GRAPH_OBJECT_NAME_UIDS[graph] = name_uid_map + return name_uid_map + + +# DEVICE MANIPULATION + + +class _TfDeviceCaptureOp: + """Class for capturing the TF device scope.""" + + def __init__(self): + self.device = None + + def _set_device(self, device): + """This method captures TF's explicit device scope setting.""" + if isinstance(device, device_spec.DeviceSpecV2): + device = device.to_string() + self.device = device + + def _set_device_from_string(self, device_str): + self.device = device_str + + +def _get_current_tf_device(): + """Return explicit device of current context, otherwise returns `None`. + + Returns: + If the current device scope is explicitly set, it returns a string with + the device (`CPU` or `GPU`). If the scope is not explicitly set, it will + return `None`. + """ + graph = get_graph() + op = _TfDeviceCaptureOp() + graph._apply_device_functions(op) + if tf2.enabled(): + return device_spec.DeviceSpecV2.from_string(op.device) + else: + return device_spec.DeviceSpecV1.from_string(op.device) + + +def _is_current_explicit_device(device_type): + """Check if the current device is explicitly set on the device type specified. + + Args: + device_type: A string containing `GPU` or `CPU` (case-insensitive). + + Returns: + A boolean indicating if the current device scope is explicitly set on the + device type. + + Raises: + ValueError: If the `device_type` string indicates an unsupported device. + """ + device_type = device_type.upper() + if device_type not in ['CPU', 'GPU']: + raise ValueError('`device_type` should be either "CPU" or "GPU".') + device = _get_current_tf_device() + return device is not None and device.device_type == device_type.upper() + + +def _get_available_gpus(): + """Get a list of available GPU devices (formatted as strings). + + Returns: + A list of available GPU devices. + """ + if ops.executing_eagerly_outside_functions(): + # Returns names of devices directly. + return [d.name for d in config.list_logical_devices('GPU')] + + global _LOCAL_DEVICES + if _LOCAL_DEVICES is None: + _LOCAL_DEVICES = get_session().list_devices() + return [x.name for x in _LOCAL_DEVICES if x.device_type == 'GPU'] + + +def _has_nchw_support(): + """Check whether the current scope supports NCHW ops. + + TensorFlow does not support NCHW on CPU. Therefore we check if we are not + explicitly put on + CPU, and have GPUs available. In this case there will be soft-placing on the + GPU device. + + Returns: + bool: if the current scope device placement would support nchw + """ + explicitly_on_cpu = _is_current_explicit_device('CPU') + gpus_available = bool(_get_available_gpus()) + return not explicitly_on_cpu and gpus_available + + +# VARIABLE MANIPULATION + + +def _constant_to_tensor(x, dtype): + """Convert the input `x` to a tensor of type `dtype`. + + This is slightly faster than the _to_tensor function, at the cost of + handling fewer cases. + + Args: + x: An object to be converted (numpy arrays, floats, ints and lists of + them). + dtype: The destination type. + + Returns: + A tensor. + """ + return constant_op.constant(x, dtype=dtype) + + +def _to_tensor(x, dtype): + """Convert the input `x` to a tensor of type `dtype`. + + Args: + x: An object to be converted (numpy array, list, tensors). + dtype: The destination type. + + Returns: + A tensor. + """ + return tensor_conversion.convert_to_tensor_v2_with_dispatch(x, dtype=dtype) + + +@doc_controls.do_not_generate_docs +def is_sparse(tensor): + """Returns whether a tensor is a sparse tensor. + + Args: + tensor: A tensor instance. + + Returns: + A boolean. + + Example: + + + >>> a = tf.keras.backend.placeholder((2, 2), sparse=False) + >>> print(tf.keras.backend.is_sparse(a)) + False + >>> b = tf.keras.backend.placeholder((2, 2), sparse=True) + >>> print(tf.keras.backend.is_sparse(b)) + True + + """ + spec = getattr(tensor, '_type_spec', None) + if spec is not None: + return isinstance(spec, sparse_tensor.SparseTensorSpec) + return isinstance(tensor, sparse_tensor.SparseTensor) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def to_dense(tensor): + """Converts a sparse tensor into a dense tensor and returns it. + + Args: + tensor: A tensor instance (potentially sparse). + + Returns: + A dense tensor. + + Examples: + + + >>> b = tf.keras.backend.placeholder((2, 2), sparse=True) + >>> print(tf.keras.backend.is_sparse(b)) + True + >>> c = tf.keras.backend.to_dense(b) + >>> print(tf.keras.backend.is_sparse(c)) + False + + """ + if is_sparse(tensor): + return sparse_ops.sparse_tensor_to_dense(tensor) + else: + return tensor + + +@doc_controls.do_not_generate_docs +def name_scope(name): + """A context manager for use when defining a Python op. + + This context manager pushes a name scope, which will make the name of all + operations added within it have a prefix. + + For example, to define a new Python op called `my_op`: + + + def my_op(a): + with tf.name_scope("MyOp") as scope: + a = tf.convert_to_tensor(a, name="a") + # Define some computation that uses `a`. + return foo_op(..., name=scope) + + + When executed, the Tensor `a` will have the name `MyOp/a`. + + Args: + name: The prefix to use on all names created within the name scope. + + Returns: + Name scope context manager. + """ + return ops.name_scope_v2(name) + + +@doc_controls.do_not_generate_docs +def variable(value, dtype=None, name=None, constraint=None): + """Instantiates a variable and returns it. + + Args: + value: Numpy array, initial value of the tensor. + dtype: Tensor type. + name: Optional name string for the tensor. + constraint: Optional projection function to be + applied to the variable after an optimizer update. + + Returns: + A variable instance (with Keras metadata included). + + Examples: + + >>> val = np.array([[1, 2], [3, 4]]) + >>> kvar = tf.keras.backend.variable(value=val, dtype='float64', + ... name='example_var') + >>> tf.keras.backend.dtype(kvar) + 'float64' + >>> print(kvar) + + + """ + if dtype is None: + dtype = floatx() + if hasattr(value, 'tocoo'): + sparse_coo = value.tocoo() + indices = np.concatenate((np.expand_dims(sparse_coo.row, 1), np.expand_dims( + sparse_coo.col, 1)), 1) + v = sparse_tensor.SparseTensor( + indices=indices, values=sparse_coo.data, dense_shape=sparse_coo.shape) + v._keras_shape = sparse_coo.shape + return v + v = variables_module.Variable( + value, + dtype=dtypes_module.as_dtype(dtype), + name=name, + constraint=constraint) + if isinstance(value, np.ndarray): + v._keras_shape = value.shape + elif hasattr(value, 'shape'): + v._keras_shape = int_shape(value) + track_variable(v) + return v + + +def track_tf_optimizer(tf_optimizer): + """Tracks the given TF optimizer for initialization of its variables.""" + if context.executing_eagerly(): + return + optimizers = _GRAPH_TF_OPTIMIZERS[None] + optimizers.add(tf_optimizer) + + +def track_variable(v): + """Tracks the given variable for initialization.""" + if context.executing_eagerly(): + return + graph = v.graph if hasattr(v, 'graph') else get_graph() + _GRAPH_VARIABLES[graph].add(v) + + +def observe_object_name(name): + """Observe a name and make sure it won't be used by `unique_object_name`.""" + OBSERVED_NAMES.add(name) + + +def unique_object_name(name, + name_uid_map=None, + avoid_names=None, + namespace='', + zero_based=False, + avoid_observed_names=False): + """Makes a object name (or arbitrary string) unique within a TensorFlow graph. + + Args: + name: String name to make unique. + name_uid_map: An optional defaultdict(int) to use when creating unique + names. If None (default), uses a per-Graph dictionary. + avoid_names: An optional set or dict with names which should not be used. If + None (default), don't avoid any names unless `avoid_observed_names` is + True. + namespace: Gets a name which is unique within the (graph, namespace). Layers + which are not Networks use a blank namespace and so get graph-global + names. + zero_based: If True, name sequences start with no suffix (e.g. "dense", + "dense_1"). If False, naming is one-based ("dense_1", "dense_2"). + avoid_observed_names: If True, avoid any names that have been observed by + `backend.observe_object_name`. + + Returns: + Unique string name. + + Example: + + + unique_object_name('dense') # dense_1 + unique_object_name('dense') # dense_2 + + """ + if name_uid_map is None: + name_uid_map = get_default_graph_uid_map() + if avoid_names is None: + if avoid_observed_names: + avoid_names = OBSERVED_NAMES + else: + avoid_names = set() + proposed_name = None + while proposed_name is None or proposed_name in avoid_names: + name_key = (namespace, name) + if zero_based: + number = name_uid_map[name_key] + if number: + proposed_name = name + '_' + str(number) + else: + proposed_name = name + name_uid_map[name_key] += 1 + else: + name_uid_map[name_key] += 1 + proposed_name = name + '_' + str(name_uid_map[name_key]) + return proposed_name + + +def _get_variables(graph=None): + """Returns variables corresponding to the given graph for initialization.""" + assert not context.executing_eagerly() + variables = _GRAPH_VARIABLES[graph] + for opt in _GRAPH_TF_OPTIMIZERS[graph]: + variables.update(opt.optimizer.variables()) + return variables + + +def _initialize_variables(session): + """Utility to initialize uninitialized variables on the fly.""" + variables = _get_variables(get_graph()) + candidate_vars = [] + for v in variables: + if not getattr(v, '_keras_initialized', False): + candidate_vars.append(v) + if candidate_vars: + # This step is expensive, so we only run it on variables not already + # marked as initialized. + is_initialized = session.run( + [variable_v1.is_variable_initialized(v) for v in candidate_vars]) + # TODO(kathywu): Some metric variables loaded from SavedModel are never + # actually used, and do not have an initializer. + should_be_initialized = [ + (not is_initialized[n]) and v.initializer is not None + for n, v in enumerate(candidate_vars)] + uninitialized_vars = [] + for flag, v in zip(should_be_initialized, candidate_vars): + if flag: + uninitialized_vars.append(v) + v._keras_initialized = True + if uninitialized_vars: + session.run(variables_module.variables_initializer(uninitialized_vars)) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def constant(value, dtype=None, shape=None, name=None): + """Creates a constant tensor. + + Args: + value: A constant value (or list) + dtype: The type of the elements of the resulting tensor. + shape: Optional dimensions of resulting tensor. + name: Optional name for the tensor. + + Returns: + A Constant Tensor. + """ + if dtype is None: + dtype = floatx() + + return constant_op.constant(value, dtype=dtype, shape=shape, name=name) + + +def is_keras_tensor(x): + """Returns whether `x` is a Keras tensor. + + A "Keras tensor" is a tensor that was returned by a Keras layer, + (`Layer` class) or by `Input`. + + Args: + x: A candidate tensor. + + Returns: + A boolean: Whether the argument is a Keras tensor. + + Raises: + ValueError: In case `x` is not a symbolic tensor. + + Examples: + + >>> np_var = np.array([1, 2]) + >>> # A numpy array is not a symbolic tensor. + >>> tf.keras.backend.is_keras_tensor(np_var) + Traceback (most recent call last): + ... + ValueError: Unexpectedly found an instance of type ``. + Expected a symbolic tensor instance. + >>> keras_var = tf.keras.backend.variable(np_var) + >>> # A variable created with the keras backend is not a Keras tensor. + >>> tf.keras.backend.is_keras_tensor(keras_var) + False + >>> keras_placeholder = tf.keras.backend.placeholder(shape=(2, 4, 5)) + >>> # A placeholder is a Keras tensor. + >>> tf.keras.backend.is_keras_tensor(keras_placeholder) + True + >>> keras_input = tf.keras.layers.Input([10]) + >>> # An Input is a Keras tensor. + >>> tf.keras.backend.is_keras_tensor(keras_input) + True + >>> keras_layer_output = tf.keras.layers.Dense(10)(keras_input) + >>> # Any Keras layer output is a Keras tensor. + >>> tf.keras.backend.is_keras_tensor(keras_layer_output) + True + + """ + if not isinstance(x, + (tensor_lib.Tensor, variables_module.Variable, + sparse_tensor.SparseTensor, ragged_tensor.RaggedTensor, + keras_tensor.KerasTensor)): + raise ValueError('Unexpectedly found an instance of type `' + str(type(x)) + + '`. Expected a symbolic tensor instance.') + if ops.executing_eagerly_outside_functions(): + return isinstance(x, keras_tensor.KerasTensor) + return hasattr(x, '_keras_history') + + +@doc_controls.do_not_generate_docs +def placeholder(shape=None, + ndim=None, + dtype=None, + sparse=False, + name=None, + ragged=False): + """Instantiates a placeholder tensor and returns it. + + Args: + shape: Shape of the placeholder + (integer tuple, may include `None` entries). + ndim: Number of axes of the tensor. + At least one of {`shape`, `ndim`} must be specified. + If both are specified, `shape` is used. + dtype: Placeholder type. + sparse: Boolean, whether the placeholder should have a sparse type. + name: Optional name string for the placeholder. + ragged: Boolean, whether the placeholder should have a ragged type. + In this case, values of 'None' in the 'shape' argument represent + ragged dimensions. For more information about RaggedTensors, see this + [guide](https://www.tensorflow.org/guide/ragged_tensors). + + Raises: + ValueError: If called with sparse = True and ragged = True. + + Returns: + Tensor instance (with Keras metadata included). + + Examples: + + + >>> input_ph = tf.keras.backend.placeholder(shape=(2, 4, 5)) + >>> input_ph + + + """ + if sparse and ragged: + raise ValueError( + 'Cannot set both sparse and ragged to True when creating a placeholder.' + ) + if dtype is None: + dtype = floatx() + if not shape: + if ndim: + shape = (None,) * ndim + if ops.executing_eagerly_outside_functions(): + if sparse: + spec = sparse_tensor.SparseTensorSpec( + shape=shape, dtype=dtype) + elif ragged: + ragged_rank = 0 + for i in range(1, len(shape)): + # Hacky because could be tensorshape or tuple maybe? + # Or just tensorshape? + if shape[i] is None or ( + hasattr(shape[i], 'value') and + shape[i].value is None): + ragged_rank = i + spec = ragged_tensor.RaggedTensorSpec( + shape=shape, dtype=dtype, ragged_rank=ragged_rank) + else: + spec = tensor_lib.TensorSpec( + shape=shape, dtype=dtype, name=name) + x = keras_tensor.keras_tensor_from_type_spec(spec, name=name) + else: + with get_graph().as_default(): + if sparse: + x = array_ops.sparse_placeholder(dtype, shape=shape, name=name) + elif ragged: + ragged_rank = 0 + for i in range(1, len(shape)): + if shape[i] is None: + ragged_rank = i + type_spec = ragged_tensor.RaggedTensorSpec( + shape=shape, dtype=dtype, ragged_rank=ragged_rank) + def tensor_spec_to_placeholder(tensorspec): + return array_ops.placeholder(tensorspec.dtype, tensorspec.shape) + x = nest.map_structure(tensor_spec_to_placeholder, type_spec, + expand_composites=True) + else: + x = array_ops.placeholder(dtype, shape=shape, name=name) + + if context.executing_eagerly(): + # Add keras_history connectivity information to the placeholder + # when the placeholder is built in a top-level eager context + # (intended to be used with keras.backend.function) + from tensorflow.python.keras.engine import input_layer # pylint: disable=g-import-not-at-top + x = input_layer.Input(tensor=x) + x._is_backend_placeholder = True + + return x + + +def is_placeholder(x): + """Returns whether `x` is a placeholder. + + Args: + x: A candidate placeholder. + + Returns: + Boolean. + """ + try: + if ops.executing_eagerly_outside_functions(): + return hasattr(x, '_is_backend_placeholder') + from tensorflow.python.keras.utils import tf_utils # pylint: disable=g-import-not-at-top + if tf_utils.is_extension_type(x): + flat_components = nest.flatten(x, expand_composites=True) + return py_any(is_placeholder(c) for c in flat_components) + else: + return x.op.type == 'Placeholder' + except AttributeError: + return False + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def shape(x): + """Returns the symbolic shape of a tensor or variable. + + Args: + x: A tensor or variable. + + Returns: + A symbolic shape (which is itself a tensor). + + Examples: + + >>> val = np.array([[1, 2], [3, 4]]) + >>> kvar = tf.keras.backend.variable(value=val) + >>> tf.keras.backend.shape(kvar) + + >>> input = tf.keras.backend.placeholder(shape=(2, 4, 5)) + >>> tf.keras.backend.shape(input) + + + """ + return array_ops.shape(x) + + +@doc_controls.do_not_generate_docs +def int_shape(x): + """Returns the shape of tensor or variable as a tuple of int or None entries. + + Args: + x: Tensor or variable. + + Returns: + A tuple of integers (or None entries). + + Examples: + + >>> input = tf.keras.backend.placeholder(shape=(2, 4, 5)) + >>> tf.keras.backend.int_shape(input) + (2, 4, 5) + >>> val = np.array([[1, 2], [3, 4]]) + >>> kvar = tf.keras.backend.variable(value=val) + >>> tf.keras.backend.int_shape(kvar) + (2, 2) + + """ + try: + shape = x.shape + if not isinstance(shape, tuple): + shape = tuple(shape.as_list()) + return shape + except ValueError: + return None + + +@doc_controls.do_not_generate_docs +def ndim(x): + """Returns the number of axes in a tensor, as an integer. + + Args: + x: Tensor or variable. + + Returns: + Integer (scalar), number of axes. + + Examples: + + + >>> input = tf.keras.backend.placeholder(shape=(2, 4, 5)) + >>> val = np.array([[1, 2], [3, 4]]) + >>> kvar = tf.keras.backend.variable(value=val) + >>> tf.keras.backend.ndim(input) + 3 + >>> tf.keras.backend.ndim(kvar) + 2 + + """ + return x.shape.rank + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def dtype(x): + """Returns the dtype of a Keras tensor or variable, as a string. + + Args: + x: Tensor or variable. + + Returns: + String, dtype of `x`. + + Examples: + + >>> tf.keras.backend.dtype(tf.keras.backend.placeholder(shape=(2,4,5))) + 'float32' + >>> tf.keras.backend.dtype(tf.keras.backend.placeholder(shape=(2,4,5), + ... dtype='float32')) + 'float32' + >>> tf.keras.backend.dtype(tf.keras.backend.placeholder(shape=(2,4,5), + ... dtype='float64')) + 'float64' + >>> kvar = tf.keras.backend.variable(np.array([[1, 2], [3, 4]])) + >>> tf.keras.backend.dtype(kvar) + 'float32' + >>> kvar = tf.keras.backend.variable(np.array([[1, 2], [3, 4]]), + ... dtype='float32') + >>> tf.keras.backend.dtype(kvar) + 'float32' + + """ + return x.dtype.base_dtype.name + + +@doc_controls.do_not_generate_docs +def dtype_numpy(x): + """Returns the numpy dtype of a Keras tensor or variable. + + Args: + x: Tensor or variable. + + Returns: + numpy.dtype, dtype of `x`. + """ + return dtypes_module.as_dtype(x.dtype).as_numpy_dtype + + +@doc_controls.do_not_generate_docs +def eval(x): + """Evaluates the value of a variable. + + Args: + x: A variable. + + Returns: + A Numpy array. + + Examples: + + >>> kvar = tf.keras.backend.variable(np.array([[1, 2], [3, 4]]), + ... dtype='float32') + >>> tf.keras.backend.eval(kvar) + array([[1., 2.], + [3., 4.]], dtype=float32) + + """ + return get_value(to_dense(x)) + + +@doc_controls.do_not_generate_docs +def zeros(shape, dtype=None, name=None): + """Instantiates an all-zeros variable and returns it. + + Args: + shape: Tuple or list of integers, shape of returned Keras variable + dtype: data type of returned Keras variable + name: name of returned Keras variable + + Returns: + A variable (including Keras metadata), filled with `0.0`. + Note that if `shape` was symbolic, we cannot return a variable, + and will return a dynamically-shaped tensor instead. + + Example: + + >>> kvar = tf.keras.backend.zeros((3,4)) + >>> tf.keras.backend.eval(kvar) + array([[0., 0., 0., 0.], + [0., 0., 0., 0.], + [0., 0., 0., 0.]], dtype=float32) + >>> A = tf.constant([1,2,3]) + >>> kvar2 = tf.keras.backend.zeros(A.shape) # [0., 0., 0.] + >>> tf.keras.backend.eval(kvar2) + array([0., 0., 0.], dtype=float32) + >>> kvar3 = tf.keras.backend.zeros(A.shape,dtype=tf.int32) + >>> tf.keras.backend.eval(kvar3) + array([0, 0, 0], dtype=int32) + >>> kvar4 = tf.keras.backend.zeros([2,3]) + >>> tf.keras.backend.eval(kvar4) + array([[0., 0., 0.], + [0., 0., 0.]], dtype=float32) + + """ + with ops.init_scope(): + if dtype is None: + dtype = floatx() + tf_dtype = dtypes_module.as_dtype(dtype) + v = array_ops.zeros(shape=shape, dtype=tf_dtype, name=name) + if py_all(v.shape.as_list()): + return variable(v, dtype=dtype, name=name) + return v + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def ones(shape, dtype=None, name=None): + """Instantiates an all-ones variable and returns it. + + Args: + shape: Tuple of integers, shape of returned Keras variable. + dtype: String, data type of returned Keras variable. + name: String, name of returned Keras variable. + + Returns: + A Keras variable, filled with `1.0`. + Note that if `shape` was symbolic, we cannot return a variable, + and will return a dynamically-shaped tensor instead. + + Example: + + + >>> kvar = tf.keras.backend.ones((3,4)) + >>> tf.keras.backend.eval(kvar) + array([[1., 1., 1., 1.], + [1., 1., 1., 1.], + [1., 1., 1., 1.]], dtype=float32) + + """ + with ops.init_scope(): + if dtype is None: + dtype = floatx() + tf_dtype = dtypes_module.as_dtype(dtype) + v = array_ops.ones(shape=shape, dtype=tf_dtype, name=name) + if py_all(v.shape.as_list()): + return variable(v, dtype=dtype, name=name) + return v + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def eye(size, dtype=None, name=None): + """Instantiate an identity matrix and returns it. + + Args: + size: Integer, number of rows/columns. + dtype: String, data type of returned Keras variable. + name: String, name of returned Keras variable. + + Returns: + A Keras variable, an identity matrix. + + Example: + + + >>> kvar = tf.keras.backend.eye(3) + >>> tf.keras.backend.eval(kvar) + array([[1., 0., 0.], + [0., 1., 0.], + [0., 0., 1.]], dtype=float32) + + + """ + if dtype is None: + dtype = floatx() + tf_dtype = dtypes_module.as_dtype(dtype) + return variable(linalg_ops.eye(size, dtype=tf_dtype), dtype, name) + + +@doc_controls.do_not_generate_docs +def zeros_like(x, dtype=None, name=None): + """Instantiates an all-zeros variable of the same shape as another tensor. + + Args: + x: Keras variable or Keras tensor. + dtype: dtype of returned Keras variable. + `None` uses the dtype of `x`. + name: name for the variable to create. + + Returns: + A Keras variable with the shape of `x` filled with zeros. + + Example: + + ```python + from tensorflow.keras import backend as K + kvar = K.variable(np.random.random((2,3))) + kvar_zeros = K.zeros_like(kvar) + K.eval(kvar_zeros) + # array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) + ``` + """ + return array_ops.zeros_like(x, dtype=dtype, name=name) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def ones_like(x, dtype=None, name=None): + """Instantiates an all-ones variable of the same shape as another tensor. + + Args: + x: Keras variable or tensor. + dtype: String, dtype of returned Keras variable. + None uses the dtype of x. + name: String, name for the variable to create. + + Returns: + A Keras variable with the shape of x filled with ones. + + Example: + + >>> kvar = tf.keras.backend.variable(np.random.random((2,3))) + >>> kvar_ones = tf.keras.backend.ones_like(kvar) + >>> tf.keras.backend.eval(kvar_ones) + array([[1., 1., 1.], + [1., 1., 1.]], dtype=float32) + + """ + return array_ops.ones_like(x, dtype=dtype, name=name) + + +def identity(x, name=None): + """Returns a tensor with the same content as the input tensor. + + Args: + x: The input tensor. + name: String, name for the variable to create. + + Returns: + A tensor of the same shape, type and content. + """ + return array_ops.identity(x, name=name) + + +@doc_controls.do_not_generate_docs +def random_uniform_variable(shape, low, high, dtype=None, name=None, seed=None): + """Instantiates a variable with values drawn from a uniform distribution. + + Args: + shape: Tuple of integers, shape of returned Keras variable. + low: Float, lower boundary of the output interval. + high: Float, upper boundary of the output interval. + dtype: String, dtype of returned Keras variable. + name: String, name of returned Keras variable. + seed: Integer, random seed. + + Returns: + A Keras variable, filled with drawn samples. + + Example: + + >>> kvar = tf.keras.backend.random_uniform_variable(shape=(2,3), + ... low=0.0, high=1.0) + >>> kvar + + """ + if dtype is None: + dtype = floatx() + tf_dtype = dtypes_module.as_dtype(dtype) + if seed is None: + # ensure that randomness is conditioned by the Numpy RNG + seed = np.random.randint(10e8) + value = init_ops.random_uniform_initializer( + low, high, dtype=tf_dtype, seed=seed)(shape) + return variable(value, dtype=dtype, name=name) + + +@doc_controls.do_not_generate_docs +def random_normal_variable(shape, mean, scale, dtype=None, name=None, + seed=None): + """Instantiates a variable with values drawn from a normal distribution. + + Args: + shape: Tuple of integers, shape of returned Keras variable. + mean: Float, mean of the normal distribution. + scale: Float, standard deviation of the normal distribution. + dtype: String, dtype of returned Keras variable. + name: String, name of returned Keras variable. + seed: Integer, random seed. + + Returns: + A Keras variable, filled with drawn samples. + + Example: + + >>> kvar = tf.keras.backend.random_normal_variable(shape=(2,3), + ... mean=0.0, scale=1.0) + >>> kvar + + """ + if dtype is None: + dtype = floatx() + tf_dtype = dtypes_module.as_dtype(dtype) + if seed is None: + # ensure that randomness is conditioned by the Numpy RNG + seed = np.random.randint(10e8) + value = init_ops.random_normal_initializer( + mean, scale, dtype=tf_dtype, seed=seed)(shape) + return variable(value, dtype=dtype, name=name) + + +@doc_controls.do_not_generate_docs +def count_params(x): + """Returns the static number of elements in a variable or tensor. + + Args: + x: Variable or tensor. + + Returns: + Integer, the number of scalars in `x`. + + Example: + + >>> kvar = tf.keras.backend.zeros((2,3)) + >>> tf.keras.backend.count_params(kvar) + 6 + >>> tf.keras.backend.eval(kvar) + array([[0., 0., 0.], + [0., 0., 0.]], dtype=float32) + + """ + return np.prod(x.shape.as_list()) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def cast(x, dtype): + """Casts a tensor to a different dtype and returns it. + + You can cast a Keras variable but it still returns a Keras tensor. + + Args: + x: Keras tensor (or variable). + dtype: String, either (`'float16'`, `'float32'`, or `'float64'`). + + Returns: + Keras tensor with dtype `dtype`. + + Examples: + Cast a float32 variable to a float64 tensor + + >>> input = tf.keras.backend.ones(shape=(1,3)) + >>> print(input) + + >>> cast_input = tf.keras.backend.cast(input, dtype='float64') + >>> print(cast_input) + tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float64) + + """ + return math_ops.cast(x, dtype) + + +# UPDATES OPS + + +@doc_controls.do_not_generate_docs +def update(x, new_x): + return state_ops.assign(x, new_x) + + +@doc_controls.do_not_generate_docs +def update_add(x, increment): + """Update the value of `x` by adding `increment`. + + Args: + x: A Variable. + increment: A tensor of same shape as `x`. + + Returns: + The variable `x` updated. + """ + return state_ops.assign_add(x, increment) + + +@doc_controls.do_not_generate_docs +def update_sub(x, decrement): + """Update the value of `x` by subtracting `decrement`. + + Args: + x: A Variable. + decrement: A tensor of same shape as `x`. + + Returns: + The variable `x` updated. + """ + return state_ops.assign_sub(x, decrement) + + +@doc_controls.do_not_generate_docs +def moving_average_update(x, value, momentum): + """Compute the exponential moving average of a value. + + The moving average 'x' is updated with 'value' following: + + ``` + x = x * momentum + value * (1 - momentum) + ``` + + For example: + + >>> x = tf.Variable(0.0) + >>> momentum=0.9 + >>> moving_average_update(x, value = 2.0, momentum=momentum).numpy() + >>> x.numpy() + 0.2 + + The result will be biased towards the initial value of the variable. + + If the variable was initialized to zero, you can divide by + `1 - momentum ** num_updates` to debias it (Section 3 of + [Kingma et al., 2015](https://arxiv.org/abs/1412.6980)): + + >>> num_updates = 1.0 + >>> x_zdb = x/(1 - momentum**num_updates) + >>> x_zdb.numpy() + 2.0 + + Args: + x: A Variable, the moving average. + value: A tensor with the same shape as `x`, the new value to be + averaged in. + momentum: The moving average momentum. + + Returns: + The updated variable. + """ + if tf2.enabled(): + momentum = math_ops.cast(momentum, x.dtype) + value = math_ops.cast(value, x.dtype) + return x.assign(x * momentum + value * (1 - momentum)) + else: + return moving_averages.assign_moving_average( + x, value, momentum, zero_debias=True) + + +# LINEAR ALGEBRA + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def dot(x, y): + """Multiplies 2 tensors (and/or variables) and returns a tensor. + + This operation corresponds to `numpy.dot(a, b, out=None)`. + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A tensor, dot product of `x` and `y`. + + Examples: + + If inputs `x` and `y` are 2-D arrays, then it is equivalent to `tf.matmul`. + >>> x = tf.keras.backend.placeholder(shape=(2, 3)) + >>> y = tf.keras.backend.placeholder(shape=(3, 4)) + >>> xy = tf.keras.backend.dot(x, y) + >>> xy + + + >>> x = tf.keras.backend.placeholder(shape=(32, 28, 3)) + >>> y = tf.keras.backend.placeholder(shape=(3, 4)) + >>> xy = tf.keras.backend.dot(x, y) + >>> xy + + + If `x` is an N-D array and `y` is an M-D array (where M>=2), it is a sum + product over the last axis of `x` and the second-to-last axis of `y`. + >>> x = tf.keras.backend.random_uniform_variable(shape=(2, 3), low=0, high=1) + >>> y = tf.keras.backend.ones((4, 3, 5)) + >>> xy = tf.keras.backend.dot(x, y) + >>> tf.keras.backend.int_shape(xy) + (2, 4, 5) + """ + if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2): + x_shape = [] + for i, s in zip(int_shape(x), array_ops_stack.unstack(array_ops.shape(x))): + if i is not None: + x_shape.append(i) + else: + x_shape.append(s) + x_shape = tuple(x_shape) + y_shape = [] + for i, s in zip(int_shape(y), array_ops_stack.unstack(array_ops.shape(y))): + if i is not None: + y_shape.append(i) + else: + y_shape.append(s) + y_shape = tuple(y_shape) + y_permute_dim = list(range(ndim(y))) + y_permute_dim = [y_permute_dim.pop(-2)] + y_permute_dim + xt = array_ops.reshape(x, [-1, x_shape[-1]]) + yt = array_ops.reshape( + array_ops.transpose(y, perm=y_permute_dim), [y_shape[-2], -1]) + return array_ops.reshape( + math_ops.matmul(xt, yt), x_shape[:-1] + y_shape[:-2] + y_shape[-1:]) + if is_sparse(x): + out = sparse_ops.sparse_tensor_dense_matmul(x, y) + else: + out = math_ops.matmul(x, y) + return out + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def batch_dot(x, y, axes=None): + """Batchwise dot product. + + `batch_dot` is used to compute dot product of `x` and `y` when + `x` and `y` are data in batch, i.e. in a shape of + `(batch_size, :)`. + `batch_dot` results in a tensor or variable with less dimensions + than the input. If the number of dimensions is reduced to 1, + we use `expand_dims` to make sure that ndim is at least 2. + + Args: + x: Keras tensor or variable with `ndim >= 2`. + y: Keras tensor or variable with `ndim >= 2`. + axes: Tuple or list of integers with target dimensions, or single integer. + The sizes of `x.shape[axes[0]]` and `y.shape[axes[1]]` should be equal. + + Returns: + A tensor with shape equal to the concatenation of `x`'s shape + (less the dimension that was summed over) and `y`'s shape + (less the batch dimension and the dimension that was summed over). + If the final rank is 1, we reshape it to `(batch_size, 1)`. + + Examples: + + >>> x_batch = tf.keras.backend.ones(shape=(32, 20, 1)) + >>> y_batch = tf.keras.backend.ones(shape=(32, 30, 20)) + >>> xy_batch_dot = tf.keras.backend.batch_dot(x_batch, y_batch, axes=(1, 2)) + >>> tf.keras.backend.int_shape(xy_batch_dot) + (32, 1, 30) + + Shape inference: + Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, 30, 20)`. + If `axes` is (1, 2), to find the output shape of resultant tensor, + loop through each dimension in `x`'s shape and `y`'s shape: + * `x.shape[0]` : 100 : append to output shape + * `x.shape[1]` : 20 : do not append to output shape, + dimension 1 of `x` has been summed over. (`dot_axes[0]` = 1) + * `y.shape[0]` : 100 : do not append to output shape, + always ignore first dimension of `y` + * `y.shape[1]` : 30 : append to output shape + * `y.shape[2]` : 20 : do not append to output shape, + dimension 2 of `y` has been summed over. (`dot_axes[1]` = 2) + `output_shape` = `(100, 30)` + """ + x_shape = int_shape(x) + y_shape = int_shape(y) + + x_ndim = len(x_shape) + y_ndim = len(y_shape) + + if x_ndim < 2 or y_ndim < 2: + raise ValueError('Cannot do batch_dot on inputs ' + 'with rank < 2. ' + 'Received inputs with shapes ' + + str(x_shape) + ' and ' + + str(y_shape) + '.') + + x_batch_size = x_shape[0] + y_batch_size = y_shape[0] + + if x_batch_size is not None and y_batch_size is not None: + if x_batch_size != y_batch_size: + raise ValueError('Cannot do batch_dot on inputs ' + 'with different batch sizes. ' + 'Received inputs with shapes ' + + str(x_shape) + ' and ' + + str(y_shape) + '.') + if isinstance(axes, int): + axes = [axes, axes] + + if axes is None: + if y_ndim == 2: + axes = [x_ndim - 1, y_ndim - 1] + else: + axes = [x_ndim - 1, y_ndim - 2] + + if py_any(isinstance(a, (list, tuple)) for a in axes): + raise ValueError('Multiple target dimensions are not supported. ' + + 'Expected: None, int, (int, int), ' + + 'Provided: ' + str(axes)) + + # if tuple, convert to list. + axes = list(axes) + + # convert negative indices. + if axes[0] < 0: + axes[0] += x_ndim + if axes[1] < 0: + axes[1] += y_ndim + + # sanity checks + if 0 in axes: + raise ValueError('Cannot perform batch_dot over axis 0. ' + 'If your inputs are not batched, ' + 'add a dummy batch dimension to your ' + 'inputs using K.expand_dims(x, 0)') + a0, a1 = axes + d1 = x_shape[a0] + d2 = y_shape[a1] + + if d1 is not None and d2 is not None and d1 != d2: + raise ValueError('Cannot do batch_dot on inputs with shapes ' + + str(x_shape) + ' and ' + str(y_shape) + + ' with axes=' + str(axes) + '. x.shape[%d] != ' + 'y.shape[%d] (%d != %d).' % (axes[0], axes[1], d1, d2)) + + # backup ndims. Need them later. + orig_x_ndim = x_ndim + orig_y_ndim = y_ndim + + # if rank is 2, expand to 3. + if x_ndim == 2: + x = array_ops.expand_dims(x, 1) + a0 += 1 + x_ndim += 1 + if y_ndim == 2: + y = array_ops.expand_dims(y, 2) + y_ndim += 1 + + # bring x's dimension to be reduced to last axis. + if a0 != x_ndim - 1: + pattern = list(range(x_ndim)) + for i in range(a0, x_ndim - 1): + pattern[i] = pattern[i + 1] + pattern[-1] = a0 + x = array_ops.transpose(x, pattern) + + # bring y's dimension to be reduced to axis 1. + if a1 != 1: + pattern = list(range(y_ndim)) + for i in range(a1, 1, -1): + pattern[i] = pattern[i - 1] + pattern[1] = a1 + y = array_ops.transpose(y, pattern) + + # normalize both inputs to rank 3. + if x_ndim > 3: + # squash middle dimensions of x. + x_shape = shape(x) + x_mid_dims = x_shape[1:-1] + x_squashed_shape = array_ops_stack.stack( + [x_shape[0], -1, x_shape[-1]]) + x = array_ops.reshape(x, x_squashed_shape) + x_squashed = True + else: + x_squashed = False + + if y_ndim > 3: + # squash trailing dimensions of y. + y_shape = shape(y) + y_trail_dims = y_shape[2:] + y_squashed_shape = array_ops_stack.stack( + [y_shape[0], y_shape[1], -1]) + y = array_ops.reshape(y, y_squashed_shape) + y_squashed = True + else: + y_squashed = False + + result = math_ops.matmul(x, y) + + # if inputs were squashed, we have to reshape the matmul output. + output_shape = array_ops.shape(result) + do_reshape = False + + if x_squashed: + output_shape = array_ops.concat( + [output_shape[:1], + x_mid_dims, + output_shape[-1:]], 0) + do_reshape = True + + if y_squashed: + output_shape = array_ops.concat([output_shape[:-1], y_trail_dims], 0) + do_reshape = True + + if do_reshape: + result = array_ops.reshape(result, output_shape) + + # if the inputs were originally rank 2, we remove the added 1 dim. + if orig_x_ndim == 2: + result = array_ops.squeeze(result, 1) + elif orig_y_ndim == 2: + result = array_ops.squeeze(result, -1) + + return result + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def transpose(x): + """Transposes a tensor and returns it. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + + Examples: + + >>> var = tf.keras.backend.variable([[1, 2, 3], [4, 5, 6]]) + >>> tf.keras.backend.eval(var) + array([[1., 2., 3.], + [4., 5., 6.]], dtype=float32) + >>> var_transposed = tf.keras.backend.transpose(var) + >>> tf.keras.backend.eval(var_transposed) + array([[1., 4.], + [2., 5.], + [3., 6.]], dtype=float32) + >>> input = tf.keras.backend.placeholder((2, 3)) + >>> input + + >>> input_transposed = tf.keras.backend.transpose(input) + >>> input_transposed + + """ + return array_ops.transpose(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def gather(reference, indices): + """Retrieves the elements of indices `indices` in the tensor `reference`. + + Args: + reference: A tensor. + indices: An integer tensor of indices. + + Returns: + A tensor of same type as `reference`. + + Examples: + + >>> var = tf.keras.backend.variable([[1, 2, 3], [4, 5, 6]]) + >>> tf.keras.backend.eval(var) + array([[1., 2., 3.], + [4., 5., 6.]], dtype=float32) + >>> var_gathered = tf.keras.backend.gather(var, [0]) + >>> tf.keras.backend.eval(var_gathered) + array([[1., 2., 3.]], dtype=float32) + >>> var_gathered = tf.keras.backend.gather(var, [1]) + >>> tf.keras.backend.eval(var_gathered) + array([[4., 5., 6.]], dtype=float32) + >>> var_gathered = tf.keras.backend.gather(var, [0,1,0]) + >>> tf.keras.backend.eval(var_gathered) + array([[1., 2., 3.], + [4., 5., 6.], + [1., 2., 3.]], dtype=float32) + """ + return array_ops.gather(reference, indices) + + +# ELEMENT-WISE OPERATIONS + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def max(x, axis=None, keepdims=False): + """Maximum value in a tensor. + + Args: + x: A tensor or variable. + axis: An integer, the axis to find maximum values. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, + the reduced dimension is retained with length 1. + + Returns: + A tensor with maximum values of `x`. + """ + return math_ops.reduce_max(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def min(x, axis=None, keepdims=False): + """Minimum value in a tensor. + + Args: + x: A tensor or variable. + axis: An integer, the axis to find minimum values. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, + the reduced dimension is retained with length 1. + + Returns: + A tensor with minimum values of `x`. + """ + return math_ops.reduce_min(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def sum(x, axis=None, keepdims=False): + """Sum of the values in a tensor, alongside the specified axis. + + Args: + x: A tensor or variable. + axis: An integer, the axis to sum over. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, + the reduced dimension is retained with length 1. + + Returns: + A tensor with sum of `x`. + """ + return math_ops.reduce_sum(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def prod(x, axis=None, keepdims=False): + """Multiplies the values in a tensor, alongside the specified axis. + + Args: + x: A tensor or variable. + axis: An integer, the axis to compute the product. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, + the reduced dimension is retained with length 1. + + Returns: + A tensor with the product of elements of `x`. + """ + return math_ops.reduce_prod(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def cumsum(x, axis=0): + """Cumulative sum of the values in a tensor, alongside the specified axis. + + Args: + x: A tensor or variable. + axis: An integer, the axis to compute the sum. + + Returns: + A tensor of the cumulative sum of values of `x` along `axis`. + """ + return math_ops.cumsum(x, axis=axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def cumprod(x, axis=0): + """Cumulative product of the values in a tensor, alongside the specified axis. + + Args: + x: A tensor or variable. + axis: An integer, the axis to compute the product. + + Returns: + A tensor of the cumulative product of values of `x` along `axis`. + """ + return math_ops.cumprod(x, axis=axis) + + +@doc_controls.do_not_generate_docs +def var(x, axis=None, keepdims=False): + """Variance of a tensor, alongside the specified axis. + + Args: + x: A tensor or variable. + axis: An integer, the axis to compute the variance. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, + the reduced dimension is retained with length 1. + + Returns: + A tensor with the variance of elements of `x`. + """ + if x.dtype.base_dtype == dtypes_module.bool: + x = math_ops.cast(x, floatx()) + return math_ops.reduce_variance(x, axis=axis, keepdims=keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def std(x, axis=None, keepdims=False): + """Standard deviation of a tensor, alongside the specified axis. + + It is an alias to `tf.math.reduce_std`. + + Args: + x: A tensor or variable. It should have numerical dtypes. Boolean type + inputs will be converted to float. + axis: An integer, the axis to compute the standard deviation. If `None` + (the default), reduces all dimensions. Must be in the range + `[-rank(x), rank(x))`. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, the reduced dimension is retained with + length 1. + + Returns: + A tensor with the standard deviation of elements of `x` with same dtype. + Boolean type input will be converted to float. + """ + if x.dtype.base_dtype == dtypes_module.bool: + x = math_ops.cast(x, floatx()) + return math_ops.reduce_std(x, axis=axis, keepdims=keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def mean(x, axis=None, keepdims=False): + """Mean of a tensor, alongside the specified axis. + + Args: + x: A tensor or variable. + axis: A list of integer. Axes to compute the mean. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1 for each entry in `axis`. If `keepdims` is `True`, + the reduced dimensions are retained with length 1. + + Returns: + A tensor with the mean of elements of `x`. + """ + if x.dtype.base_dtype == dtypes_module.bool: + x = math_ops.cast(x, floatx()) + return math_ops.reduce_mean(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def any(x, axis=None, keepdims=False): + """Bitwise reduction (logical OR). + + Args: + x: Tensor or variable. + axis: axis along which to perform the reduction. + keepdims: whether the drop or broadcast the reduction axes. + + Returns: + A uint8 tensor (0s and 1s). + """ + x = math_ops.cast(x, dtypes_module.bool) + return math_ops.reduce_any(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def all(x, axis=None, keepdims=False): + """Bitwise reduction (logical AND). + + Args: + x: Tensor or variable. + axis: axis along which to perform the reduction. + keepdims: whether the drop or broadcast the reduction axes. + + Returns: + A uint8 tensor (0s and 1s). + """ + x = math_ops.cast(x, dtypes_module.bool) + return math_ops.reduce_all(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def argmax(x, axis=-1): + """Returns the index of the maximum value along an axis. + + Args: + x: Tensor or variable. + axis: axis along which to perform the reduction. + + Returns: + A tensor. + """ + return math_ops.argmax(x, axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def argmin(x, axis=-1): + """Returns the index of the minimum value along an axis. + + Args: + x: Tensor or variable. + axis: axis along which to perform the reduction. + + Returns: + A tensor. + """ + return math_ops.argmin(x, axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def square(x): + """Element-wise square. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.square(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def abs(x): + """Element-wise absolute value. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.abs(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def sqrt(x): + """Element-wise square root. + + This function clips negative tensor values to 0 before computing the + square root. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + zero = _constant_to_tensor(0., x.dtype.base_dtype) + x = math_ops.maximum(x, zero) + return math_ops.sqrt(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def exp(x): + """Element-wise exponential. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.exp(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def log(x): + """Element-wise log. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.log(x) + + +def logsumexp(x, axis=None, keepdims=False): + """Computes log(sum(exp(elements across dimensions of a tensor))). + + This function is more numerically stable than log(sum(exp(x))). + It avoids overflows caused by taking the exp of large inputs and + underflows caused by taking the log of small inputs. + + Args: + x: A tensor or variable. + axis: An integer, the axis to reduce over. + keepdims: A boolean, whether to keep the dimensions or not. + If `keepdims` is `False`, the rank of the tensor is reduced + by 1. If `keepdims` is `True`, the reduced dimension is + retained with length 1. + + Returns: + The reduced tensor. + """ + return math_ops.reduce_logsumexp(x, axis, keepdims) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def round(x): + """Element-wise rounding to the closest integer. + + In case of tie, the rounding mode used is "half to even". + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.round(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def sign(x): + """Element-wise sign. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.sign(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def pow(x, a): + """Element-wise exponentiation. + + Args: + x: Tensor or variable. + a: Python integer. + + Returns: + A tensor. + """ + return math_ops.pow(x, a) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def clip(x, min_value, max_value): + """Element-wise value clipping. + + Args: + x: Tensor or variable. + min_value: Python float, integer, or tensor. + max_value: Python float, integer, or tensor. + + Returns: + A tensor. + """ + if (isinstance(min_value, (int, float)) and + isinstance(max_value, (int, float))): + if max_value < min_value: + max_value = min_value + if min_value is None: + min_value = -np.inf + if max_value is None: + max_value = np.inf + return clip_ops.clip_by_value(x, min_value, max_value) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def equal(x, y): + """Element-wise equality between two tensors. + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A bool tensor. + """ + return math_ops.equal(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def not_equal(x, y): + """Element-wise inequality between two tensors. + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A bool tensor. + """ + return math_ops.not_equal(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def greater(x, y): + """Element-wise truth value of (x > y). + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A bool tensor. + """ + return math_ops.greater(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def greater_equal(x, y): + """Element-wise truth value of (x >= y). + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A bool tensor. + """ + return math_ops.greater_equal(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def less(x, y): + """Element-wise truth value of (x < y). + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A bool tensor. + """ + return math_ops.less(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def less_equal(x, y): + """Element-wise truth value of (x <= y). + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A bool tensor. + """ + return math_ops.less_equal(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def maximum(x, y): + """Element-wise maximum of two tensors. + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A tensor with the element wise maximum value(s) of `x` and `y`. + + Examples: + + >>> x = tf.Variable([[1, 2], [3, 4]]) + >>> y = tf.Variable([[2, 1], [0, -1]]) + >>> m = tf.keras.backend.maximum(x, y) + >>> m + + """ + return math_ops.maximum(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def minimum(x, y): + """Element-wise minimum of two tensors. + + Args: + x: Tensor or variable. + y: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.minimum(x, y) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def sin(x): + """Computes sin of x element-wise. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.sin(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def cos(x): + """Computes cos of x element-wise. + + Args: + x: Tensor or variable. + + Returns: + A tensor. + """ + return math_ops.cos(x) + + +def _regular_normalize_batch_in_training(x, + gamma, + beta, + reduction_axes, + epsilon=1e-3): + """Non-fused version of `normalize_batch_in_training`. + + Args: + x: Input tensor or variable. + gamma: Tensor by which to scale the input. + beta: Tensor with which to center the input. + reduction_axes: iterable of integers, + axes over which to normalize. + epsilon: Fuzz factor. + + Returns: + A tuple length of 3, `(normalized_tensor, mean, variance)`. + """ + mean, var = nn.moments(x, reduction_axes, None, None, False) + normed = nn.batch_normalization(x, mean, var, beta, gamma, epsilon) + return normed, mean, var + + +def _broadcast_normalize_batch_in_training(x, + gamma, + beta, + reduction_axes, + epsilon=1e-3): + """Non-fused, broadcast version of `normalize_batch_in_training`. + + Args: + x: Input tensor or variable. + gamma: Tensor by which to scale the input. + beta: Tensor with which to center the input. + reduction_axes: iterable of integers, + axes over which to normalize. + epsilon: Fuzz factor. + + Returns: + A tuple length of 3, `(normalized_tensor, mean, variance)`. + """ + mean, var = nn.moments(x, reduction_axes, None, None, False) + target_shape = [] + for axis in range(ndim(x)): + if axis in reduction_axes: + target_shape.append(1) + else: + target_shape.append(array_ops.shape(x)[axis]) + target_shape = array_ops_stack.stack(target_shape) + + broadcast_mean = array_ops.reshape(mean, target_shape) + broadcast_var = array_ops.reshape(var, target_shape) + if gamma is None: + broadcast_gamma = None + else: + broadcast_gamma = array_ops.reshape(gamma, target_shape) + if beta is None: + broadcast_beta = None + else: + broadcast_beta = array_ops.reshape(beta, target_shape) + + normed = nn.batch_normalization(x, broadcast_mean, broadcast_var, + broadcast_beta, broadcast_gamma, epsilon) + return normed, mean, var + + +def _fused_normalize_batch_in_training(x, + gamma, + beta, + reduction_axes, + epsilon=1e-3): + """Fused version of `normalize_batch_in_training`. + + Args: + x: Input tensor or variable. + gamma: Tensor by which to scale the input. + beta: Tensor with which to center the input. + reduction_axes: iterable of integers, + axes over which to normalize. + epsilon: Fuzz factor. + + Returns: + A tuple length of 3, `(normalized_tensor, mean, variance)`. + """ + if list(reduction_axes) == [0, 1, 2]: + normalization_axis = 3 + tf_data_format = 'NHWC' + else: + normalization_axis = 1 + tf_data_format = 'NCHW' + + if gamma is None: + gamma = constant_op.constant( + 1.0, dtype=x.dtype, shape=[x.shape[normalization_axis]]) + if beta is None: + beta = constant_op.constant( + 0.0, dtype=x.dtype, shape=[x.shape[normalization_axis]]) + + return nn.fused_batch_norm( + x, gamma, beta, epsilon=epsilon, data_format=tf_data_format) + + +@doc_controls.do_not_generate_docs +def normalize_batch_in_training(x, gamma, beta, reduction_axes, epsilon=1e-3): + """Computes mean and std for batch then apply batch_normalization on batch. + + Args: + x: Input tensor or variable. + gamma: Tensor by which to scale the input. + beta: Tensor with which to center the input. + reduction_axes: iterable of integers, + axes over which to normalize. + epsilon: Fuzz factor. + + Returns: + A tuple length of 3, `(normalized_tensor, mean, variance)`. + """ + if ndim(x) == 4 and list(reduction_axes) in [[0, 1, 2], [0, 2, 3]]: + if not _has_nchw_support() and list(reduction_axes) == [0, 2, 3]: + return _broadcast_normalize_batch_in_training( + x, gamma, beta, reduction_axes, epsilon=epsilon) + return _fused_normalize_batch_in_training( + x, gamma, beta, reduction_axes, epsilon=epsilon) + else: + if sorted(reduction_axes) == list(range(ndim(x)))[:-1]: + return _regular_normalize_batch_in_training( + x, gamma, beta, reduction_axes, epsilon=epsilon) + else: + return _broadcast_normalize_batch_in_training( + x, gamma, beta, reduction_axes, epsilon=epsilon) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def batch_normalization(x, mean, var, beta, gamma, axis=-1, epsilon=1e-3): + """Applies batch normalization on x given mean, var, beta and gamma. + + I.e. returns: + `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta` + + Args: + x: Input tensor or variable. + mean: Mean of batch. + var: Variance of batch. + beta: Tensor with which to center the input. + gamma: Tensor by which to scale the input. + axis: Integer, the axis that should be normalized. + (typically the features axis). + epsilon: Fuzz factor. + + Returns: + A tensor. + """ + if ndim(x) == 4: + # The CPU implementation of `fused_batch_norm` only supports NHWC + if axis == 1 or axis == -3: + tf_data_format = 'NCHW' + elif axis == 3 or axis == -1: + tf_data_format = 'NHWC' + else: + tf_data_format = None + + if (tf_data_format == 'NHWC' or + tf_data_format == 'NCHW' and _has_nchw_support()): + # The mean / var / beta / gamma tensors may be broadcasted + # so they may have extra axes of size 1, which should be squeezed. + if ndim(mean) > 1: + mean = array_ops.reshape(mean, [-1]) + if ndim(var) > 1: + var = array_ops.reshape(var, [-1]) + if beta is None: + beta = zeros_like(mean) + elif ndim(beta) > 1: + beta = array_ops.reshape(beta, [-1]) + if gamma is None: + gamma = ones_like(mean) + elif ndim(gamma) > 1: + gamma = array_ops.reshape(gamma, [-1]) + y, _, _ = nn.fused_batch_norm( + x, + gamma, + beta, + epsilon=epsilon, + mean=mean, + variance=var, + data_format=tf_data_format, + is_training=False + ) + return y + return nn.batch_normalization(x, mean, var, beta, gamma, epsilon) + + +# SHAPE OPERATIONS + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def concatenate(tensors, axis=-1): + """Concatenates a list of tensors alongside the specified axis. + + Args: + tensors: list of tensors to concatenate. + axis: concatenation axis. + + Returns: + A tensor. + + Example: + + >>> a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> b = tf.constant([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) + >>> tf.keras.backend.concatenate((a, b), axis=-1) + + + """ + if axis < 0: + rank = ndim(tensors[0]) + if rank: + axis %= rank + else: + axis = 0 + + if py_all(is_sparse(x) for x in tensors): + return sparse_ops.sparse_concat(axis, tensors) + elif py_all(isinstance(x, ragged_tensor.RaggedTensor) for x in tensors): + return array_ops.concat(tensors, axis) + else: + return array_ops.concat([to_dense(x) for x in tensors], axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def reshape(x, shape): + """Reshapes a tensor to the specified shape. + + Args: + x: Tensor or variable. + shape: Target shape tuple. + + Returns: + A tensor. + + Example: + + >>> a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) + >>> a + + >>> tf.keras.backend.reshape(a, shape=(2, 6)) + + + """ + return array_ops.reshape(x, shape) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def permute_dimensions(x, pattern): + """Permutes axes in a tensor. + + Args: + x: Tensor or variable. + pattern: A tuple of + dimension indices, e.g. `(0, 2, 1)`. + + Returns: + A tensor. + + Example: + + >>> a = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) + >>> a + + >>> tf.keras.backend.permute_dimensions(a, pattern=(1, 0)) + + + """ + return array_ops.transpose(x, perm=pattern) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def resize_images(x, height_factor, width_factor, data_format, + interpolation='nearest'): + """Resizes the images contained in a 4D tensor. + + Args: + x: Tensor or variable to resize. + height_factor: Positive integer. + width_factor: Positive integer. + data_format: One of `"channels_first"`, `"channels_last"`. + interpolation: A string, one of `nearest` or `bilinear`. + + Returns: + A tensor. + + Raises: + ValueError: in case of incorrect value for + `data_format` or `interpolation`. + """ + if data_format == 'channels_first': + rows, cols = 2, 3 + elif data_format == 'channels_last': + rows, cols = 1, 2 + else: + raise ValueError('Invalid `data_format` argument: %s' % (data_format,)) + + new_shape = x.shape[rows:cols + 1] + if new_shape.is_fully_defined(): + new_shape = constant_op.constant(new_shape.as_list(), dtype='int32') + else: + new_shape = array_ops.shape_v2(x)[rows:cols + 1] + new_shape *= constant_op.constant( + np.array([height_factor, width_factor], dtype='int32')) + + if data_format == 'channels_first': + x = permute_dimensions(x, [0, 2, 3, 1]) + if interpolation == 'nearest': + x = image_ops.resize_images_v2( + x, new_shape, method=image_ops.ResizeMethod.NEAREST_NEIGHBOR) + elif interpolation == 'bilinear': + x = image_ops.resize_images_v2(x, new_shape, + method=image_ops.ResizeMethod.BILINEAR) + else: + raise ValueError('interpolation should be one ' + 'of "nearest" or "bilinear".') + if data_format == 'channels_first': + x = permute_dimensions(x, [0, 3, 1, 2]) + + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def resize_volumes(x, depth_factor, height_factor, width_factor, data_format): + """Resizes the volume contained in a 5D tensor. + + Args: + x: Tensor or variable to resize. + depth_factor: Positive integer. + height_factor: Positive integer. + width_factor: Positive integer. + data_format: One of `"channels_first"`, `"channels_last"`. + + Returns: + A tensor. + + Raises: + ValueError: if `data_format` is neither + `channels_last` or `channels_first`. + """ + if data_format == 'channels_first': + output = repeat_elements(x, depth_factor, axis=2) + output = repeat_elements(output, height_factor, axis=3) + output = repeat_elements(output, width_factor, axis=4) + return output + elif data_format == 'channels_last': + output = repeat_elements(x, depth_factor, axis=1) + output = repeat_elements(output, height_factor, axis=2) + output = repeat_elements(output, width_factor, axis=3) + return output + else: + raise ValueError('Invalid data_format: ' + str(data_format)) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def repeat_elements(x, rep, axis): + """Repeats the elements of a tensor along an axis, like `np.repeat`. + + If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output + will have shape `(s1, s2 * rep, s3)`. + + Args: + x: Tensor or variable. + rep: Python integer, number of times to repeat. + axis: Axis along which to repeat. + + Returns: + A tensor. + + Example: + + >>> b = tf.constant([1, 2, 3]) + >>> tf.keras.backend.repeat_elements(b, rep=2, axis=0) + + + """ + x_shape = x.shape.as_list() + # For static axis + if x_shape[axis] is not None: + # slices along the repeat axis + splits = array_ops.split(value=x, + num_or_size_splits=x_shape[axis], + axis=axis) + # repeat each slice the given number of reps + x_rep = [s for s in splits for _ in range(rep)] + return concatenate(x_rep, axis) + + # Here we use tf.tile to mimic behavior of np.repeat so that + # we can handle dynamic shapes (that include None). + # To do that, we need an auxiliary axis to repeat elements along + # it and then merge them along the desired axis. + + # Repeating + auxiliary_axis = axis + 1 + x_shape = array_ops.shape(x) + x_rep = array_ops.expand_dims(x, axis=auxiliary_axis) + reps = np.ones(len(x.shape) + 1) + reps[auxiliary_axis] = rep + x_rep = array_ops.tile(x_rep, reps) + + # Merging + reps = np.delete(reps, auxiliary_axis) + reps[axis] = rep + reps = array_ops.constant(reps, dtype='int32') + x_shape *= reps + x_rep = array_ops.reshape(x_rep, x_shape) + + # Fix shape representation + x_shape = x.shape.as_list() + x_rep.set_shape(x_shape) + x_rep._keras_shape = tuple(x_shape) + return x_rep + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def repeat(x, n): + """Repeats a 2D tensor. + + if `x` has shape (samples, dim) and `n` is `2`, + the output will have shape `(samples, 2, dim)`. + + Args: + x: Tensor or variable. + n: Python integer, number of times to repeat. + + Returns: + A tensor. + + Example: + + >>> b = tf.constant([[1, 2], [3, 4]]) + >>> b + + >>> tf.keras.backend.repeat(b, n=2) + + + """ + assert ndim(x) == 2 + x = array_ops.expand_dims(x, 1) + pattern = array_ops_stack.stack([1, n, 1]) + return array_ops.tile(x, pattern) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def arange(start, stop=None, step=1, dtype='int32'): + """Creates a 1D tensor containing a sequence of integers. + + The function arguments use the same convention as + Theano's arange: if only one argument is provided, + it is in fact the "stop" argument and "start" is 0. + + The default type of the returned tensor is `'int32'` to + match TensorFlow's default. + + Args: + start: Start value. + stop: Stop value. + step: Difference between two successive values. + dtype: Integer dtype to use. + + Returns: + An integer tensor. + + Example: + + >>> tf.keras.backend.arange(start=0, stop=10, step=1.5) + + + + + """ + # Match the behavior of numpy and Theano by returning an empty sequence. + if stop is None and start < 0: + start = 0 + result = math_ops.range(start, limit=stop, delta=step, name='arange') + if dtype != 'int32': + result = cast(result, dtype) + return result + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def tile(x, n): + """Creates a tensor by tiling `x` by `n`. + + Args: + x: A tensor or variable + n: A list of integer. The length must be the same as the number of + dimensions in `x`. + + Returns: + A tiled tensor. + """ + if isinstance(n, int): + n = [n] + return array_ops.tile(x, n) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def flatten(x): + """Flatten a tensor. + + Args: + x: A tensor or variable. + + Returns: + A tensor, reshaped into 1-D + + Example: + + >>> b = tf.constant([[1, 2], [3, 4]]) + >>> b + + >>> tf.keras.backend.flatten(b) + + + """ + return array_ops.reshape(x, [-1]) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def batch_flatten(x): + """Turn a nD tensor into a 2D tensor with same 0th dimension. + + In other words, it flattens each data samples of a batch. + + Args: + x: A tensor or variable. + + Returns: + A tensor. + + Examples: + Flattening a 3D tensor to 2D by collapsing the last dimension. + + >>> x_batch = tf.keras.backend.ones(shape=(2, 3, 4, 5)) + >>> x_batch_flatten = batch_flatten(x_batch) + >>> tf.keras.backend.int_shape(x_batch_flatten) + (2, 60) + + """ + x = array_ops.reshape(x, array_ops_stack.stack([-1, prod(shape(x)[1:])])) + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def expand_dims(x, axis=-1): + """Adds a 1-sized dimension at index "axis". + + Args: + x: A tensor or variable. + axis: Position where to add a new axis. + + Returns: + A tensor with expanded dimensions. + """ + return array_ops.expand_dims(x, axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def squeeze(x, axis): + """Removes a 1-dimension from the tensor at index "axis". + + Args: + x: A tensor or variable. + axis: Axis to drop. + + Returns: + A tensor with the same data as `x` but reduced dimensions. + """ + return array_ops.squeeze(x, [axis]) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def temporal_padding(x, padding=(1, 1)): + """Pads the middle dimension of a 3D tensor. + + Args: + x: Tensor or variable. + padding: Tuple of 2 integers, how many zeros to + add at the start and end of dim 1. + + Returns: + A padded 3D tensor. + """ + assert len(padding) == 2 + pattern = [[0, 0], [padding[0], padding[1]], [0, 0]] + return array_ops.pad(x, pattern) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None): + """Pads the 2nd and 3rd dimensions of a 4D tensor. + + Args: + x: Tensor or variable. + padding: Tuple of 2 tuples, padding pattern. + data_format: One of `channels_last` or `channels_first`. + + Returns: + A padded 4D tensor. + + Raises: + ValueError: if `data_format` is neither + `channels_last` or `channels_first`. + """ + assert len(padding) == 2 + assert len(padding[0]) == 2 + assert len(padding[1]) == 2 + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + if data_format == 'channels_first': + pattern = [[0, 0], [0, 0], list(padding[0]), list(padding[1])] + else: + pattern = [[0, 0], list(padding[0]), list(padding[1]), [0, 0]] + return array_ops.pad(x, pattern) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1)), data_format=None): + """Pads 5D tensor with zeros along the depth, height, width dimensions. + + Pads these dimensions with respectively + "padding[0]", "padding[1]" and "padding[2]" zeros left and right. + + For 'channels_last' data_format, + the 2nd, 3rd and 4th dimension will be padded. + For 'channels_first' data_format, + the 3rd, 4th and 5th dimension will be padded. + + Args: + x: Tensor or variable. + padding: Tuple of 3 tuples, padding pattern. + data_format: One of `channels_last` or `channels_first`. + + Returns: + A padded 5D tensor. + + Raises: + ValueError: if `data_format` is neither + `channels_last` or `channels_first`. + + """ + assert len(padding) == 3 + assert len(padding[0]) == 2 + assert len(padding[1]) == 2 + assert len(padding[2]) == 2 + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + if data_format == 'channels_first': + pattern = [[0, 0], [0, 0], [padding[0][0], padding[0][1]], + [padding[1][0], padding[1][1]], [padding[2][0], padding[2][1]]] + else: + pattern = [[0, 0], [padding[0][0], padding[0][1]], + [padding[1][0], padding[1][1]], [padding[2][0], + padding[2][1]], [0, 0]] + return array_ops.pad(x, pattern) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def stack(x, axis=0): + """Stacks a list of rank `R` tensors into a rank `R+1` tensor. + + Args: + x: List of tensors. + axis: Axis along which to perform stacking. + + Returns: + A tensor. + + Example: + + >>> a = tf.constant([[1, 2],[3, 4]]) + >>> b = tf.constant([[10, 20],[30, 40]]) + >>> tf.keras.backend.stack((a, b)) + + + """ + return array_ops_stack.stack(x, axis=axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def one_hot(indices, num_classes): + """Computes the one-hot representation of an integer tensor. + + Args: + indices: nD integer tensor of shape + `(batch_size, dim1, dim2, ... dim(n-1))` + num_classes: Integer, number of classes to consider. + + Returns: + (n + 1)D one hot representation of the input + with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)` + + Returns: + The one-hot tensor. + """ + return array_ops.one_hot(indices, depth=num_classes, axis=-1) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def reverse(x, axes): + """Reverse a tensor along the specified axes. + + Args: + x: Tensor to reverse. + axes: Integer or iterable of integers. + Axes to reverse. + + Returns: + A tensor. + """ + if isinstance(axes, int): + axes = [axes] + return array_ops.reverse(x, axes) + + +# VALUE MANIPULATION +_VALUE_SET_CODE_STRING = """ + >>> K = tf.keras.backend # Common keras convention + >>> v = K.variable(1.) + + >>> # reassign + >>> K.set_value(v, 2.) + >>> print(K.get_value(v)) + 2.0 + + >>> # increment + >>> K.set_value(v, K.get_value(v) + 1) + >>> print(K.get_value(v)) + 3.0 + + Variable semantics in TensorFlow 2 are eager execution friendly. The above + code is roughly equivalent to: + + >>> v = tf.Variable(1.) + + >>> v.assign(2.) + >>> print(v.numpy()) + 2.0 + + >>> v.assign_add(1.) + >>> print(v.numpy()) + 3.0"""[3:] # Prune first newline and indent to match the docstring template. + + +@doc_controls.do_not_generate_docs +def get_value(x): + """Returns the value of a variable. + + `backend.get_value` is the complement of `backend.set_value`, and provides + a generic interface for reading from variables while abstracting away the + differences between TensorFlow 1.x and 2.x semantics. + + {snippet} + + Args: + x: input variable. + + Returns: + A Numpy array. + """ + if not tensor_util.is_tf_type(x): + return x + if context.executing_eagerly() or isinstance(x, ops.EagerTensor): + return x.numpy() + if not getattr(x, '_in_graph_mode', True): + # This is a variable which was created in an eager context, but is being + # evaluated from a Graph. + with context.eager_mode(): + return x.numpy() + + if ops.executing_eagerly_outside_functions(): + # This method of evaluating works inside the Keras FuncGraph. + with ops.init_scope(): + return x.numpy() + + with x.graph.as_default(): + return x.eval(session=get_session((x,))) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def batch_get_value(tensors): + """Returns the value of more than one tensor variable. + + Args: + tensors: list of ops to run. + + Returns: + A list of Numpy arrays. + + Raises: + RuntimeError: If this method is called inside defun. + """ + if context.executing_eagerly(): + return [x.numpy() for x in tensors] + elif ops.inside_function(): # pylint: disable=protected-access + raise RuntimeError('Cannot get value inside Tensorflow graph function.') + if tensors: + return get_session(tensors).run(tensors) + else: + return [] + + +@doc_controls.do_not_generate_docs +def set_value(x, value): + """Sets the value of a variable, from a Numpy array. + + `backend.set_value` is the complement of `backend.get_value`, and provides + a generic interface for assigning to variables while abstracting away the + differences between TensorFlow 1.x and 2.x semantics. + + {snippet} + + Args: + x: Variable to set to a new value. + value: Value to set the tensor to, as a Numpy array + (of the same shape). + """ + value = np.asarray(value, dtype=dtype_numpy(x)) + if ops.executing_eagerly_outside_functions(): + x.assign(value) + else: + with get_graph().as_default(): + tf_dtype = dtypes_module.as_dtype(x.dtype.name.split('_')[0]) + if hasattr(x, '_assign_placeholder'): + assign_placeholder = x._assign_placeholder + assign_op = x._assign_op + else: + # In order to support assigning weights to resizable variables in + # Keras, we make a placeholder with the correct number of dimensions + # but with None in each dimension. This way, we can assign weights + # of any size (as long as they have the correct dimensionality). + placeholder_shape = tensor_shape.TensorShape([None] * value.ndim) + assign_placeholder = array_ops.placeholder( + tf_dtype, shape=placeholder_shape) + assign_op = x.assign(assign_placeholder) + x._assign_placeholder = assign_placeholder + x._assign_op = assign_op + get_session().run(assign_op, feed_dict={assign_placeholder: value}) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def batch_set_value(tuples): + """Sets the values of many tensor variables at once. + + Args: + tuples: a list of tuples `(tensor, value)`. + `value` should be a Numpy array. + """ + if context.executing_eagerly() or ops.inside_function(): + for x, value in tuples: + x.assign(np.asarray(value, dtype=dtype_numpy(x))) + else: + with get_graph().as_default(): + if tuples: + assign_ops = [] + feed_dict = {} + for x, value in tuples: + value = np.asarray(value, dtype=dtype_numpy(x)) + tf_dtype = dtypes_module.as_dtype(x.dtype.name.split('_')[0]) + if hasattr(x, '_assign_placeholder'): + assign_placeholder = x._assign_placeholder + assign_op = x._assign_op + else: + # In order to support assigning weights to resizable variables in + # Keras, we make a placeholder with the correct number of dimensions + # but with None in each dimension. This way, we can assign weights + # of any size (as long as they have the correct dimensionality). + placeholder_shape = tensor_shape.TensorShape([None] * value.ndim) + assign_placeholder = array_ops.placeholder( + tf_dtype, shape=placeholder_shape) + assign_op = x.assign(assign_placeholder) + x._assign_placeholder = assign_placeholder + x._assign_op = assign_op + assign_ops.append(assign_op) + feed_dict[assign_placeholder] = value + get_session().run(assign_ops, feed_dict=feed_dict) + + +get_value.__doc__ = get_value.__doc__.format(snippet=_VALUE_SET_CODE_STRING) +set_value.__doc__ = set_value.__doc__.format(snippet=_VALUE_SET_CODE_STRING) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def print_tensor(x, message='', summarize=3): + """Prints `message` and the tensor value when evaluated. + + Note that `print_tensor` returns a new tensor identical to `x` + which should be used in the following code. Otherwise the + print operation is not taken into account during evaluation. + + Example: + + >>> x = tf.constant([[1.0, 2.0], [3.0, 4.0]]) + >>> _ = tf.keras.backend.print_tensor(x) + [[1 2] + [3 4]] + + Args: + x: Tensor to print. + message: Message to print jointly with the tensor. + summarize: The first and last `summarize` elements within each dimension + are recursively printed per Tensor. If None, then the first 3 and last + 3 elements of each dimension are printed for each tensor. If set to + -1, it will print all elements of every tensor. + + Returns: + The same tensor `x`, unchanged. + """ + if isinstance(x, tensor_lib.Tensor) and hasattr(x, 'graph'): + with get_graph().as_default(): + op = logging_ops.print_v2( + message, x, output_stream=sys.stdout, summarize=summarize) + with ops.control_dependencies([op]): + return array_ops.identity(x) + else: + logging_ops.print_v2( + message, x, output_stream=sys.stdout, summarize=summarize) + return x + +# GRAPH MANIPULATION + + +class GraphExecutionFunction: + """Runs a computation graph. + + It's possible to pass arguments to `tf.Session.run()` via `session_kwargs`. + In particular additional operations via `fetches` argument and additional + tensor substitutions via `feed_dict` arguments. Note that given + substitutions are merged with substitutions from `inputs`. Even though + `feed_dict` is passed once in the constructor (called in `model.compile()`) + we can modify the values in the dictionary. Through this feed_dict we can + provide additional substitutions besides Keras inputs. + + Args: + inputs: Feed placeholders to the computation graph. + outputs: Output tensors to fetch. + updates: Additional update ops to be run at function call. + name: A name to help users identify what this function does. + session_kwargs: Arguments to `tf.Session.run()`: + `fetches`, `feed_dict`, `options`, `run_metadata`. + """ + + def __init__(self, inputs, outputs, updates=None, name=None, + **session_kwargs): + updates = updates or [] + if not isinstance(updates, (list, tuple)): + raise TypeError('`updates` in a Keras backend function ' + 'should be a list or tuple.') + + self._inputs_structure = inputs + self.inputs = nest.flatten(inputs, expand_composites=True) + self._outputs_structure = outputs + self.outputs = cast_variables_to_tensor( + nest.flatten(outputs, expand_composites=True)) + # TODO(b/127668432): Consider using autograph to generate these + # dependencies in call. + # Index 0 = total loss or model output for `predict`. + with ops.control_dependencies([self.outputs[0]]): + updates_ops = [] + for update in updates: + if isinstance(update, tuple): + p, new_p = update + updates_ops.append(state_ops.assign(p, new_p)) + else: + # assumed already an op + updates_ops.append(update) + self.updates_op = control_flow_ops.group(*updates_ops) + self.name = name + # additional tensor substitutions + self.feed_dict = session_kwargs.pop('feed_dict', None) + # additional operations + self.fetches = session_kwargs.pop('fetches', []) + if not isinstance(self.fetches, list): + self.fetches = [self.fetches] + self.run_options = session_kwargs.pop('options', None) + self.run_metadata = session_kwargs.pop('run_metadata', None) + # The main use case of `fetches` being passed to a model is the ability + # to run custom updates + # This requires us to wrap fetches in `identity` ops. + self.fetches = [array_ops.identity(x) for x in self.fetches] + self.session_kwargs = session_kwargs + # This mapping keeps track of the function that should receive the + # output from a fetch in `fetches`: { fetch: function(fetch_output) } + # A Callback can use this to register a function with access to the + # output values for a fetch it added. + self.fetch_callbacks = {} + + if session_kwargs: + raise ValueError('Some keys in session_kwargs are not supported at this ' + 'time: %s' % (session_kwargs.keys(),)) + + self._callable_fn = None + self._feed_arrays = None + self._feed_symbols = None + self._symbol_vals = None + self._fetches = None + self._session = None + + def _make_callable(self, feed_arrays, feed_symbols, symbol_vals, session): + """Generates a callable that runs the graph. + + Args: + feed_arrays: List of input tensors to be fed Numpy arrays at runtime. + feed_symbols: List of input tensors to be fed symbolic tensors at runtime. + symbol_vals: List of symbolic tensors to be fed to `feed_symbols`. + session: Session to use to generate the callable. + + Returns: + Function that runs the graph according to the above options. + """ + # Prepare callable options. + callable_opts = config_pb2.CallableOptions() + # Handle external-data feed. + for x in feed_arrays: + callable_opts.feed.append(x.name) + if self.feed_dict: + for key in sorted(self.feed_dict.keys()): + callable_opts.feed.append(key.name) + # Handle symbolic feed. + for x, y in zip(feed_symbols, symbol_vals): + connection = callable_opts.tensor_connection.add() + if x.dtype != y.dtype: + y = math_ops.cast(y, dtype=x.dtype) + from_tensor = _as_graph_element(y) + if from_tensor is None: + from_tensor = y + connection.from_tensor = from_tensor.name # Data tensor + connection.to_tensor = x.name # Placeholder + # Handle fetches. + for x in self.outputs + self.fetches: + callable_opts.fetch.append(x.name) + # Handle updates. + callable_opts.target.append(self.updates_op.name) + # Handle run_options. + if self.run_options: + callable_opts.run_options.CopyFrom(self.run_options) + # Create callable. + callable_fn = session._make_callable_from_options(callable_opts) + # Cache parameters corresponding to the generated callable, so that + # we can detect future mismatches and refresh the callable. + self._callable_fn = callable_fn + self._feed_arrays = feed_arrays + self._feed_symbols = feed_symbols + self._symbol_vals = symbol_vals + self._fetches = list(self.fetches) + self._session = session + + def _call_fetch_callbacks(self, fetches_output): + for fetch, output in zip(self._fetches, fetches_output): + if fetch in self.fetch_callbacks: + self.fetch_callbacks[fetch](output) + + def _eval_if_composite(self, tensor): + """Helper method which evaluates any CompositeTensors passed to it.""" + # We need to evaluate any composite tensor objects that have been + # reconstructed in 'pack_sequence_as', since otherwise they'll be output as + # actual CompositeTensor objects instead of the value(s) contained in the + # CompositeTensors. E.g., if output_structure contains a SparseTensor, then + # this ensures that we return its value as a SparseTensorValue rather than + # a SparseTensor. + from tensorflow.python.keras.utils import tf_utils # pylint: disable=g-import-not-at-top + if tf_utils.is_extension_type(tensor): + return self._session.run(tensor) + else: + return tensor + + def __call__(self, inputs): + inputs = nest.flatten(inputs, expand_composites=True) + + session = get_session(inputs) + feed_arrays = [] + array_vals = [] + feed_symbols = [] + symbol_vals = [] + for tensor, value in zip(self.inputs, inputs): + if value is None: + continue + + if tensor_util.is_tf_type(value): + # Case: feeding symbolic tensor. + feed_symbols.append(tensor) + symbol_vals.append(value) + else: + # Case: feeding Numpy array. + feed_arrays.append(tensor) + # We need to do array conversion and type casting at this level, since + # `callable_fn` only supports exact matches. + tensor_type = dtypes_module.as_dtype(tensor.dtype) + array_vals.append(np.asarray(value, + dtype=tensor_type.as_numpy_dtype)) + + if self.feed_dict: + for key in sorted(self.feed_dict.keys()): + array_vals.append( + np.asarray(self.feed_dict[key], dtype=key.dtype.as_numpy_dtype)) + + # Refresh callable if anything has changed. + if (self._callable_fn is None or feed_arrays != self._feed_arrays or + symbol_vals != self._symbol_vals or + feed_symbols != self._feed_symbols or self.fetches != self._fetches or + session != self._session): + self._make_callable(feed_arrays, feed_symbols, symbol_vals, session) + + fetched = self._callable_fn(*array_vals, + run_metadata=self.run_metadata) + self._call_fetch_callbacks(fetched[-len(self._fetches):]) + output_structure = nest.pack_sequence_as( + self._outputs_structure, + fetched[:len(self.outputs)], + expand_composites=True) + # We need to evaluate any composite tensor objects that have been + # reconstructed in 'pack_sequence_as', since otherwise they'll be output as + # actual CompositeTensor objects instead of the value(s) contained in the + # CompositeTensors. E.g., if output_structure contains a SparseTensor, then + # this ensures that we return its value as a SparseTensorValue rather than + # a SparseTensor. + return nest.map_structure(self._eval_if_composite, output_structure) + + +@doc_controls.do_not_generate_docs +def function(inputs, outputs, updates=None, name=None, **kwargs): + """Instantiates a Keras function. + + Args: + inputs: List of placeholder tensors. + outputs: List of output tensors. + updates: List of update ops. + name: String, name of function. + **kwargs: Passed to `tf.Session.run`. + + Returns: + Output values as Numpy arrays. + + Raises: + ValueError: if invalid kwargs are passed in or if in eager execution. + """ + if ops.executing_eagerly_outside_functions(): + if kwargs: + raise ValueError('Session keyword arguments are not supported during ' + 'eager execution. You passed: %s' % (kwargs,)) + if updates: + raise ValueError('`updates` argument is not supported during ' + 'eager execution. You passed: %s' % (updates,)) + from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top + from tensorflow.python.keras.utils import tf_utils # pylint: disable=g-import-not-at-top + model = models.Model(inputs=inputs, outputs=outputs) + + wrap_outputs = isinstance(outputs, list) and len(outputs) == 1 + def func(model_inputs): + outs = model(model_inputs) + if wrap_outputs: + outs = [outs] + return tf_utils.sync_to_numpy_or_python_type(outs) + + return func + + if kwargs: + for key in kwargs: + if (key not in tf_inspect.getfullargspec(session_module.Session.run)[0] + and key not in ['inputs', 'outputs', 'updates', 'name']): + msg = ('Invalid argument "%s" passed to K.function with TensorFlow ' + 'backend') % key + raise ValueError(msg) + return GraphExecutionFunction( + inputs, outputs, updates=updates, name=name, **kwargs) + + +@doc_controls.do_not_generate_docs +def gradients(loss, variables): + """Returns the gradients of `loss` w.r.t. `variables`. + + Args: + loss: Scalar tensor to minimize. + variables: List of variables. + + Returns: + A gradients tensor. + """ + return gradients_module.gradients( + loss, variables, colocate_gradients_with_ops=True) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def stop_gradient(variables): + """Returns `variables` but with zero gradient w.r.t. every other variable. + + Args: + variables: Tensor or list of tensors to consider constant with respect + to any other variable. + + + Returns: + A single tensor or a list of tensors (depending on the passed argument) + that has no gradient with respect to any other variable. + """ + if isinstance(variables, (list, tuple)): + return map(array_ops.stop_gradient, variables) + return array_ops.stop_gradient(variables) + + +# CONTROL FLOW + + +@dispatch.add_dispatch_support +def rnn(step_function, + inputs, + initial_states, + go_backwards=False, + mask=None, + constants=None, + unroll=False, + input_length=None, + time_major=False, + zero_output_for_mask=False): + """Iterates over the time dimension of a tensor. + + Args: + step_function: RNN step function. + Args; + input; Tensor with shape `(samples, ...)` (no time dimension), + representing input for the batch of samples at a certain + time step. + states; List of tensors. + Returns; + output; Tensor with shape `(samples, output_dim)` + (no time dimension). + new_states; List of tensors, same length and shapes + as 'states'. The first state in the list must be the + output tensor at the previous timestep. + inputs: Tensor of temporal data of shape `(samples, time, ...)` + (at least 3D), or nested tensors, and each of which has shape + `(samples, time, ...)`. + initial_states: Tensor with shape `(samples, state_size)` + (no time dimension), containing the initial values for the states used + in the step function. In the case that state_size is in a nested + shape, the shape of initial_states will also follow the nested + structure. + go_backwards: Boolean. If True, do the iteration over the time + dimension in reverse order and return the reversed sequence. + mask: Binary tensor with shape `(samples, time, 1)`, + with a zero for every element that is masked. + constants: List of constant values passed at each step. + unroll: Whether to unroll the RNN or to use a symbolic `while_loop`. + input_length: An integer or a 1-D Tensor, depending on whether + the time dimension is fixed-length or not. In case of variable length + input, it is used for masking in case there's no mask specified. + time_major: Boolean. If true, the inputs and outputs will be in shape + `(timesteps, batch, ...)`, whereas in the False case, it will be + `(batch, timesteps, ...)`. Using `time_major = True` is a bit more + efficient because it avoids transposes at the beginning and end of the + RNN calculation. However, most TensorFlow data is batch-major, so by + default this function accepts input and emits output in batch-major + form. + zero_output_for_mask: Boolean. If True, the output for masked timestep + will be zeros, whereas in the False case, output from previous + timestep is returned. + + Returns: + A tuple, `(last_output, outputs, new_states)`. + last_output: the latest output of the rnn, of shape `(samples, ...)` + outputs: tensor with shape `(samples, time, ...)` where each + entry `outputs[s, t]` is the output of the step function + at time `t` for sample `s`. + new_states: list of tensors, latest states returned by + the step function, of shape `(samples, ...)`. + + Raises: + ValueError: if input dimension is less than 3. + ValueError: if `unroll` is `True` but input timestep is not a fixed + number. + ValueError: if `mask` is provided (not `None`) but states is not provided + (`len(states)` == 0). + """ + + def swap_batch_timestep(input_t): + # Swap the batch and timestep dim for the incoming tensor. + axes = list(range(len(input_t.shape))) + axes[0], axes[1] = 1, 0 + return array_ops.transpose(input_t, axes) + + if not time_major: + inputs = nest.map_structure(swap_batch_timestep, inputs) + + flatted_inputs = nest.flatten(inputs) + time_steps = flatted_inputs[0].shape[0] + batch = flatted_inputs[0].shape[1] + time_steps_t = array_ops.shape(flatted_inputs[0])[0] + + for input_ in flatted_inputs: + input_.shape.with_rank_at_least(3) + + if mask is not None: + if mask.dtype != dtypes_module.bool: + mask = math_ops.cast(mask, dtypes_module.bool) + if len(mask.shape) == 2: + mask = expand_dims(mask) + if not time_major: + mask = swap_batch_timestep(mask) + + if constants is None: + constants = [] + + # tf.where needs its condition tensor to be the same shape as its two + # result tensors, but in our case the condition (mask) tensor is + # (nsamples, 1), and inputs are (nsamples, ndimensions) or even more. + # So we need to broadcast the mask to match the shape of inputs. + # That's what the tile call does, it just repeats the mask along its + # second dimension n times. + def _expand_mask(mask_t, input_t, fixed_dim=1): + if nest.is_nested(mask_t): + raise ValueError('mask_t is expected to be tensor, but got %s' % mask_t) + if nest.is_nested(input_t): + raise ValueError('input_t is expected to be tensor, but got %s' % input_t) + rank_diff = len(input_t.shape) - len(mask_t.shape) + for _ in range(rank_diff): + mask_t = array_ops.expand_dims(mask_t, -1) + multiples = [1] * fixed_dim + input_t.shape.as_list()[fixed_dim:] + return array_ops.tile(mask_t, multiples) + + if unroll: + if not time_steps: + raise ValueError('Unrolling requires a fixed number of timesteps.') + states = tuple(initial_states) + successive_states = [] + successive_outputs = [] + + # Process the input tensors. The input tensor need to be split on the + # time_step dim, and reverse if go_backwards is True. In the case of nested + # input, the input is flattened and then transformed individually. + # The result of this will be a tuple of lists, each of the item in tuple is + # list of the tensor with shape (batch, feature) + def _process_single_input_t(input_t): + input_t = array_ops_stack.unstack(input_t) # unstack for time_step dim + if go_backwards: + input_t.reverse() + return input_t + + if nest.is_nested(inputs): + processed_input = nest.map_structure(_process_single_input_t, inputs) + else: + processed_input = (_process_single_input_t(inputs),) + + def _get_input_tensor(time): + inp = [t_[time] for t_ in processed_input] + return nest.pack_sequence_as(inputs, inp) + + if mask is not None: + mask_list = array_ops_stack.unstack(mask) + if go_backwards: + mask_list.reverse() + + for i in range(time_steps): + inp = _get_input_tensor(i) + mask_t = mask_list[i] + output, new_states = step_function(inp, + tuple(states) + tuple(constants)) + tiled_mask_t = _expand_mask(mask_t, output) + + if not successive_outputs: + prev_output = zeros_like(output) + else: + prev_output = successive_outputs[-1] + + output = array_ops.where_v2(tiled_mask_t, output, prev_output) + + flat_states = nest.flatten(states) + flat_new_states = nest.flatten(new_states) + tiled_mask_t = tuple(_expand_mask(mask_t, s) for s in flat_states) + flat_final_states = tuple( + array_ops.where_v2(m, s, ps) + for m, s, ps in zip(tiled_mask_t, flat_new_states, flat_states)) + states = nest.pack_sequence_as(states, flat_final_states) + + successive_outputs.append(output) + successive_states.append(states) + last_output = successive_outputs[-1] + new_states = successive_states[-1] + outputs = array_ops_stack.stack(successive_outputs) + + if zero_output_for_mask: + last_output = array_ops.where_v2( + _expand_mask(mask_list[-1], last_output), last_output, + zeros_like(last_output)) + outputs = array_ops.where_v2( + _expand_mask(mask, outputs, fixed_dim=2), outputs, + zeros_like(outputs)) + + else: # mask is None + for i in range(time_steps): + inp = _get_input_tensor(i) + output, states = step_function(inp, tuple(states) + tuple(constants)) + successive_outputs.append(output) + successive_states.append(states) + last_output = successive_outputs[-1] + new_states = successive_states[-1] + outputs = array_ops_stack.stack(successive_outputs) + + else: # Unroll == False + states = tuple(initial_states) + + # Create input tensor array, if the inputs is nested tensors, then it will + # be flattened first, and tensor array will be created one per flattened + # tensor. + input_ta = tuple( + tensor_array_ops.TensorArray( + dtype=inp.dtype, + size=time_steps_t, + tensor_array_name='input_ta_%s' % i) + for i, inp in enumerate(flatted_inputs)) + input_ta = tuple( + ta.unstack(input_) if not go_backwards else ta + .unstack(reverse(input_, 0)) + for ta, input_ in zip(input_ta, flatted_inputs)) + + # Get the time(0) input and compute the output for that, the output will be + # used to determine the dtype of output tensor array. Don't read from + # input_ta due to TensorArray clear_after_read default to True. + input_time_zero = nest.pack_sequence_as(inputs, + [inp[0] for inp in flatted_inputs]) + # output_time_zero is used to determine the cell output shape and its dtype. + # the value is discarded. + output_time_zero, _ = step_function( + input_time_zero, tuple(initial_states) + tuple(constants)) + output_ta = tuple( + tensor_array_ops.TensorArray( + dtype=out.dtype, + size=time_steps_t, + element_shape=out.shape, + tensor_array_name='output_ta_%s' % i) + for i, out in enumerate(nest.flatten(output_time_zero))) + + time = constant_op.constant(0, dtype='int32', name='time') + + # We only specify the 'maximum_iterations' when building for XLA since that + # causes slowdowns on GPU in TF. + if (not context.executing_eagerly() and + control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph())): + max_iterations = math_ops.reduce_max(input_length) + else: + max_iterations = None + + while_loop_kwargs = { + 'cond': lambda time, *_: time < time_steps_t, + 'maximum_iterations': max_iterations, + 'parallel_iterations': 32, + 'swap_memory': True, + } + if mask is not None: + if go_backwards: + mask = reverse(mask, 0) + + mask_ta = tensor_array_ops.TensorArray( + dtype=dtypes_module.bool, + size=time_steps_t, + tensor_array_name='mask_ta') + mask_ta = mask_ta.unstack(mask) + + def masking_fn(time): + return mask_ta.read(time) + + def compute_masked_output(mask_t, flat_out, flat_mask): + tiled_mask_t = tuple( + _expand_mask(mask_t, o, fixed_dim=len(mask_t.shape)) + for o in flat_out) + return tuple( + array_ops.where_v2(m, o, fm) + for m, o, fm in zip(tiled_mask_t, flat_out, flat_mask)) + elif isinstance(input_length, tensor_lib.Tensor): + if go_backwards: + max_len = math_ops.reduce_max(input_length, axis=0) + rev_input_length = math_ops.subtract(max_len - 1, input_length) + + def masking_fn(time): + return math_ops.less(rev_input_length, time) + else: + + def masking_fn(time): + return math_ops.greater(input_length, time) + + def compute_masked_output(mask_t, flat_out, flat_mask): + return tuple( + array_ops.where(mask_t, o, zo) + for (o, zo) in zip(flat_out, flat_mask)) + else: + masking_fn = None + + if masking_fn is not None: + # Mask for the T output will be base on the output of T - 1. In the case + # T = 0, a zero filled tensor will be used. + flat_zero_output = tuple(array_ops.zeros_like(o) + for o in nest.flatten(output_time_zero)) + def _step(time, output_ta_t, prev_output, *states): + """RNN step function. + + Args: + time: Current timestep value. + output_ta_t: TensorArray. + prev_output: tuple of outputs from time - 1. + *states: List of states. + + Returns: + Tuple: `(time + 1, output_ta_t, output) + tuple(new_states)` + """ + current_input = tuple(ta.read(time) for ta in input_ta) + # maybe set shape. + current_input = nest.pack_sequence_as(inputs, current_input) + mask_t = masking_fn(time) + output, new_states = step_function(current_input, + tuple(states) + tuple(constants)) + # mask output + flat_output = nest.flatten(output) + flat_mask_output = (flat_zero_output if zero_output_for_mask + else nest.flatten(prev_output)) + flat_new_output = compute_masked_output(mask_t, flat_output, + flat_mask_output) + + # mask states + flat_state = nest.flatten(states) + flat_new_state = nest.flatten(new_states) + for state, new_state in zip(flat_state, flat_new_state): + if isinstance(new_state, tensor_lib.Tensor): + new_state.set_shape(state.shape) + flat_final_state = compute_masked_output(mask_t, flat_new_state, + flat_state) + new_states = nest.pack_sequence_as(new_states, flat_final_state) + + output_ta_t = tuple( + ta.write(time, out) + for ta, out in zip(output_ta_t, flat_new_output)) + return (time + 1, output_ta_t, + tuple(flat_new_output)) + tuple(new_states) + + final_outputs = while_loop.while_loop( + body=_step, + loop_vars=(time, output_ta, flat_zero_output) + states, + **while_loop_kwargs) + # Skip final_outputs[2] which is the output for final timestep. + new_states = final_outputs[3:] + else: + def _step(time, output_ta_t, *states): + """RNN step function. + + Args: + time: Current timestep value. + output_ta_t: TensorArray. + *states: List of states. + + Returns: + Tuple: `(time + 1,output_ta_t) + tuple(new_states)` + """ + current_input = tuple(ta.read(time) for ta in input_ta) + current_input = nest.pack_sequence_as(inputs, current_input) + output, new_states = step_function(current_input, + tuple(states) + tuple(constants)) + flat_state = nest.flatten(states) + flat_new_state = nest.flatten(new_states) + for state, new_state in zip(flat_state, flat_new_state): + if isinstance(new_state, tensor_lib.Tensor): + new_state.set_shape(state.shape) + + flat_output = nest.flatten(output) + output_ta_t = tuple( + ta.write(time, out) for ta, out in zip(output_ta_t, flat_output)) + new_states = nest.pack_sequence_as(initial_states, flat_new_state) + return (time + 1, output_ta_t) + tuple(new_states) + + final_outputs = while_loop.while_loop( + body=_step, loop_vars=(time, output_ta) + states, **while_loop_kwargs) + new_states = final_outputs[2:] + + output_ta = final_outputs[1] + + outputs = tuple(o.stack() for o in output_ta) + last_output = tuple(o[-1] for o in outputs) + + outputs = nest.pack_sequence_as(output_time_zero, outputs) + last_output = nest.pack_sequence_as(output_time_zero, last_output) + + # static shape inference + def set_shape(output_): + if isinstance(output_, tensor_lib.Tensor): + shape = output_.shape.as_list() + shape[0] = time_steps + shape[1] = batch + output_.set_shape(shape) + return output_ + + outputs = nest.map_structure(set_shape, outputs) + + if not time_major: + outputs = nest.map_structure(swap_batch_timestep, outputs) + + return last_output, outputs, new_states + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def switch(condition, then_expression, else_expression): + """Switches between two operations depending on a scalar value. + + Note that both `then_expression` and `else_expression` + should be symbolic tensors of the *same shape*. + + Args: + condition: tensor (`int` or `bool`). + then_expression: either a tensor, or a callable that returns a tensor. + else_expression: either a tensor, or a callable that returns a tensor. + + Returns: + The selected tensor. + + Raises: + ValueError: If rank of `condition` is greater than rank of expressions. + """ + if condition.dtype != dtypes_module.bool: + condition = math_ops.cast(condition, 'bool') + cond_ndim = ndim(condition) + if not cond_ndim: + if not callable(then_expression): + + def then_expression_fn(): + return then_expression + else: + then_expression_fn = then_expression + if not callable(else_expression): + + def else_expression_fn(): + return else_expression + else: + else_expression_fn = else_expression + x = cond.cond(condition, then_expression_fn, else_expression_fn) + else: + # tf.where needs its condition tensor + # to be the same shape as its two + # result tensors + if callable(then_expression): + then_expression = then_expression() + if callable(else_expression): + else_expression = else_expression() + expr_ndim = ndim(then_expression) + if cond_ndim > expr_ndim: + raise ValueError('Rank of `condition` should be less than or' + ' equal to rank of `then_expression` and ' + '`else_expression`. ndim(condition)=' + str(cond_ndim) + + ', ndim(then_expression)' + '=' + str(expr_ndim)) + if cond_ndim > 1: + ndim_diff = expr_ndim - cond_ndim + cond_shape = array_ops.concat( + [array_ops.shape(condition), [1] * ndim_diff], axis=0) + condition = array_ops.reshape(condition, cond_shape) + expr_shape = array_ops.shape(then_expression) + shape_diff = expr_shape - cond_shape + tile_shape = array_ops.where_v2(shape_diff > 0, expr_shape, + array_ops.ones_like(expr_shape)) + condition = array_ops.tile(condition, tile_shape) + x = array_ops.where_v2(condition, then_expression, else_expression) + return x + + +@doc_controls.do_not_generate_docs +def in_train_phase(x, alt, training=None): + """Selects `x` in train phase, and `alt` otherwise. + + Note that `alt` should have the *same shape* as `x`. + + Args: + x: What to return in train phase + (tensor or callable that returns a tensor). + alt: What to return otherwise + (tensor or callable that returns a tensor). + training: Optional scalar tensor + (or Python boolean, or Python integer) + specifying the learning phase. + + Returns: + Either `x` or `alt` based on the `training` flag. + the `training` flag defaults to `K.learning_phase()`. + """ + from tensorflow.python.keras.engine import base_layer_utils # pylint: disable=g-import-not-at-top + if training is None: + training = base_layer_utils.call_context().training + + if training is None: + training = learning_phase() + + # TODO(b/138862903): Handle the case when training is tensor. + if not tensor_util.is_tf_type(training): + if training == 1 or training is True: + if callable(x): + return x() + else: + return x + + elif training == 0 or training is False: + if callable(alt): + return alt() + else: + return alt + + # else: assume learning phase is a placeholder tensor. + x = switch(training, x, alt) + return x + + +@doc_controls.do_not_generate_docs +def in_test_phase(x, alt, training=None): + """Selects `x` in test phase, and `alt` otherwise. + + Note that `alt` should have the *same shape* as `x`. + + Args: + x: What to return in test phase + (tensor or callable that returns a tensor). + alt: What to return otherwise + (tensor or callable that returns a tensor). + training: Optional scalar tensor + (or Python boolean, or Python integer) + specifying the learning phase. + + Returns: + Either `x` or `alt` based on `K.learning_phase`. + """ + return in_train_phase(alt, x, training=training) + + +# NN OPERATIONS + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def relu(x, alpha=0., max_value=None, threshold=0): + """Rectified linear unit. + + With default values, it returns element-wise `max(x, 0)`. + + Otherwise, it follows: + `f(x) = max_value` for `x >= max_value`, + `f(x) = x` for `threshold <= x < max_value`, + `f(x) = alpha * (x - threshold)` otherwise. + + Args: + x: A tensor or variable. + alpha: A scalar, slope of negative section (default=`0.`). + max_value: float. Saturation threshold. + threshold: float. Threshold value for thresholded activation. + + Returns: + A tensor. + """ + # While x can be a tensor or variable, we also see cases where + # numpy arrays, lists, tuples are passed as well. + # lists, tuples do not have 'dtype' attribute. + dtype = getattr(x, 'dtype', floatx()) + if alpha != 0.: + if max_value is None and threshold == 0: + return nn.leaky_relu(x, alpha=alpha) + + if threshold != 0: + negative_part = nn.relu(-x + threshold) + else: + negative_part = nn.relu(-x) + + clip_max = max_value is not None + + if threshold != 0: + # computes x for x > threshold else 0 + x = x * math_ops.cast(math_ops.greater(x, threshold), dtype=dtype) + elif max_value == 6: + # if no threshold, then can use nn.relu6 native TF op for performance + x = nn.relu6(x) + clip_max = False + else: + x = nn.relu(x) + + if clip_max: + max_value = _constant_to_tensor(max_value, x.dtype.base_dtype) + zero = _constant_to_tensor(0, x.dtype.base_dtype) + x = clip_ops.clip_by_value(x, zero, max_value) + + if alpha != 0.: + alpha = _to_tensor(alpha, x.dtype.base_dtype) + x -= alpha * negative_part + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def elu(x, alpha=1.): + """Exponential linear unit. + + Args: + x: A tensor or variable to compute the activation function for. + alpha: A scalar, slope of negative section. + + Returns: + A tensor. + """ + res = nn.elu(x) + if alpha == 1: + return res + else: + return array_ops.where_v2(x > 0, res, alpha * res) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def softmax(x, axis=-1): + """Softmax of a tensor. + + Args: + x: A tensor or variable. + axis: The dimension softmax would be performed on. + The default is -1 which indicates the last dimension. + + Returns: + A tensor. + """ + return nn.softmax(x, axis=axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def softplus(x): + """Softplus of a tensor. + + Args: + x: A tensor or variable. + + Returns: + A tensor. + """ + return math_ops.softplus(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def softsign(x): + """Softsign of a tensor. + + Args: + x: A tensor or variable. + + Returns: + A tensor. + """ + return nn.softsign(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def categorical_crossentropy(target, output, from_logits=False, axis=-1): + """Categorical crossentropy between an output tensor and a target tensor. + + Args: + target: A tensor of the same shape as `output`. + output: A tensor resulting from a softmax + (unless `from_logits` is True, in which + case `output` is expected to be the logits). + from_logits: Boolean, whether `output` is the + result of a softmax, or is a tensor of logits. + axis: Int specifying the channels axis. `axis=-1` corresponds to data + format `channels_last`, and `axis=1` corresponds to data format + `channels_first`. + + Returns: + Output tensor. + + Raises: + ValueError: if `axis` is neither -1 nor one of the axes of `output`. + + Example: + + >>> a = tf.constant([1., 0., 0., 0., 1., 0., 0., 0., 1.], shape=[3,3]) + >>> print(a) + tf.Tensor( + [[1. 0. 0.] + [0. 1. 0.] + [0. 0. 1.]], shape=(3, 3), dtype=float32) + >>> b = tf.constant([.9, .05, .05, .05, .89, .06, .05, .01, .94], shape=[3,3]) + >>> print(b) + tf.Tensor( + [[0.9 0.05 0.05] + [0.05 0.89 0.06] + [0.05 0.01 0.94]], shape=(3, 3), dtype=float32) + >>> loss = tf.keras.backend.categorical_crossentropy(a, b) + >>> print(np.around(loss, 5)) + [0.10536 0.11653 0.06188] + >>> loss = tf.keras.backend.categorical_crossentropy(a, a) + >>> print(np.around(loss, 5)) + [0. 0. 0.] + + """ + target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target) + output = tensor_conversion.convert_to_tensor_v2_with_dispatch(output) + target.shape.assert_is_compatible_with(output.shape) + + # Use logits whenever they are available. `softmax` and `sigmoid` + # activations cache logits on the `output` Tensor. + if hasattr(output, '_keras_logits'): + output = output._keras_logits # pylint: disable=protected-access + if from_logits: + warnings.warn( + '"`categorical_crossentropy` received `from_logits=True`, but ' + 'the `output` argument was produced by a sigmoid or softmax ' + 'activation and thus does not represent logits. Was this intended?"') + from_logits = True + + if from_logits: + return nn.softmax_cross_entropy_with_logits_v2( + labels=target, logits=output, axis=axis) + + if (not isinstance(output, (ops.EagerTensor, variables_module.Variable)) and + output.op.type == 'Softmax') and not hasattr(output, '_keras_history'): + # When softmax activation function is used for output operation, we + # use logits from the softmax function directly to compute loss in order + # to prevent collapsing zero when training. + # See b/117284466 + assert len(output.op.inputs) == 1 + output = output.op.inputs[0] + return nn.softmax_cross_entropy_with_logits_v2( + labels=target, logits=output, axis=axis) + + # scale preds so that the class probas of each sample sum to 1 + output = output / math_ops.reduce_sum(output, axis, True) + # Compute cross entropy from probabilities. + epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype) + output = clip_ops.clip_by_value(output, epsilon_, 1. - epsilon_) + return -math_ops.reduce_sum(target * math_ops.log(output), axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): + """Categorical crossentropy with integer targets. + + Args: + target: An integer tensor. + output: A tensor resulting from a softmax + (unless `from_logits` is True, in which + case `output` is expected to be the logits). + from_logits: Boolean, whether `output` is the + result of a softmax, or is a tensor of logits. + axis: Int specifying the channels axis. `axis=-1` corresponds to data + format `channels_last`, and `axis=1` corresponds to data format + `channels_first`. + + Returns: + Output tensor. + + Raises: + ValueError: if `axis` is neither -1 nor one of the axes of `output`. + """ + target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target) + output = tensor_conversion.convert_to_tensor_v2_with_dispatch(output) + + # Use logits whenever they are available. `softmax` and `sigmoid` + # activations cache logits on the `output` Tensor. + if hasattr(output, '_keras_logits'): + output = output._keras_logits # pylint: disable=protected-access + if from_logits: + warnings.warn( + '"`sparse_categorical_crossentropy` received `from_logits=True`, but ' + 'the `output` argument was produced by a sigmoid or softmax ' + 'activation and thus does not represent logits. Was this intended?"') + from_logits = True + elif (not from_logits and + not isinstance(output, (ops.EagerTensor, variables_module.Variable)) and + output.op.type == 'Softmax') and not hasattr(output, '_keras_history'): + # When softmax activation function is used for output operation, we + # use logits from the softmax function directly to compute loss in order + # to prevent collapsing zero when training. + # See b/117284466 + assert len(output.op.inputs) == 1 + output = output.op.inputs[0] + from_logits = True + elif not from_logits: + epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype) + output = clip_ops.clip_by_value(output, epsilon_, 1 - epsilon_) + output = math_ops.log(output) + + if isinstance(output.shape, (tuple, list)): + output_rank = len(output.shape) + else: + output_rank = output.shape.ndims + if output_rank is not None: + axis %= output_rank + if axis != output_rank - 1: + permutation = list( + itertools.chain(range(axis), range(axis + 1, output_rank), [axis])) + output = array_ops.transpose(output, perm=permutation) + elif axis != -1: + raise ValueError( + 'Cannot compute sparse categorical crossentropy with `axis={}` on an ' + 'output tensor with unknown rank'.format(axis)) + + target = cast(target, 'int64') + + # Try to adjust the shape so that rank of labels = rank of logits - 1. + output_shape = array_ops.shape_v2(output) + target_rank = target.shape.ndims + + update_shape = ( + target_rank is not None and output_rank is not None and + target_rank != output_rank - 1) + if update_shape: + target = flatten(target) + output = array_ops.reshape(output, [-1, output_shape[-1]]) + + if py_any(_is_symbolic_tensor(v) for v in [target, output]): + with get_graph().as_default(): + res = nn.sparse_softmax_cross_entropy_with_logits_v2( + labels=target, logits=output) + else: + res = nn.sparse_softmax_cross_entropy_with_logits_v2( + labels=target, logits=output) + + if update_shape and output_rank >= 3: + # If our output includes timesteps or spatial dimensions we need to reshape + return array_ops.reshape(res, output_shape[:-1]) + else: + return res + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def binary_crossentropy(target, output, from_logits=False): + """Binary crossentropy between an output tensor and a target tensor. + + Args: + target: A tensor with the same shape as `output`. + output: A tensor. + from_logits: Whether `output` is expected to be a logits tensor. + By default, we consider that `output` + encodes a probability distribution. + + Returns: + A tensor. + """ + target = tensor_conversion.convert_to_tensor_v2_with_dispatch(target) + output = tensor_conversion.convert_to_tensor_v2_with_dispatch(output) + + # Use logits whenever they are available. `softmax` and `sigmoid` + # activations cache logits on the `output` Tensor. + if hasattr(output, '_keras_logits'): + output = output._keras_logits # pylint: disable=protected-access + if from_logits: + warnings.warn( + '"`binary_crossentropy` received `from_logits=True`, but the `output`' + ' argument was produced by a sigmoid or softmax activation and thus ' + 'does not represent logits. Was this intended?"') + from_logits = True + + if from_logits: + return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output) + + if (not isinstance(output, (ops.EagerTensor, variables_module.Variable)) and + output.op.type == 'Sigmoid') and not hasattr(output, '_keras_history'): + # When sigmoid activation function is used for output operation, we + # use logits from the sigmoid function directly to compute loss in order + # to prevent collapsing zero when training. + assert len(output.op.inputs) == 1 + output = output.op.inputs[0] + return nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output) + + epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype) + output = clip_ops.clip_by_value(output, epsilon_, 1. - epsilon_) + + # Compute cross entropy from probabilities. + bce = target * math_ops.log(output + epsilon()) + bce += (1 - target) * math_ops.log(1 - output + epsilon()) + return -bce + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def sigmoid(x): + """Element-wise sigmoid. + + Args: + x: A tensor or variable. + + Returns: + A tensor. + """ + return nn.sigmoid(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def hard_sigmoid(x): + """Segment-wise linear approximation of sigmoid. + + Faster than sigmoid. + Returns `0.` if `x < -2.5`, `1.` if `x > 2.5`. + In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`. + + Args: + x: A tensor or variable. + + Returns: + A tensor. + """ + point_two = _constant_to_tensor(0.2, x.dtype.base_dtype) + point_five = _constant_to_tensor(0.5, x.dtype.base_dtype) + x = math_ops.multiply(x, point_two) + x = math_ops.add(x, point_five) + x = clip_ops.clip_by_value(x, 0., 1.) + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def tanh(x): + """Element-wise tanh. + + Args: + x: A tensor or variable. + + Returns: + A tensor. + """ + return nn.tanh(x) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def dropout(x, level, noise_shape=None, seed=None): + """Sets entries in `x` to zero at random, while scaling the entire tensor. + + Args: + x: tensor + level: fraction of the entries in the tensor + that will be set to 0. + noise_shape: shape for randomly generated keep/drop flags, + must be broadcastable to the shape of `x` + seed: random seed to ensure determinism. + + Returns: + A tensor. + """ + if seed is None: + seed = np.random.randint(10e6) + return nn.dropout_v2(x, rate=level, noise_shape=noise_shape, seed=seed) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def l2_normalize(x, axis=None): + """Normalizes a tensor wrt the L2 norm alongside the specified axis. + + Args: + x: Tensor or variable. + axis: axis along which to perform normalization. + + Returns: + A tensor. + """ + return nn.l2_normalize(x, axis=axis) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def in_top_k(predictions, targets, k): + """Returns whether the `targets` are in the top `k` `predictions`. + + Args: + predictions: A tensor of shape `(batch_size, classes)` and type `float32`. + targets: A 1D tensor of length `batch_size` and type `int32` or `int64`. + k: An `int`, number of top elements to consider. + + Returns: + A 1D tensor of length `batch_size` and type `bool`. + `output[i]` is `True` if `predictions[i, targets[i]]` is within top-`k` + values of `predictions[i]`. + """ + return nn.in_top_k(predictions, targets, k) + + +# CONVOLUTIONS + + +def _preprocess_conv1d_input(x, data_format): + """Transpose and cast the input before the conv1d. + + Args: + x: input tensor. + data_format: string, `"channels_last"` or `"channels_first"`. + + Returns: + A tensor. + """ + tf_data_format = 'NWC' # to pass TF Conv2dNative operations + if data_format == 'channels_first': + if not _has_nchw_support(): + x = array_ops.transpose(x, (0, 2, 1)) # NCW -> NWC + else: + tf_data_format = 'NCW' + return x, tf_data_format + + +def _preprocess_conv2d_input(x, data_format, force_transpose=False): + """Transpose and cast the input before the conv2d. + + Args: + x: input tensor. + data_format: string, `"channels_last"` or `"channels_first"`. + force_transpose: Boolean. If True, the input will always be transposed + from NCHW to NHWC if `data_format` is `"channels_first"`. + If False, the transposition only occurs on CPU (GPU ops are + assumed to support NCHW). + + Returns: + A tensor. + """ + tf_data_format = 'NHWC' + if data_format == 'channels_first': + if not _has_nchw_support() or force_transpose: + x = array_ops.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC + else: + tf_data_format = 'NCHW' + return x, tf_data_format + + +def _preprocess_conv3d_input(x, data_format): + """Transpose and cast the input before the conv3d. + + Args: + x: input tensor. + data_format: string, `"channels_last"` or `"channels_first"`. + + Returns: + A tensor. + """ + tf_data_format = 'NDHWC' + if data_format == 'channels_first': + if not _has_nchw_support(): + x = array_ops.transpose(x, (0, 2, 3, 4, 1)) + else: + tf_data_format = 'NCDHW' + return x, tf_data_format + + +def _preprocess_padding(padding): + """Convert keras' padding to TensorFlow's padding. + + Args: + padding: string, one of 'same' , 'valid' + + Returns: + a string, one of 'SAME', 'VALID'. + + Raises: + ValueError: if invalid `padding'` + """ + if padding == 'same': + padding = 'SAME' + elif padding == 'valid': + padding = 'VALID' + else: + raise ValueError('Invalid padding: ' + str(padding)) + return padding + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def conv1d(x, + kernel, + strides=1, + padding='valid', + data_format=None, + dilation_rate=1): + """1D convolution. + + Args: + x: Tensor or variable. + kernel: kernel tensor. + strides: stride integer. + padding: string, `"same"`, `"causal"` or `"valid"`. + data_format: string, one of "channels_last", "channels_first". + dilation_rate: integer dilate rate. + + Returns: + A tensor, result of 1D convolution. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + kernel_shape = kernel.shape.as_list() + if padding == 'causal': + # causal (dilated) convolution: + left_pad = dilation_rate * (kernel_shape[0] - 1) + x = temporal_padding(x, (left_pad, 0)) + padding = 'valid' + padding = _preprocess_padding(padding) + + x, tf_data_format = _preprocess_conv1d_input(x, data_format) + x = nn.convolution( + input=x, + filter=kernel, + dilation_rate=dilation_rate, + strides=strides, + padding=padding, + data_format=tf_data_format) + if data_format == 'channels_first' and tf_data_format == 'NWC': + x = array_ops.transpose(x, (0, 2, 1)) # NWC -> NCW + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def conv2d(x, + kernel, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1)): + """2D convolution. + + Args: + x: Tensor or variable. + kernel: kernel tensor. + strides: strides tuple. + padding: string, `"same"` or `"valid"`. + data_format: `"channels_last"` or `"channels_first"`. + dilation_rate: tuple of 2 integers. + + Returns: + A tensor, result of 2D convolution. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + x, tf_data_format = _preprocess_conv2d_input(x, data_format) + padding = _preprocess_padding(padding) + x = nn.convolution( + input=x, + filter=kernel, + dilation_rate=dilation_rate, + strides=strides, + padding=padding, + data_format=tf_data_format) + if data_format == 'channels_first' and tf_data_format == 'NHWC': + x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def conv2d_transpose(x, + kernel, + output_shape, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1)): + """2D deconvolution (i.e. + + transposed convolution). + + Args: + x: Tensor or variable. + kernel: kernel tensor. + output_shape: 1D int tensor for the output shape. + strides: strides tuple. + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + dilation_rate: Tuple of 2 integers. + + Returns: + A tensor, result of transposed 2D convolution. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + # `atrous_conv2d_transpose` only supports NHWC format, even on GPU. + if data_format == 'channels_first' and dilation_rate != (1, 1): + force_transpose = True + else: + force_transpose = False + + x, tf_data_format = _preprocess_conv2d_input(x, data_format, force_transpose) + + if data_format == 'channels_first' and tf_data_format == 'NHWC': + output_shape = (output_shape[0], output_shape[2], output_shape[3], + output_shape[1]) + if output_shape[0] is None: + output_shape = (shape(x)[0],) + tuple(output_shape[1:]) + + if isinstance(output_shape, (tuple, list)): + output_shape = array_ops_stack.stack(list(output_shape)) + + padding = _preprocess_padding(padding) + if tf_data_format == 'NHWC': + strides = (1,) + strides + (1,) + else: + strides = (1, 1) + strides + + if dilation_rate == (1, 1): + x = nn.conv2d_transpose(x, kernel, output_shape, strides, + padding=padding, + data_format=tf_data_format) + else: + assert dilation_rate[0] == dilation_rate[1] + x = nn.atrous_conv2d_transpose( + x, + kernel, + output_shape, + rate=dilation_rate[0], + padding=padding) + if data_format == 'channels_first' and tf_data_format == 'NHWC': + x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW + return x + + +def separable_conv1d(x, + depthwise_kernel, + pointwise_kernel, + strides=1, + padding='valid', + data_format=None, + dilation_rate=1): + """1D convolution with separable filters. + + Args: + x: input tensor + depthwise_kernel: convolution kernel for the depthwise convolution. + pointwise_kernel: kernel for the 1x1 convolution. + strides: stride integer. + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + dilation_rate: integer dilation rate. + + Returns: + Output tensor. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + if isinstance(strides, int): + strides = (strides,) + if isinstance(dilation_rate, int): + dilation_rate = (dilation_rate,) + + x, tf_data_format = _preprocess_conv1d_input(x, data_format) + padding = _preprocess_padding(padding) + if not isinstance(strides, tuple): + strides = tuple(strides) + if tf_data_format == 'NWC': + spatial_start_dim = 1 + strides = (1,) + strides * 2 + (1,) + else: + spatial_start_dim = 2 + strides = (1, 1) + strides * 2 + x = array_ops.expand_dims(x, spatial_start_dim) + depthwise_kernel = array_ops.expand_dims(depthwise_kernel, 0) + pointwise_kernel = array_ops.expand_dims(pointwise_kernel, 0) + dilation_rate = (1,) + dilation_rate + + x = nn.separable_conv2d( + x, + depthwise_kernel, + pointwise_kernel, + strides=strides, + padding=padding, + rate=dilation_rate, + data_format=tf_data_format) + + x = array_ops.squeeze(x, [spatial_start_dim]) + + if data_format == 'channels_first' and tf_data_format == 'NWC': + x = array_ops.transpose(x, (0, 2, 1)) # NWC -> NCW + + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def separable_conv2d(x, + depthwise_kernel, + pointwise_kernel, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1)): + """2D convolution with separable filters. + + Args: + x: input tensor + depthwise_kernel: convolution kernel for the depthwise convolution. + pointwise_kernel: kernel for the 1x1 convolution. + strides: strides tuple (length 2). + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + dilation_rate: tuple of integers, + dilation rates for the separable convolution. + + Returns: + Output tensor. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + ValueError: if `strides` is not a tuple of 2 integers. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + if len(strides) != 2: + raise ValueError('`strides` must be a tuple of 2 integers.') + + x, tf_data_format = _preprocess_conv2d_input(x, data_format) + padding = _preprocess_padding(padding) + if not isinstance(strides, tuple): + strides = tuple(strides) + if tf_data_format == 'NHWC': + strides = (1,) + strides + (1,) + else: + strides = (1, 1) + strides + + x = nn.separable_conv2d( + x, + depthwise_kernel, + pointwise_kernel, + strides=strides, + padding=padding, + rate=dilation_rate, + data_format=tf_data_format) + if data_format == 'channels_first' and tf_data_format == 'NHWC': + x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def depthwise_conv2d(x, + depthwise_kernel, + strides=(1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1)): + """2D convolution with separable filters. + + Args: + x: input tensor + depthwise_kernel: convolution kernel for the depthwise convolution. + strides: strides tuple (length 2). + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + dilation_rate: tuple of integers, + dilation rates for the separable convolution. + + Returns: + Output tensor. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + x, tf_data_format = _preprocess_conv2d_input(x, data_format) + padding = _preprocess_padding(padding) + if tf_data_format == 'NHWC': + strides = (1,) + strides + (1,) + else: + strides = (1, 1) + strides + + x = nn.depthwise_conv2d( + x, + depthwise_kernel, + strides=strides, + padding=padding, + rate=dilation_rate, + data_format=tf_data_format) + if data_format == 'channels_first' and tf_data_format == 'NHWC': + x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def conv3d(x, + kernel, + strides=(1, 1, 1), + padding='valid', + data_format=None, + dilation_rate=(1, 1, 1)): + """3D convolution. + + Args: + x: Tensor or variable. + kernel: kernel tensor. + strides: strides tuple. + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + dilation_rate: tuple of 3 integers. + + Returns: + A tensor, result of 3D convolution. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + x, tf_data_format = _preprocess_conv3d_input(x, data_format) + padding = _preprocess_padding(padding) + x = nn.convolution( + input=x, + filter=kernel, + dilation_rate=dilation_rate, + strides=strides, + padding=padding, + data_format=tf_data_format) + if data_format == 'channels_first' and tf_data_format == 'NDHWC': + x = array_ops.transpose(x, (0, 4, 1, 2, 3)) + return x + + +def conv3d_transpose(x, + kernel, + output_shape, + strides=(1, 1, 1), + padding='valid', + data_format=None): + """3D deconvolution (i.e. + + transposed convolution). + + Args: + x: input tensor. + kernel: kernel tensor. + output_shape: 1D int tensor for the output shape. + strides: strides tuple. + padding: string, "same" or "valid". + data_format: string, `"channels_last"` or `"channels_first"`. + + Returns: + A tensor, result of transposed 3D convolution. + + Raises: + ValueError: if `data_format` is neither `channels_last` or + `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + if isinstance(output_shape, (tuple, list)): + output_shape = array_ops_stack.stack(output_shape) + + x, tf_data_format = _preprocess_conv3d_input(x, data_format) + + if data_format == 'channels_first' and tf_data_format == 'NDHWC': + output_shape = (output_shape[0], output_shape[2], output_shape[3], + output_shape[4], output_shape[1]) + if output_shape[0] is None: + output_shape = (array_ops.shape(x)[0],) + tuple(output_shape[1:]) + output_shape = array_ops_stack.stack(list(output_shape)) + + padding = _preprocess_padding(padding) + if tf_data_format == 'NDHWC': + strides = (1,) + strides + (1,) + else: + strides = (1, 1) + strides + + x = nn.conv3d_transpose( + x, + kernel, + output_shape, + strides, + padding=padding, + data_format=tf_data_format) + if data_format == 'channels_first' and tf_data_format == 'NDHWC': + x = array_ops.transpose(x, (0, 4, 1, 2, 3)) + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def pool2d(x, + pool_size, + strides=(1, 1), + padding='valid', + data_format=None, + pool_mode='max'): + """2D Pooling. + + Args: + x: Tensor or variable. + pool_size: tuple of 2 integers. + strides: tuple of 2 integers. + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + pool_mode: string, `"max"` or `"avg"`. + + Returns: + A tensor, result of 2D pooling. + + Raises: + ValueError: if `data_format` is neither `"channels_last"` or + `"channels_first"`. + ValueError: if `pool_size` is not a tuple of 2 integers. + ValueError: if `strides` is not a tuple of 2 integers. + ValueError: if `pool_mode` is neither `"max"` or `"avg"`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + if len(pool_size) != 2: + raise ValueError('`pool_size` must be a tuple of 2 integers.') + if len(strides) != 2: + raise ValueError('`strides` must be a tuple of 2 integers.') + + x, tf_data_format = _preprocess_conv2d_input(x, data_format) + padding = _preprocess_padding(padding) + if tf_data_format == 'NHWC': + strides = (1,) + strides + (1,) + pool_size = (1,) + pool_size + (1,) + else: + strides = (1, 1) + strides + pool_size = (1, 1) + pool_size + + if pool_mode == 'max': + x = nn.max_pool( + x, pool_size, strides, padding=padding, data_format=tf_data_format) + elif pool_mode == 'avg': + x = nn.avg_pool( + x, pool_size, strides, padding=padding, data_format=tf_data_format) + else: + raise ValueError('Invalid pooling mode: ' + str(pool_mode)) + + if data_format == 'channels_first' and tf_data_format == 'NHWC': + x = array_ops.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW + return x + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def pool3d(x, + pool_size, + strides=(1, 1, 1), + padding='valid', + data_format=None, + pool_mode='max'): + """3D Pooling. + + Args: + x: Tensor or variable. + pool_size: tuple of 3 integers. + strides: tuple of 3 integers. + padding: string, `"same"` or `"valid"`. + data_format: string, `"channels_last"` or `"channels_first"`. + pool_mode: string, `"max"` or `"avg"`. + + Returns: + A tensor, result of 3D pooling. + + Raises: + ValueError: if `data_format` is neither `"channels_last"` or + `"channels_first"`. + ValueError: if `pool_mode` is neither `"max"` or `"avg"`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + x, tf_data_format = _preprocess_conv3d_input(x, data_format) + padding = _preprocess_padding(padding) + if tf_data_format == 'NDHWC': + strides = (1,) + strides + (1,) + pool_size = (1,) + pool_size + (1,) + else: + strides = (1, 1) + strides + pool_size = (1, 1) + pool_size + + if pool_mode == 'max': + x = nn.max_pool3d( + x, pool_size, strides, padding=padding, data_format=tf_data_format) + elif pool_mode == 'avg': + x = nn.avg_pool3d( + x, pool_size, strides, padding=padding, data_format=tf_data_format) + else: + raise ValueError('Invalid pooling mode: ' + str(pool_mode)) + + if data_format == 'channels_first' and tf_data_format == 'NDHWC': + x = array_ops.transpose(x, (0, 4, 1, 2, 3)) + return x + + +def local_conv(inputs, + kernel, + kernel_size, + strides, + output_shape, + data_format=None): + """Apply N-D convolution with un-shared weights. + + Args: + inputs: (N+2)-D tensor with shape + (batch_size, channels_in, d_in1, ..., d_inN) + if data_format='channels_first', or + (batch_size, d_in1, ..., d_inN, channels_in) + if data_format='channels_last'. + kernel: the unshared weight for N-D convolution, + with shape (output_items, feature_dim, channels_out), where + feature_dim = np.prod(kernel_size) * channels_in, + output_items = np.prod(output_shape). + kernel_size: a tuple of N integers, specifying the + spatial dimensions of the N-D convolution window. + strides: a tuple of N integers, specifying the strides + of the convolution along the spatial dimensions. + output_shape: a tuple of (d_out1, ..., d_outN) specifying the spatial + dimensionality of the output. + data_format: string, "channels_first" or "channels_last". + + Returns: + An (N+2)-D tensor with shape: + (batch_size, channels_out) + output_shape + if data_format='channels_first', or: + (batch_size,) + output_shape + (channels_out,) + if data_format='channels_last'. + + Raises: + ValueError: if `data_format` is neither + `channels_last` nor `channels_first`. + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + + kernel_shape = int_shape(kernel) + feature_dim = kernel_shape[1] + channels_out = kernel_shape[-1] + ndims = len(output_shape) + spatial_dimensions = list(range(ndims)) + + xs = [] + output_axes_ticks = [range(axis_max) for axis_max in output_shape] + for position in itertools.product(*output_axes_ticks): + slices = [slice(None)] + + if data_format == 'channels_first': + slices.append(slice(None)) + + slices.extend( + slice(position[d] * strides[d], position[d] * strides[d] + + kernel_size[d]) for d in spatial_dimensions) + + if data_format == 'channels_last': + slices.append(slice(None)) + + xs.append(reshape(inputs[slices], (1, -1, feature_dim))) + + x_aggregate = concatenate(xs, axis=0) + output = batch_dot(x_aggregate, kernel) + output = reshape(output, output_shape + (-1, channels_out)) + + if data_format == 'channels_first': + permutation = [ndims, ndims + 1] + spatial_dimensions + else: + permutation = [ndims] + spatial_dimensions + [ndims + 1] + + return permute_dimensions(output, permutation) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def local_conv1d(inputs, kernel, kernel_size, strides, data_format=None): + """Apply 1D conv with un-shared weights. + + Args: + inputs: 3D tensor with shape: + (batch_size, steps, input_dim) + if data_format is "channels_last" or + (batch_size, input_dim, steps) + if data_format is "channels_first". + kernel: the unshared weight for convolution, + with shape (output_length, feature_dim, filters). + kernel_size: a tuple of a single integer, + specifying the length of the 1D convolution window. + strides: a tuple of a single integer, + specifying the stride length of the convolution. + data_format: the data format, channels_first or channels_last. + + Returns: + A 3d tensor with shape: + (batch_size, output_length, filters) + if data_format='channels_first' + or 3D tensor with shape: + (batch_size, filters, output_length) + if data_format='channels_last'. + """ + output_shape = (kernel.shape[0],) + return local_conv(inputs, + kernel, + kernel_size, + strides, + output_shape, + data_format) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def local_conv2d(inputs, + kernel, + kernel_size, + strides, + output_shape, + data_format=None): + """Apply 2D conv with un-shared weights. + + Args: + inputs: 4D tensor with shape: + (batch_size, filters, new_rows, new_cols) + if data_format='channels_first' + or 4D tensor with shape: + (batch_size, new_rows, new_cols, filters) + if data_format='channels_last'. + kernel: the unshared weight for convolution, + with shape (output_items, feature_dim, filters). + kernel_size: a tuple of 2 integers, specifying the + width and height of the 2D convolution window. + strides: a tuple of 2 integers, specifying the strides + of the convolution along the width and height. + output_shape: a tuple with (output_row, output_col). + data_format: the data format, channels_first or channels_last. + + Returns: + A 4D tensor with shape: + (batch_size, filters, new_rows, new_cols) + if data_format='channels_first' + or 4D tensor with shape: + (batch_size, new_rows, new_cols, filters) + if data_format='channels_last'. + """ + return local_conv(inputs, + kernel, + kernel_size, + strides, + output_shape, + data_format) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def bias_add(x, bias, data_format=None): + """Adds a bias vector to a tensor. + + Args: + x: Tensor or variable. + bias: Bias tensor to add. + data_format: string, `"channels_last"` or `"channels_first"`. + + Returns: + Output tensor. + + Raises: + ValueError: In one of the two cases below: + 1. invalid `data_format` argument. + 2. invalid bias shape. + the bias should be either a vector or + a tensor with ndim(x) - 1 dimension + """ + if data_format is None: + data_format = image_data_format() + if data_format not in {'channels_first', 'channels_last'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + bias_shape = int_shape(bias) + if len(bias_shape) != 1 and len(bias_shape) != ndim(x) - 1: + raise ValueError( + 'Unexpected bias dimensions %d, expect to be 1 or %d dimensions' % + (len(bias_shape), ndim(x) - 1)) + + if len(bias_shape) == 1: + if data_format == 'channels_first': + return nn.bias_add(x, bias, data_format='NCHW') + return nn.bias_add(x, bias, data_format='NHWC') + if ndim(x) in (3, 4, 5): + if data_format == 'channels_first': + bias_reshape_axis = (1, bias_shape[-1]) + bias_shape[:-1] + return x + reshape(bias, bias_reshape_axis) + return x + reshape(bias, (1,) + bias_shape) + return nn.bias_add(x, bias) + + +# RANDOMNESS + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def random_normal(shape, mean=0.0, stddev=1.0, dtype=None, seed=None): + """Returns a tensor with normal distribution of values. + + It is an alias to `tf.random.normal`. + + Args: + shape: A tuple of integers, the shape of tensor to create. + mean: A float, the mean value of the normal distribution to draw samples. + Default to 0.0. + stddev: A float, the standard deviation of the normal distribution + to draw samples. Default to 1.0. + dtype: `tf.dtypes.DType`, dtype of returned tensor. Default to use Keras + backend dtype which is float32. + seed: Integer, random seed. Will use a random numpy integer when not + specified. + + Returns: + A tensor with normal distribution of values. + + Example: + + >>> random_normal_tensor = tf.keras.backend.random_normal(shape=(2,3), + ... mean=0.0, stddev=1.0) + >>> random_normal_tensor + + """ + if dtype is None: + dtype = floatx() + if seed is None: + seed = np.random.randint(10e6) + return random_ops.random_normal( + shape, mean=mean, stddev=stddev, dtype=dtype, seed=seed) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def random_uniform(shape, minval=0.0, maxval=1.0, dtype=None, seed=None): + """Returns a tensor with uniform distribution of values. + + Args: + shape: A tuple of integers, the shape of tensor to create. + minval: A float, lower boundary of the uniform distribution + to draw samples. + maxval: A float, upper boundary of the uniform distribution + to draw samples. + dtype: String, dtype of returned tensor. + seed: Integer, random seed. + + Returns: + A tensor. + + Example: + + >>> random_uniform_tensor = tf.keras.backend.random_uniform(shape=(2,3), + ... minval=0.0, maxval=1.0) + >>> random_uniform_tensor + + """ + if dtype is None: + dtype = floatx() + if seed is None: + seed = np.random.randint(10e6) + return random_ops.random_uniform( + shape, minval=minval, maxval=maxval, dtype=dtype, seed=seed) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def random_binomial(shape, p=0.0, dtype=None, seed=None): + """Returns a tensor with random binomial distribution of values. + + DEPRECATED, use `tf.keras.backend.random_bernoulli` instead. + + The binomial distribution with parameters `n` and `p` is the probability + distribution of the number of successful Bernoulli process. Only supports + `n` = 1 for now. + + Args: + shape: A tuple of integers, the shape of tensor to create. + p: A float, `0. <= p <= 1`, probability of binomial distribution. + dtype: String, dtype of returned tensor. + seed: Integer, random seed. + + Returns: + A tensor. + + Example: + + >>> random_binomial_tensor = tf.keras.backend.random_binomial(shape=(2,3), + ... p=0.5) + >>> random_binomial_tensor + + """ + warnings.warn('`tf.keras.backend.random_binomial` is deprecated, ' + 'and will be removed in a future version.' + 'Please use `tf.keras.backend.random_bernoulli` instead.') + return random_bernoulli(shape, p, dtype, seed) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def random_bernoulli(shape, p=0.0, dtype=None, seed=None): + """Returns a tensor with random bernoulli distribution of values. + + Args: + shape: A tuple of integers, the shape of tensor to create. + p: A float, `0. <= p <= 1`, probability of bernoulli distribution. + dtype: String, dtype of returned tensor. + seed: Integer, random seed. + + Returns: + A tensor. + """ + if dtype is None: + dtype = floatx() + if seed is None: + seed = np.random.randint(10e6) + return array_ops.where_v2( + random_ops.random_uniform(shape, dtype=dtype, seed=seed) <= p, + array_ops.ones(shape, dtype=dtype), array_ops.zeros(shape, dtype=dtype)) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def truncated_normal(shape, mean=0.0, stddev=1.0, dtype=None, seed=None): + """Returns a tensor with truncated random normal distribution of values. + + The generated values follow a normal distribution + with specified mean and standard deviation, + except that values whose magnitude is more than + two standard deviations from the mean are dropped and re-picked. + + Args: + shape: A tuple of integers, the shape of tensor to create. + mean: Mean of the values. + stddev: Standard deviation of the values. + dtype: String, dtype of returned tensor. + seed: Integer, random seed. + + Returns: + A tensor. + """ + if dtype is None: + dtype = floatx() + if seed is None: + seed = np.random.randint(10e6) + return random_ops.truncated_normal( + shape, mean, stddev, dtype=dtype, seed=seed) + + +# CTC +# TensorFlow has a native implementation, but it uses sparse tensors +# and therefore requires a wrapper for Keras. The functions below convert +# dense to sparse tensors and also wraps up the beam search code that is +# in TensorFlow's CTC implementation + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def ctc_label_dense_to_sparse(labels, label_lengths): + """Converts CTC labels from dense to sparse. + + Args: + labels: dense CTC labels. + label_lengths: length of the labels. + + Returns: + A sparse tensor representation of the labels. + """ + label_shape = array_ops.shape(labels) + num_batches_tns = array_ops_stack.stack([label_shape[0]]) + max_num_labels_tns = array_ops_stack.stack([label_shape[1]]) + + def range_less_than(old_input, current_input): + return array_ops.expand_dims( + math_ops.range(array_ops.shape(old_input)[1]), 0) < array_ops.fill( + max_num_labels_tns, current_input) + + init = math_ops.cast( + array_ops.fill([1, label_shape[1]], 0), dtypes_module.bool) + dense_mask = functional_ops.scan( + range_less_than, label_lengths, initializer=init, parallel_iterations=1) + dense_mask = dense_mask[:, 0, :] + + label_array = array_ops.reshape( + array_ops.tile(math_ops.range(0, label_shape[1]), num_batches_tns), + label_shape) + label_ind = array_ops.boolean_mask(label_array, dense_mask) + + batch_array = array_ops.transpose( + array_ops.reshape( + array_ops.tile(math_ops.range(0, label_shape[0]), max_num_labels_tns), + reverse(label_shape, 0))) + batch_ind = array_ops.boolean_mask(batch_array, dense_mask) + indices = array_ops.transpose( + array_ops.reshape(concatenate([batch_ind, label_ind], axis=0), [2, -1])) + + vals_sparse = array_ops.gather_nd(labels, indices) + + return sparse_tensor.SparseTensor( + math_ops.cast(indices, dtypes_module.int64), vals_sparse, + math_ops.cast(label_shape, dtypes_module.int64)) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def ctc_batch_cost(y_true, y_pred, input_length, label_length): + """Runs CTC loss algorithm on each batch element. + + Args: + y_true: tensor `(samples, max_string_length)` + containing the truth labels. + y_pred: tensor `(samples, time_steps, num_categories)` + containing the prediction, or output of the softmax. + input_length: tensor `(samples, 1)` containing the sequence length for + each batch item in `y_pred`. + label_length: tensor `(samples, 1)` containing the sequence length for + each batch item in `y_true`. + + Returns: + Tensor with shape (samples,1) containing the + CTC loss of each element. + """ + label_length = math_ops.cast( + array_ops.squeeze(label_length, axis=-1), dtypes_module.int32) + input_length = math_ops.cast( + array_ops.squeeze(input_length, axis=-1), dtypes_module.int32) + sparse_labels = math_ops.cast( + ctc_label_dense_to_sparse(y_true, label_length), dtypes_module.int32) + + y_pred = math_ops.log(array_ops.transpose(y_pred, perm=[1, 0, 2]) + epsilon()) + + return array_ops.expand_dims( + ctc.ctc_loss( + inputs=y_pred, labels=sparse_labels, sequence_length=input_length), 1) + + +@dispatch.add_dispatch_support +@doc_controls.do_not_generate_docs +def ctc_decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1): + """Decodes the output of a softmax. + + Can use either greedy search (also known as best path) + or a constrained dictionary search. + + Args: + y_pred: tensor `(samples, time_steps, num_categories)` + containing the prediction, or output of the softmax. + input_length: tensor `(samples, )` containing the sequence length for + each batch item in `y_pred`. + greedy: perform much faster best-path search if `true`. + This does not use a dictionary. + beam_width: if `greedy` is `false`: a beam search decoder will be used + with a beam of this width. + top_paths: if `greedy` is `false`, + how many of the most probable paths will be returned. + + Returns: + Tuple: + List: if `greedy` is `true`, returns a list of one element that + contains the decoded sequence. + If `false`, returns the `top_paths` most probable + decoded sequences. + Each decoded sequence has shape (samples, time_steps). + Important: blank labels are returned as `-1`. + Tensor `(top_paths, )` that contains + the log probability of each decoded sequence. + """ + input_shape = shape(y_pred) + num_samples, num_steps = input_shape[0], input_shape[1] + y_pred = math_ops.log(array_ops.transpose(y_pred, perm=[1, 0, 2]) + epsilon()) + input_length = math_ops.cast(input_length, dtypes_module.int32) + + if greedy: + (decoded, log_prob) = ctc.ctc_greedy_decoder( + inputs=y_pred, sequence_length=input_length) + else: + (decoded, log_prob) = ctc.ctc_beam_search_decoder( + inputs=y_pred, + sequence_length=input_length, + beam_width=beam_width, + top_paths=top_paths) + decoded_dense = [] + for st in decoded: + st = sparse_tensor.SparseTensor( + st.indices, st.values, (num_samples, num_steps)) + decoded_dense.append( + sparse_ops.sparse_tensor_to_dense(sp_input=st, default_value=-1)) + return (decoded_dense, log_prob) + + +# HIGH ORDER FUNCTIONS + + +@doc_controls.do_not_generate_docs +def map_fn(fn, elems, name=None, dtype=None): + """Map the function fn over the elements elems and return the outputs. + + Args: + fn: Callable that will be called upon each element in elems + elems: tensor + name: A string name for the map node in the graph + dtype: Output data type. + + Returns: + Tensor with dtype `dtype`. + """ + return map_fn_lib.map_fn(fn, elems, name=name, dtype=dtype) + + +@doc_controls.do_not_generate_docs +def foldl(fn, elems, initializer=None, name=None): + """Reduce elems using fn to combine them from left to right. + + Args: + fn: Callable that will be called upon each element in elems and an + accumulator, for instance `lambda acc, x: acc + x` + elems: tensor + initializer: The first value used (`elems[0]` in case of None) + name: A string name for the foldl node in the graph + + Returns: + Tensor with same type and shape as `initializer`. + """ + return functional_ops.foldl(fn, elems, initializer=initializer, name=name) + + +@doc_controls.do_not_generate_docs +def foldr(fn, elems, initializer=None, name=None): + """Reduce elems using fn to combine them from right to left. + + Args: + fn: Callable that will be called upon each element in elems and an + accumulator, for instance `lambda acc, x: acc + x` + elems: tensor + initializer: The first value used (`elems[-1]` in case of None) + name: A string name for the foldr node in the graph + + Returns: + Same type and shape as initializer + """ + return functional_ops.foldr(fn, elems, initializer=initializer, name=name) + +# Load Keras default configuration from config file if present. +# Set Keras base dir path given KERAS_HOME env variable, if applicable. +# Otherwise either ~/.keras or /tmp. +if 'KERAS_HOME' in os.environ: + _keras_dir = os.environ.get('KERAS_HOME') +else: + _keras_base_dir = os.path.expanduser('~') + _keras_dir = os.path.join(_keras_base_dir, '.keras') +_config_path = os.path.expanduser(os.path.join(_keras_dir, 'keras.json')) +if os.path.exists(_config_path): + try: + with open(_config_path) as fh: + _config = json.load(fh) + except ValueError: + _config = {} + _floatx = _config.get('floatx', floatx()) + assert _floatx in {'float16', 'float32', 'float64'} + _epsilon = _config.get('epsilon', epsilon()) + assert isinstance(_epsilon, float) + _image_data_format = _config.get('image_data_format', image_data_format()) + assert _image_data_format in {'channels_last', 'channels_first'} + set_floatx(_floatx) + set_epsilon(_epsilon) + set_image_data_format(_image_data_format) + +# Save config file. +if not os.path.exists(_keras_dir): + try: + os.makedirs(_keras_dir) + except OSError: + # Except permission denied and potential race conditions + # in multi-threaded environments. + pass + +if not os.path.exists(_config_path): + _config = { + 'floatx': floatx(), + 'epsilon': epsilon(), + 'backend': 'tensorflow', + 'image_data_format': image_data_format() + } + try: + with open(_config_path, 'w') as f: + f.write(json.dumps(_config, indent=4)) + except IOError: + # Except permission denied. + pass + + +def configure_and_create_distributed_session(distribution_strategy): + """Configure session config and create a session with it.""" + + def _create_session(distribution_strategy): + """Create the Distributed Strategy session.""" + session_config = get_default_session_config() + + # If a session already exists, merge in its config; in the case there is a + # conflict, take values of the existing config. + global _SESSION + if getattr(_SESSION, 'session', None) and _SESSION.session._config: + session_config.MergeFrom(_SESSION.session._config) + + if is_tpu_strategy(distribution_strategy): + # TODO(priyag, yuefengz): Remove this workaround when Distribute + # Coordinator is integrated with keras and we can create a session from + # there. + distribution_strategy.configure(session_config) + master = distribution_strategy.extended._tpu_cluster_resolver.master() # pylint: disable=protected-access + session = session_module.Session(config=session_config, target=master) + else: + worker_context = dc.get_current_worker_context() + if worker_context: + dc_session_config = worker_context.session_config + # Merge the default session config to the one from distribute + # coordinator, which is fine for now since they don't have + # conflicting configurations. + dc_session_config.MergeFrom(session_config) + session = session_module.Session( + config=dc_session_config, target=worker_context.master_target) + else: + distribution_strategy.configure(session_config) + session = session_module.Session(config=session_config) + + set_session(session) + + if distribution_strategy.extended._in_multi_worker_mode(): + dc.run_distribute_coordinator( + _create_session, + distribution_strategy) + else: + _create_session(distribution_strategy) + + +def _is_tpu_strategy_class(clz): + is_tpu_strat = lambda k: k.__name__.startswith('TPUStrategy') + if is_tpu_strat(clz): + return True + return py_any(map(_is_tpu_strategy_class, clz.__bases__)) + + +def is_tpu_strategy(strategy): + """Returns whether input is a TPUStrategy instance or subclass instance.""" + return _is_tpu_strategy_class(strategy.__class__) + + +def cast_variables_to_tensor(tensors): + + def _cast_variables_to_tensor(tensor): + if isinstance(tensor, variables_module.Variable): + return array_ops.identity(tensor) + return tensor + + return nest.map_structure(_cast_variables_to_tensor, tensors) + + +def _is_symbolic_tensor(x): + return tensor_util.is_tf_type(x) and not isinstance(x, ops.EagerTensor) + + +def convert_inputs_if_ragged(inputs): + """Converts any ragged tensors to dense.""" + + def _convert_ragged_input(inputs): + if isinstance(inputs, ragged_tensor.RaggedTensor): + return inputs.to_tensor() + return inputs + + flat_inputs = nest.flatten(inputs) + contains_ragged = py_any( + isinstance(i, ragged_tensor.RaggedTensor) for i in flat_inputs) + + if not contains_ragged: + return inputs, None + + inputs = nest.map_structure(_convert_ragged_input, inputs) + # Multiple mask are not yet supported, so one mask is used on all inputs. + # We approach this similarly when using row lengths to ignore steps. + nested_row_lengths = math_ops.cast(flat_inputs[0].nested_row_lengths()[0], + 'int32') + return inputs, nested_row_lengths + + +def maybe_convert_to_ragged(is_ragged_input, output, nested_row_lengths, + go_backwards=False): + """Converts any ragged input back to its initial structure.""" + if not is_ragged_input: + return output + + if go_backwards: + # Reverse based on the timestep dim, so that nested_row_lengths will mask + # from the correct direction. Return the reverse ragged tensor. + output = reverse(output, [1]) + ragged = ragged_tensor.RaggedTensor.from_tensor(output, nested_row_lengths) + return reverse(ragged, [1]) + else: + return ragged_tensor.RaggedTensor.from_tensor(output, nested_row_lengths) + + +class ContextValueCache(weakref.WeakKeyDictionary): + """Container that caches (possibly tensor) values based on the context. + + This class is similar to defaultdict, where values may be produced by the + default factory specified during initialization. This class also has a default + value for the key (when key is `None`) -- the key is set to the current graph + or eager context. The default factories for key and value are only used in + `__getitem__` and `setdefault`. The `.get()` behavior remains the same. + + This object will return the value of the current graph or closest parent graph + if the current graph is a function. This is to reflect the fact that if a + tensor is created in eager/graph, child functions may capture that tensor. + + The default factory method may accept keyword arguments (unlike defaultdict, + which only accepts callables with 0 arguments). To pass keyword arguments to + `default_factory`, use the `setdefault` method instead of `__getitem__`. + + An example of how this class can be used in different contexts: + + ``` + cache = ContextValueCache(int) + + # Eager mode + cache[None] += 2 + cache[None] += 4 + assert cache[None] == 6 + + # Graph mode + with tf.Graph().as_default() as g: + cache[None] += 5 + cache[g] += 3 + assert cache[g] == 8 + ``` + + Example of a default factory with arguments: + + ``` + cache = ContextValueCache(lambda x: x + 1) + g = tf.get_default_graph() + + # Example with keyword argument. + value = cache.setdefault(key=g, kwargs={'x': 3}) + assert cache[g] == 4 + ``` + """ + + def __init__(self, default_factory): + self.default_factory = default_factory + weakref.WeakKeyDictionary.__init__(self) + + def _key(self): + if context.executing_eagerly(): + return _DUMMY_EAGER_GRAPH.key + else: + return ops.get_default_graph() + + def _get_parent_graph(self, graph): + """Returns the parent graph or dummy eager object.""" + # TODO(b/149317164): Currently FuncGraphs use ops.get_default_graph() as the + # outer graph. This results in outer_graph always being a Graph, + # even in eager mode (get_default_graph will create a new Graph if there + # isn't a default graph). Because of this bug, we have to specially set the + # key when eager execution is enabled. + parent_graph = graph.outer_graph + if (not isinstance(parent_graph, func_graph.FuncGraph) and + ops.executing_eagerly_outside_functions()): + return _DUMMY_EAGER_GRAPH.key + return parent_graph + + def _get_recursive(self, key): + """Gets the value at key or the closest parent graph.""" + value = self.get(key) + if value is not None: + return value + + # Since FuncGraphs are able to capture tensors and variables from their + # parent graphs, recursively search to see if there is a value stored for + # one of the parent graphs. + if isinstance(key, func_graph.FuncGraph): + return self._get_recursive(self._get_parent_graph(key)) + return None + + def __getitem__(self, key): + """Gets the value at key (or current context), or sets default value. + + Args: + key: May be `None` or `Graph`object. When `None`, the key is set to the + current context. + + Returns: + Either the cached or default value. + """ + if key is None: + key = self._key() + + value = self._get_recursive(key) + if value is None: + value = self[key] = self.default_factory() # pylint:disable=not-callable + return value + + def setdefault(self, key=None, default=None, kwargs=None): + """Sets the default value if key is not in dict, and returns the value.""" + if key is None: + key = self._key() + kwargs = kwargs or {} + + if default is None and key not in self: + default = self.default_factory(**kwargs) + return weakref.WeakKeyDictionary.setdefault(self, key, default) + +# This dictionary holds a mapping {graph: learning_phase}. In eager mode, a +# dummy object is used. +# A learning phase is a bool tensor used to run Keras models in +# either train mode (learning_phase == 1) or test mode (learning_phase == 0). +_GRAPH_LEARNING_PHASES = ContextValueCache(_default_learning_phase) + +# This dictionary holds a mapping between a graph and variables to initialize +# in the graph. +_GRAPH_VARIABLES = ContextValueCache(object_identity.ObjectIdentityWeakSet) + +# This dictionary holds a mapping between a graph and TF optimizers created in +# the graph. +_GRAPH_TF_OPTIMIZERS = ContextValueCache(object_identity.ObjectIdentityWeakSet) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/backend_config.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/backend_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ad2adba81f23e29d90655eaa01048573120259be --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/backend_config.py @@ -0,0 +1,140 @@ +# 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. +# ============================================================================== +"""Keras backend config API.""" + +from tensorflow.python.util import dispatch + +# The type of float to use throughout a session. +_FLOATX = 'float32' + +# Epsilon fuzz factor used throughout the codebase. +_EPSILON = 1e-7 + +# Default image data format, one of "channels_last", "channels_first". +_IMAGE_DATA_FORMAT = 'channels_last' + + +@dispatch.add_dispatch_support +def epsilon(): + """Returns the value of the fuzz factor used in numeric expressions. + + Returns: + A float. + + Example: + >>> tf.keras.backend.epsilon() + 1e-07 + """ + return _EPSILON + + +def set_epsilon(value): + """Sets the value of the fuzz factor used in numeric expressions. + + Args: + value: float. New value of epsilon. + + Example: + >>> tf.keras.backend.epsilon() + 1e-07 + >>> tf.keras.backend.set_epsilon(1e-5) + >>> tf.keras.backend.epsilon() + 1e-05 + >>> tf.keras.backend.set_epsilon(1e-7) + """ + global _EPSILON + _EPSILON = value + + +def floatx(): + """Returns the default float type, as a string. + + E.g. `'float16'`, `'float32'`, `'float64'`. + + Returns: + String, the current default float type. + + Example: + >>> tf.keras.backend.floatx() + 'float32' + """ + return _FLOATX + + +def set_floatx(value): + """Sets the default float type. + + Note: It is not recommended to set this to float16 for training, as this will + likely cause numeric stability issues. Instead, mixed precision, which is + using a mix of float16 and float32, can be used by calling + `tf.keras.mixed_precision.set_global_policy('mixed_float16')`. See the + [mixed precision guide]( + https://www.tensorflow.org/guide/keras/mixed_precision) for details. + + Args: + value: String; `'float16'`, `'float32'`, or `'float64'`. + + Example: + >>> tf.keras.backend.floatx() + 'float32' + >>> tf.keras.backend.set_floatx('float64') + >>> tf.keras.backend.floatx() + 'float64' + >>> tf.keras.backend.set_floatx('float32') + + Raises: + ValueError: In case of invalid value. + """ + global _FLOATX + if value not in {'float16', 'float32', 'float64'}: + raise ValueError('Unknown floatx type: ' + str(value)) + _FLOATX = str(value) + + +@dispatch.add_dispatch_support +def image_data_format(): + """Returns the default image data format convention. + + Returns: + A string, either `'channels_first'` or `'channels_last'` + + Example: + >>> tf.keras.backend.image_data_format() + 'channels_last' + """ + return _IMAGE_DATA_FORMAT + + +def set_image_data_format(data_format): + """Sets the value of the image data format convention. + + Args: + data_format: string. `'channels_first'` or `'channels_last'`. + + Example: + >>> tf.keras.backend.image_data_format() + 'channels_last' + >>> tf.keras.backend.set_image_data_format('channels_first') + >>> tf.keras.backend.image_data_format() + 'channels_first' + >>> tf.keras.backend.set_image_data_format('channels_last') + + Raises: + ValueError: In case of invalid `data_format` value. + """ + global _IMAGE_DATA_FORMAT + if data_format not in {'channels_last', 'channels_first'}: + raise ValueError('Unknown data_format: ' + str(data_format)) + _IMAGE_DATA_FORMAT = str(data_format) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/callbacks.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..f243a952d987a54169c6facce3e122ace3a88014 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/callbacks.py @@ -0,0 +1,2876 @@ +# 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. +# ============================================================================== +# pylint: disable=g-import-not-at-top +# pylint: disable=g-classes-have-attributes +"""Callbacks: utilities called at certain points during model training.""" + +import collections +import copy +import csv +import json +import os +import re +import sys +import time + +import numpy as np + +from tensorflow.core.framework import summary_pb2 +from tensorflow.python.checkpoint import checkpoint_management +from tensorflow.python.checkpoint import checkpoint_options as checkpoint_options_lib +from tensorflow.python.data.ops import iterator_ops +from tensorflow.python.distribute import collective_all_reduce_strategy +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.distribute import mirrored_strategy +from tensorflow.python.distribute import parameter_server_strategy_v2 +from tensorflow.python.distribute import tpu_strategy +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor as tensor_lib +from tensorflow.python.keras import backend +from tensorflow.python.keras.distribute import distributed_file_utils +from tensorflow.python.keras.distribute import worker_training_state +from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.keras.utils.data_utils import Sequence +from tensorflow.python.keras.utils.generic_utils import Progbar +from tensorflow.python.keras.utils.io_utils import path_to_string +from tensorflow.python.keras.utils.mode_keys import ModeKeys +from tensorflow.python.lib.io import file_io +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.platform import gfile +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import profiler_v2 as profiler +from tensorflow.python.saved_model import save_options as save_options_lib +from tensorflow.python.util import nest +from tensorflow.tools.docs import doc_controls + +try: + import requests +except ImportError: + requests = None + + +# Note: `configure_callbacks` is only used in TF1. +def configure_callbacks(callbacks, + model, + do_validation=False, + batch_size=None, + epochs=None, + steps_per_epoch=None, + samples=None, + verbose=1, + count_mode='steps', + mode=ModeKeys.TRAIN): + """Configures callbacks for use in various training loops. + + Args: + callbacks: List of Callbacks. + model: Model being trained. + do_validation: Whether or not validation loop will be run. + batch_size: Number of samples per batch. + epochs: Number of epoch to train. + steps_per_epoch: Number of batches to run per training epoch. + samples: Number of training samples. + verbose: int, 0 or 1. Keras logging verbosity to pass to ProgbarLogger. + count_mode: One of 'steps' or 'samples'. Per-batch or per-sample count. + mode: String. One of ModeKeys.TRAIN, ModeKeys.TEST, or ModeKeys.PREDICT. + Which loop mode to configure callbacks for. + + Returns: + Instance of CallbackList used to control all Callbacks. + """ + # Check if callbacks have already been configured. + if isinstance(callbacks, CallbackList): + return callbacks + + if not callbacks: + callbacks = [] + + # Add additional callbacks during training. + if mode == ModeKeys.TRAIN: + model.history = History() + callbacks = [BaseLogger()] + (callbacks or []) + [model.history] + if verbose: + callbacks.append(ProgbarLogger(count_mode)) + callback_list = CallbackList(callbacks) + + # Set callback model + callback_model = model._get_callback_model() # pylint: disable=protected-access + callback_list.set_model(callback_model) + + set_callback_parameters( + callback_list, + model, + do_validation=do_validation, + batch_size=batch_size, + epochs=epochs, + steps_per_epoch=steps_per_epoch, + samples=samples, + verbose=verbose, + mode=mode) + + callback_list.model.stop_training = False + return callback_list + + +def set_callback_parameters(callback_list, + model, + do_validation=False, + batch_size=None, + epochs=None, + steps_per_epoch=None, + samples=None, + verbose=1, + mode=ModeKeys.TRAIN): + """Sets callback parameters. + + Args: + callback_list: CallbackList instance. + model: Model being trained. + do_validation: Whether or not validation loop will be run. + batch_size: Number of samples per batch. + epochs: Number of epoch to train. + steps_per_epoch: Number of batches to run per training epoch. + samples: Number of training samples. + verbose: int, 0 or 1. Keras logging verbosity to pass to ProgbarLogger. + mode: String. One of ModeKeys.TRAIN, ModeKeys.TEST, or ModeKeys.PREDICT. + Which loop mode to configure callbacks for. + """ + metric_names = model.metrics_names + for cbk in callback_list: + if isinstance(cbk, (BaseLogger, ProgbarLogger)): + cbk.stateful_metrics = metric_names[1:] # Exclude `loss` + + # Set callback parameters + callback_metrics = [] + # When we have deferred build scenario with iterator input, we will compile + # when we standardize first batch of data. + if mode != ModeKeys.PREDICT: + callback_metrics = copy.copy(metric_names) + if do_validation: + callback_metrics += ['val_' + n for n in metric_names] + callback_params = { + 'batch_size': batch_size, + 'epochs': epochs, + 'steps': steps_per_epoch, + 'samples': samples, + 'verbose': verbose, + 'do_validation': do_validation, + 'metrics': callback_metrics, + } + callback_list.set_params(callback_params) + + +def _is_generator_like(data): + """Checks if data is a generator, Sequence, or Iterator.""" + return (hasattr(data, '__next__') or hasattr(data, 'next') or isinstance( + data, (Sequence, iterator_ops.Iterator, iterator_ops.IteratorBase))) + + +def make_logs(model, logs, outputs, mode, prefix=''): + """Computes logs for sending to `on_batch_end` methods.""" + metric_names = model.metrics_names + if mode in {ModeKeys.TRAIN, ModeKeys.TEST} and metric_names: + for label, output in zip(metric_names, outputs): + logs[prefix + label] = output + else: + logs['outputs'] = outputs + return logs + + +class CallbackList: + """Container abstracting a list of callbacks.""" + + def __init__(self, + callbacks=None, + add_history=False, + add_progbar=False, + model=None, + **params): + """Container for `Callback` instances. + + This object wraps a list of `Callback` instances, making it possible + to call them all at once via a single endpoint + (e.g. `callback_list.on_epoch_end(...)`). + + Args: + callbacks: List of `Callback` instances. + add_history: Whether a `History` callback should be added, if one does not + already exist in the `callbacks` list. + add_progbar: Whether a `ProgbarLogger` callback should be added, if one + does not already exist in the `callbacks` list. + model: The `Model` these callbacks are used with. + **params: If provided, parameters will be passed to each `Callback` via + `Callback.set_params`. + """ + self.callbacks = nest.flatten(callbacks) if callbacks else [] + self._add_default_callbacks(add_history, add_progbar) + + if model: + self.set_model(model) + if params: + self.set_params(params) + + # Performance optimization: determines if batch hooks need to be called. + # pylint: disable=protected-access + self._supports_tf_logs = all( + getattr(cb, '_supports_tf_logs', False) for cb in self.callbacks) + self._batch_hooks_support_tf_logs = all( + getattr(cb, '_supports_tf_logs', False) + for cb in self.callbacks + if cb._implements_train_batch_hooks() or cb + ._implements_test_batch_hooks() or cb._implements_predict_batch_hooks()) + + self._should_call_train_batch_hooks = any( + cb._implements_train_batch_hooks() for cb in self.callbacks) + self._should_call_test_batch_hooks = any( + cb._implements_test_batch_hooks() for cb in self.callbacks) + self._should_call_predict_batch_hooks = any( + cb._implements_predict_batch_hooks() for cb in self.callbacks) + # pylint: enable=protected-access + + self._disallow_batch_hooks_in_ps_strategy() + + # Performance check: Check batch hooks for slowness compared to batch time. + # Only run check for custom callbacks (i.e. not present in this file). + self._check_timing = any( + cbk.__class__.__name__ not in globals() for cbk in self.callbacks) + self._num_batches_for_timing_check = 5 + self._hook_times = {} + self._batch_start_time = None + self._batch_times = [] + + def _add_default_callbacks(self, add_history, add_progbar): + """Adds `Callback`s that are always present.""" + self._progbar = None + self._history = None + + for cb in self.callbacks: + if isinstance(cb, ProgbarLogger): + self._progbar = cb + elif isinstance(cb, History): + self._history = cb + + if self._progbar is None and add_progbar: + self._progbar = ProgbarLogger(count_mode='steps') + self.callbacks.insert(0, self._progbar) + + if self._history is None and add_history: + self._history = History() + self.callbacks.append(self._history) + + def _process_logs(self, logs, is_batch_hook=False): + """Turns tensors into numpy arrays or Python scalars if necessary.""" + if logs is None: + return {} + if self._supports_tf_logs: + return logs + if is_batch_hook and self._batch_hooks_support_tf_logs: + return logs + return tf_utils.sync_to_numpy_or_python_type(logs) + + def append(self, callback): + self.callbacks.append(callback) + + def set_params(self, params): + self.params = params + for callback in self.callbacks: + callback.set_params(params) + + def set_model(self, model): + self.model = model + if self._history: + model.history = self._history + for callback in self.callbacks: + callback.set_model(model) + + def _call_batch_hook(self, mode, hook, batch, logs=None): + """Helper function for all batch_{begin | end} methods.""" + if not self.callbacks: + return + + if hook == 'begin': + self._call_batch_begin_hook(mode, batch, logs) + elif hook == 'end': + self._call_batch_end_hook(mode, batch, logs) + else: + raise ValueError('Unrecognized hook: {}'.format(hook)) + + def _call_batch_begin_hook(self, mode, batch, logs): + """Helper function for `on_*_batch_begin` methods.""" + hook_name = 'on_{mode}_batch_begin'.format(mode=mode) + self._call_batch_hook_helper(hook_name, batch, logs) + + if self._check_timing: + self._batch_start_time = time.time() + + def _call_batch_end_hook(self, mode, batch, logs): + """Helper function for `on_*_batch_end` methods.""" + hook_name = 'on_{mode}_batch_end'.format(mode=mode) + + if self._check_timing and batch >= 1: + batch_time = time.time() - self._batch_start_time + self._batch_times.append(batch_time) + + self._call_batch_hook_helper(hook_name, batch, logs) + + if len(self._batch_times) >= self._num_batches_for_timing_check: + end_hook_name = hook_name + begin_hook_name = 'on_{mode}_batch_begin'.format(mode=mode) + avg_batch_time = sum(self._batch_times) / len(self._batch_times) + avg_end_hook_time = sum(self._hook_times[end_hook_name]) / len( + self._hook_times[end_hook_name]) + avg_begin_hook_time = sum(self._hook_times[begin_hook_name]) / len( + self._hook_times[begin_hook_name]) + + threshold_time = 1.0 * avg_batch_time + warning_msg = ('Callback method `{hook}` is slow compared to ' + 'the batch time (batch time: {batch_time:.4f}s vs ' + '`{hook}` time: {hook_time:.4f}s). Check your callbacks.') + if avg_begin_hook_time > threshold_time: + logging.warning(warning_msg.format( + hook=begin_hook_name, + batch_time=avg_batch_time, + hook_time=avg_begin_hook_time)) + if avg_end_hook_time > threshold_time: + logging.warning(warning_msg.format( + hook=end_hook_name, + batch_time=avg_batch_time, + hook_time=avg_end_hook_time)) + self._check_timing = False + self._batch_start_time = None + self._batch_times = [] + self._hook_times = {} + + def _call_batch_hook_helper(self, hook_name, batch, logs): + """Helper function for `on_*_batch_*` methods.""" + if self._check_timing: + start_time = time.time() + + logs = self._process_logs(logs, is_batch_hook=True) + for callback in self.callbacks: + hook = getattr(callback, hook_name) + hook(batch, logs) + + if self._check_timing: + if hook_name not in self._hook_times: + self._hook_times[hook_name] = [] + self._hook_times[hook_name].append(time.time() - start_time) + + def _call_begin_hook(self, mode): + """Helper function for on_{train|test|predict}_begin methods.""" + if mode == ModeKeys.TRAIN: + self.on_train_begin() + elif mode == ModeKeys.TEST: + self.on_test_begin() + else: + self.on_predict_begin() + + def _call_end_hook(self, mode): + """Helper function for on_{train|test|predict}_end methods.""" + if mode == ModeKeys.TRAIN: + self.on_train_end() + elif mode == ModeKeys.TEST: + self.on_test_end() + else: + self.on_predict_end() + + def on_batch_begin(self, batch, logs=None): + if self._should_call_train_batch_hooks: + self._call_batch_hook(ModeKeys.TRAIN, 'begin', batch, logs=logs) + + def on_batch_end(self, batch, logs=None): + if self._should_call_train_batch_hooks: + self._call_batch_hook(ModeKeys.TRAIN, 'end', batch, logs=logs) + + def on_epoch_begin(self, epoch, logs=None): + """Calls the `on_epoch_begin` methods of its callbacks. + + This function should only be called during TRAIN mode. + + Args: + epoch: Integer, index of epoch. + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_epoch_begin(epoch, logs) + + def on_epoch_end(self, epoch, logs=None): + """Calls the `on_epoch_end` methods of its callbacks. + + This function should only be called during TRAIN mode. + + Args: + epoch: Integer, index of epoch. + logs: Dict, metric results for this training epoch, and for the + validation epoch if validation is performed. Validation result keys + are prefixed with `val_`. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_epoch_end(epoch, logs) + + def on_train_batch_begin(self, batch, logs=None): + """Calls the `on_train_batch_begin` methods of its callbacks. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict, contains the return value of `model.train_step`. Typically, + the values of the `Model`'s metrics are returned. Example: + `{'loss': 0.2, 'accuracy': 0.7}`. + """ + if self._should_call_train_batch_hooks: + self._call_batch_hook(ModeKeys.TRAIN, 'begin', batch, logs=logs) + + def on_train_batch_end(self, batch, logs=None): + """Calls the `on_train_batch_end` methods of its callbacks. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict. Aggregated metric results up until this batch. + """ + if self._should_call_train_batch_hooks: + self._call_batch_hook(ModeKeys.TRAIN, 'end', batch, logs=logs) + + def on_test_batch_begin(self, batch, logs=None): + """Calls the `on_test_batch_begin` methods of its callbacks. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict, contains the return value of `model.test_step`. Typically, + the values of the `Model`'s metrics are returned. Example: + `{'loss': 0.2, 'accuracy': 0.7}`. + """ + if self._should_call_test_batch_hooks: + self._call_batch_hook(ModeKeys.TEST, 'begin', batch, logs=logs) + + def on_test_batch_end(self, batch, logs=None): + """Calls the `on_test_batch_end` methods of its callbacks. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict. Aggregated metric results up until this batch. + """ + if self._should_call_test_batch_hooks: + self._call_batch_hook(ModeKeys.TEST, 'end', batch, logs=logs) + + def on_predict_batch_begin(self, batch, logs=None): + """Calls the `on_predict_batch_begin` methods of its callbacks. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict, contains the return value of `model.predict_step`, + it typically returns a dict with a key 'outputs' containing + the model's outputs. + """ + if self._should_call_predict_batch_hooks: + self._call_batch_hook(ModeKeys.PREDICT, 'begin', batch, logs=logs) + + def on_predict_batch_end(self, batch, logs=None): + """Calls the `on_predict_batch_end` methods of its callbacks. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict. Aggregated metric results up until this batch. + """ + if self._should_call_predict_batch_hooks: + self._call_batch_hook(ModeKeys.PREDICT, 'end', batch, logs=logs) + + def on_train_begin(self, logs=None): + """Calls the `on_train_begin` methods of its callbacks. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_train_begin(logs) + + def on_train_end(self, logs=None): + """Calls the `on_train_end` methods of its callbacks. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_train_end(logs) + + def on_test_begin(self, logs=None): + """Calls the `on_test_begin` methods of its callbacks. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_test_begin(logs) + + def on_test_end(self, logs=None): + """Calls the `on_test_end` methods of its callbacks. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_test_end(logs) + + def on_predict_begin(self, logs=None): + """Calls the 'on_predict_begin` methods of its callbacks. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_predict_begin(logs) + + def on_predict_end(self, logs=None): + """Calls the `on_predict_end` methods of its callbacks. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + logs = self._process_logs(logs) + for callback in self.callbacks: + callback.on_predict_end(logs) + + def __iter__(self): + return iter(self.callbacks) + + def _disallow_batch_hooks_in_ps_strategy(self): + """Error out if batch-level callbacks are passed with PSStrategy.""" + # pylint: disable=protected-access + strategy = distribute_lib.get_strategy() + if strategy._should_use_with_coordinator: + unsupported_callbacks = [] + for cb in self.callbacks: + # These Callbacks can accept RemoteValues directly. + if getattr(cb, '_supports_tf_logs', False): + continue + if (cb._implements_train_batch_hooks() or + cb._implements_test_batch_hooks() or + cb._implements_predict_batch_hooks()): + unsupported_callbacks.append(cb) + if unsupported_callbacks: + raise ValueError('Batch-level `Callback`s are not supported with ' + '`ParameterServerStrategy`. Found unsupported ' + 'callbacks: {}'.format(unsupported_callbacks)) + # pylint: enable=protected-access + + +class Callback: + """Abstract base class used to build new callbacks. + + Callbacks can be passed to keras methods such as `fit`, `evaluate`, and + `predict` in order to hook into the various stages of the model training and + inference lifecycle. + + To create a custom callback, subclass `keras.callbacks.Callback` and override + the method associated with the stage of interest. See + https://www.tensorflow.org/guide/keras/custom_callback for more information. + + Example: + + >>> training_finished = False + >>> class MyCallback(tf.keras.callbacks.Callback): + ... def on_train_end(self, logs=None): + ... global training_finished + ... training_finished = True + >>> model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))]) + >>> model.compile(loss='mean_squared_error') + >>> model.fit(tf.constant([[1.0]]), tf.constant([[1.0]]), + ... callbacks=[MyCallback()]) + >>> assert training_finished == True + + If you want to use `Callback` objects in a custom training loop: + + 1. You should pack all your callbacks into a single `callbacks.CallbackList` + so they can all be called together. + 2. You will need to manually call all the `on_*` methods at the apropriate + locations in your loop. Like this: + + ``` + callbacks = tf.keras.callbacks.CallbackList([...]) + callbacks.append(...) + + callbacks.on_train_begin(...) + for epoch in range(EPOCHS): + callbacks.on_epoch_begin(epoch) + for i, data in dataset.enumerate(): + callbacks.on_train_batch_begin(i) + batch_logs = model.train_step(data) + callbacks.on_train_batch_end(i, batch_logs) + epoch_logs = ... + callbacks.on_epoch_end(epoch, epoch_logs) + final_logs=... + callbacks.on_train_end(final_logs) + ``` + + Attributes: + params: Dict. Training parameters + (eg. verbosity, batch size, number of epochs...). + model: Instance of `keras.models.Model`. + Reference of the model being trained. + + The `logs` dictionary that callback methods + take as argument will contain keys for quantities relevant to + the current batch or epoch (see method-specific docstrings). + """ + + def __init__(self): + self.validation_data = None # pylint: disable=g-missing-from-attributes + self.model = None + # Whether this Callback should only run on the chief worker in a + # Multi-Worker setting. + # TODO(omalleyt): Make this attr public once solution is stable. + self._chief_worker_only = None + self._supports_tf_logs = False + + def set_params(self, params): + self.params = params + + def set_model(self, model): + self.model = model + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_batch_begin(self, batch, logs=None): + """A backwards compatibility alias for `on_train_batch_begin`.""" + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_batch_end(self, batch, logs=None): + """A backwards compatibility alias for `on_train_batch_end`.""" + + @doc_controls.for_subclass_implementers + def on_epoch_begin(self, epoch, logs=None): + """Called at the start of an epoch. + + Subclasses should override for any actions to run. This function should only + be called during TRAIN mode. + + Args: + epoch: Integer, index of epoch. + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + + @doc_controls.for_subclass_implementers + def on_epoch_end(self, epoch, logs=None): + """Called at the end of an epoch. + + Subclasses should override for any actions to run. This function should only + be called during TRAIN mode. + + Args: + epoch: Integer, index of epoch. + logs: Dict, metric results for this training epoch, and for the + validation epoch if validation is performed. Validation result keys + are prefixed with `val_`. For training epoch, the values of the + `Model`'s metrics are returned. Example : `{'loss': 0.2, 'accuracy': + 0.7}`. + """ + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_train_batch_begin(self, batch, logs=None): + """Called at the beginning of a training batch in `fit` methods. + + Subclasses should override for any actions to run. + + Note that if the `steps_per_execution` argument to `compile` in + `tf.keras.Model` is set to `N`, this method will only be called every `N` + batches. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict, contains the return value of `model.train_step`. Typically, + the values of the `Model`'s metrics are returned. Example: + `{'loss': 0.2, 'accuracy': 0.7}`. + """ + # For backwards compatibility. + self.on_batch_begin(batch, logs=logs) + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_train_batch_end(self, batch, logs=None): + """Called at the end of a training batch in `fit` methods. + + Subclasses should override for any actions to run. + + Note that if the `steps_per_execution` argument to `compile` in + `tf.keras.Model` is set to `N`, this method will only be called every `N` + batches. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict. Aggregated metric results up until this batch. + """ + # For backwards compatibility. + self.on_batch_end(batch, logs=logs) + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_test_batch_begin(self, batch, logs=None): + """Called at the beginning of a batch in `evaluate` methods. + + Also called at the beginning of a validation batch in the `fit` + methods, if validation data is provided. + + Subclasses should override for any actions to run. + + Note that if the `steps_per_execution` argument to `compile` in + `tf.keras.Model` is set to `N`, this method will only be called every `N` + batches. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict, contains the return value of `model.test_step`. Typically, + the values of the `Model`'s metrics are returned. Example: + `{'loss': 0.2, 'accuracy': 0.7}`. + """ + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_test_batch_end(self, batch, logs=None): + """Called at the end of a batch in `evaluate` methods. + + Also called at the end of a validation batch in the `fit` + methods, if validation data is provided. + + Subclasses should override for any actions to run. + + Note that if the `steps_per_execution` argument to `compile` in + `tf.keras.Model` is set to `N`, this method will only be called every `N` + batches. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict. Aggregated metric results up until this batch. + """ + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_predict_batch_begin(self, batch, logs=None): + """Called at the beginning of a batch in `predict` methods. + + Subclasses should override for any actions to run. + + Note that if the `steps_per_execution` argument to `compile` in + `tf.keras.Model` is set to `N`, this method will only be called every `N` + batches. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict, contains the return value of `model.predict_step`, + it typically returns a dict with a key 'outputs' containing + the model's outputs. + """ + + @doc_controls.for_subclass_implementers + @generic_utils.default + def on_predict_batch_end(self, batch, logs=None): + """Called at the end of a batch in `predict` methods. + + Subclasses should override for any actions to run. + + Note that if the `steps_per_execution` argument to `compile` in + `tf.keras.Model` is set to `N`, this method will only be called every `N` + batches. + + Args: + batch: Integer, index of batch within the current epoch. + logs: Dict. Aggregated metric results up until this batch. + """ + + @doc_controls.for_subclass_implementers + def on_train_begin(self, logs=None): + """Called at the beginning of training. + + Subclasses should override for any actions to run. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + + @doc_controls.for_subclass_implementers + def on_train_end(self, logs=None): + """Called at the end of training. + + Subclasses should override for any actions to run. + + Args: + logs: Dict. Currently the output of the last call to `on_epoch_end()` + is passed to this argument for this method but that may change in + the future. + """ + + @doc_controls.for_subclass_implementers + def on_test_begin(self, logs=None): + """Called at the beginning of evaluation or validation. + + Subclasses should override for any actions to run. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + + @doc_controls.for_subclass_implementers + def on_test_end(self, logs=None): + """Called at the end of evaluation or validation. + + Subclasses should override for any actions to run. + + Args: + logs: Dict. Currently the output of the last call to + `on_test_batch_end()` is passed to this argument for this method + but that may change in the future. + """ + + @doc_controls.for_subclass_implementers + def on_predict_begin(self, logs=None): + """Called at the beginning of prediction. + + Subclasses should override for any actions to run. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + + @doc_controls.for_subclass_implementers + def on_predict_end(self, logs=None): + """Called at the end of prediction. + + Subclasses should override for any actions to run. + + Args: + logs: Dict. Currently no data is passed to this argument for this method + but that may change in the future. + """ + + def _implements_train_batch_hooks(self): + """Determines if this Callback should be called for each train batch.""" + return (not generic_utils.is_default(self.on_batch_begin) or + not generic_utils.is_default(self.on_batch_end) or + not generic_utils.is_default(self.on_train_batch_begin) or + not generic_utils.is_default(self.on_train_batch_end)) + + def _implements_test_batch_hooks(self): + """Determines if this Callback should be called for each test batch.""" + return (not generic_utils.is_default(self.on_test_batch_begin) or + not generic_utils.is_default(self.on_test_batch_end)) + + def _implements_predict_batch_hooks(self): + """Determines if this Callback should be called for each predict batch.""" + return (not generic_utils.is_default(self.on_predict_batch_begin) or + not generic_utils.is_default(self.on_predict_batch_end)) + + +class BaseLogger(Callback): + """Callback that accumulates epoch averages of metrics. + + This callback is automatically applied to every Keras model. + + Args: + stateful_metrics: Iterable of string names of metrics that + should *not* be averaged over an epoch. + Metrics in this list will be logged as-is in `on_epoch_end`. + All others will be averaged in `on_epoch_end`. + """ + + def __init__(self, stateful_metrics=None): + super(BaseLogger, self).__init__() + self.stateful_metrics = set(stateful_metrics or []) + + def on_epoch_begin(self, epoch, logs=None): + self.seen = 0 + self.totals = {} + + def on_batch_end(self, batch, logs=None): + logs = logs or {} + batch_size = logs.get('size', 0) + # In case of distribution strategy we can potentially run multiple steps + # at the same time, we should account for that in the `seen` calculation. + num_steps = logs.get('num_steps', 1) + self.seen += batch_size * num_steps + + for k, v in logs.items(): + if k in self.stateful_metrics: + self.totals[k] = v + else: + if k in self.totals: + self.totals[k] += v * batch_size + else: + self.totals[k] = v * batch_size + + def on_epoch_end(self, epoch, logs=None): + if logs is not None: + for k in self.params['metrics']: + if k in self.totals: + # Make value available to next callbacks. + if k in self.stateful_metrics: + logs[k] = self.totals[k] + else: + logs[k] = self.totals[k] / self.seen + + +class TerminateOnNaN(Callback): + """Callback that terminates training when a NaN loss is encountered. + """ + + def __init__(self): + super(TerminateOnNaN, self).__init__() + self._supports_tf_logs = True + + def on_batch_end(self, batch, logs=None): + logs = logs or {} + loss = logs.get('loss') + if loss is not None: + loss = tf_utils.sync_to_numpy_or_python_type(loss) + if np.isnan(loss) or np.isinf(loss): + print('Batch %d: Invalid loss, terminating training' % (batch)) + self.model.stop_training = True + + +class ProgbarLogger(Callback): + """Callback that prints metrics to stdout. + + Args: + count_mode: One of `"steps"` or `"samples"`. + Whether the progress bar should + count samples seen or steps (batches) seen. + stateful_metrics: Iterable of string names of metrics that + should *not* be averaged over an epoch. + Metrics in this list will be logged as-is. + All others will be averaged over time (e.g. loss, etc). + If not provided, defaults to the `Model`'s metrics. + + Raises: + ValueError: In case of invalid `count_mode`. + """ + + def __init__(self, count_mode='samples', stateful_metrics=None): + super(ProgbarLogger, self).__init__() + self._supports_tf_logs = True + if count_mode == 'samples': + self.use_steps = False + elif count_mode == 'steps': + self.use_steps = True + else: + raise ValueError('Unknown `count_mode`: ' + str(count_mode)) + # Defaults to all Model's metrics except for loss. + self.stateful_metrics = set(stateful_metrics) if stateful_metrics else set() + + self.seen = 0 + self.progbar = None + self.target = None + self.verbose = 1 + self.epochs = 1 + + self._train_step, self._test_step, self._predict_step = None, None, None + self._call_batch_hooks = True + + self._called_in_fit = False + + def set_params(self, params): + self.verbose = params['verbose'] + self.epochs = params['epochs'] + if self.use_steps and 'steps' in params: + self.target = params['steps'] + elif not self.use_steps and 'samples' in params: + self.target = params['samples'] + else: + self.target = None # Will be inferred at the end of the first epoch. + + self._call_batch_hooks = self.verbose == 1 + if self.target is None: + try: + self._train_step = self.model._train_counter # pylint: disable=protected-access + self._test_step = self.model._test_counter # pylint: disable=protected-access + self._predict_step = self.model._predict_counter # pylint: disable=protected-access + except AttributeError: + self._call_batch_hooks = True + + def on_train_begin(self, logs=None): + # When this logger is called inside `fit`, validation is silent. + self._called_in_fit = True + + def on_test_begin(self, logs=None): + if not self._called_in_fit: + self._reset_progbar() + self._maybe_init_progbar() + + def on_predict_begin(self, logs=None): + self._reset_progbar() + self._maybe_init_progbar() + + def on_epoch_begin(self, epoch, logs=None): + self._reset_progbar() + self._maybe_init_progbar() + if self.verbose and self.epochs > 1: + print('Epoch %d/%d' % (epoch + 1, self.epochs)) + + def on_train_batch_end(self, batch, logs=None): + self._batch_update_progbar(batch, logs) + + def on_test_batch_end(self, batch, logs=None): + if not self._called_in_fit: + self._batch_update_progbar(batch, logs) + + def on_predict_batch_end(self, batch, logs=None): + # Don't pass prediction results. + self._batch_update_progbar(batch, None) + + def on_epoch_end(self, epoch, logs=None): + self._finalize_progbar(logs, self._train_step) + + def on_test_end(self, logs=None): + if not self._called_in_fit: + self._finalize_progbar(logs, self._test_step) + + def on_predict_end(self, logs=None): + self._finalize_progbar(logs, self._predict_step) + + def _reset_progbar(self): + self.seen = 0 + self.progbar = None + + def _maybe_init_progbar(self): + """Instantiate a `Progbar` if not yet, and update the stateful metrics.""" + # TODO(rchao): Legacy TF1 code path may use list for + # `self.stateful_metrics`. Remove "cast to set" when TF1 support is dropped. + self.stateful_metrics = set(self.stateful_metrics) + + if self.model: + # Update the existing stateful metrics as `self.model.metrics` may contain + # updated metrics after `MetricsContainer` is built in the first train + # step. + self.stateful_metrics = self.stateful_metrics.union( + set(m.name for m in self.model.metrics)) + + if self.progbar is None: + self.progbar = Progbar( + target=self.target, + verbose=self.verbose, + stateful_metrics=self.stateful_metrics, + unit_name='step' if self.use_steps else 'sample') + + self.progbar._update_stateful_metrics(self.stateful_metrics) # pylint: disable=protected-access + + def _implements_train_batch_hooks(self): + return self._call_batch_hooks + + def _implements_test_batch_hooks(self): + return self._call_batch_hooks + + def _implements_predict_batch_hooks(self): + return self._call_batch_hooks + + def _batch_update_progbar(self, batch, logs=None): + """Updates the progbar.""" + logs = logs or {} + self._maybe_init_progbar() + if self.use_steps: + self.seen = batch + 1 # One-indexed. + else: + # v1 path only. + logs = copy.copy(logs) + batch_size = logs.pop('size', 0) + num_steps = logs.pop('num_steps', 1) + logs.pop('batch', None) + add_seen = num_steps * batch_size + self.seen += add_seen + + if self.verbose == 1: + # Only block async when verbose = 1. + logs = tf_utils.sync_to_numpy_or_python_type(logs) + self.progbar.update(self.seen, list(logs.items()), finalize=False) + + def _finalize_progbar(self, logs, counter): + logs = tf_utils.sync_to_numpy_or_python_type(logs or {}) + if self.target is None: + if counter is not None: + counter = counter.numpy() + if not self.use_steps: + counter *= logs.get('size', 1) + self.target = counter or self.seen + self.progbar.target = self.target + self.progbar.update(self.target, list(logs.items()), finalize=True) + + +class History(Callback): + """Callback that records events into a `History` object. + + This callback is automatically applied to + every Keras model. The `History` object + gets returned by the `fit` method of models. + + Example: + + >>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + >>> model.compile(tf.keras.optimizers.SGD(), loss='mse') + >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5), + ... epochs=10, verbose=1) + >>> print(history.params) + {'verbose': 1, 'epochs': 10, 'steps': 1} + >>> # check the keys of history object + >>> print(history.history.keys()) + dict_keys(['loss']) + + """ + + def __init__(self): + super(History, self).__init__() + self.history = {} + + def on_train_begin(self, logs=None): + self.epoch = [] + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + self.epoch.append(epoch) + for k, v in logs.items(): + self.history.setdefault(k, []).append(v) + + # Set the history attribute on the model after the epoch ends. This will + # make sure that the state which is set is the latest one. + self.model.history = self + + +class ModelCheckpoint(Callback): + """Callback to save the Keras model or model weights at some frequency. + + `ModelCheckpoint` callback is used in conjunction with training using + `model.fit()` to save a model or weights (in a checkpoint file) at some + interval, so the model or weights can be loaded later to continue the training + from the state saved. + + A few options this callback provides include: + + - Whether to only keep the model that has achieved the "best performance" so + far, or whether to save the model at the end of every epoch regardless of + performance. + - Definition of 'best'; which quantity to monitor and whether it should be + maximized or minimized. + - The frequency it should save at. Currently, the callback supports saving at + the end of every epoch, or after a fixed number of training batches. + - Whether only weights are saved, or the whole model is saved. + + Note: If you get `WARNING:tensorflow:Can save best model only with + available, skipping` see the description of the `monitor` argument for + details on how to get this right. + + Example: + + ```python + model.compile(loss=..., optimizer=..., + metrics=['accuracy']) + + EPOCHS = 10 + checkpoint_filepath = '/tmp/checkpoint' + model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint( + filepath=checkpoint_filepath, + save_weights_only=True, + monitor='val_accuracy', + mode='max', + save_best_only=True) + + # Model weights are saved at the end of every epoch, if it's the best seen + # so far. + model.fit(epochs=EPOCHS, callbacks=[model_checkpoint_callback]) + + # The model weights (that are considered the best) are loaded into the model. + model.load_weights(checkpoint_filepath) + ``` + + Args: + filepath: string or `PathLike`, path to save the model file. e.g. + filepath = os.path.join(working_dir, 'ckpt', file_name). `filepath` + can contain named formatting options, which will be filled the value of + `epoch` and keys in `logs` (passed in `on_epoch_end`). For example: if + `filepath` is `weights.{epoch:02d}-{val_loss:.2f}.hdf5`, then the model + checkpoints will be saved with the epoch number and the validation loss + in the filename. The directory of the filepath should not be reused by + any other callbacks to avoid conflicts. + monitor: The metric name to monitor. Typically the metrics are set by the + `Model.compile` method. Note: + + * Prefix the name with `"val_`" to monitor validation metrics. + * Use `"loss"` or "`val_loss`" to monitor the model's total loss. + * If you specify metrics as strings, like `"accuracy"`, pass the same + string (with or without the `"val_"` prefix). + * If you pass `metrics.Metric` objects, `monitor` should be set to + `metric.name` + * If you're not sure about the metric names you can check the contents + of the `history.history` dictionary returned by + `history = model.fit()` + * Multi-output models set additional prefixes on the metric names. + + verbose: verbosity mode, 0 or 1. + save_best_only: if `save_best_only=True`, it only saves when the model + is considered the "best" and the latest best model according to the + quantity monitored will not be overwritten. If `filepath` doesn't + contain formatting options like `{epoch}` then `filepath` will be + overwritten by each new better model. + mode: one of {'auto', 'min', 'max'}. If `save_best_only=True`, the + decision to overwrite the current save file is made based on either + the maximization or the minimization of the monitored quantity. + For `val_acc`, this should be `max`, for `val_loss` this should be + `min`, etc. In `auto` mode, the mode is set to `max` if the quantities + monitored are 'acc' or start with 'fmeasure' and are set to `min` for + the rest of the quantities. + save_weights_only: if True, then only the model's weights will be saved + (`model.save_weights(filepath)`), else the full model is saved + (`model.save(filepath)`). + save_freq: `'epoch'` or integer. When using `'epoch'`, the callback saves + the model after each epoch. When using integer, the callback saves the + model at end of this many batches. If the `Model` is compiled with + `steps_per_execution=N`, then the saving criteria will be + checked every Nth batch. Note that if the saving isn't aligned to + epochs, the monitored metric may potentially be less reliable (it + could reflect as little as 1 batch, since the metrics get reset every + epoch). Defaults to `'epoch'`. + options: Optional `tf.train.CheckpointOptions` object if + `save_weights_only` is true or optional `tf.saved_model.SaveOptions` + object if `save_weights_only` is false. + **kwargs: Additional arguments for backwards compatibility. Possible key + is `period`. + """ + + def __init__(self, + filepath, + monitor='val_loss', + verbose=0, + save_best_only=False, + save_weights_only=False, + mode='auto', + save_freq='epoch', + options=None, + **kwargs): + super(ModelCheckpoint, self).__init__() + self._supports_tf_logs = True + self.monitor = monitor + self.verbose = verbose + self.filepath = path_to_string(filepath) + self.save_best_only = save_best_only + self.save_weights_only = save_weights_only + self.save_freq = save_freq + self.epochs_since_last_save = 0 + self._batches_seen_since_last_saving = 0 + self._last_batch_seen = 0 + + if save_weights_only: + if options is None or isinstance( + options, checkpoint_options_lib.CheckpointOptions): + self._options = options or checkpoint_options_lib.CheckpointOptions() + else: + raise TypeError('If save_weights_only is True, then `options` must be ' + 'either None or a tf.train.CheckpointOptions') + else: + if options is None or isinstance(options, save_options_lib.SaveOptions): + self._options = options or save_options_lib.SaveOptions() + else: + raise TypeError('If save_weights_only is False, then `options` must be' + 'either None or a tf.saved_model.SaveOptions') + + # Deprecated field `load_weights_on_restart` is for loading the checkpoint + # file from `filepath` at the start of `model.fit()` + # TODO(rchao): Remove the arg during next breaking release. + if 'load_weights_on_restart' in kwargs: + self.load_weights_on_restart = kwargs['load_weights_on_restart'] + logging.warning('`load_weights_on_restart` argument is deprecated. ' + 'Please use `model.load_weights()` for loading weights ' + 'before the start of `model.fit()`.') + else: + self.load_weights_on_restart = False + + # Deprecated field `period` is for the number of epochs between which + # the model is saved. + if 'period' in kwargs: + self.period = kwargs['period'] + logging.warning('`period` argument is deprecated. Please use `save_freq` ' + 'to specify the frequency in number of batches seen.') + else: + self.period = 1 + + if mode not in ['auto', 'min', 'max']: + logging.warning('ModelCheckpoint mode %s is unknown, ' + 'fallback to auto mode.', mode) + mode = 'auto' + + if mode == 'min': + self.monitor_op = np.less + self.best = np.Inf + elif mode == 'max': + self.monitor_op = np.greater + self.best = -np.Inf + else: + if 'acc' in self.monitor or self.monitor.startswith('fmeasure'): + self.monitor_op = np.greater + self.best = -np.Inf + else: + self.monitor_op = np.less + self.best = np.Inf + + if self.save_freq != 'epoch' and not isinstance(self.save_freq, int): + raise ValueError('Unrecognized save_freq: {}'.format(self.save_freq)) + + # Only the chief worker writes model checkpoints, but all workers + # restore checkpoint at on_train_begin(). + self._chief_worker_only = False + + def on_train_begin(self, logs=None): + if self.load_weights_on_restart: + filepath_to_load = ( + self._get_most_recently_modified_file_matching_pattern(self.filepath)) + if (filepath_to_load is not None and + self._checkpoint_exists(filepath_to_load)): + try: + # `filepath` may contain placeholders such as `{epoch:02d}`, and + # thus it attempts to load the most recently modified file with file + # name matching the pattern. + self.model.load_weights(filepath_to_load) + except (IOError, ValueError) as e: + raise ValueError('Error loading file from {}. Reason: {}'.format( + filepath_to_load, e)) + + def _implements_train_batch_hooks(self): + # Only call batch hooks when saving on batch + return self.save_freq != 'epoch' + + def on_train_batch_end(self, batch, logs=None): + if self._should_save_on_batch(batch): + self._save_model(epoch=self._current_epoch, logs=logs) + + def on_epoch_begin(self, epoch, logs=None): + self._current_epoch = epoch + + def on_epoch_end(self, epoch, logs=None): + self.epochs_since_last_save += 1 + # pylint: disable=protected-access + if self.save_freq == 'epoch': + self._save_model(epoch=epoch, logs=logs) + + def _should_save_on_batch(self, batch): + """Handles batch-level saving logic, supports steps_per_execution.""" + if self.save_freq == 'epoch': + return False + + if batch <= self._last_batch_seen: # New epoch. + add_batches = batch + 1 # batches are zero-indexed. + else: + add_batches = batch - self._last_batch_seen + self._batches_seen_since_last_saving += add_batches + self._last_batch_seen = batch + + if self._batches_seen_since_last_saving >= self.save_freq: + self._batches_seen_since_last_saving = 0 + return True + return False + + def _save_model(self, epoch, logs): + """Saves the model. + + Args: + epoch: the epoch this iteration is in. + logs: the `logs` dict passed in to `on_batch_end` or `on_epoch_end`. + """ + logs = logs or {} + + if isinstance(self.save_freq, + int) or self.epochs_since_last_save >= self.period: + # Block only when saving interval is reached. + logs = tf_utils.sync_to_numpy_or_python_type(logs) + self.epochs_since_last_save = 0 + filepath = self._get_file_path(epoch, logs) + + try: + if self.save_best_only: + current = logs.get(self.monitor) + if current is None: + logging.warning('Can save best model only with %s available, ' + 'skipping.', self.monitor) + else: + if self.monitor_op(current, self.best): + if self.verbose > 0: + print('\nEpoch %05d: %s improved from %0.5f to %0.5f,' + ' saving model to %s' % (epoch + 1, self.monitor, + self.best, current, filepath)) + self.best = current + if self.save_weights_only: + self.model.save_weights( + filepath, overwrite=True, options=self._options) + else: + self.model.save(filepath, overwrite=True, options=self._options) + else: + if self.verbose > 0: + print('\nEpoch %05d: %s did not improve from %0.5f' % + (epoch + 1, self.monitor, self.best)) + else: + if self.verbose > 0: + print('\nEpoch %05d: saving model to %s' % (epoch + 1, filepath)) + if self.save_weights_only: + self.model.save_weights( + filepath, overwrite=True, options=self._options) + else: + self.model.save(filepath, overwrite=True, options=self._options) + + self._maybe_remove_file() + except IsADirectoryError as e: # h5py 3.x + raise IOError('Please specify a non-directory filepath for ' + 'ModelCheckpoint. Filepath used is an existing ' + 'directory: {}'.format(filepath)) + except IOError as e: # h5py 2.x + # `e.errno` appears to be `None` so checking the content of `e.args[0]`. + if 'is a directory' in str(e.args[0]).lower(): + raise IOError('Please specify a non-directory filepath for ' + 'ModelCheckpoint. Filepath used is an existing ' + 'directory: {}'.format(filepath)) + # Re-throw the error for any other causes. + raise e + + def _get_file_path(self, epoch, logs): + """Returns the file path for checkpoint.""" + # pylint: disable=protected-access + try: + # `filepath` may contain placeholders such as `{epoch:02d}` and + # `{mape:.2f}`. A mismatch between logged metrics and the path's + # placeholders can cause formatting to fail. + file_path = self.filepath.format(epoch=epoch + 1, **logs) + except KeyError as e: + raise KeyError('Failed to format this callback filepath: "{}". ' + 'Reason: {}'.format(self.filepath, e)) + self._write_filepath = distributed_file_utils.write_filepath( + file_path, self.model.distribute_strategy) + return self._write_filepath + + def _maybe_remove_file(self): + # Remove the checkpoint directory in multi-worker training where this worker + # should not checkpoint. It is a dummy directory previously saved for sync + # distributed training. + distributed_file_utils.remove_temp_dir_with_filepath( + self._write_filepath, self.model.distribute_strategy) + + def _checkpoint_exists(self, filepath): + """Returns whether the checkpoint `filepath` refers to exists.""" + if filepath.endswith('.h5'): + return file_io.file_exists_v2(filepath) + tf_saved_model_exists = file_io.file_exists_v2(filepath) + tf_weights_only_checkpoint_exists = file_io.file_exists_v2( + filepath + '.index') + return tf_saved_model_exists or tf_weights_only_checkpoint_exists + + def _get_most_recently_modified_file_matching_pattern(self, pattern): + """Returns the most recently modified filepath matching pattern. + + Pattern may contain python formatting placeholder. If + `tf.train.latest_checkpoint()` does not return None, use that; otherwise, + check for most recently modified one that matches the pattern. + + In the rare case where there are more than one pattern-matching file having + the same modified time that is most recent among all, return the filepath + that is largest (by `>` operator, lexicographically using the numeric + equivalents). This provides a tie-breaker when multiple files are most + recent. Note that a larger `filepath` can sometimes indicate a later time of + modification (for instance, when epoch/batch is used as formatting option), + but not necessarily (when accuracy or loss is used). The tie-breaker is + put in the logic as best effort to return the most recent, and to avoid + undeterministic result. + + Modified time of a file is obtained with `os.path.getmtime()`. + + This utility function is best demonstrated via an example: + + ```python + file_pattern = 'f.batch{batch:02d}epoch{epoch:02d}.h5' + test_dir = self.get_temp_dir() + path_pattern = os.path.join(test_dir, file_pattern) + file_paths = [ + os.path.join(test_dir, file_name) for file_name in + ['f.batch03epoch02.h5', 'f.batch02epoch02.h5', 'f.batch01epoch01.h5'] + ] + for file_path in file_paths: + # Write something to each of the files + self.assertEqual( + _get_most_recently_modified_file_matching_pattern(path_pattern), + file_paths[-1]) + ``` + + Args: + pattern: The file pattern that may optionally contain python placeholder + such as `{epoch:02d}`. + + Returns: + The most recently modified file's full filepath matching `pattern`. If + `pattern` does not contain any placeholder, this returns the filepath + that + exactly matches `pattern`. Returns `None` if no match is found. + """ + dir_name = os.path.dirname(pattern) + base_name = os.path.basename(pattern) + base_name_regex = '^' + re.sub(r'{.*}', r'.*', base_name) + '$' + + # If tf.train.latest_checkpoint tells us there exists a latest checkpoint, + # use that as it is more robust than `os.path.getmtime()`. + latest_tf_checkpoint = checkpoint_management.latest_checkpoint(dir_name) + if latest_tf_checkpoint is not None and re.match( + base_name_regex, os.path.basename(latest_tf_checkpoint)): + return latest_tf_checkpoint + + latest_mod_time = 0 + file_path_with_latest_mod_time = None + n_file_with_latest_mod_time = 0 + file_path_with_largest_file_name = None + + if file_io.file_exists_v2(dir_name): + for file_name in os.listdir(dir_name): + # Only consider if `file_name` matches the pattern. + if re.match(base_name_regex, file_name): + file_path = os.path.join(dir_name, file_name) + mod_time = os.path.getmtime(file_path) + if (file_path_with_largest_file_name is None or + file_path > file_path_with_largest_file_name): + file_path_with_largest_file_name = file_path + if mod_time > latest_mod_time: + latest_mod_time = mod_time + file_path_with_latest_mod_time = file_path + # In the case a file with later modified time is found, reset + # the counter for the number of files with latest modified time. + n_file_with_latest_mod_time = 1 + elif mod_time == latest_mod_time: + # In the case a file has modified time tied with the most recent, + # increment the counter for the number of files with latest modified + # time by 1. + n_file_with_latest_mod_time += 1 + + if n_file_with_latest_mod_time == 1: + # Return the sole file that has most recent modified time. + return file_path_with_latest_mod_time + else: + # If there are more than one file having latest modified time, return + # the file path with the largest file name. + return file_path_with_largest_file_name + + +class BackupAndRestore(Callback): + """Callback to back up and restore the training state. + + `BackupAndRestore` callback is intended to recover from interruptions that + happened in the middle of a model.fit execution by backing up the + training states in a temporary checkpoint file (based on TF CheckpointManager) + at the end of each epoch. If training restarted before completion, the + training state and model are restored to the most recently saved state at the + beginning of a new model.fit() run. + Note that user is responsible to bring jobs back up. + This callback is important for the backup and restore mechanism for fault + tolerance purpose. And the model to be restored from an previous checkpoint is + expected to be the same as the one used to back up. If user changes arguments + passed to compile or fit, the checkpoint saved for fault tolerance can become + invalid. + + Note: + 1. This callback is not compatible with disabling eager execution. + 2. A checkpoint is saved at the end of each epoch, when restoring we'll redo + any partial work from an unfinished epoch in which the training got restarted + (so the work done before a interruption doesn't affect the final model state). + 3. This works for both single worker and multi-worker mode, only + MirroredStrategy and MultiWorkerMirroredStrategy are supported for now. + + Example: + + >>> class InterruptingCallback(tf.keras.callbacks.Callback): + ... def on_epoch_begin(self, epoch, logs=None): + ... if epoch == 4: + ... raise RuntimeError('Interrupting!') + >>> callback = tf.keras.callbacks.experimental.BackupAndRestore( + ... backup_dir="/tmp/backup") + >>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + >>> model.compile(tf.keras.optimizers.SGD(), loss='mse') + >>> try: + ... model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10, + ... batch_size=1, callbacks=[callback, InterruptingCallback()], + ... verbose=0) + ... except: + ... pass + >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5), epochs=10, + ... batch_size=1, callbacks=[callback], verbose=0) + >>> # Only 6 more epochs are run, since first trainning got interrupted at + >>> # zero-indexed epoch 4, second training will continue from 4 to 9. + >>> len(history.history['loss']) + 6 + + Args: + backup_dir: String, path to store the checkpoint. + e.g. backup_dir = os.path.join(working_dir, 'backup') + This is the directory in which the system stores temporary files to + recover the model from jobs terminated unexpectedly. The directory + cannot be reused elsewhere to store other files, e.g. by + BackupAndRestore callback of another training, or by another callback + (ModelCheckpoint) of the same training. + """ + + def __init__(self, backup_dir): + super(BackupAndRestore, self).__init__() + self.backup_dir = backup_dir + self._supports_tf_logs = True + self._supported_strategies = ( + mirrored_strategy.MirroredStrategy, + collective_all_reduce_strategy.CollectiveAllReduceStrategy, + tpu_strategy.TPUStrategy, tpu_strategy.TPUStrategyV2, + parameter_server_strategy_v2.ParameterServerStrategyV2) + + if not context.executing_eagerly(): + if ops.inside_function(): + raise ValueError('This Callback\'s method contains Python state and ' + 'should be called outside of `tf.function`s.') + else: # Legacy graph mode: + raise ValueError( + 'BackupAndRestore only supports eager mode. In graph ' + 'mode, consider using ModelCheckpoint to manually save ' + 'and restore weights with `model.load_weights()` and by ' + 'providing `initial_epoch` in `model.fit()` for fault tolerance.') + + # Only the chief worker writes model checkpoints, but all workers + # restore checkpoint at on_train_begin(). + self._chief_worker_only = False + + def on_train_begin(self, logs=None): + # TrainingState is used to manage the training state needed for + # failure-recovery of a worker in training. + # pylint: disable=protected-access + + if self.model._distribution_strategy and not isinstance( + self.model.distribute_strategy, self._supported_strategies): + raise NotImplementedError( + '%s is not supported yet. ' + 'Currently BackupAndRestore callback only supports empty strategy, ' + 'MirroredStrategy, MultiWorkerMirroredStrategy and TPUStrategy.' % + type(self.model.distribute_strategy).__name__) + self.model._training_state = ( + worker_training_state.WorkerTrainingState(self.model, self.backup_dir)) + self._training_state = self.model._training_state + self._training_state.restore() + + def on_train_end(self, logs=None): + # pylint: disable=protected-access + # On exit of training, delete the training state backup file that was saved + # for the purpose of worker recovery. + self._training_state.delete_backup() + + # Clean up the training state. + del self._training_state + del self.model._training_state + + def on_epoch_end(self, epoch, logs=None): + # Back up the model and current epoch for possible future recovery. + self._training_state.back_up(epoch) + + +class EarlyStopping(Callback): + """Stop training when a monitored metric has stopped improving. + + Assuming the goal of a training is to minimize the loss. With this, the + metric to be monitored would be `'loss'`, and mode would be `'min'`. A + `model.fit()` training loop will check at end of every epoch whether + the loss is no longer decreasing, considering the `min_delta` and + `patience` if applicable. Once it's found no longer decreasing, + `model.stop_training` is marked True and the training terminates. + + The quantity to be monitored needs to be available in `logs` dict. + To make it so, pass the loss or metrics at `model.compile()`. + + Args: + monitor: Quantity to be monitored. + min_delta: Minimum change in the monitored quantity + to qualify as an improvement, i.e. an absolute + change of less than min_delta, will count as no + improvement. + patience: Number of epochs with no improvement + after which training will be stopped. + verbose: verbosity mode. + mode: One of `{"auto", "min", "max"}`. In `min` mode, + training will stop when the quantity + monitored has stopped decreasing; in `"max"` + mode it will stop when the quantity + monitored has stopped increasing; in `"auto"` + mode, the direction is automatically inferred + from the name of the monitored quantity. + baseline: Baseline value for the monitored quantity. + Training will stop if the model doesn't show improvement over the + baseline. + restore_best_weights: Whether to restore model weights from + the epoch with the best value of the monitored quantity. + If False, the model weights obtained at the last step of + training are used. An epoch will be restored regardless + of the performance relative to the `baseline`. If no epoch + improves on `baseline`, training will run for `patience` + epochs and restore weights from the best epoch in that set. + + Example: + + >>> callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3) + >>> # This callback will stop the training when there is no improvement in + >>> # the loss for three consecutive epochs. + >>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + >>> model.compile(tf.keras.optimizers.SGD(), loss='mse') + >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5), + ... epochs=10, batch_size=1, callbacks=[callback], + ... verbose=0) + >>> len(history.history['loss']) # Only 4 epochs are run. + 4 + """ + + def __init__(self, + monitor='val_loss', + min_delta=0, + patience=0, + verbose=0, + mode='auto', + baseline=None, + restore_best_weights=False): + super(EarlyStopping, self).__init__() + + self.monitor = monitor + self.patience = patience + self.verbose = verbose + self.baseline = baseline + self.min_delta = abs(min_delta) + self.wait = 0 + self.stopped_epoch = 0 + self.restore_best_weights = restore_best_weights + self.best_weights = None + + if mode not in ['auto', 'min', 'max']: + logging.warning('EarlyStopping mode %s is unknown, ' + 'fallback to auto mode.', mode) + mode = 'auto' + + if mode == 'min': + self.monitor_op = np.less + elif mode == 'max': + self.monitor_op = np.greater + else: + if 'acc' in self.monitor: + self.monitor_op = np.greater + else: + self.monitor_op = np.less + + if self.monitor_op == np.greater: + self.min_delta *= 1 + else: + self.min_delta *= -1 + + def on_train_begin(self, logs=None): + # Allow instances to be re-used + self.wait = 0 + self.stopped_epoch = 0 + self.best = np.Inf if self.monitor_op == np.less else -np.Inf + self.best_weights = None + + def on_epoch_end(self, epoch, logs=None): + current = self.get_monitor_value(logs) + if current is None: + return + if self.restore_best_weights and self.best_weights is None: + # Restore the weights after first epoch if no progress is ever made. + self.best_weights = self.model.get_weights() + + self.wait += 1 + if self._is_improvement(current, self.best): + self.best = current + if self.restore_best_weights: + self.best_weights = self.model.get_weights() + # Only restart wait if we beat both the baseline and our previous best. + if self.baseline is None or self._is_improvement(current, self.baseline): + self.wait = 0 + + if self.wait >= self.patience: + self.stopped_epoch = epoch + self.model.stop_training = True + if self.restore_best_weights and self.best_weights is not None: + if self.verbose > 0: + print('Restoring model weights from the end of the best epoch.') + self.model.set_weights(self.best_weights) + + def on_train_end(self, logs=None): + if self.stopped_epoch > 0 and self.verbose > 0: + print('Epoch %05d: early stopping' % (self.stopped_epoch + 1)) + + def get_monitor_value(self, logs): + logs = logs or {} + monitor_value = logs.get(self.monitor) + if monitor_value is None: + logging.warning('Early stopping conditioned on metric `%s` ' + 'which is not available. Available metrics are: %s', + self.monitor, ','.join(list(logs.keys()))) + return monitor_value + + def _is_improvement(self, monitor_value, reference_value): + return self.monitor_op(monitor_value - self.min_delta, reference_value) + + +class RemoteMonitor(Callback): + """Callback used to stream events to a server. + + Requires the `requests` library. + Events are sent to `root + '/publish/epoch/end/'` by default. Calls are + HTTP POST, with a `data` argument which is a + JSON-encoded dictionary of event data. + If `send_as_json=True`, the content type of the request will be + `"application/json"`. + Otherwise the serialized JSON will be sent within a form. + + Args: + root: String; root url of the target server. + path: String; path relative to `root` to which the events will be sent. + field: String; JSON field under which the data will be stored. + The field is used only if the payload is sent within a form + (i.e. send_as_json is set to False). + headers: Dictionary; optional custom HTTP headers. + send_as_json: Boolean; whether the request should be + sent as `"application/json"`. + """ + + def __init__(self, + root='http://localhost:9000', + path='/publish/epoch/end/', + field='data', + headers=None, + send_as_json=False): + super(RemoteMonitor, self).__init__() + + self.root = root + self.path = path + self.field = field + self.headers = headers + self.send_as_json = send_as_json + + def on_epoch_end(self, epoch, logs=None): + if requests is None: + raise ImportError('RemoteMonitor requires the `requests` library.') + logs = logs or {} + send = {} + send['epoch'] = epoch + for k, v in logs.items(): + # np.ndarray and np.generic are not scalar types + # therefore we must unwrap their scalar values and + # pass to the json-serializable dict 'send' + if isinstance(v, (np.ndarray, np.generic)): + send[k] = v.item() + else: + send[k] = v + try: + if self.send_as_json: + requests.post(self.root + self.path, json=send, headers=self.headers) + else: + requests.post( + self.root + self.path, {self.field: json.dumps(send)}, + headers=self.headers) + except requests.exceptions.RequestException: + logging.warning('Warning: could not reach RemoteMonitor ' + 'root server at ' + str(self.root)) + + +class LearningRateScheduler(Callback): + """Learning rate scheduler. + + At the beginning of every epoch, this callback gets the updated learning rate + value from `schedule` function provided at `__init__`, with the current epoch + and current learning rate, and applies the updated learning rate + on the optimizer. + + Args: + schedule: a function that takes an epoch index (integer, indexed from 0) + and current learning rate (float) as inputs and returns a new + learning rate as output (float). + verbose: int. 0: quiet, 1: update messages. + + Example: + + >>> # This function keeps the initial learning rate for the first ten epochs + >>> # and decreases it exponentially after that. + >>> def scheduler(epoch, lr): + ... if epoch < 10: + ... return lr + ... else: + ... return lr * tf.math.exp(-0.1) + >>> + >>> model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + >>> model.compile(tf.keras.optimizers.SGD(), loss='mse') + >>> round(model.optimizer.lr.numpy(), 5) + 0.01 + + >>> callback = tf.keras.callbacks.LearningRateScheduler(scheduler) + >>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5), + ... epochs=15, callbacks=[callback], verbose=0) + >>> round(model.optimizer.lr.numpy(), 5) + 0.00607 + + """ + + def __init__(self, schedule, verbose=0): + super(LearningRateScheduler, self).__init__() + self.schedule = schedule + self.verbose = verbose + + def on_epoch_begin(self, epoch, logs=None): + if not hasattr(self.model.optimizer, 'lr'): + raise ValueError('Optimizer must have a "lr" attribute.') + try: # new API + lr = float(backend.get_value(self.model.optimizer.lr)) + lr = self.schedule(epoch, lr) + except TypeError: # Support for old API for backward compatibility + lr = self.schedule(epoch) + if not isinstance(lr, (tensor_lib.Tensor, float, np.float32, np.float64)): + raise ValueError('The output of the "schedule" function ' + 'should be float.') + if isinstance(lr, tensor_lib.Tensor) and not lr.dtype.is_floating: + raise ValueError('The dtype of Tensor should be float') + backend.set_value(self.model.optimizer.lr, backend.get_value(lr)) + if self.verbose > 0: + print('\nEpoch %05d: LearningRateScheduler setting learning ' + 'rate to %s.' % (epoch + 1, lr)) + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + logs['lr'] = backend.get_value(self.model.optimizer.lr) + + +def keras_model_summary(name, data, step=None): + """Writes a Keras model as JSON to as a Summary. + + Writing the Keras model configuration allows the TensorBoard graph plugin to + render a conceptual graph, as opposed to graph of ops. In case the model fails + to serialize as JSON, it ignores and returns False. + + Args: + name: A name for this summary. The summary tag used for TensorBoard will be + this name prefixed by any active name scopes. + data: A Keras Model to write. + step: Explicit `int64`-castable monotonic step value for this summary. If + omitted, this defaults to `tf.summary.experimental.get_step()`, which must + not be None. + + Returns: + True on success, or False if no summary was written because no default + summary writer was available. + + Raises: + ValueError: if a default writer exists, but no step was provided and + `tf.summary.experimental.get_step()` is None. + """ + summary_metadata = summary_pb2.SummaryMetadata() + # Hard coding a plugin name. Please refer to go/tb-plugin-name-hardcode for + # the rationale. + summary_metadata.plugin_data.plugin_name = 'graph_keras_model' + # version number = 1 + summary_metadata.plugin_data.content = b'1' + + try: + json_string = data.to_json() + except Exception as exc: # pylint: disable=broad-except + # An exception should not break a model code. + logging.warning('Model failed to serialize as JSON. Ignoring... %s', exc) + return False + + with summary_ops_v2.summary_scope(name, 'graph_keras_model', + [data, step]) as (tag, _): + with ops.device('cpu:0'): + tensor = constant_op.constant(json_string, dtype=dtypes.string) + return summary_ops_v2.write( + tag=tag, tensor=tensor, step=step, metadata=summary_metadata) + + +class TensorBoard(Callback, version_utils.TensorBoardVersionSelector): + # pylint: disable=line-too-long + """Enable visualizations for TensorBoard. + + TensorBoard is a visualization tool provided with TensorFlow. + + This callback logs events for TensorBoard, including: + + * Metrics summary plots + * Training graph visualization + * Activation histograms + * Sampled profiling + + When used in `Model.evaluate`, in addition to epoch summaries, there will be + a summary that records evaluation metrics vs `Model.optimizer.iterations` + written. The metric names will be prepended with `evaluation`, with + `Model.optimizer.iterations` being the step in the visualized TensorBoard. + + If you have installed TensorFlow with pip, you should be able + to launch TensorBoard from the command line: + + ``` + tensorboard --logdir=path_to_your_logs + ``` + + You can find more information about TensorBoard + [here](https://www.tensorflow.org/get_started/summaries_and_tensorboard). + + Args: + log_dir: the path of the directory where to save the log files to be + parsed by TensorBoard. e.g. log_dir = os.path.join(working_dir, 'logs') + This directory should not be reused by any other callbacks. + histogram_freq: frequency (in epochs) at which to compute activation and + weight histograms for the layers of the model. If set to 0, histograms + won't be computed. Validation data (or split) must be specified for + histogram visualizations. + write_graph: whether to visualize the graph in TensorBoard. The log file + can become quite large when write_graph is set to True. + write_images: whether to write model weights to visualize as image in + TensorBoard. + write_steps_per_second: whether to log the training steps per second into + Tensorboard. This supports both epoch and batch frequency logging. + update_freq: `'batch'` or `'epoch'` or integer. When using `'batch'`, + writes the losses and metrics to TensorBoard after each batch. The same + applies for `'epoch'`. If using an integer, let's say `1000`, the + callback will write the metrics and losses to TensorBoard every 1000 + batches. Note that writing too frequently to TensorBoard can slow down + your training. + profile_batch: Profile the batch(es) to sample compute characteristics. + profile_batch must be a non-negative integer or a tuple of integers. + A pair of positive integers signify a range of batches to profile. + By default, it will profile the second batch. Set profile_batch=0 + to disable profiling. + embeddings_freq: frequency (in epochs) at which embedding layers will be + visualized. If set to 0, embeddings won't be visualized. + embeddings_metadata: Dictionary which maps embedding layer names to the + filename of a file in which to save metadata for the embedding layer. + In case the same metadata file is to be + used for all embedding layers, a single filename can be passed. + + Examples: + + Basic usage: + + ```python + tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="./logs") + model.fit(x_train, y_train, epochs=2, callbacks=[tensorboard_callback]) + # Then run the tensorboard command to view the visualizations. + ``` + + Custom batch-level summaries in a subclassed Model: + + ```python + class MyModel(tf.keras.Model): + + def build(self, _): + self.dense = tf.keras.layers.Dense(10) + + def call(self, x): + outputs = self.dense(x) + tf.summary.histogram('outputs', outputs) + return outputs + + model = MyModel() + model.compile('sgd', 'mse') + + # Make sure to set `update_freq=N` to log a batch-level summary every N batches. + # In addition to any `tf.summary` contained in `Model.call`, metrics added in + # `Model.compile` will be logged every N batches. + tb_callback = tf.keras.callbacks.TensorBoard('./logs', update_freq=1) + model.fit(x_train, y_train, callbacks=[tb_callback]) + ``` + + Custom batch-level summaries in a Functional API Model: + + ```python + def my_summary(x): + tf.summary.histogram('x', x) + return x + + inputs = tf.keras.Input(10) + x = tf.keras.layers.Dense(10)(inputs) + outputs = tf.keras.layers.Lambda(my_summary)(x) + model = tf.keras.Model(inputs, outputs) + model.compile('sgd', 'mse') + + # Make sure to set `update_freq=N` to log a batch-level summary every N batches. + # In addition to any `tf.summary` contained in `Model.call`, metrics added in + # `Model.compile` will be logged every N batches. + tb_callback = tf.keras.callbacks.TensorBoard('./logs', update_freq=1) + model.fit(x_train, y_train, callbacks=[tb_callback]) + ``` + + Profiling: + + ```python + # Profile a single batch, e.g. the 5th batch. + tensorboard_callback = tf.keras.callbacks.TensorBoard( + log_dir='./logs', profile_batch=5) + model.fit(x_train, y_train, epochs=2, callbacks=[tensorboard_callback]) + + # Profile a range of batches, e.g. from 10 to 20. + tensorboard_callback = tf.keras.callbacks.TensorBoard( + log_dir='./logs', profile_batch=(10,20)) + model.fit(x_train, y_train, epochs=2, callbacks=[tensorboard_callback]) + ``` + """ + + # pylint: enable=line-too-long + + def __init__(self, + log_dir='logs', + histogram_freq=0, + write_graph=True, + write_images=False, + write_steps_per_second=False, + update_freq='epoch', + profile_batch=2, + embeddings_freq=0, + embeddings_metadata=None, + **kwargs): + super(TensorBoard, self).__init__() + self._supports_tf_logs = True + self._validate_kwargs(kwargs) + + self.log_dir = path_to_string(log_dir) + self.histogram_freq = histogram_freq + self.write_graph = write_graph + self.write_images = write_images + self.write_steps_per_second = write_steps_per_second + self.update_freq = 1 if update_freq == 'batch' else update_freq + self.embeddings_freq = embeddings_freq + self.embeddings_metadata = embeddings_metadata + self._init_profile_batch(profile_batch) + self._global_train_batch = 0 + self._previous_epoch_iterations = 0 + self._train_accumulated_time = 0 + self._batch_start_time = 0 + + # Lazily initialized in order to avoid creating event files when + # not needed. + self._writers = {} + + # Used to restore any existing `SummaryWriter` after training ends. + self._prev_summary_state = [] + + def _validate_kwargs(self, kwargs): + """Handle arguments were supported in V1.""" + if kwargs.get('write_grads', False): + logging.warning('`write_grads` will be ignored in TensorFlow 2.0 ' + 'for the `TensorBoard` Callback.') + if kwargs.get('batch_size', False): + logging.warning('`batch_size` is no longer needed in the ' + '`TensorBoard` Callback and will be ignored ' + 'in TensorFlow 2.0.') + if kwargs.get('embeddings_layer_names', False): + logging.warning('`embeddings_layer_names` is not supported in ' + 'TensorFlow 2.0. Instead, all `Embedding` layers ' + 'will be visualized.') + if kwargs.get('embeddings_data', False): + logging.warning('`embeddings_data` is not supported in TensorFlow ' + '2.0. Instead, all `Embedding` variables will be ' + 'visualized.') + + unrecognized_kwargs = set(kwargs.keys()) - { + 'write_grads', 'embeddings_layer_names', 'embeddings_data', 'batch_size' + } + + # Only allow kwargs that were supported in V1. + if unrecognized_kwargs: + raise ValueError('Unrecognized arguments in `TensorBoard` ' + 'Callback: ' + str(unrecognized_kwargs)) + + def set_model(self, model): + """Sets Keras model and writes graph if specified.""" + self.model = model + self._log_write_dir = self._get_log_write_dir() + + self._train_dir = os.path.join(self._log_write_dir, 'train') + self._train_step = self.model._train_counter # pylint: disable=protected-access + + self._val_dir = os.path.join(self._log_write_dir, 'validation') + self._val_step = self.model._test_counter # pylint: disable=protected-access + + self._writers = {} # Resets writers. + + self._should_write_train_graph = False + if self.write_graph: + self._write_keras_model_summary() + self._should_write_train_graph = True + if self.embeddings_freq: + self._configure_embeddings() + + @property + def _train_writer(self): + if 'train' not in self._writers: + self._writers['train'] = summary_ops_v2.create_file_writer_v2( + self._train_dir) + return self._writers['train'] + + @property + def _val_writer(self): + if 'val' not in self._writers: + self._writers['val'] = summary_ops_v2.create_file_writer_v2(self._val_dir) + return self._writers['val'] + + def _get_log_write_dir(self): + """For multi-worker, only chief should write, others write to '/tmp'.""" + return distributed_file_utils.write_dirpath(self.log_dir, + self.model.distribute_strategy) + + def _delete_tmp_write_dir(self): + """Deletes tmp write directories for multi-worker.""" + distributed_file_utils.remove_temp_dirpath(self.log_dir, + self.model.distribute_strategy) + + def _write_keras_model_train_graph(self): + """Writes Keras model train_function graph to TensorBoard.""" + with self._train_writer.as_default(): + with summary_ops_v2.record_if(True): + train_fn = self.model.train_tf_function + # If the train_function is a `tf.function`, we can write out a graph + if hasattr(train_fn, 'function_spec'): + summary_ops_v2.graph(train_fn._concrete_stateful_fn.graph) # pylint: disable=protected-access + + def _write_keras_model_summary(self): + """Writes Keras graph network summary to TensorBoard.""" + with self._train_writer.as_default(): + with summary_ops_v2.record_if(True): + summary_writable = ( + self.model._is_graph_network or # pylint: disable=protected-access + self.model.__class__.__name__ == 'Sequential') # pylint: disable=protected-access + if summary_writable: + keras_model_summary('keras', self.model, step=0) + + def _configure_embeddings(self): + """Configure the Projector for embeddings.""" + # TODO(omalleyt): Add integration tests. + from google.protobuf import text_format + from tensorflow.python.keras.layers import embeddings + from tensorflow.python.keras.protobuf import projector_config_pb2 + + config = projector_config_pb2.ProjectorConfig() + for layer in self.model.layers: + if isinstance(layer, embeddings.Embedding): + embedding = config.embeddings.add() + # Embeddings are always the first layer, so this naming should be + # consistent in any keras models checkpoints. + name = 'layer_with_weights-0/embeddings/.ATTRIBUTES/VARIABLE_VALUE' + embedding.tensor_name = name + + if self.embeddings_metadata is not None: + if isinstance(self.embeddings_metadata, str): + embedding.metadata_path = self.embeddings_metadata + else: + if layer.name in self.embeddings_metadata.keys(): + embedding.metadata_path = self.embeddings_metadata.pop(layer.name) + + if self.embeddings_metadata and not isinstance(self.embeddings_metadata, + str): + raise ValueError('Unrecognized `Embedding` layer names passed to ' + '`keras.callbacks.TensorBoard` `embeddings_metadata` ' + 'argument: ' + str(self.embeddings_metadata.keys())) + + config_pbtxt = text_format.MessageToString(config) + path = os.path.join(self._log_write_dir, 'projector_config.pbtxt') + with gfile.Open(path, 'w') as f: + f.write(config_pbtxt) + + def _push_writer(self, writer, step): + """Sets the default writer for custom batch-level summaries.""" + if self.update_freq == 'epoch': + return + + should_record = lambda: math_ops.equal(step % self.update_freq, 0) + # TODO(b/151339474): Fix deadlock when not using .value() here. + summary_context = (writer.as_default(step.value()), + summary_ops_v2.record_if(should_record)) + self._prev_summary_state.append(summary_context) + summary_context[0].__enter__() + summary_context[1].__enter__() + + def _pop_writer(self): + """Pops the current writer.""" + if self.update_freq == 'epoch': + return + + # See _push_writer for the content of the previous_context, which is pair + # of context. + previous_context = self._prev_summary_state.pop() + previous_context[1].__exit__(*sys.exc_info()) + previous_context[0].__exit__(*sys.exc_info()) + + def _close_writers(self): + for writer in self._writers.values(): + writer.close() + + def _init_profile_batch(self, profile_batch): + """Validate profile_batch value and set the range of batches to profile. + Sets values of _start_batch and _stop_batch attributes, + specifying the start and stop batch to profile. + Setting `profile_batch=0` disables profiling. + + Args: + profile_batch: The range of batches to profile. Should be a non-negative + integer or a comma separated string of pair of positive integers. A pair + of positive integers signify a range of batches to profile. + + Raises: + ValueError: If profile_batch is not an integer or a comma separated pair + of positive integers. + + """ + profile_batch_error_message = ( + 'profile_batch must be a non-negative integer or 2-tuple of positive ' + 'integers. A pair of positive integers signifies a range of batches ' + 'to profile. Found: {}'.format(profile_batch)) + + # Support legacy way of specifying "start,stop" or "start" as str. + if isinstance(profile_batch, str): + profile_batch = str(profile_batch).split(',') + profile_batch = nest.map_structure(int, profile_batch) + + if isinstance(profile_batch, int): + self._start_batch = profile_batch + self._stop_batch = profile_batch + elif isinstance(profile_batch, (tuple, list)) and len(profile_batch) == 2: + self._start_batch, self._stop_batch = profile_batch + else: + raise ValueError(profile_batch_error_message) + + if self._start_batch < 0 or self._stop_batch < self._start_batch: + raise ValueError(profile_batch_error_message) + + # True when the profiler was successfully started by this callback. + # We track the status here to make sure callbacks do not interfere with + # each other. The callback will only stop the profiler it started. + self._profiler_started = False + if self._start_batch > 0: + # Warm up and improve the profiling accuracy. + self._start_profiler(logdir='') + self._stop_profiler(save=False) + # True when a trace is running. + self._is_tracing = False + + # Setting `profile_batch=0` disables profiling. + self._should_trace = not (self._start_batch == 0 and self._stop_batch == 0) + + def on_train_begin(self, logs=None): + self._global_train_batch = 0 + self._previous_epoch_iterations = 0 + self._train_accumulated_time = 0 + self._push_writer(self._train_writer, self._train_step) + + def on_train_end(self, logs=None): + self._pop_writer() + + if self._is_tracing: + self._stop_trace() + + self._close_writers() + self._delete_tmp_write_dir() + + def on_test_begin(self, logs=None): + self._push_writer(self._val_writer, self._val_step) + + def on_test_end(self, logs=None): + if self.model.optimizer and hasattr(self.model.optimizer, 'iterations'): + with summary_ops_v2.record_if(True), self._val_writer.as_default(): + for name, value in logs.items(): + summary_ops_v2.scalar( + 'evaluation_' + name + '_vs_iterations', + value, + step=self.model.optimizer.iterations.read_value()) + self._pop_writer() + + def _implements_train_batch_hooks(self): + # Only call batch hooks when tracing or write_steps_per_second are enabled + return self._should_trace or self.write_steps_per_second + + def on_train_batch_begin(self, batch, logs=None): + self._global_train_batch += 1 + if self.write_steps_per_second: + self._batch_start_time = time.time() + if not self._should_trace: + return + + if self._global_train_batch == self._start_batch: + self._start_trace() + + def on_train_batch_end(self, batch, logs=None): + if self._should_write_train_graph: + self._write_keras_model_train_graph() + self._should_write_train_graph = False + if self.write_steps_per_second: + batch_run_time = time.time() - self._batch_start_time + self._train_accumulated_time += batch_run_time + summary_ops_v2.scalar( + 'batch_steps_per_second', 1. / batch_run_time, step=self._train_step) + if not self._should_trace: + return + + if self._is_tracing and self._global_train_batch >= self._stop_batch: + self._stop_trace() + + def on_epoch_begin(self, epoch, logs=None): + # Keeps track of epoch for profiling. + if self.write_steps_per_second: + self._previous_epoch_iterations = self.model.optimizer.iterations.numpy() + self._train_accumulated_time = 0 + + def on_epoch_end(self, epoch, logs=None): + """Runs metrics and histogram summaries at epoch end.""" + self._log_epoch_metrics(epoch, logs) + + if self.histogram_freq and epoch % self.histogram_freq == 0: + self._log_weights(epoch) + + if self.embeddings_freq and epoch % self.embeddings_freq == 0: + self._log_embeddings(epoch) + + def _start_trace(self): + summary_ops_v2.trace_on(graph=True, profiler=False) + self._start_profiler(logdir=self._train_dir) + self._is_tracing = True + + def _stop_trace(self, batch=None): + """Logs the trace graph to TensorBoard.""" + if batch is None: + batch = self._stop_batch + with self._train_writer.as_default(): + with summary_ops_v2.record_if(True): + # TODO(b/126388999): Remove step info in the summary name. + summary_ops_v2.trace_export(name='batch_%d' % batch, step=batch) + self._stop_profiler() + self._is_tracing = False + + def _collect_learning_rate(self, logs): + lr_schedule = getattr(self.model.optimizer, 'lr', None) + if isinstance(lr_schedule, learning_rate_schedule.LearningRateSchedule): + logs['learning_rate'] = lr_schedule(self.model.optimizer.iterations) + return logs + + def _compute_steps_per_second(self): + current_iteration = self.model.optimizer.iterations.numpy() + steps_per_second = ((current_iteration - self._previous_epoch_iterations) / + (self._train_accumulated_time)) + return steps_per_second + + def _log_epoch_metrics(self, epoch, logs): + """Writes epoch metrics out as scalar summaries. + + Args: + epoch: Int. The global step to use for TensorBoard. + logs: Dict. Keys are scalar summary names, values are scalars. + """ + if not logs: + return + + train_logs = {k: v for k, v in logs.items() if not k.startswith('val_')} + val_logs = {k: v for k, v in logs.items() if k.startswith('val_')} + train_logs = self._collect_learning_rate(train_logs) + if self.write_steps_per_second: + train_logs['steps_per_second'] = self._compute_steps_per_second() + + with summary_ops_v2.record_if(True): + if train_logs: + with self._train_writer.as_default(): + for name, value in train_logs.items(): + summary_ops_v2.scalar('epoch_' + name, value, step=epoch) + if val_logs: + with self._val_writer.as_default(): + for name, value in val_logs.items(): + name = name[4:] # Remove 'val_' prefix. + summary_ops_v2.scalar('epoch_' + name, value, step=epoch) + + def _log_weights(self, epoch): + """Logs the weights of the Model to TensorBoard.""" + with self._train_writer.as_default(): + with summary_ops_v2.record_if(True): + for layer in self.model.layers: + for weight in layer.weights: + weight_name = weight.name.replace(':', '_') + summary_ops_v2.histogram(weight_name, weight, step=epoch) + if self.write_images: + self._log_weight_as_image(weight, weight_name, epoch) + self._train_writer.flush() + + def _log_weight_as_image(self, weight, weight_name, epoch): + """Logs a weight as a TensorBoard image.""" + w_img = array_ops.squeeze(weight) + shape = backend.int_shape(w_img) + if len(shape) == 1: # Bias case + w_img = array_ops.reshape(w_img, [1, shape[0], 1, 1]) + elif len(shape) == 2: # Dense layer kernel case + if shape[0] > shape[1]: + w_img = array_ops.transpose(w_img) + shape = backend.int_shape(w_img) + w_img = array_ops.reshape(w_img, [1, shape[0], shape[1], 1]) + elif len(shape) == 3: # ConvNet case + if backend.image_data_format() == 'channels_last': + # Switch to channels_first to display every kernel as a separate + # image. + w_img = array_ops.transpose(w_img, perm=[2, 0, 1]) + shape = backend.int_shape(w_img) + w_img = array_ops.reshape(w_img, [shape[0], shape[1], shape[2], 1]) + + shape = backend.int_shape(w_img) + # Not possible to handle 3D convnets etc. + if len(shape) == 4 and shape[-1] in [1, 3, 4]: + summary_ops_v2.image(weight_name, w_img, step=epoch) + + def _log_embeddings(self, epoch): + embeddings_ckpt = os.path.join(self._log_write_dir, 'train', + 'keras_embedding.ckpt-{}'.format(epoch)) + self.model.save_weights(embeddings_ckpt) + + def _start_profiler(self, logdir): + """Starts the profiler if currently inactive. + + Args: + logdir: Directory where profiler results will be saved. + """ + if self._profiler_started: + return + try: + profiler.start(logdir=logdir) + self._profiler_started = True + except errors.AlreadyExistsError as e: + # Profiler errors should not be fatal. + logging.error('Failed to start profiler: %s', e.message) + + def _stop_profiler(self, save=True): + """Stops the profiler if currently active. + + Args: + save: Whether to save the profiler results to TensorBoard. + """ + if not self._profiler_started: + return + try: + profiler.stop(save=save) + except errors.UnavailableError as e: + # Profiler errors should not be fatal. + logging.error('Failed to stop profiler: %s', e.message) + finally: + self._profiler_started = False + + +class ReduceLROnPlateau(Callback): + """Reduce learning rate when a metric has stopped improving. + + Models often benefit from reducing the learning rate by a factor + of 2-10 once learning stagnates. This callback monitors a + quantity and if no improvement is seen for a 'patience' number + of epochs, the learning rate is reduced. + + Example: + + ```python + reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, + patience=5, min_lr=0.001) + model.fit(X_train, Y_train, callbacks=[reduce_lr]) + ``` + + Args: + monitor: quantity to be monitored. + factor: factor by which the learning rate will be reduced. + `new_lr = lr * factor`. + patience: number of epochs with no improvement after which learning rate + will be reduced. + verbose: int. 0: quiet, 1: update messages. + mode: one of `{'auto', 'min', 'max'}`. In `'min'` mode, + the learning rate will be reduced when the + quantity monitored has stopped decreasing; in `'max'` mode it will be + reduced when the quantity monitored has stopped increasing; in `'auto'` + mode, the direction is automatically inferred from the name of the + monitored quantity. + min_delta: threshold for measuring the new optimum, to only focus on + significant changes. + cooldown: number of epochs to wait before resuming normal operation after + lr has been reduced. + min_lr: lower bound on the learning rate. + """ + + def __init__(self, + monitor='val_loss', + factor=0.1, + patience=10, + verbose=0, + mode='auto', + min_delta=1e-4, + cooldown=0, + min_lr=0, + **kwargs): + super(ReduceLROnPlateau, self).__init__() + + self.monitor = monitor + if factor >= 1.0: + raise ValueError('ReduceLROnPlateau ' 'does not support a factor >= 1.0.') + if 'epsilon' in kwargs: + min_delta = kwargs.pop('epsilon') + logging.warning('`epsilon` argument is deprecated and ' + 'will be removed, use `min_delta` instead.') + self.factor = factor + self.min_lr = min_lr + self.min_delta = min_delta + self.patience = patience + self.verbose = verbose + self.cooldown = cooldown + self.cooldown_counter = 0 # Cooldown counter. + self.wait = 0 + self.best = 0 + self.mode = mode + self.monitor_op = None + self._reset() + + def _reset(self): + """Resets wait counter and cooldown counter. + """ + if self.mode not in ['auto', 'min', 'max']: + logging.warning('Learning rate reduction mode %s is unknown, ' + 'fallback to auto mode.', self.mode) + self.mode = 'auto' + if (self.mode == 'min' or + (self.mode == 'auto' and 'acc' not in self.monitor)): + self.monitor_op = lambda a, b: np.less(a, b - self.min_delta) + self.best = np.Inf + else: + self.monitor_op = lambda a, b: np.greater(a, b + self.min_delta) + self.best = -np.Inf + self.cooldown_counter = 0 + self.wait = 0 + + def on_train_begin(self, logs=None): + self._reset() + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + logs['lr'] = backend.get_value(self.model.optimizer.lr) + current = logs.get(self.monitor) + if current is None: + logging.warning('Learning rate reduction is conditioned on metric `%s` ' + 'which is not available. Available metrics are: %s', + self.monitor, ','.join(list(logs.keys()))) + + else: + if self.in_cooldown(): + self.cooldown_counter -= 1 + self.wait = 0 + + if self.monitor_op(current, self.best): + self.best = current + self.wait = 0 + elif not self.in_cooldown(): + self.wait += 1 + if self.wait >= self.patience: + old_lr = backend.get_value(self.model.optimizer.lr) + if old_lr > np.float32(self.min_lr): + new_lr = old_lr * self.factor + new_lr = max(new_lr, self.min_lr) + backend.set_value(self.model.optimizer.lr, new_lr) + if self.verbose > 0: + print('\nEpoch %05d: ReduceLROnPlateau reducing learning ' + 'rate to %s.' % (epoch + 1, new_lr)) + self.cooldown_counter = self.cooldown + self.wait = 0 + + def in_cooldown(self): + return self.cooldown_counter > 0 + + +class CSVLogger(Callback): + """Callback that streams epoch results to a CSV file. + + Supports all values that can be represented as a string, + including 1D iterables such as `np.ndarray`. + + Example: + + ```python + csv_logger = CSVLogger('training.log') + model.fit(X_train, Y_train, callbacks=[csv_logger]) + ``` + + Args: + filename: Filename of the CSV file, e.g. `'run/log.csv'`. + separator: String used to separate elements in the CSV file. + append: Boolean. True: append if file exists (useful for continuing + training). False: overwrite existing file. + """ + + def __init__(self, filename, separator=',', append=False): + self.sep = separator + self.filename = path_to_string(filename) + self.append = append + self.writer = None + self.keys = None + self.append_header = True + super(CSVLogger, self).__init__() + + def on_train_begin(self, logs=None): + if self.append: + if file_io.file_exists_v2(self.filename): + with gfile.GFile(self.filename, 'r') as f: + self.append_header = not bool(len(f.readline())) + mode = 'a' + else: + mode = 'w' + self.csv_file = gfile.GFile(self.filename, mode) + + def on_epoch_end(self, epoch, logs=None): + logs = logs or {} + + def handle_value(k): + is_zero_dim_ndarray = isinstance(k, np.ndarray) and k.ndim == 0 + if isinstance(k, str): + return k + elif isinstance(k, collections.abc.Iterable) and not is_zero_dim_ndarray: + return '"[%s]"' % (', '.join(map(str, k))) + else: + return k + + if self.keys is None: + self.keys = sorted(logs.keys()) + + if self.model.stop_training: + # We set NA so that csv parsers do not fail for this last epoch. + logs = dict((k, logs[k]) if k in logs else (k, 'NA') for k in self.keys) + + if not self.writer: + + class CustomDialect(csv.excel): + delimiter = self.sep + + fieldnames = ['epoch'] + self.keys + + self.writer = csv.DictWriter( + self.csv_file, + fieldnames=fieldnames, + dialect=CustomDialect) + if self.append_header: + self.writer.writeheader() + + row_dict = collections.OrderedDict({'epoch': epoch}) + row_dict.update((key, handle_value(logs[key])) for key in self.keys) + self.writer.writerow(row_dict) + self.csv_file.flush() + + def on_train_end(self, logs=None): + self.csv_file.close() + self.writer = None + + +class LambdaCallback(Callback): + r"""Callback for creating simple, custom callbacks on-the-fly. + + This callback is constructed with anonymous functions that will be called + at the appropriate time (during `Model.{fit | evaluate | predict}`). + Note that the callbacks expects positional arguments, as: + + - `on_epoch_begin` and `on_epoch_end` expect two positional arguments: + `epoch`, `logs` + - `on_batch_begin` and `on_batch_end` expect two positional arguments: + `batch`, `logs` + - `on_train_begin` and `on_train_end` expect one positional argument: + `logs` + + Args: + on_epoch_begin: called at the beginning of every epoch. + on_epoch_end: called at the end of every epoch. + on_batch_begin: called at the beginning of every batch. + on_batch_end: called at the end of every batch. + on_train_begin: called at the beginning of model training. + on_train_end: called at the end of model training. + + Example: + + ```python + # Print the batch number at the beginning of every batch. + batch_print_callback = LambdaCallback( + on_batch_begin=lambda batch,logs: print(batch)) + + # Stream the epoch loss to a file in JSON format. The file content + # is not well-formed JSON but rather has a JSON object per line. + import json + json_log = open('loss_log.json', mode='wt', buffering=1) + json_logging_callback = LambdaCallback( + on_epoch_end=lambda epoch, logs: json_log.write( + json.dumps({'epoch': epoch, 'loss': logs['loss']}) + '\n'), + on_train_end=lambda logs: json_log.close() + ) + + # Terminate some processes after having finished model training. + processes = ... + cleanup_callback = LambdaCallback( + on_train_end=lambda logs: [ + p.terminate() for p in processes if p.is_alive()]) + + model.fit(..., + callbacks=[batch_print_callback, + json_logging_callback, + cleanup_callback]) + ``` + """ + + def __init__(self, + on_epoch_begin=None, + on_epoch_end=None, + on_batch_begin=None, + on_batch_end=None, + on_train_begin=None, + on_train_end=None, + **kwargs): + super(LambdaCallback, self).__init__() + self.__dict__.update(kwargs) + if on_epoch_begin is not None: + self.on_epoch_begin = on_epoch_begin + else: + self.on_epoch_begin = lambda epoch, logs: None + if on_epoch_end is not None: + self.on_epoch_end = on_epoch_end + else: + self.on_epoch_end = lambda epoch, logs: None + if on_batch_begin is not None: + self.on_batch_begin = on_batch_begin + else: + self.on_batch_begin = lambda batch, logs: None + if on_batch_end is not None: + self.on_batch_end = on_batch_end + else: + self.on_batch_end = lambda batch, logs: None + if on_train_begin is not None: + self.on_train_begin = on_train_begin + else: + self.on_train_begin = lambda logs: None + if on_train_end is not None: + self.on_train_end = on_train_end + else: + self.on_train_end = lambda logs: None diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/callbacks_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/callbacks_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..58e5cc534b37b3d28b8bbf750fdf15d780eebc6d --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/callbacks_v1.py @@ -0,0 +1,481 @@ +# 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. +# ============================================================================== +# pylint: disable=g-import-not-at-top +# pylint: disable=g-classes-have-attributes +"""Callbacks: utilities called at certain points during model training.""" + +import os +import numpy as np + +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.keras import backend as K +from tensorflow.python.keras import callbacks +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.ops import summary_ops_v2 +from tensorflow.python.ops import variables +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.profiler import profiler_v2 as profiler +from tensorflow.python.summary import summary as tf_summary +from tensorflow.python.training import saver + + +class TensorBoard(callbacks.TensorBoard): + # pylint: disable=line-too-long + """Enable visualizations for TensorBoard. + + TensorBoard is a visualization tool provided with TensorFlow. + + This callback logs events for TensorBoard, including: + * Metrics summary plots + * Training graph visualization + * Activation histograms + * Sampled profiling + + If you have installed TensorFlow with pip, you should be able + to launch TensorBoard from the command line: + + ```sh + tensorboard --logdir=path_to_your_logs + ``` + + You can find more information about TensorBoard + [here](https://www.tensorflow.org/get_started/summaries_and_tensorboard). + + Args: + log_dir: the path of the directory where to save the log files to be + parsed by TensorBoard. + histogram_freq: frequency (in epochs) at which to compute activation and + weight histograms for the layers of the model. If set to 0, histograms + won't be computed. Validation data (or split) must be specified for + histogram visualizations. + write_graph: whether to visualize the graph in TensorBoard. The log file + can become quite large when write_graph is set to True. + write_grads: whether to visualize gradient histograms in TensorBoard. + `histogram_freq` must be greater than 0. + batch_size: size of batch of inputs to feed to the network for histograms + computation. + write_images: whether to write model weights to visualize as image in + TensorBoard. + embeddings_freq: frequency (in epochs) at which selected embedding layers + will be saved. If set to 0, embeddings won't be computed. Data to be + visualized in TensorBoard's Embedding tab must be passed as + `embeddings_data`. + embeddings_layer_names: a list of names of layers to keep eye on. If None + or empty list all the embedding layer will be watched. + embeddings_metadata: a dictionary which maps layer name to a file name in + which metadata for this embedding layer is saved. + [Here are details]( + https://www.tensorflow.org/how_tos/embedding_viz/#metadata_optional) + about metadata files format. In case if the same metadata file is + used for all embedding layers, string can be passed. + embeddings_data: data to be embedded at layers specified in + `embeddings_layer_names`. Numpy array (if the model has a single input) + or list of Numpy arrays (if the model has multiple inputs). Learn more + about embeddings [in this guide]( + https://www.tensorflow.org/programmers_guide/embedding). + update_freq: `'batch'` or `'epoch'` or integer. When using `'batch'`, + writes the losses and metrics to TensorBoard after each batch. The same + applies for `'epoch'`. If using an integer, let's say `1000`, the + callback will write the metrics and losses to TensorBoard every 1000 + samples. Note that writing too frequently to TensorBoard can slow down + your training. + profile_batch: Profile the batch to sample compute characteristics. By + default, it will profile the second batch. Set profile_batch=0 to + disable profiling. + + Raises: + ValueError: If histogram_freq is set and no validation data is provided. + + @compatibility(eager) + Using the `TensorBoard` callback will work when eager execution is enabled, + with the restriction that outputting histogram summaries of weights and + gradients is not supported. Consequently, `histogram_freq` will be ignored. + @end_compatibility + """ + + # pylint: enable=line-too-long + + def __init__(self, + log_dir='./logs', + histogram_freq=0, + batch_size=32, + write_graph=True, + write_grads=False, + write_images=False, + embeddings_freq=0, + embeddings_layer_names=None, + embeddings_metadata=None, + embeddings_data=None, + update_freq='epoch', + profile_batch=2): + # Don't call super's init since it is an eager-only version. + callbacks.Callback.__init__(self) + self.log_dir = log_dir + self.histogram_freq = histogram_freq + if self.histogram_freq and context.executing_eagerly(): + logging.warning( + UserWarning('Weight and gradient histograms not supported for eager' + 'execution, setting `histogram_freq` to `0`.')) + self.histogram_freq = 0 + self.merged = None + self.write_graph = write_graph + self.write_grads = write_grads + self.write_images = write_images + self.batch_size = batch_size + self._current_batch = 0 + self._total_batches_seen = 0 + self._total_val_batches_seen = 0 + self.embeddings_freq = embeddings_freq + self.embeddings_layer_names = embeddings_layer_names + self.embeddings_metadata = embeddings_metadata + self.embeddings_data = embeddings_data + if update_freq == 'batch': + self.update_freq = 1 + else: + self.update_freq = update_freq + self._samples_seen = 0 + self._samples_seen_at_last_write = 0 + # TODO(fishx): Add a link to the full profiler tutorial. + self._profile_batch = profile_batch + # True when the profiler was successfully started by this callback. + # We track the status here to make sure callbacks do not interfere with + # each other. The callback will only stop the profiler it started. + self._profiler_started = False + + # TensorBoard should only write summaries on the chief when in a + # Multi-Worker setting. + self._chief_worker_only = True + + def _init_writer(self, model): + """Sets file writer.""" + if context.executing_eagerly(): + self.writer = summary_ops_v2.create_file_writer_v2(self.log_dir) + if not model.run_eagerly and self.write_graph: + with self.writer.as_default(): + summary_ops_v2.graph(K.get_graph()) + elif self.write_graph: + self.writer = tf_summary.FileWriter(self.log_dir, K.get_graph()) + else: + self.writer = tf_summary.FileWriter(self.log_dir) + + def _make_histogram_ops(self, model): + """Defines histogram ops when histogram_freq > 0.""" + # only make histogram summary op if it hasn't already been made + if self.histogram_freq and self.merged is None: + for layer in self.model.layers: + for weight in layer.weights: + mapped_weight_name = weight.name.replace(':', '_') + tf_summary.histogram(mapped_weight_name, weight) + if self.write_images: + w_img = array_ops.squeeze(weight) + shape = K.int_shape(w_img) + if len(shape) == 2: # dense layer kernel case + if shape[0] > shape[1]: + w_img = array_ops.transpose(w_img) + shape = K.int_shape(w_img) + w_img = array_ops.reshape(w_img, [1, shape[0], shape[1], 1]) + elif len(shape) == 3: # convnet case + if K.image_data_format() == 'channels_last': + # switch to channels_first to display + # every kernel as a separate image + w_img = array_ops.transpose(w_img, perm=[2, 0, 1]) + shape = K.int_shape(w_img) + w_img = array_ops.reshape(w_img, + [shape[0], shape[1], shape[2], 1]) + elif len(shape) == 1: # bias case + w_img = array_ops.reshape(w_img, [1, shape[0], 1, 1]) + else: + # not possible to handle 3D convnets etc. + continue + + shape = K.int_shape(w_img) + assert len(shape) == 4 and shape[-1] in [1, 3, 4] + tf_summary.image(mapped_weight_name, w_img) + + if self.write_grads: + for weight in layer.trainable_weights: + mapped_weight_name = weight.name.replace(':', '_') + grads = model.optimizer.get_gradients(model.total_loss, weight) + + def is_indexed_slices(grad): + return type(grad).__name__ == 'IndexedSlices' + + grads = [ + grad.values if is_indexed_slices(grad) else grad + for grad in grads + ] + tf_summary.histogram('{}_grad'.format(mapped_weight_name), grads) + + if hasattr(layer, 'output'): + if isinstance(layer.output, list): + for i, output in enumerate(layer.output): + tf_summary.histogram('{}_out_{}'.format(layer.name, i), output) + else: + tf_summary.histogram('{}_out'.format(layer.name), layer.output) + + def set_model(self, model): + """Sets Keras model and creates summary ops.""" + + self.model = model + self._init_writer(model) + # histogram summaries only enabled in graph mode + if not context.executing_eagerly(): + self._make_histogram_ops(model) + self.merged = tf_summary.merge_all() + + # If both embedding_freq and embeddings_data are available, we will + # visualize embeddings. + if self.embeddings_freq and self.embeddings_data is not None: + # Avoid circular dependency. + from tensorflow.python.keras.engine import training_utils_v1 # pylint: disable=g-import-not-at-top + self.embeddings_data = training_utils_v1.standardize_input_data( + self.embeddings_data, model.input_names) + + # If embedding_layer_names are not provided, get all of the embedding + # layers from the model. + embeddings_layer_names = self.embeddings_layer_names + if not embeddings_layer_names: + embeddings_layer_names = [ + layer.name + for layer in self.model.layers + if type(layer).__name__ == 'Embedding' + ] + + self.assign_embeddings = [] + embeddings_vars = {} + + self.batch_id = batch_id = array_ops.placeholder(dtypes.int32) + self.step = step = array_ops.placeholder(dtypes.int32) + + for layer in self.model.layers: + if layer.name in embeddings_layer_names: + embedding_input = self.model.get_layer(layer.name).output + embedding_size = np.prod(embedding_input.shape[1:]) + embedding_input = array_ops.reshape(embedding_input, + (step, int(embedding_size))) + shape = (self.embeddings_data[0].shape[0], int(embedding_size)) + embedding = variables.Variable( + array_ops.zeros(shape), name=layer.name + '_embedding') + embeddings_vars[layer.name] = embedding + batch = state_ops.assign(embedding[batch_id:batch_id + step], + embedding_input) + self.assign_embeddings.append(batch) + + self.saver = saver.Saver(list(embeddings_vars.values())) + + # Create embeddings_metadata dictionary + if isinstance(self.embeddings_metadata, str): + embeddings_metadata = { + layer_name: self.embeddings_metadata + for layer_name in embeddings_vars.keys() + } + else: + # If embedding_metadata is already a dictionary + embeddings_metadata = self.embeddings_metadata + + try: + from tensorboard.plugins import projector + except ImportError: + raise ImportError('Failed to import TensorBoard. Please make sure that ' + 'TensorBoard integration is complete."') + + # TODO(psv): Add integration tests to test embedding visualization + # with TensorBoard callback. We are unable to write a unit test for this + # because TensorBoard dependency assumes TensorFlow package is installed. + config = projector.ProjectorConfig() + for layer_name, tensor in embeddings_vars.items(): + embedding = config.embeddings.add() + embedding.tensor_name = tensor.name + + if (embeddings_metadata is not None and + layer_name in embeddings_metadata): + embedding.metadata_path = embeddings_metadata[layer_name] + + projector.visualize_embeddings(self.writer, config) + + def _fetch_callback(self, summary): + self.writer.add_summary(summary, self._total_val_batches_seen) + self._total_val_batches_seen += 1 + + def _write_custom_summaries(self, step, logs=None): + """Writes metrics out as custom scalar summaries. + + Args: + step: the global step to use for TensorBoard. + logs: dict. Keys are scalar summary names, values are + NumPy scalars. + + """ + logs = logs or {} + if context.executing_eagerly(): + # use v2 summary ops + with self.writer.as_default(), summary_ops_v2.record_if(True): + for name, value in logs.items(): + if isinstance(value, np.ndarray): + value = value.item() + summary_ops_v2.scalar(name, value, step=step) + else: + # use FileWriter from v1 summary + for name, value in logs.items(): + if isinstance(value, np.ndarray): + value = value.item() + summary = tf_summary.Summary() + summary_value = summary.value.add() + summary_value.simple_value = value + summary_value.tag = name + self.writer.add_summary(summary, step) + self.writer.flush() + + def on_train_batch_begin(self, batch, logs=None): + if self._total_batches_seen == self._profile_batch - 1: + self._start_profiler() + + def on_train_batch_end(self, batch, logs=None): + return self.on_batch_end(batch, logs) + + def on_test_begin(self, logs=None): + pass + + def on_test_end(self, logs=None): + pass + + def on_batch_end(self, batch, logs=None): + """Writes scalar summaries for metrics on every training batch. + + Performs profiling if current batch is in profiler_batches. + """ + # Don't output batch_size and batch number as TensorBoard summaries + logs = logs or {} + self._samples_seen += logs.get('size', 1) + samples_seen_since = self._samples_seen - self._samples_seen_at_last_write + if self.update_freq != 'epoch' and samples_seen_since >= self.update_freq: + batch_logs = {('batch_' + k): v + for k, v in logs.items() + if k not in ['batch', 'size', 'num_steps']} + self._write_custom_summaries(self._total_batches_seen, batch_logs) + self._samples_seen_at_last_write = self._samples_seen + self._total_batches_seen += 1 + self._stop_profiler() + + def on_train_begin(self, logs=None): + pass + + def on_epoch_begin(self, epoch, logs=None): + """Add histogram op to Model eval_function callbacks, reset batch count.""" + + # check if histogram summary should be run for this epoch + if self.histogram_freq and epoch % self.histogram_freq == 0: + # pylint: disable=protected-access + # add the histogram summary op if it should run this epoch + self.model._make_test_function() + if self.merged not in self.model.test_function.fetches: + self.model.test_function.fetches.append(self.merged) + self.model.test_function.fetch_callbacks[ + self.merged] = self._fetch_callback + # pylint: enable=protected-access + + def on_epoch_end(self, epoch, logs=None): + """Checks if summary ops should run next epoch, logs scalar summaries.""" + + # don't output batch_size and + # batch number as TensorBoard summaries + logs = {('epoch_' + k): v + for k, v in logs.items() + if k not in ['batch', 'size', 'num_steps']} + if self.update_freq == 'epoch': + step = epoch + else: + step = self._samples_seen + self._write_custom_summaries(step, logs) + + # pop the histogram summary op after each epoch + if self.histogram_freq: + # pylint: disable=protected-access + if self.merged in self.model.test_function.fetches: + self.model.test_function.fetches.remove(self.merged) + if self.merged in self.model.test_function.fetch_callbacks: + self.model.test_function.fetch_callbacks.pop(self.merged) + # pylint: enable=protected-access + + if self.embeddings_data is None and self.embeddings_freq: + raise ValueError('To visualize embeddings, embeddings_data must ' + 'be provided.') + + if self.embeddings_freq and self.embeddings_data is not None: + if epoch % self.embeddings_freq == 0: + # We need a second forward-pass here because we're passing + # the `embeddings_data` explicitly. This design allows to pass + # arbitrary data as `embeddings_data` and results from the fact + # that we need to know the size of the `tf.Variable`s which + # hold the embeddings in `set_model`. At this point, however, + # the `validation_data` is not yet set. + + embeddings_data = self.embeddings_data + n_samples = embeddings_data[0].shape[0] + i = 0 + sess = K.get_session() + while i < n_samples: + step = min(self.batch_size, n_samples - i) + batch = slice(i, i + step) + + if isinstance(self.model.input, list): + feed_dict = { + model_input: embeddings_data[idx][batch] + for idx, model_input in enumerate(self.model.input) + } + else: + feed_dict = {self.model.input: embeddings_data[0][batch]} + + feed_dict.update({self.batch_id: i, self.step: step}) + + if not isinstance(K.learning_phase(), int): + feed_dict[K.learning_phase()] = False + + sess.run(self.assign_embeddings, feed_dict=feed_dict) + self.saver.save(sess, + os.path.join(self.log_dir, 'keras_embedding.ckpt'), + epoch) + + i += self.batch_size + + def on_train_end(self, logs=None): + self._stop_profiler() + self.writer.close() + + def _start_profiler(self): + """Starts the profiler if currently inactive.""" + if self._profiler_started: + return + try: + profiler.start(logdir=self.log_dir) + self._profiler_started = True + except errors.AlreadyExistsError as e: + # Profiler errors should not be fatal. + logging.error('Failed to start profiler: %s', e.message) + + def _stop_profiler(self): + """Stops the profiler if currently active.""" + if not self._profiler_started: + return + try: + profiler.stop() + except errors.UnavailableError as e: + # Profiler errors should not be fatal. + logging.error('Failed to stop profiler: %s', e.message) + finally: + self._profiler_started = False diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/combinations.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/combinations.py new file mode 100644 index 0000000000000000000000000000000000000000..e2f8a7468d0b50182116d140c7c05bef3c206383 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/combinations.py @@ -0,0 +1,106 @@ +# Copyright 2020 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""This module customizes `test_combinations` for `tf.keras` related tests.""" + +import functools + +from tensorflow.python import tf2 +from tensorflow.python.framework import combinations +from tensorflow.python.framework import test_combinations +from tensorflow.python.keras import testing_utils + +KERAS_MODEL_TYPES = ['functional', 'subclass', 'sequential'] + + +def keras_mode_combinations(mode=None, run_eagerly=None): + """Returns the default test combinations for tf.keras tests. + + Note that if tf2 is enabled, then v1 session test will be skipped. + + Args: + mode: List of modes to run the tests. The valid options are 'graph' and + 'eager'. Default to ['graph', 'eager'] if not specified. If a empty list + is provide, then the test will run under the context based on tf's + version, eg graph for v1 and eager for v2. + run_eagerly: List of `run_eagerly` value to be run with the tests. + Default to [True, False] if not specified. Note that for `graph` mode, + run_eagerly value will only be False. + + Returns: + A list contains all the combinations to be used to generate test cases. + """ + if mode is None: + mode = ['eager'] if tf2.enabled() else ['graph', 'eager'] + if run_eagerly is None: + run_eagerly = [True, False] + result = [] + if 'eager' in mode: + result += combinations.combine(mode=['eager'], run_eagerly=run_eagerly) + if 'graph' in mode: + result += combinations.combine(mode=['graph'], run_eagerly=[False]) + return result + + +def keras_model_type_combinations(): + return combinations.combine(model_type=KERAS_MODEL_TYPES) + + +class KerasModeCombination(test_combinations.TestCombination): + """Combination for Keras test mode. + + It by default includes v1_session, v2_eager and v2_tf_function. + """ + + def context_managers(self, kwargs): + run_eagerly = kwargs.pop('run_eagerly', None) + + if run_eagerly is not None: + return [testing_utils.run_eagerly_scope(run_eagerly)] + else: + return [] + + def parameter_modifiers(self): + return [test_combinations.OptionalParameter('run_eagerly')] + + +class KerasModelTypeCombination(test_combinations.TestCombination): + """Combination for Keras model types when doing model test. + + It by default includes 'functional', 'subclass', 'sequential'. + + Various methods in `testing_utils` to get models will auto-generate a model + of the currently active Keras model type. This allows unittests to confirm + the equivalence between different Keras models. + """ + + def context_managers(self, kwargs): + model_type = kwargs.pop('model_type', None) + if model_type in KERAS_MODEL_TYPES: + return [testing_utils.model_type_scope(model_type)] + else: + return [] + + def parameter_modifiers(self): + return [test_combinations.OptionalParameter('model_type')] + + +_defaults = combinations.generate.keywords['test_combinations'] +generate = functools.partial( + combinations.generate, + test_combinations=_defaults + + (KerasModeCombination(), KerasModelTypeCombination())) +combine = test_combinations.combine +times = test_combinations.times +NamedObject = test_combinations.NamedObject diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/constraints.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..85a38e8dc850660cf24bb217a05d45e757dff6cc --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/constraints.py @@ -0,0 +1,341 @@ +# 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. +# ============================================================================== +# pylint: disable=invalid-name +# pylint: disable=g-classes-have-attributes +"""Constraints: functions that impose constraints on weight values.""" + +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import backend +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import while_loop +from tensorflow.tools.docs import doc_controls + + +class Constraint: + """Base class for weight constraints. + + A `Constraint` instance works like a stateless function. + Users who subclass this + class should override the `__call__` method, which takes a single + weight parameter and return a projected version of that parameter + (e.g. normalized or clipped). Constraints can be used with various Keras + layers via the `kernel_constraint` or `bias_constraint` arguments. + + Here's a simple example of a non-negative weight constraint: + + >>> class NonNegative(tf.keras.constraints.Constraint): + ... + ... def __call__(self, w): + ... return w * tf.cast(tf.math.greater_equal(w, 0.), w.dtype) + + >>> weight = tf.constant((-1.0, 1.0)) + >>> NonNegative()(weight) + + + >>> tf.keras.layers.Dense(4, kernel_constraint=NonNegative()) + """ + + def __call__(self, w): + """Applies the constraint to the input weight variable. + + By default, the inputs weight variable is not modified. + Users should override this method to implement their own projection + function. + + Args: + w: Input weight variable. + + Returns: + Projected variable (by default, returns unmodified inputs). + """ + return w + + def get_config(self): + """Returns a Python dict of the object config. + + A constraint config is a Python dictionary (JSON-serializable) that can + be used to reinstantiate the same object. + + Returns: + Python dict containing the configuration of the constraint object. + """ + return {} + + +class MaxNorm(Constraint): + """MaxNorm weight constraint. + + Constrains the weights incident to each hidden unit + to have a norm less than or equal to a desired value. + + Also available via the shortcut function `tf.keras.constraints.max_norm`. + + Args: + max_value: the maximum norm value for the incoming weights. + axis: integer, axis along which to calculate weight norms. + For instance, in a `Dense` layer the weight matrix + has shape `(input_dim, output_dim)`, + set `axis` to `0` to constrain each weight vector + of length `(input_dim,)`. + In a `Conv2D` layer with `data_format="channels_last"`, + the weight tensor has shape + `(rows, cols, input_depth, output_depth)`, + set `axis` to `[0, 1, 2]` + to constrain the weights of each filter tensor of size + `(rows, cols, input_depth)`. + + """ + + def __init__(self, max_value=2, axis=0): + self.max_value = max_value + self.axis = axis + + @doc_controls.do_not_generate_docs + def __call__(self, w): + norms = backend.sqrt( + math_ops.reduce_sum(math_ops.square(w), axis=self.axis, keepdims=True)) + desired = backend.clip(norms, 0, self.max_value) + return w * (desired / (backend.epsilon() + norms)) + + @doc_controls.do_not_generate_docs + def get_config(self): + return {'max_value': self.max_value, 'axis': self.axis} + + +class NonNeg(Constraint): + """Constrains the weights to be non-negative. + + Also available via the shortcut function `tf.keras.constraints.non_neg`. + """ + + def __call__(self, w): + return w * math_ops.cast(math_ops.greater_equal(w, 0.), backend.floatx()) + + +class UnitNorm(Constraint): + """Constrains the weights incident to each hidden unit to have unit norm. + + Also available via the shortcut function `tf.keras.constraints.unit_norm`. + + Args: + axis: integer, axis along which to calculate weight norms. + For instance, in a `Dense` layer the weight matrix + has shape `(input_dim, output_dim)`, + set `axis` to `0` to constrain each weight vector + of length `(input_dim,)`. + In a `Conv2D` layer with `data_format="channels_last"`, + the weight tensor has shape + `(rows, cols, input_depth, output_depth)`, + set `axis` to `[0, 1, 2]` + to constrain the weights of each filter tensor of size + `(rows, cols, input_depth)`. + """ + + def __init__(self, axis=0): + self.axis = axis + + @doc_controls.do_not_generate_docs + def __call__(self, w): + return w / ( + backend.epsilon() + backend.sqrt( + math_ops.reduce_sum( + math_ops.square(w), axis=self.axis, keepdims=True))) + + @doc_controls.do_not_generate_docs + def get_config(self): + return {'axis': self.axis} + + +class MinMaxNorm(Constraint): + """MinMaxNorm weight constraint. + + Constrains the weights incident to each hidden unit + to have the norm between a lower bound and an upper bound. + + Also available via the shortcut function `tf.keras.constraints.min_max_norm`. + + Args: + min_value: the minimum norm for the incoming weights. + max_value: the maximum norm for the incoming weights. + rate: rate for enforcing the constraint: weights will be + rescaled to yield + `(1 - rate) * norm + rate * norm.clip(min_value, max_value)`. + Effectively, this means that rate=1.0 stands for strict + enforcement of the constraint, while rate<1.0 means that + weights will be rescaled at each step to slowly move + towards a value inside the desired interval. + axis: integer, axis along which to calculate weight norms. + For instance, in a `Dense` layer the weight matrix + has shape `(input_dim, output_dim)`, + set `axis` to `0` to constrain each weight vector + of length `(input_dim,)`. + In a `Conv2D` layer with `data_format="channels_last"`, + the weight tensor has shape + `(rows, cols, input_depth, output_depth)`, + set `axis` to `[0, 1, 2]` + to constrain the weights of each filter tensor of size + `(rows, cols, input_depth)`. + """ + + def __init__(self, min_value=0.0, max_value=1.0, rate=1.0, axis=0): + self.min_value = min_value + self.max_value = max_value + self.rate = rate + self.axis = axis + + @doc_controls.do_not_generate_docs + def __call__(self, w): + norms = backend.sqrt( + math_ops.reduce_sum(math_ops.square(w), axis=self.axis, keepdims=True)) + desired = ( + self.rate * backend.clip(norms, self.min_value, self.max_value) + + (1 - self.rate) * norms) + return w * (desired / (backend.epsilon() + norms)) + + @doc_controls.do_not_generate_docs + def get_config(self): + return { + 'min_value': self.min_value, + 'max_value': self.max_value, + 'rate': self.rate, + 'axis': self.axis + } + + +class RadialConstraint(Constraint): + """Constrains `Conv2D` kernel weights to be the same for each radius. + + Also available via the shortcut function + `tf.keras.constraints.radial_constraint`. + + For example, the desired output for the following 4-by-4 kernel: + + ``` + kernel = [[v_00, v_01, v_02, v_03], + [v_10, v_11, v_12, v_13], + [v_20, v_21, v_22, v_23], + [v_30, v_31, v_32, v_33]] + ``` + + is this:: + + ``` + kernel = [[v_11, v_11, v_11, v_11], + [v_11, v_33, v_33, v_11], + [v_11, v_33, v_33, v_11], + [v_11, v_11, v_11, v_11]] + ``` + + This constraint can be applied to any `Conv2D` layer version, including + `Conv2DTranspose` and `SeparableConv2D`, and with either `"channels_last"` or + `"channels_first"` data format. The method assumes the weight tensor is of + shape `(rows, cols, input_depth, output_depth)`. + """ + + @doc_controls.do_not_generate_docs + def __call__(self, w): + w_shape = w.shape + if w_shape.rank is None or w_shape.rank != 4: + raise ValueError( + 'The weight tensor must be of rank 4, but is of shape: %s' % w_shape) + + height, width, channels, kernels = w_shape + w = backend.reshape(w, (height, width, channels * kernels)) + # TODO(cpeter): Switch map_fn for a faster tf.vectorized_map once + # backend.switch is supported. + w = backend.map_fn( + self._kernel_constraint, + backend.stack(array_ops_stack.unstack(w, axis=-1), axis=0)) + return backend.reshape( + backend.stack(array_ops_stack.unstack(w, axis=0), axis=-1), + (height, width, channels, kernels)) + + def _kernel_constraint(self, kernel): + """Radially constraints a kernel with shape (height, width, channels).""" + padding = backend.constant([[1, 1], [1, 1]], dtype='int32') + + kernel_shape = backend.shape(kernel)[0] + start = backend.cast(kernel_shape / 2, 'int32') + + kernel_new = backend.switch( + backend.cast(math_ops.floormod(kernel_shape, 2), 'bool'), + lambda: kernel[start - 1:start, start - 1:start], + lambda: kernel[start - 1:start, start - 1:start] + backend.zeros( # pylint: disable=g-long-lambda + (2, 2), dtype=kernel.dtype)) + index = backend.switch( + backend.cast(math_ops.floormod(kernel_shape, 2), 'bool'), + lambda: backend.constant(0, dtype='int32'), + lambda: backend.constant(1, dtype='int32')) + while_condition = lambda index, *args: backend.less(index, start) + + def body_fn(i, array): + return i + 1, array_ops.pad( + array, + padding, + constant_values=kernel[start + i, start + i]) + + _, kernel_new = while_loop.while_loop( + while_condition, + body_fn, [index, kernel_new], + shape_invariants=[ + index.get_shape(), + tensor_shape.TensorShape([None, None]) + ]) + return kernel_new + + +# Aliases. + +max_norm = MaxNorm +non_neg = NonNeg +unit_norm = UnitNorm +min_max_norm = MinMaxNorm +radial_constraint = RadialConstraint + +# Legacy aliases. +maxnorm = max_norm +nonneg = non_neg +unitnorm = unit_norm + + +def serialize(constraint): + return serialize_keras_object(constraint) + + +def deserialize(config, custom_objects=None): + return deserialize_keras_object( + config, + module_objects=globals(), + custom_objects=custom_objects, + printable_module_name='constraint') + + +def get(identifier): + if identifier is None: + return None + if isinstance(identifier, dict): + return deserialize(identifier) + elif isinstance(identifier, str): + config = {'class_name': str(identifier), 'config': {}} + return deserialize(config) + elif callable(identifier): + return identifier + else: + raise ValueError('Could not interpret constraint identifier: ' + + str(identifier)) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/keras_parameterized.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/keras_parameterized.py new file mode 100644 index 0000000000000000000000000000000000000000..054df939e8e59a8212524d2bdece749ad28d59de --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/keras_parameterized.py @@ -0,0 +1,478 @@ +# 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. +# ============================================================================== +"""Utilities for unit-testing Keras.""" + +import collections +import functools +import itertools +import unittest + +from absl.testing import parameterized + +from tensorflow.python import keras +from tensorflow.python import tf2 +from tensorflow.python.eager import context +from tensorflow.python.framework import ops +from tensorflow.python.keras import testing_utils +from tensorflow.python.platform import test +from tensorflow.python.util import nest + +try: + import h5py # pylint:disable=g-import-not-at-top +except ImportError: + h5py = None + + +class TestCase(test.TestCase, parameterized.TestCase): + + def tearDown(self): + keras.backend.clear_session() + super(TestCase, self).tearDown() + + +def run_with_all_saved_model_formats( + test_or_class=None, + exclude_formats=None): + """Execute the decorated test with all Keras saved model formats). + + This decorator is intended to be applied either to individual test methods in + a `keras_parameterized.TestCase` class, or directly to a test class that + extends it. Doing so will cause the contents of the individual test + method (or all test methods in the class) to be executed multiple times - once + for each Keras saved model format. + + The Keras saved model formats include: + 1. HDF5: 'h5' + 2. SavedModel: 'tf' + + Note: if stacking this decorator with absl.testing's parameterized decorators, + those should be at the bottom of the stack. + + Various methods in `testing_utils` to get file path for saved models will + auto-generate a string of the two saved model formats. This allows unittests + to confirm the equivalence between the two Keras saved model formats. + + For example, consider the following unittest: + + ```python + class MyTests(testing_utils.KerasTestCase): + + @testing_utils.run_with_all_saved_model_formats + def test_foo(self): + save_format = testing_utils.get_save_format() + saved_model_dir = '/tmp/saved_model/' + model = keras.models.Sequential() + model.add(keras.layers.Dense(2, input_shape=(3,))) + model.add(keras.layers.Dense(3)) + model.compile(loss='mse', optimizer='sgd', metrics=['acc']) + + keras.models.save_model(model, saved_model_dir, save_format=save_format) + model = keras.models.load_model(saved_model_dir) + + if __name__ == "__main__": + tf.test.main() + ``` + + This test tries to save the model into the formats of 'hdf5', 'h5', 'keras', + 'tensorflow', and 'tf'. + + We can also annotate the whole class if we want this to apply to all tests in + the class: + ```python + @testing_utils.run_with_all_saved_model_formats + class MyTests(testing_utils.KerasTestCase): + + def test_foo(self): + save_format = testing_utils.get_save_format() + saved_model_dir = '/tmp/saved_model/' + model = keras.models.Sequential() + model.add(keras.layers.Dense(2, input_shape=(3,))) + model.add(keras.layers.Dense(3)) + model.compile(loss='mse', optimizer='sgd', metrics=['acc']) + + keras.models.save_model(model, saved_model_dir, save_format=save_format) + model = tf.keras.models.load_model(saved_model_dir) + + if __name__ == "__main__": + tf.test.main() + ``` + + Args: + test_or_class: test method or class to be annotated. If None, + this method returns a decorator that can be applied to a test method or + test class. If it is not None this returns the decorator applied to the + test or class. + exclude_formats: A collection of Keras saved model formats to not run. + (May also be a single format not wrapped in a collection). + Defaults to None. + + Returns: + Returns a decorator that will run the decorated test method multiple times: + once for each desired Keras saved model format. + + Raises: + ImportError: If abseil parameterized is not installed or not included as + a target dependency. + """ + # Exclude h5 save format if H5py isn't available. + if h5py is None: + exclude_formats.append(['h5']) + saved_model_formats = ['h5', 'tf', 'tf_no_traces'] + params = [('_%s' % saved_format, saved_format) + for saved_format in saved_model_formats + if saved_format not in nest.flatten(exclude_formats)] + + def single_method_decorator(f): + """Decorator that constructs the test cases.""" + # Use named_parameters so it can be individually run from the command line + @parameterized.named_parameters(*params) + @functools.wraps(f) + def decorated(self, saved_format, *args, **kwargs): + """A run of a single test case w/ the specified model type.""" + if saved_format == 'h5': + _test_h5_saved_model_format(f, self, *args, **kwargs) + elif saved_format == 'tf': + _test_tf_saved_model_format(f, self, *args, **kwargs) + elif saved_format == 'tf_no_traces': + _test_tf_saved_model_format_no_traces(f, self, *args, **kwargs) + else: + raise ValueError('Unknown model type: %s' % (saved_format,)) + return decorated + + return _test_or_class_decorator(test_or_class, single_method_decorator) + + +def _test_h5_saved_model_format(f, test_or_class, *args, **kwargs): + with testing_utils.saved_model_format_scope('h5'): + f(test_or_class, *args, **kwargs) + + +def _test_tf_saved_model_format(f, test_or_class, *args, **kwargs): + with testing_utils.saved_model_format_scope('tf'): + f(test_or_class, *args, **kwargs) + + +def _test_tf_saved_model_format_no_traces(f, test_or_class, *args, **kwargs): + with testing_utils.saved_model_format_scope('tf', save_traces=False): + f(test_or_class, *args, **kwargs) + + +def run_with_all_weight_formats(test_or_class=None, exclude_formats=None): + """Runs all tests with the supported formats for saving weights.""" + exclude_formats = exclude_formats or [] + exclude_formats.append('tf_no_traces') # Only applies to saving models + return run_with_all_saved_model_formats(test_or_class, exclude_formats) + + +# TODO(kaftan): Possibly enable 'subclass_custom_build' when tests begin to pass +# it. Or perhaps make 'subclass' always use a custom build method. +def run_with_all_model_types( + test_or_class=None, + exclude_models=None): + """Execute the decorated test with all Keras model types. + + This decorator is intended to be applied either to individual test methods in + a `keras_parameterized.TestCase` class, or directly to a test class that + extends it. Doing so will cause the contents of the individual test + method (or all test methods in the class) to be executed multiple times - once + for each Keras model type. + + The Keras model types are: ['functional', 'subclass', 'sequential'] + + Note: if stacking this decorator with absl.testing's parameterized decorators, + those should be at the bottom of the stack. + + Various methods in `testing_utils` to get models will auto-generate a model + of the currently active Keras model type. This allows unittests to confirm + the equivalence between different Keras models. + + For example, consider the following unittest: + + ```python + class MyTests(testing_utils.KerasTestCase): + + @testing_utils.run_with_all_model_types( + exclude_models = ['sequential']) + def test_foo(self): + model = testing_utils.get_small_mlp(1, 4, input_dim=3) + optimizer = RMSPropOptimizer(learning_rate=0.001) + loss = 'mse' + metrics = ['mae'] + model.compile(optimizer, loss, metrics=metrics) + + inputs = np.zeros((10, 3)) + targets = np.zeros((10, 4)) + dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) + dataset = dataset.repeat(100) + dataset = dataset.batch(10) + + model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) + + if __name__ == "__main__": + tf.test.main() + ``` + + This test tries building a small mlp as both a functional model and as a + subclass model. + + We can also annotate the whole class if we want this to apply to all tests in + the class: + ```python + @testing_utils.run_with_all_model_types(exclude_models = ['sequential']) + class MyTests(testing_utils.KerasTestCase): + + def test_foo(self): + model = testing_utils.get_small_mlp(1, 4, input_dim=3) + optimizer = RMSPropOptimizer(learning_rate=0.001) + loss = 'mse' + metrics = ['mae'] + model.compile(optimizer, loss, metrics=metrics) + + inputs = np.zeros((10, 3)) + targets = np.zeros((10, 4)) + dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) + dataset = dataset.repeat(100) + dataset = dataset.batch(10) + + model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) + + if __name__ == "__main__": + tf.test.main() + ``` + + + Args: + test_or_class: test method or class to be annotated. If None, + this method returns a decorator that can be applied to a test method or + test class. If it is not None this returns the decorator applied to the + test or class. + exclude_models: A collection of Keras model types to not run. + (May also be a single model type not wrapped in a collection). + Defaults to None. + + Returns: + Returns a decorator that will run the decorated test method multiple times: + once for each desired Keras model type. + + Raises: + ImportError: If abseil parameterized is not installed or not included as + a target dependency. + """ + model_types = ['functional', 'subclass', 'sequential'] + params = [('_%s' % model, model) for model in model_types + if model not in nest.flatten(exclude_models)] + + def single_method_decorator(f): + """Decorator that constructs the test cases.""" + # Use named_parameters so it can be individually run from the command line + @parameterized.named_parameters(*params) + @functools.wraps(f) + def decorated(self, model_type, *args, **kwargs): + """A run of a single test case w/ the specified model type.""" + if model_type == 'functional': + _test_functional_model_type(f, self, *args, **kwargs) + elif model_type == 'subclass': + _test_subclass_model_type(f, self, *args, **kwargs) + elif model_type == 'sequential': + _test_sequential_model_type(f, self, *args, **kwargs) + else: + raise ValueError('Unknown model type: %s' % (model_type,)) + return decorated + + return _test_or_class_decorator(test_or_class, single_method_decorator) + + +def _test_functional_model_type(f, test_or_class, *args, **kwargs): + with testing_utils.model_type_scope('functional'): + f(test_or_class, *args, **kwargs) + + +def _test_subclass_model_type(f, test_or_class, *args, **kwargs): + with testing_utils.model_type_scope('subclass'): + f(test_or_class, *args, **kwargs) + + +def _test_sequential_model_type(f, test_or_class, *args, **kwargs): + with testing_utils.model_type_scope('sequential'): + f(test_or_class, *args, **kwargs) + + +def run_all_keras_modes(test_or_class=None, + config=None, + always_skip_v1=False, + always_skip_eager=False, + **kwargs): + """Execute the decorated test with all keras execution modes. + + This decorator is intended to be applied either to individual test methods in + a `keras_parameterized.TestCase` class, or directly to a test class that + extends it. Doing so will cause the contents of the individual test + method (or all test methods in the class) to be executed multiple times - + once executing in legacy graph mode, once running eagerly and with + `should_run_eagerly` returning True, and once running eagerly with + `should_run_eagerly` returning False. + + If Tensorflow v2 behavior is enabled, legacy graph mode will be skipped, and + the test will only run twice. + + Note: if stacking this decorator with absl.testing's parameterized decorators, + those should be at the bottom of the stack. + + For example, consider the following unittest: + + ```python + class MyTests(testing_utils.KerasTestCase): + + @testing_utils.run_all_keras_modes + def test_foo(self): + model = testing_utils.get_small_functional_mlp(1, 4, input_dim=3) + optimizer = RMSPropOptimizer(learning_rate=0.001) + loss = 'mse' + metrics = ['mae'] + model.compile( + optimizer, loss, metrics=metrics, + run_eagerly=testing_utils.should_run_eagerly()) + + inputs = np.zeros((10, 3)) + targets = np.zeros((10, 4)) + dataset = dataset_ops.Dataset.from_tensor_slices((inputs, targets)) + dataset = dataset.repeat(100) + dataset = dataset.batch(10) + + model.fit(dataset, epochs=1, steps_per_epoch=2, verbose=1) + + if __name__ == "__main__": + tf.test.main() + ``` + + This test will try compiling & fitting the small functional mlp using all + three Keras execution modes. + + Args: + test_or_class: test method or class to be annotated. If None, + this method returns a decorator that can be applied to a test method or + test class. If it is not None this returns the decorator applied to the + test or class. + config: An optional config_pb2.ConfigProto to use to configure the + session when executing graphs. + always_skip_v1: If True, does not try running the legacy graph mode even + when Tensorflow v2 behavior is not enabled. + always_skip_eager: If True, does not execute the decorated test + with eager execution modes. + **kwargs: Additional kwargs for configuring tests for + in-progress Keras behaviors/ refactorings that we haven't fully + rolled out yet + + Returns: + Returns a decorator that will run the decorated test method multiple times. + + Raises: + ImportError: If abseil parameterized is not installed or not included as + a target dependency. + """ + if kwargs: + raise ValueError('Unrecognized keyword args: {}'.format(kwargs)) + + params = [('_v2_function', 'v2_function')] + if not always_skip_eager: + params.append(('_v2_eager', 'v2_eager')) + if not (always_skip_v1 or tf2.enabled()): + params.append(('_v1_session', 'v1_session')) + + def single_method_decorator(f): + """Decorator that constructs the test cases.""" + + # Use named_parameters so it can be individually run from the command line + @parameterized.named_parameters(*params) + @functools.wraps(f) + def decorated(self, run_mode, *args, **kwargs): + """A run of a single test case w/ specified run mode.""" + if run_mode == 'v1_session': + _v1_session_test(f, self, config, *args, **kwargs) + elif run_mode == 'v2_eager': + _v2_eager_test(f, self, *args, **kwargs) + elif run_mode == 'v2_function': + _v2_function_test(f, self, *args, **kwargs) + else: + return ValueError('Unknown run mode %s' % run_mode) + + return decorated + + return _test_or_class_decorator(test_or_class, single_method_decorator) + + +def _v1_session_test(f, test_or_class, config, *args, **kwargs): + with ops.get_default_graph().as_default(): + with testing_utils.run_eagerly_scope(False): + with test_or_class.test_session(config=config): + f(test_or_class, *args, **kwargs) + + +def _v2_eager_test(f, test_or_class, *args, **kwargs): + with context.eager_mode(): + with testing_utils.run_eagerly_scope(True): + f(test_or_class, *args, **kwargs) + + +def _v2_function_test(f, test_or_class, *args, **kwargs): + with context.eager_mode(): + with testing_utils.run_eagerly_scope(False): + f(test_or_class, *args, **kwargs) + + +def _test_or_class_decorator(test_or_class, single_method_decorator): + """Decorate a test or class with a decorator intended for one method. + + If the test_or_class is a class: + This will apply the decorator to all test methods in the class. + + If the test_or_class is an iterable of already-parameterized test cases: + This will apply the decorator to all the cases, and then flatten the + resulting cross-product of test cases. This allows stacking the Keras + parameterized decorators w/ each other, and to apply them to test methods + that have already been marked with an absl parameterized decorator. + + Otherwise, treat the obj as a single method and apply the decorator directly. + + Args: + test_or_class: A test method (that may have already been decorated with a + parameterized decorator, or a test class that extends + keras_parameterized.TestCase + single_method_decorator: + A parameterized decorator intended for a single test method. + Returns: + The decorated result. + """ + def _decorate_test_or_class(obj): + if isinstance(obj, collections.abc.Iterable): + return itertools.chain.from_iterable( + single_method_decorator(method) for method in obj) + if isinstance(obj, type): + cls = obj + for name, value in cls.__dict__.copy().items(): + if callable(value) and name.startswith( + unittest.TestLoader.testMethodPrefix): + setattr(cls, name, single_method_decorator(value)) + + cls = type(cls).__new__(type(cls), cls.__name__, cls.__bases__, + cls.__dict__.copy()) + return cls + + return single_method_decorator(obj) + + if test_or_class is not None: + return _decorate_test_or_class(test_or_class) + + return _decorate_test_or_class diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/losses.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..f03e7de0ed932fb0abb307e91df1a99c4c28ef43 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/losses.py @@ -0,0 +1,2106 @@ +# 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. +# ============================================================================== +# pylint: disable=g-classes-have-attributes +"""Built-in loss functions.""" + +import abc +import functools + +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import ops +from tensorflow.python.framework import smart_cond +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_spec +from tensorflow.python.framework import tensor_util +from tensorflow.python.keras import backend +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.keras.utils import tf_utils +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops.losses import losses_impl +from tensorflow.python.ops.ragged import ragged_map_ops +from tensorflow.python.ops.ragged import ragged_tensor +from tensorflow.python.ops.ragged import ragged_util +from tensorflow.python.util import dispatch +from tensorflow.tools.docs import doc_controls + + +class Loss: + """Loss base class. + + To be implemented by subclasses: + * `call()`: Contains the logic for loss calculation using `y_true`, `y_pred`. + + Example subclass implementation: + + ```python + class MeanSquaredError(Loss): + + def call(self, y_true, y_pred): + y_pred = tf.convert_to_tensor_v2(y_pred) + y_true = tf.cast(y_true, y_pred.dtype) + return tf.reduce_mean(math_ops.square(y_pred - y_true), axis=-1) + ``` + + When used with `tf.distribute.Strategy`, outside of built-in training loops + such as `tf.keras` `compile` and `fit`, please use 'SUM' or 'NONE' reduction + types, and reduce losses explicitly in your training loop. Using 'AUTO' or + 'SUM_OVER_BATCH_SIZE' will raise an error. + + Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for more + details on this. + + You can implement 'SUM_OVER_BATCH_SIZE' using global batch size like: + + ```python + with strategy.scope(): + loss_obj = tf.keras.losses.CategoricalCrossentropy( + reduction=tf.keras.losses.Reduction.NONE) + .... + loss = (tf.reduce_sum(loss_obj(labels, predictions)) * + (1. / global_batch_size)) + ``` + """ + + def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name=None): + """Initializes `Loss` class. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. + """ + losses_utils.ReductionV2.validate(reduction) + self.reduction = reduction + self.name = name + # SUM_OVER_BATCH is only allowed in losses managed by `fit` or + # CannedEstimators. + self._allow_sum_over_batch_size = False + self._set_name_scope() + + def _set_name_scope(self): + """Creates a valid `name_scope` name.""" + if self.name is None: + self._name_scope = self.__class__.__name__ + elif self.name == '': + self._name_scope = 'lambda' + else: + # E.g. '_my_loss' => 'my_loss' + self._name_scope = self.name.strip('_') + + def __call__(self, y_true, y_pred, sample_weight=None): + """Invokes the `Loss` instance. + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except + sparse loss functions such as sparse categorical crossentropy where + shape = `[batch_size, d0, .. dN-1]` + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]` + sample_weight: Optional `sample_weight` acts as a coefficient for the + loss. If a scalar is provided, then the loss is simply scaled by the + given value. If `sample_weight` is a tensor of size `[batch_size]`, then + the total loss for each sample of the batch is rescaled by the + corresponding element in the `sample_weight` vector. If the shape of + `sample_weight` is `[batch_size, d0, .. dN-1]` (or can be broadcasted to + this shape), then each loss element of `y_pred` is scaled + by the corresponding value of `sample_weight`. (Note on`dN-1`: all loss + functions reduce by 1 dimension, usually axis=-1.) + + Returns: + Weighted loss float `Tensor`. If `reduction` is `NONE`, this has + shape `[batch_size, d0, .. dN-1]`; otherwise, it is scalar. (Note `dN-1` + because all loss functions reduce by 1 dimension, usually axis=-1.) + + Raises: + ValueError: If the shape of `sample_weight` is invalid. + """ + # If we are wrapping a lambda function strip '<>' from the name as it is not + # accepted in scope name. + graph_ctx = tf_utils.graph_context_for_symbolic_tensors( + y_true, y_pred, sample_weight) + with backend.name_scope(self._name_scope), graph_ctx: + if context.executing_eagerly(): + call_fn = self.call + else: + call_fn = autograph.tf_convert(self.call, ag_ctx.control_status_ctx()) + losses = call_fn(y_true, y_pred) + return losses_utils.compute_weighted_loss( + losses, sample_weight, reduction=self._get_reduction()) + + @classmethod + def from_config(cls, config): + """Instantiates a `Loss` from its config (output of `get_config()`). + + Args: + config: Output of `get_config()`. + + Returns: + A `Loss` instance. + """ + return cls(**config) + + def get_config(self): + """Returns the config dictionary for a `Loss` instance.""" + return {'reduction': self.reduction, 'name': self.name} + + @abc.abstractmethod + @doc_controls.for_subclass_implementers + def call(self, y_true, y_pred): + """Invokes the `Loss` instance. + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`, except + sparse loss functions such as sparse categorical crossentropy where + shape = `[batch_size, d0, .. dN-1]` + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]` + + Returns: + Loss values with the shape `[batch_size, d0, .. dN-1]`. + """ + raise NotImplementedError('Must be implemented in subclasses.') + + def _get_reduction(self): + """Handles `AUTO` reduction cases and returns the reduction value.""" + if (not self._allow_sum_over_batch_size and + distribute_lib.has_strategy() and + (self.reduction == losses_utils.ReductionV2.AUTO or + self.reduction == losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE)): + raise ValueError( + 'Please use `tf.keras.losses.Reduction.SUM` or ' + '`tf.keras.losses.Reduction.NONE` for loss reduction when losses are ' + 'used with `tf.distribute.Strategy` outside of the built-in training ' + 'loops. You can implement ' + '`tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE` using global batch ' + 'size like:\n```\nwith strategy.scope():\n' + ' loss_obj = tf.keras.losses.CategoricalCrossentropy(' + 'reduction=tf.keras.losses.Reduction.NONE)\n....\n' + ' loss = tf.reduce_sum(loss_obj(labels, predictions)) * ' + '(1. / global_batch_size)\n```\nPlease see ' + 'https://www.tensorflow.org/tutorials/distribute/custom_training' + ' for more details.') + + if self.reduction == losses_utils.ReductionV2.AUTO: + return losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE + return self.reduction + + +class LossFunctionWrapper(Loss): + """Wraps a loss function in the `Loss` class.""" + + def __init__(self, + fn, + reduction=losses_utils.ReductionV2.AUTO, + name=None, + **kwargs): + """Initializes `LossFunctionWrapper` class. + + Args: + fn: The loss function to wrap, with signature `fn(y_true, y_pred, + **kwargs)`. + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. + **kwargs: The keyword arguments that are passed on to `fn`. + """ + super().__init__(reduction=reduction, name=name) + self.fn = fn + self._fn_kwargs = kwargs + + def call(self, y_true, y_pred): + """Invokes the `LossFunctionWrapper` instance. + + Args: + y_true: Ground truth values. + y_pred: The predicted values. + + Returns: + Loss values per sample. + """ + if tensor_util.is_tf_type(y_pred) and tensor_util.is_tf_type(y_true): + y_pred, y_true = losses_utils.squeeze_or_expand_dimensions(y_pred, y_true) + + ag_fn = autograph.tf_convert(self.fn, ag_ctx.control_status_ctx()) + return ag_fn(y_true, y_pred, **self._fn_kwargs) + + def get_config(self): + config = {} + for k, v in self._fn_kwargs.items(): + config[k] = backend.eval(v) if tf_utils.is_tensor_or_variable(v) else v + base_config = super().get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class MeanSquaredError(LossFunctionWrapper): + """Computes the mean of squares of errors between labels and predictions. + + `loss = square(y_true - y_pred)` + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[1., 1.], [1., 0.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> mse = tf.keras.losses.MeanSquaredError() + >>> mse(y_true, y_pred).numpy() + 0.5 + + >>> # Calling with 'sample_weight'. + >>> mse(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy() + 0.25 + + >>> # Using 'sum' reduction type. + >>> mse = tf.keras.losses.MeanSquaredError( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> mse(y_true, y_pred).numpy() + 1.0 + + >>> # Using 'none' reduction type. + >>> mse = tf.keras.losses.MeanSquaredError( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> mse(y_true, y_pred).numpy() + array([0.5, 0.5], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.MeanSquaredError()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='mean_squared_error'): + """Initializes `MeanSquaredError` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'mean_squared_error'. + """ + super().__init__(mean_squared_error, name=name, reduction=reduction) + + +class MeanAbsoluteError(LossFunctionWrapper): + """Computes the mean of absolute difference between labels and predictions. + + `loss = abs(y_true - y_pred)` + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[1., 1.], [1., 0.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> mae = tf.keras.losses.MeanAbsoluteError() + >>> mae(y_true, y_pred).numpy() + 0.5 + + >>> # Calling with 'sample_weight'. + >>> mae(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy() + 0.25 + + >>> # Using 'sum' reduction type. + >>> mae = tf.keras.losses.MeanAbsoluteError( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> mae(y_true, y_pred).numpy() + 1.0 + + >>> # Using 'none' reduction type. + >>> mae = tf.keras.losses.MeanAbsoluteError( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> mae(y_true, y_pred).numpy() + array([0.5, 0.5], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.MeanAbsoluteError()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='mean_absolute_error'): + """Initializes `MeanAbsoluteError` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'mean_absolute_error'. + """ + super().__init__(mean_absolute_error, name=name, reduction=reduction) + + +class MeanAbsolutePercentageError(LossFunctionWrapper): + """Computes the mean absolute percentage error between `y_true` and `y_pred`. + + `loss = 100 * abs(y_true - y_pred) / y_true` + + Standalone usage: + + >>> y_true = [[2., 1.], [2., 3.]] + >>> y_pred = [[1., 1.], [1., 0.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> mape = tf.keras.losses.MeanAbsolutePercentageError() + >>> mape(y_true, y_pred).numpy() + 50. + + >>> # Calling with 'sample_weight'. + >>> mape(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy() + 20. + + >>> # Using 'sum' reduction type. + >>> mape = tf.keras.losses.MeanAbsolutePercentageError( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> mape(y_true, y_pred).numpy() + 100. + + >>> # Using 'none' reduction type. + >>> mape = tf.keras.losses.MeanAbsolutePercentageError( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> mape(y_true, y_pred).numpy() + array([25., 75.], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss=tf.keras.losses.MeanAbsolutePercentageError()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='mean_absolute_percentage_error'): + """Initializes `MeanAbsolutePercentageError` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to + 'mean_absolute_percentage_error'. + """ + super().__init__( + mean_absolute_percentage_error, name=name, reduction=reduction) + + +class MeanSquaredLogarithmicError(LossFunctionWrapper): + """Computes the mean squared logarithmic error between `y_true` and `y_pred`. + + `loss = square(log(y_true + 1.) - log(y_pred + 1.))` + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[1., 1.], [1., 0.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> msle = tf.keras.losses.MeanSquaredLogarithmicError() + >>> msle(y_true, y_pred).numpy() + 0.240 + + >>> # Calling with 'sample_weight'. + >>> msle(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy() + 0.120 + + >>> # Using 'sum' reduction type. + >>> msle = tf.keras.losses.MeanSquaredLogarithmicError( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> msle(y_true, y_pred).numpy() + 0.480 + + >>> # Using 'none' reduction type. + >>> msle = tf.keras.losses.MeanSquaredLogarithmicError( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> msle(y_true, y_pred).numpy() + array([0.240, 0.240], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss=tf.keras.losses.MeanSquaredLogarithmicError()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='mean_squared_logarithmic_error'): + """Initializes `MeanSquaredLogarithmicError` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to + 'mean_squared_logarithmic_error'. + """ + super().__init__( + mean_squared_logarithmic_error, name=name, reduction=reduction) + + +class BinaryCrossentropy(LossFunctionWrapper): + """Computes the cross-entropy loss between true labels and predicted labels. + + Use this cross-entropy loss for binary (0 or 1) classification applications. + The loss function requires the following inputs: + + - `y_true` (true label): This is either 0 or 1. + - `y_pred` (predicted value): This is the model's prediction, i.e, a single + floating-point value which either represents a + [logit](https://en.wikipedia.org/wiki/Logit), (i.e, value in [-inf, inf] + when `from_logits=True`) or a probability (i.e, value in [0., 1.] when + `from_logits=False`). + + **Recommended Usage:** (set `from_logits=True`) + + With `tf.keras` API: + + ```python + model.compile( + loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), + .... + ) + ``` + + As a standalone function: + + >>> # Example 1: (batch_size = 1, number of samples = 4) + >>> y_true = [0, 1, 0, 0] + >>> y_pred = [-18.6, 0.51, 2.94, -12.8] + >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True) + >>> bce(y_true, y_pred).numpy() + 0.865 + + >>> # Example 2: (batch_size = 2, number of samples = 4) + >>> y_true = [[0, 1], [0, 0]] + >>> y_pred = [[-18.6, 0.51], [2.94, -12.8]] + >>> # Using default 'auto'/'sum_over_batch_size' reduction type. + >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True) + >>> bce(y_true, y_pred).numpy() + 0.865 + >>> # Using 'sample_weight' attribute + >>> bce(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy() + 0.243 + >>> # Using 'sum' reduction` type. + >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True, + ... reduction=tf.keras.losses.Reduction.SUM) + >>> bce(y_true, y_pred).numpy() + 1.730 + >>> # Using 'none' reduction type. + >>> bce = tf.keras.losses.BinaryCrossentropy(from_logits=True, + ... reduction=tf.keras.losses.Reduction.NONE) + >>> bce(y_true, y_pred).numpy() + array([0.235, 1.496], dtype=float32) + + **Default Usage:** (set `from_logits=False`) + + >>> # Make the following updates to the above "Recommended Usage" section + >>> # 1. Set `from_logits=False` + >>> tf.keras.losses.BinaryCrossentropy() # OR ...('from_logits=False') + >>> # 2. Update `y_pred` to use probabilities instead of logits + >>> y_pred = [0.6, 0.3, 0.2, 0.8] # OR [[0.6, 0.3], [0.2, 0.8]] + """ + + def __init__(self, + from_logits=False, + label_smoothing=0, + axis=-1, + reduction=losses_utils.ReductionV2.AUTO, + name='binary_crossentropy'): + """Initializes `BinaryCrossentropy` instance. + + Args: + from_logits: Whether to interpret `y_pred` as a tensor of + [logit](https://en.wikipedia.org/wiki/Logit) values. By default, we + assume that `y_pred` contains probabilities (i.e., values in [0, 1]). + label_smoothing: Float in [0, 1]. When 0, no smoothing occurs. When > 0, + we compute the loss between the predicted labels and a smoothed version + of the true labels, where the smoothing squeezes the labels towards 0.5. + Larger values of `label_smoothing` correspond to heavier smoothing. + axis: The axis along which to compute crossentropy (the features axis). + Defaults to -1. + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Name for the op. Defaults to 'binary_crossentropy'. + """ + super().__init__( + binary_crossentropy, + name=name, + reduction=reduction, + from_logits=from_logits, + label_smoothing=label_smoothing, + axis=axis) + self.from_logits = from_logits + + +class CategoricalCrossentropy(LossFunctionWrapper): + """Computes the crossentropy loss between the labels and predictions. + + Use this crossentropy loss function when there are two or more label classes. + We expect labels to be provided in a `one_hot` representation. If you want to + provide labels as integers, please use `SparseCategoricalCrossentropy` loss. + There should be `# classes` floating point values per feature. + + In the snippet below, there is `# classes` floating pointing values per + example. The shape of both `y_pred` and `y_true` are + `[batch_size, num_classes]`. + + Standalone usage: + + >>> y_true = [[0, 1, 0], [0, 0, 1]] + >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> cce = tf.keras.losses.CategoricalCrossentropy() + >>> cce(y_true, y_pred).numpy() + 1.177 + + >>> # Calling with 'sample_weight'. + >>> cce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy() + 0.814 + + >>> # Using 'sum' reduction type. + >>> cce = tf.keras.losses.CategoricalCrossentropy( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> cce(y_true, y_pred).numpy() + 2.354 + + >>> # Using 'none' reduction type. + >>> cce = tf.keras.losses.CategoricalCrossentropy( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> cce(y_true, y_pred).numpy() + array([0.0513, 2.303], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalCrossentropy()) + ``` + """ + + def __init__(self, + from_logits=False, + label_smoothing=0, + axis=-1, + reduction=losses_utils.ReductionV2.AUTO, + name='categorical_crossentropy'): + """Initializes `CategoricalCrossentropy` instance. + + Args: + from_logits: Whether `y_pred` is expected to be a logits tensor. By + default, we assume that `y_pred` encodes a probability distribution. + label_smoothing: Float in [0, 1]. When > 0, label values are smoothed, + meaning the confidence on label values are relaxed. For example, if + `0.1`, use `0.1 / num_classes` for non-target labels and + `0.9 + 0.1 / num_classes` for target labels. + axis: The axis along which to compute crossentropy (the features axis). + Defaults to -1. + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. + Defaults to 'categorical_crossentropy'. + """ + super().__init__( + categorical_crossentropy, + name=name, + reduction=reduction, + from_logits=from_logits, + label_smoothing=label_smoothing, + axis=axis) + + +class SparseCategoricalCrossentropy(LossFunctionWrapper): + """Computes the crossentropy loss between the labels and predictions. + + Use this crossentropy loss function when there are two or more label classes. + We expect labels to be provided as integers. If you want to provide labels + using `one-hot` representation, please use `CategoricalCrossentropy` loss. + There should be `# classes` floating point values per feature for `y_pred` + and a single floating point value per feature for `y_true`. + + In the snippet below, there is a single floating point value per example for + `y_true` and `# classes` floating pointing values per example for `y_pred`. + The shape of `y_true` is `[batch_size]` and the shape of `y_pred` is + `[batch_size, num_classes]`. + + Standalone usage: + + >>> y_true = [1, 2] + >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> scce = tf.keras.losses.SparseCategoricalCrossentropy() + >>> scce(y_true, y_pred).numpy() + 1.177 + + >>> # Calling with 'sample_weight'. + >>> scce(y_true, y_pred, sample_weight=tf.constant([0.3, 0.7])).numpy() + 0.814 + + >>> # Using 'sum' reduction type. + >>> scce = tf.keras.losses.SparseCategoricalCrossentropy( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> scce(y_true, y_pred).numpy() + 2.354 + + >>> # Using 'none' reduction type. + >>> scce = tf.keras.losses.SparseCategoricalCrossentropy( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> scce(y_true, y_pred).numpy() + array([0.0513, 2.303], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss=tf.keras.losses.SparseCategoricalCrossentropy()) + ``` + """ + + def __init__(self, + from_logits=False, + reduction=losses_utils.ReductionV2.AUTO, + name='sparse_categorical_crossentropy'): + """Initializes `SparseCategoricalCrossentropy` instance. + + Args: + from_logits: Whether `y_pred` is expected to be a logits tensor. By + default, we assume that `y_pred` encodes a probability distribution. + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to + 'sparse_categorical_crossentropy'. + """ + super().__init__( + sparse_categorical_crossentropy, + name=name, + reduction=reduction, + from_logits=from_logits) + + +class Hinge(LossFunctionWrapper): + """Computes the hinge loss between `y_true` and `y_pred`. + + `loss = maximum(1 - y_true * y_pred, 0)` + + `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are + provided we will convert them to -1 or 1. + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> h = tf.keras.losses.Hinge() + >>> h(y_true, y_pred).numpy() + 1.3 + + >>> # Calling with 'sample_weight'. + >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy() + 0.55 + + >>> # Using 'sum' reduction type. + >>> h = tf.keras.losses.Hinge( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> h(y_true, y_pred).numpy() + 2.6 + + >>> # Using 'none' reduction type. + >>> h = tf.keras.losses.Hinge( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> h(y_true, y_pred).numpy() + array([1.1, 1.5], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.Hinge()) + ``` + """ + + def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='hinge'): + """Initializes `Hinge` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'hinge'. + """ + super().__init__(hinge, name=name, reduction=reduction) + + +class SquaredHinge(LossFunctionWrapper): + """Computes the squared hinge loss between `y_true` and `y_pred`. + + `loss = square(maximum(1 - y_true * y_pred, 0))` + + `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are + provided we will convert them to -1 or 1. + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> h = tf.keras.losses.SquaredHinge() + >>> h(y_true, y_pred).numpy() + 1.86 + + >>> # Calling with 'sample_weight'. + >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy() + 0.73 + + >>> # Using 'sum' reduction type. + >>> h = tf.keras.losses.SquaredHinge( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> h(y_true, y_pred).numpy() + 3.72 + + >>> # Using 'none' reduction type. + >>> h = tf.keras.losses.SquaredHinge( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> h(y_true, y_pred).numpy() + array([1.46, 2.26], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.SquaredHinge()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='squared_hinge'): + """Initializes `SquaredHinge` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'squared_hinge'. + """ + super().__init__(squared_hinge, name=name, reduction=reduction) + + +class CategoricalHinge(LossFunctionWrapper): + """Computes the categorical hinge loss between `y_true` and `y_pred`. + + `loss = maximum(neg - pos + 1, 0)` + where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)` + + Standalone usage: + + >>> y_true = [[0, 1], [0, 0]] + >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> h = tf.keras.losses.CategoricalHinge() + >>> h(y_true, y_pred).numpy() + 1.4 + + >>> # Calling with 'sample_weight'. + >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy() + 0.6 + + >>> # Using 'sum' reduction type. + >>> h = tf.keras.losses.CategoricalHinge( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> h(y_true, y_pred).numpy() + 2.8 + + >>> # Using 'none' reduction type. + >>> h = tf.keras.losses.CategoricalHinge( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> h(y_true, y_pred).numpy() + array([1.2, 1.6], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.CategoricalHinge()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='categorical_hinge'): + """Initializes `CategoricalHinge` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'categorical_hinge'. + """ + super().__init__(categorical_hinge, name=name, reduction=reduction) + + +class Poisson(LossFunctionWrapper): + """Computes the Poisson loss between `y_true` and `y_pred`. + + `loss = y_pred - y_true * log(y_pred)` + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[1., 1.], [0., 0.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> p = tf.keras.losses.Poisson() + >>> p(y_true, y_pred).numpy() + 0.5 + + >>> # Calling with 'sample_weight'. + >>> p(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy() + 0.4 + + >>> # Using 'sum' reduction type. + >>> p = tf.keras.losses.Poisson( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> p(y_true, y_pred).numpy() + 0.999 + + >>> # Using 'none' reduction type. + >>> p = tf.keras.losses.Poisson( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> p(y_true, y_pred).numpy() + array([0.999, 0.], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.Poisson()) + ``` + """ + + def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='poisson'): + """Initializes `Poisson` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'poisson'. + """ + super().__init__(poisson, name=name, reduction=reduction) + + +class LogCosh(LossFunctionWrapper): + """Computes the logarithm of the hyperbolic cosine of the prediction error. + + `logcosh = log((exp(x) + exp(-x))/2)`, + where x is the error `y_pred - y_true`. + + Standalone usage: + + >>> y_true = [[0., 1.], [0., 0.]] + >>> y_pred = [[1., 1.], [0., 0.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> l = tf.keras.losses.LogCosh() + >>> l(y_true, y_pred).numpy() + 0.108 + + >>> # Calling with 'sample_weight'. + >>> l(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy() + 0.087 + + >>> # Using 'sum' reduction type. + >>> l = tf.keras.losses.LogCosh( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> l(y_true, y_pred).numpy() + 0.217 + + >>> # Using 'none' reduction type. + >>> l = tf.keras.losses.LogCosh( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> l(y_true, y_pred).numpy() + array([0.217, 0.], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.LogCosh()) + ``` + """ + + def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='log_cosh'): + """Initializes `LogCosh` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'log_cosh'. + """ + super().__init__(log_cosh, name=name, reduction=reduction) + + +class KLDivergence(LossFunctionWrapper): + """Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`. + + `loss = y_true * log(y_true / y_pred)` + + See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence + + Standalone usage: + + >>> y_true = [[0, 1], [0, 0]] + >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> kl = tf.keras.losses.KLDivergence() + >>> kl(y_true, y_pred).numpy() + 0.458 + + >>> # Calling with 'sample_weight'. + >>> kl(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy() + 0.366 + + >>> # Using 'sum' reduction type. + >>> kl = tf.keras.losses.KLDivergence( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> kl(y_true, y_pred).numpy() + 0.916 + + >>> # Using 'none' reduction type. + >>> kl = tf.keras.losses.KLDivergence( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> kl(y_true, y_pred).numpy() + array([0.916, -3.08e-06], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.KLDivergence()) + ``` + """ + + def __init__(self, + reduction=losses_utils.ReductionV2.AUTO, + name='kl_divergence'): + """Initializes `KLDivergence` instance. + + Args: + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'kl_divergence'. + """ + super().__init__(kl_divergence, name=name, reduction=reduction) + + +class Huber(LossFunctionWrapper): + """Computes the Huber loss between `y_true` and `y_pred`. + + For each value x in `error = y_true - y_pred`: + + ``` + loss = 0.5 * x^2 if |x| <= d + loss = 0.5 * d^2 + d * (|x| - d) if |x| > d + ``` + where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss + + Standalone usage: + + >>> y_true = [[0, 1], [0, 0]] + >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> h = tf.keras.losses.Huber() + >>> h(y_true, y_pred).numpy() + 0.155 + + >>> # Calling with 'sample_weight'. + >>> h(y_true, y_pred, sample_weight=[1, 0]).numpy() + 0.09 + + >>> # Using 'sum' reduction type. + >>> h = tf.keras.losses.Huber( + ... reduction=tf.keras.losses.Reduction.SUM) + >>> h(y_true, y_pred).numpy() + 0.31 + + >>> # Using 'none' reduction type. + >>> h = tf.keras.losses.Huber( + ... reduction=tf.keras.losses.Reduction.NONE) + >>> h(y_true, y_pred).numpy() + array([0.18, 0.13], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.Huber()) + ``` + """ + + def __init__(self, + delta=1.0, + reduction=losses_utils.ReductionV2.AUTO, + name='huber_loss'): + """Initializes `Huber` instance. + + Args: + delta: A float, the point where the Huber loss function changes from a + quadratic to linear. + reduction: Type of `tf.keras.losses.Reduction` to apply to + loss. Default value is `AUTO`. `AUTO` indicates that the reduction + option will be determined by the usage context. For almost all cases + this defaults to `SUM_OVER_BATCH_SIZE`. When used with + `tf.distribute.Strategy`, outside of built-in training loops such as + `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` + will raise an error. Please see this custom training [tutorial]( + https://www.tensorflow.org/tutorials/distribute/custom_training) for + more details. + name: Optional name for the instance. Defaults to 'huber_loss'. + """ + super().__init__(huber, name=name, reduction=reduction, delta=delta) + + +@dispatch.add_dispatch_support +def mean_squared_error(y_true, y_pred): + """Computes the mean squared error between labels and predictions. + + After computing the squared distance between the inputs, the mean value over + the last dimension is returned. + + `loss = mean(square(y_true - y_pred), axis=-1)` + + Standalone usage: + + >>> y_true = np.random.randint(0, 2, size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.mean_squared_error(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> assert np.array_equal( + ... loss.numpy(), np.mean(np.square(y_true - y_pred), axis=-1)) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Mean squared error values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + return backend.mean(math_ops.squared_difference(y_pred, y_true), axis=-1) + + +def _ragged_tensor_apply_loss(loss_fn, y_true, y_pred, y_pred_extra_dim=False): + """Apply a loss function on a per batch basis. + + Args: + loss_fn: The loss function + y_true: truth values (RaggedTensor) + y_pred: predicted values (RaggedTensor) + y_pred_extra_dim: whether y_pred has an additional dimension compared to + y_true + + Returns: + Loss-function result. A dense tensor if the output has a single dimension + (per-batch loss value); a ragged tensor otherwise. + """ + + def rt_is_equiv_dense(rt): + """Returns true if this RaggedTensor has the same row_lenghts across + + all ragged dimensions and thus can be converted to a dense tensor + without loss of information. + + Args: + rt: RaggedTensor. + """ + return math_ops.reduce_all([ + math_ops.equal( + math_ops.reduce_variance(math_ops.cast(row_lens, backend.floatx())), + constant_op.constant([0.])) for row_lens in rt.nested_row_lengths() + ]) + + def _convert_to_dense(inputs): + return tuple( + rt.to_tensor() if isinstance(rt, ragged_tensor.RaggedTensor) else rt + for rt in inputs) + + def _call_loss(inputs, ragged_output): + """ Adapt the result to ragged or dense tensor according to the expected + + output type. This is done so that all the return values of the map + operation have the same type. + """ + r = loss_fn(*inputs) + if ragged_output and not isinstance(r, ragged_tensor.RaggedTensor): + r = ragged_tensor.RaggedTensor.from_tensor(r) + elif not ragged_output and isinstance(r, ragged_tensor.RaggedTensor): + r = r.to_tensor() + return r + + def _wrapper(inputs, ragged_output): + _, y_pred = inputs + if isinstance(y_pred, ragged_tensor.RaggedTensor): + return cond.cond( + rt_is_equiv_dense(y_pred), + lambda: _call_loss(_convert_to_dense(inputs), ragged_output), + lambda: _call_loss(inputs, ragged_output)) + + return loss_fn(*inputs) + + if not isinstance(y_true, ragged_tensor.RaggedTensor): + return loss_fn(y_true, y_pred.to_tensor()) + + lshape = y_pred.shape.as_list()[1:-1] + if len(lshape) > 0: + spec = ragged_tensor.RaggedTensorSpec(shape=lshape, dtype=y_pred.dtype) + else: + spec = tensor_spec.TensorSpec(shape=[], dtype=y_pred.dtype) + + nested_splits_list = [rt.nested_row_splits for rt in (y_true, y_pred)] + if y_pred_extra_dim: + # The last dimension of a categorical prediction may be ragged or not. + rdims = [len(slist) for slist in nested_splits_list] + if rdims[0] == rdims[1] - 1: + nested_splits_list[1] = nested_splits_list[1][:-1] + + map_fn = functools.partial(_wrapper, ragged_output=len(lshape) > 1) + + assertion_list = ragged_util.assert_splits_match(nested_splits_list) + with ops.control_dependencies(assertion_list): + return ragged_map_ops.map_fn(map_fn, elems=(y_true, y_pred), dtype=spec) + + +@dispatch.dispatch_for_types(mean_squared_error, ragged_tensor.RaggedTensor) +def _ragged_tensor_mse(y_true, y_pred): + """Implements support for handling RaggedTensors. + + Args: + y_true: RaggedTensor truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: RaggedTensor predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Mean squared error values. shape = `[batch_size, d0, .. dN-1]`. + When the number of dimensions of the batch feature vector [d0, .. dN] is + greater than one the return value is a RaggedTensor. Otherwise a Dense + tensor with dimensions [batch_size] is returned. + """ + return _ragged_tensor_apply_loss(mean_squared_error, y_true, y_pred) + + +@dispatch.add_dispatch_support +def mean_absolute_error(y_true, y_pred): + """Computes the mean absolute error between labels and predictions. + + `loss = mean(abs(y_true - y_pred), axis=-1)` + + Standalone usage: + + >>> y_true = np.random.randint(0, 2, size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.mean_absolute_error(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> assert np.array_equal( + ... loss.numpy(), np.mean(np.abs(y_true - y_pred), axis=-1)) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Mean absolute error values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + return backend.mean(math_ops.abs(y_pred - y_true), axis=-1) + + +@dispatch.dispatch_for_types(mean_absolute_error, ragged_tensor.RaggedTensor) +def _ragged_tensor_mae(y_true, y_pred): + """RaggedTensor adapter for mean_absolute_error.""" + return _ragged_tensor_apply_loss(mean_absolute_error, y_true, y_pred) + + +@dispatch.add_dispatch_support +def mean_absolute_percentage_error(y_true, y_pred): + """Computes the mean absolute percentage error between `y_true` and `y_pred`. + + `loss = 100 * mean(abs((y_true - y_pred) / y_true), axis=-1)` + + Standalone usage: + + >>> y_true = np.random.random(size=(2, 3)) + >>> y_true = np.maximum(y_true, 1e-7) # Prevent division by zero + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.mean_absolute_percentage_error(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> assert np.array_equal( + ... loss.numpy(), + ... 100. * np.mean(np.abs((y_true - y_pred) / y_true), axis=-1)) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Mean absolute percentage error values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + diff = math_ops.abs( + (y_true - y_pred) / backend.maximum(math_ops.abs(y_true), + backend.epsilon())) + return 100. * backend.mean(diff, axis=-1) + + +@dispatch.dispatch_for_types(mean_absolute_percentage_error, + ragged_tensor.RaggedTensor) +def _ragged_tensor_mape(y_true, y_pred): + """Support RaggedTensors.""" + return _ragged_tensor_apply_loss(mean_absolute_percentage_error, y_true, + y_pred) + + +@dispatch.add_dispatch_support +def mean_squared_logarithmic_error(y_true, y_pred): + """Computes the mean squared logarithmic error between `y_true` and `y_pred`. + + `loss = mean(square(log(y_true + 1) - log(y_pred + 1)), axis=-1)` + + Standalone usage: + + >>> y_true = np.random.randint(0, 2, size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.mean_squared_logarithmic_error(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> y_true = np.maximum(y_true, 1e-7) + >>> y_pred = np.maximum(y_pred, 1e-7) + >>> assert np.allclose( + ... loss.numpy(), + ... np.mean( + ... np.square(np.log(y_true + 1.) - np.log(y_pred + 1.)), axis=-1)) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Mean squared logarithmic error values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + first_log = math_ops.log(backend.maximum(y_pred, backend.epsilon()) + 1.) + second_log = math_ops.log(backend.maximum(y_true, backend.epsilon()) + 1.) + return backend.mean( + math_ops.squared_difference(first_log, second_log), axis=-1) + + +@dispatch.dispatch_for_types(mean_squared_logarithmic_error, + ragged_tensor.RaggedTensor) +def _ragged_tensor_msle(y_true, y_pred): + """Implements support for handling RaggedTensors.""" + return _ragged_tensor_apply_loss(mean_squared_logarithmic_error, y_true, + y_pred) + + +def _maybe_convert_labels(y_true): + """Converts binary labels into -1/1.""" + are_zeros = math_ops.equal(y_true, 0) + are_ones = math_ops.equal(y_true, 1) + is_binary = math_ops.reduce_all(math_ops.logical_or(are_zeros, are_ones)) + + def _convert_binary_labels(): + # Convert the binary labels to -1 or 1. + return 2. * y_true - 1. + + updated_y_true = smart_cond.smart_cond(is_binary, _convert_binary_labels, + lambda: y_true) + return updated_y_true + + +@dispatch.add_dispatch_support +def squared_hinge(y_true, y_pred): + """Computes the squared hinge loss between `y_true` and `y_pred`. + + `loss = mean(square(maximum(1 - y_true * y_pred, 0)), axis=-1)` + + Standalone usage: + + >>> y_true = np.random.choice([-1, 1], size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.squared_hinge(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> assert np.array_equal( + ... loss.numpy(), + ... np.mean(np.square(np.maximum(1. - y_true * y_pred, 0.)), axis=-1)) + + Args: + y_true: The ground truth values. `y_true` values are expected to be -1 or 1. + If binary (0 or 1) labels are provided we will convert them to -1 or 1. + shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Squared hinge loss values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + y_true = _maybe_convert_labels(y_true) + return backend.mean( + math_ops.square(math_ops.maximum(1. - y_true * y_pred, 0.)), axis=-1) + + +@dispatch.add_dispatch_support +def hinge(y_true, y_pred): + """Computes the hinge loss between `y_true` and `y_pred`. + + `loss = mean(maximum(1 - y_true * y_pred, 0), axis=-1)` + + Standalone usage: + + >>> y_true = np.random.choice([-1, 1], size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.hinge(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> assert np.array_equal( + ... loss.numpy(), + ... np.mean(np.maximum(1. - y_true * y_pred, 0.), axis=-1)) + + Args: + y_true: The ground truth values. `y_true` values are expected to be -1 or 1. + If binary (0 or 1) labels are provided they will be converted to -1 or 1. + shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Hinge loss values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + y_true = _maybe_convert_labels(y_true) + return backend.mean(math_ops.maximum(1. - y_true * y_pred, 0.), axis=-1) + + +@dispatch.add_dispatch_support +def categorical_hinge(y_true, y_pred): + """Computes the categorical hinge loss between `y_true` and `y_pred`. + + `loss = maximum(neg - pos + 1, 0)` + where `neg=maximum((1-y_true)*y_pred) and pos=sum(y_true*y_pred)` + + Standalone usage: + + >>> y_true = np.random.randint(0, 3, size=(2,)) + >>> y_true = tf.keras.utils.to_categorical(y_true, num_classes=3) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.categorical_hinge(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> pos = np.sum(y_true * y_pred, axis=-1) + >>> neg = np.amax((1. - y_true) * y_pred, axis=-1) + >>> assert np.array_equal(loss.numpy(), np.maximum(0., neg - pos + 1.)) + + Args: + y_true: The ground truth values. `y_true` values are expected to be + either `{-1, +1}` or `{0, 1}` (i.e. a one-hot-encoded tensor). + y_pred: The predicted values. + + Returns: + Categorical hinge loss values. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + pos = math_ops.reduce_sum(y_true * y_pred, axis=-1) + neg = math_ops.reduce_max((1. - y_true) * y_pred, axis=-1) + zero = math_ops.cast(0., y_pred.dtype) + return math_ops.maximum(neg - pos + 1., zero) + + +@dispatch.add_dispatch_support +def huber(y_true, y_pred, delta=1.0): + """Computes Huber loss value. + + For each value x in `error = y_true - y_pred`: + + ``` + loss = 0.5 * x^2 if |x| <= d + loss = d * |x| - 0.5 * d^2 if |x| > d + ``` + where d is `delta`. See: https://en.wikipedia.org/wiki/Huber_loss + + Args: + y_true: tensor of true targets. + y_pred: tensor of predicted targets. + delta: A float, the point where the Huber loss function changes from a + quadratic to linear. + + Returns: + Tensor with one scalar loss entry per sample. + """ + y_pred = math_ops.cast(y_pred, dtype=backend.floatx()) + y_true = math_ops.cast(y_true, dtype=backend.floatx()) + delta = math_ops.cast(delta, dtype=backend.floatx()) + error = math_ops.subtract(y_pred, y_true) + abs_error = math_ops.abs(error) + half = tensor_conversion.convert_to_tensor_v2_with_dispatch( + 0.5, dtype=abs_error.dtype + ) + return backend.mean( + array_ops.where_v2(abs_error <= delta, half * math_ops.square(error), + delta * abs_error - half * math_ops.square(delta)), + axis=-1) + + +@dispatch.add_dispatch_support +def log_cosh(y_true, y_pred): + """Logarithm of the hyperbolic cosine of the prediction error. + + `log(cosh(x))` is approximately equal to `(x ** 2) / 2` for small `x` and + to `abs(x) - log(2)` for large `x`. This means that 'logcosh' works mostly + like the mean squared error, but will not be so strongly affected by the + occasional wildly incorrect prediction. + + Standalone usage: + + >>> y_true = np.random.random(size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.logcosh(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> x = y_pred - y_true + >>> assert np.allclose( + ... loss.numpy(), + ... np.mean(x + np.log(np.exp(-2. * x) + 1.) - math_ops.log(2.), axis=-1), + ... atol=1e-5) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Logcosh error values. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + + def _logcosh(x): + return x + math_ops.softplus(-2. * x) - math_ops.cast( + math_ops.log(2.), x.dtype) + + return backend.mean(_logcosh(y_pred - y_true), axis=-1) + + +@dispatch.add_dispatch_support +def categorical_crossentropy(y_true, + y_pred, + from_logits=False, + label_smoothing=0, + axis=-1): + """Computes the categorical crossentropy loss. + + Standalone usage: + + >>> y_true = [[0, 1, 0], [0, 0, 1]] + >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]] + >>> loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> loss.numpy() + array([0.0513, 2.303], dtype=float32) + + Args: + y_true: Tensor of one-hot true targets. + y_pred: Tensor of predicted targets. + from_logits: Whether `y_pred` is expected to be a logits tensor. By default, + we assume that `y_pred` encodes a probability distribution. + label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. For + example, if `0.1`, use `0.1 / num_classes` for non-target labels + and `0.9 + 0.1 / num_classes` for target labels. + axis: Defaults to -1. The dimension along which the entropy is + computed. + + Returns: + Categorical crossentropy loss value. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + label_smoothing = tensor_conversion.convert_to_tensor_v2_with_dispatch( + label_smoothing, dtype=backend.floatx() + ) + + def _smooth_labels(): + num_classes = math_ops.cast(array_ops.shape(y_true)[-1], y_pred.dtype) + return y_true * (1.0 - label_smoothing) + (label_smoothing / num_classes) + + y_true = smart_cond.smart_cond(label_smoothing, _smooth_labels, + lambda: y_true) + + return backend.categorical_crossentropy( + y_true, y_pred, from_logits=from_logits, axis=axis) + + +@dispatch.dispatch_for_types(categorical_crossentropy, + ragged_tensor.RaggedTensor) +def _ragged_tensor_categorical_crossentropy(y_true, + y_pred, + from_logits=False, + label_smoothing=0, + axis=-1): + """Implements support for handling RaggedTensors. + + Args: + y_true: Tensor of one-hot true targets. + y_pred: Tensor of predicted targets. + from_logits: Whether `y_pred` is expected to be a logits tensor. By default, + we assume that `y_pred` encodes a probability distribution. + label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. For + example, if `0.1`, use `0.1 / num_classes` for non-target labels + and `0.9 + 0.1 / num_classes` for target labels. + axis: The axis along which to compute crossentropy (the features axis). + Defaults to -1. + + Returns: + Categorical crossentropy loss value. + + Expected shape: (batch, sequence_len, n_classes) with sequence_len + being variable per batch. + Return shape: (batch, sequence_len). + + When used by CategoricalCrossentropy() with the default reduction + (SUM_OVER_BATCH_SIZE), the reduction averages the loss over the + number of elements independent of the batch. E.g. if the RaggedTensor + has 2 batches with [2, 1] values respectivly the resulting loss is + the sum of the individual loss values divided by 3. + """ + fn = functools.partial( + categorical_crossentropy, + from_logits=from_logits, + label_smoothing=label_smoothing, + axis=axis) + return _ragged_tensor_apply_loss(fn, y_true, y_pred) + + +@dispatch.add_dispatch_support +def sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1): + """Computes the sparse categorical crossentropy loss. + + Standalone usage: + + >>> y_true = [1, 2] + >>> y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]] + >>> loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> loss.numpy() + array([0.0513, 2.303], dtype=float32) + + Args: + y_true: Ground truth values. + y_pred: The predicted values. + from_logits: Whether `y_pred` is expected to be a logits tensor. By default, + we assume that `y_pred` encodes a probability distribution. + axis: Defaults to -1. The dimension along which the entropy is + computed. + + Returns: + Sparse categorical crossentropy loss value. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + return backend.sparse_categorical_crossentropy( + y_true, y_pred, from_logits=from_logits, axis=axis) + + +@dispatch.dispatch_for_types(sparse_categorical_crossentropy, + ragged_tensor.RaggedTensor) +def _ragged_tensor_sparse_categorical_crossentropy(y_true, + y_pred, + from_logits=False, + axis=-1): + """ Implements support for handling RaggedTensors. + + Expected y_pred shape: (batch, sequence_len, n_classes) with sequence_len + being variable per batch. + Return shape: (batch, sequence_len). + + When used by SparseCategoricalCrossentropy() with the default reduction + (SUM_OVER_BATCH_SIZE), the reduction averages the loss over the + number of elements independent of the batch. E.g. if the RaggedTensor + has 2 batches with [2, 1] values respectively, the resulting loss is + the sum of the individual loss values divided by 3. + """ + fn = functools.partial( + sparse_categorical_crossentropy, from_logits=from_logits, axis=axis) + return _ragged_tensor_apply_loss(fn, y_true, y_pred, y_pred_extra_dim=True) + + +@dispatch.add_dispatch_support +def binary_crossentropy(y_true, + y_pred, + from_logits=False, + label_smoothing=0, + axis=-1): + """Computes the binary crossentropy loss. + + Standalone usage: + + >>> y_true = [[0, 1], [0, 0]] + >>> y_pred = [[0.6, 0.4], [0.4, 0.6]] + >>> loss = tf.keras.losses.binary_crossentropy(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> loss.numpy() + array([0.916 , 0.714], dtype=float32) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + from_logits: Whether `y_pred` is expected to be a logits tensor. By default, + we assume that `y_pred` encodes a probability distribution. + label_smoothing: Float in [0, 1]. If > `0` then smooth the labels by + squeezing them towards 0.5 That is, using `1. - 0.5 * label_smoothing` + for the target class and `0.5 * label_smoothing` for the non-target class. + axis: The axis along which the mean is computed. Defaults to -1. + + Returns: + Binary crossentropy loss value. shape = `[batch_size, d0, .. dN-1]`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + label_smoothing = tensor_conversion.convert_to_tensor_v2_with_dispatch( + label_smoothing, dtype=backend.floatx() + ) + + def _smooth_labels(): + return y_true * (1.0 - label_smoothing) + 0.5 * label_smoothing + + y_true = smart_cond.smart_cond(label_smoothing, _smooth_labels, + lambda: y_true) + + return backend.mean( + backend.binary_crossentropy(y_true, y_pred, from_logits=from_logits), + axis=axis) + + +@dispatch.dispatch_for_types(binary_crossentropy, ragged_tensor.RaggedTensor) +def _ragged_tensor_binary_crossentropy(y_true, + y_pred, + from_logits=False, + label_smoothing=0, + axis=-1): + """Implements support for handling RaggedTensors. + + Args: + y_true: Tensor of one-hot true targets. + y_pred: Tensor of predicted targets. + from_logits: Whether `y_pred` is expected to be a logits tensor. By default, + we assume that `y_pred` encodes a probability distribution. + label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. For + example, if `0.1`, use `0.1 / num_classes` for non-target labels + and `0.9 + 0.1 / num_classes` for target labels. + axis: Axis along which to compute crossentropy. + + Returns: + Binary crossentropy loss value. + + Expected shape: (batch, sequence_len) with sequence_len being variable + per batch. + Return shape: (batch,); returns the per batch mean of the loss values. + + When used by BinaryCrossentropy() with the default reduction + (SUM_OVER_BATCH_SIZE), the reduction averages the per batch losses over + the number of batches. + """ + fn = functools.partial( + binary_crossentropy, + from_logits=from_logits, + label_smoothing=label_smoothing, + axis=axis) + return _ragged_tensor_apply_loss(fn, y_true, y_pred) + + +@dispatch.add_dispatch_support +def kl_divergence(y_true, y_pred): + """Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`. + + `loss = y_true * log(y_true / y_pred)` + + See: https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence + + Standalone usage: + + >>> y_true = np.random.randint(0, 2, size=(2, 3)).astype(np.float64) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.kullback_leibler_divergence(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> y_true = tf.keras.backend.clip(y_true, 1e-7, 1) + >>> y_pred = tf.keras.backend.clip(y_pred, 1e-7, 1) + >>> assert np.array_equal( + ... loss.numpy(), np.sum(y_true * np.log(y_true / y_pred), axis=-1)) + + Args: + y_true: Tensor of true targets. + y_pred: Tensor of predicted targets. + + Returns: + A `Tensor` with loss. + + Raises: + TypeError: If `y_true` cannot be cast to the `y_pred.dtype`. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + y_true = backend.clip(y_true, backend.epsilon(), 1) + y_pred = backend.clip(y_pred, backend.epsilon(), 1) + return math_ops.reduce_sum(y_true * math_ops.log(y_true / y_pred), axis=-1) + + +@dispatch.add_dispatch_support +def poisson(y_true, y_pred): + """Computes the Poisson loss between y_true and y_pred. + + The Poisson loss is the mean of the elements of the `Tensor` + `y_pred - y_true * log(y_pred)`. + + Standalone usage: + + >>> y_true = np.random.randint(0, 2, size=(2, 3)) + >>> y_pred = np.random.random(size=(2, 3)) + >>> loss = tf.keras.losses.poisson(y_true, y_pred) + >>> assert loss.shape == (2,) + >>> y_pred = y_pred + 1e-7 + >>> assert np.allclose( + ... loss.numpy(), np.mean(y_pred - y_true * np.log(y_pred), axis=-1), + ... atol=1e-5) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + + Returns: + Poisson loss value. shape = `[batch_size, d0, .. dN-1]`. + + Raises: + InvalidArgumentError: If `y_true` and `y_pred` have incompatible shapes. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = math_ops.cast(y_true, y_pred.dtype) + return backend.mean( + y_pred - y_true * math_ops.log(y_pred + backend.epsilon()), axis=-1) + + +@dispatch.add_dispatch_support +def cosine_similarity(y_true, y_pred, axis=-1): + """Computes the cosine similarity between labels and predictions. + + Note that it is a number between -1 and 1. When it is a negative number + between -1 and 0, 0 indicates orthogonality and values closer to -1 + indicate greater similarity. The values closer to 1 indicate greater + dissimilarity. This makes it usable as a loss function in a setting + where you try to maximize the proximity between predictions and + targets. If either `y_true` or `y_pred` is a zero vector, cosine + similarity will be 0 regardless of the proximity between predictions + and targets. + + `loss = -sum(l2_norm(y_true) * l2_norm(y_pred))` + + Standalone usage: + + >>> y_true = [[0., 1.], [1., 1.], [1., 1.]] + >>> y_pred = [[1., 0.], [1., 1.], [-1., -1.]] + >>> loss = tf.keras.losses.cosine_similarity(y_true, y_pred, axis=1) + >>> loss.numpy() + array([-0., -0.999, 0.999], dtype=float32) + + Args: + y_true: Tensor of true targets. + y_pred: Tensor of predicted targets. + axis: Axis along which to determine similarity. + + Returns: + Cosine similarity tensor. + """ + y_true = nn.l2_normalize(y_true, axis=axis) + y_pred = nn.l2_normalize(y_pred, axis=axis) + return -math_ops.reduce_sum(y_true * y_pred, axis=axis) + + +class CosineSimilarity(LossFunctionWrapper): + """Computes the cosine similarity between labels and predictions. + + Note that it is a number between -1 and 1. When it is a negative number + between -1 and 0, 0 indicates orthogonality and values closer to -1 + indicate greater similarity. The values closer to 1 indicate greater + dissimilarity. This makes it usable as a loss function in a setting + where you try to maximize the proximity between predictions and targets. + If either `y_true` or `y_pred` is a zero vector, cosine similarity will be 0 + regardless of the proximity between predictions and targets. + + `loss = -sum(l2_norm(y_true) * l2_norm(y_pred))` + + Standalone usage: + + >>> y_true = [[0., 1.], [1., 1.]] + >>> y_pred = [[1., 0.], [1., 1.]] + >>> # Using 'auto'/'sum_over_batch_size' reduction type. + >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1) + >>> # l2_norm(y_true) = [[0., 1.], [1./1.414, 1./1.414]] + >>> # l2_norm(y_pred) = [[1., 0.], [1./1.414, 1./1.414]] + >>> # l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]] + >>> # loss = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1)) + >>> # = -((0. + 0.) + (0.5 + 0.5)) / 2 + >>> cosine_loss(y_true, y_pred).numpy() + -0.5 + + >>> # Calling with 'sample_weight'. + >>> cosine_loss(y_true, y_pred, sample_weight=[0.8, 0.2]).numpy() + -0.0999 + + >>> # Using 'sum' reduction type. + >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1, + ... reduction=tf.keras.losses.Reduction.SUM) + >>> cosine_loss(y_true, y_pred).numpy() + -0.999 + + >>> # Using 'none' reduction type. + >>> cosine_loss = tf.keras.losses.CosineSimilarity(axis=1, + ... reduction=tf.keras.losses.Reduction.NONE) + >>> cosine_loss(y_true, y_pred).numpy() + array([-0., -0.999], dtype=float32) + + Usage with the `compile()` API: + + ```python + model.compile(optimizer='sgd', loss=tf.keras.losses.CosineSimilarity(axis=1)) + ``` + + Args: + axis: The axis along which the cosine similarity is computed + (the features axis). Defaults to -1. + reduction: Type of `tf.keras.losses.Reduction` to apply to loss. + Default value is `AUTO`. `AUTO` indicates that the reduction option will + be determined by the usage context. For almost all cases this defaults to + `SUM_OVER_BATCH_SIZE`. When used with `tf.distribute.Strategy`, outside of + built-in training loops such as `tf.keras` `compile` and `fit`, using + `AUTO` or `SUM_OVER_BATCH_SIZE` will raise an error. Please see this + custom training [tutorial] + (https://www.tensorflow.org/tutorials/distribute/custom_training) for more + details. + name: Optional name for the instance. + """ + + def __init__(self, + axis=-1, + reduction=losses_utils.ReductionV2.AUTO, + name='cosine_similarity'): + super().__init__( + cosine_similarity, reduction=reduction, name=name, axis=axis) + + +# Aliases. + +bce = BCE = binary_crossentropy +mse = MSE = mean_squared_error +mae = MAE = mean_absolute_error +mape = MAPE = mean_absolute_percentage_error +msle = MSLE = mean_squared_logarithmic_error +kld = KLD = kullback_leibler_divergence = kl_divergence +logcosh = log_cosh +huber_loss = huber + + +def is_categorical_crossentropy(loss): + result = ((isinstance(loss, CategoricalCrossentropy) or + (isinstance(loss, LossFunctionWrapper) and + loss.fn == categorical_crossentropy) or + (hasattr(loss, '__name__') and + loss.__name__ == 'categorical_crossentropy') or + (loss == 'categorical_crossentropy'))) + return result + + +def serialize(loss): + """Serializes loss function or `Loss` instance. + + Args: + loss: A Keras `Loss` instance or a loss function. + + Returns: + Loss configuration dictionary. + """ + return serialize_keras_object(loss) + + +def deserialize(name, custom_objects=None): + """Deserializes a serialized loss class/function instance. + + Args: + name: Loss configuration. + custom_objects: Optional dictionary mapping names (strings) to custom + objects (classes and functions) to be considered during deserialization. + + Returns: + A Keras `Loss` instance or a loss function. + """ + return deserialize_keras_object( + name, + module_objects=globals(), + custom_objects=custom_objects, + printable_module_name='loss function') + + +def get(identifier): + """Retrieves a Keras loss as a `function`/`Loss` class instance. + + The `identifier` may be the string name of a loss function or `Loss` class. + + >>> loss = tf.keras.losses.get("categorical_crossentropy") + >>> type(loss) + + >>> loss = tf.keras.losses.get("CategoricalCrossentropy") + >>> type(loss) + + + You can also specify `config` of the loss to this function by passing dict + containing `class_name` and `config` as an identifier. Also note that the + `class_name` must map to a `Loss` class + + >>> identifier = {"class_name": "CategoricalCrossentropy", + ... "config": {"from_logits": True}} + >>> loss = tf.keras.losses.get(identifier) + >>> type(loss) + + + Args: + identifier: A loss identifier. One of None or string name of a loss + function/class or loss configuration dictionary or a loss function or a + loss class instance. + + Returns: + A Keras loss as a `function`/ `Loss` class instance. + + Raises: + ValueError: If `identifier` cannot be interpreted. + """ + if identifier is None: + return None + if isinstance(identifier, str): + identifier = str(identifier) + return deserialize(identifier) + if isinstance(identifier, dict): + return deserialize(identifier) + if callable(identifier): + return identifier + raise ValueError( + f'Could not interpret loss function identifier: {identifier}') + + +LABEL_DTYPES_FOR_LOSSES = { + losses_impl.sparse_softmax_cross_entropy: 'int32', + sparse_categorical_crossentropy: 'int32' +} diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/metrics.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..96e63a57d4d2061da4ba72e9b17aebe927438c3a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/metrics.py @@ -0,0 +1,3660 @@ +# 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. +# ============================================================================== +# pylint: disable=g-classes-have-attributes +# pylint: disable=g-doc-return-or-yield +"""Built-in metrics.""" + +import abc +import types +import warnings + +import numpy as np + +from tensorflow.python.autograph.core import ag_ctx +from tensorflow.python.autograph.impl import api as autograph +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_conversion +from tensorflow.python.framework import tensor_shape +from tensorflow.python.keras import activations +from tensorflow.python.keras import backend +from tensorflow.python.keras.engine import base_layer +from tensorflow.python.keras.engine import base_layer_utils +from tensorflow.python.keras.engine import keras_tensor +from tensorflow.python.keras.losses import binary_crossentropy +from tensorflow.python.keras.losses import categorical_crossentropy +from tensorflow.python.keras.losses import categorical_hinge +from tensorflow.python.keras.losses import hinge +from tensorflow.python.keras.losses import kullback_leibler_divergence +from tensorflow.python.keras.losses import logcosh +from tensorflow.python.keras.losses import mean_absolute_error +from tensorflow.python.keras.losses import mean_absolute_percentage_error +from tensorflow.python.keras.losses import mean_squared_error +from tensorflow.python.keras.losses import mean_squared_logarithmic_error +from tensorflow.python.keras.losses import poisson +from tensorflow.python.keras.losses import sparse_categorical_crossentropy +from tensorflow.python.keras.losses import squared_hinge +from tensorflow.python.keras.saving.saved_model import metric_serialization +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import losses_utils +from tensorflow.python.keras.utils import metrics_utils +from tensorflow.python.keras.utils.generic_utils import deserialize_keras_object +from tensorflow.python.keras.utils.generic_utils import serialize_keras_object +from tensorflow.python.keras.utils.generic_utils import to_list +from tensorflow.python.keras.utils.tf_utils import is_tensor_or_variable +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.ops import confusion_matrix +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn +from tensorflow.python.ops import variables as variables_module +from tensorflow.python.ops import weights_broadcast_ops +from tensorflow.python.util import dispatch +from tensorflow.python.util import nest +from tensorflow.tools.docs import doc_controls + + +class Metric(base_layer.Layer, metaclass=abc.ABCMeta): + """Encapsulates metric logic and state. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + **kwargs: Additional layer keywords arguments. + + Standalone usage: + + ```python + m = SomeMetric(...) + for input in ...: + m.update_state(input) + print('Final result: ', m.result().numpy()) + ``` + + Usage with `compile()` API: + + ```python + model = tf.keras.Sequential() + model.add(tf.keras.layers.Dense(64, activation='relu')) + model.add(tf.keras.layers.Dense(64, activation='relu')) + model.add(tf.keras.layers.Dense(10, activation='softmax')) + + model.compile(optimizer=tf.keras.optimizers.RMSprop(0.01), + loss=tf.keras.losses.CategoricalCrossentropy(), + metrics=[tf.keras.metrics.CategoricalAccuracy()]) + + data = np.random.random((1000, 32)) + labels = np.random.random((1000, 10)) + + dataset = tf.data.Dataset.from_tensor_slices((data, labels)) + dataset = dataset.batch(32) + + model.fit(dataset, epochs=10) + ``` + + To be implemented by subclasses: + * `__init__()`: All state variables should be created in this method by + calling `self.add_weight()` like: `self.var = self.add_weight(...)` + * `update_state()`: Has all updates to the state variables like: + self.var.assign_add(...). + * `result()`: Computes and returns a value for the metric + from the state variables. + + Example subclass implementation: + + ```python + class BinaryTruePositives(tf.keras.metrics.Metric): + + def __init__(self, name='binary_true_positives', **kwargs): + super(BinaryTruePositives, self).__init__(name=name, **kwargs) + self.true_positives = self.add_weight(name='tp', initializer='zeros') + + def update_state(self, y_true, y_pred, sample_weight=None): + y_true = tf.cast(y_true, tf.bool) + y_pred = tf.cast(y_pred, tf.bool) + + values = tf.logical_and(tf.equal(y_true, True), tf.equal(y_pred, True)) + values = tf.cast(values, self.dtype) + if sample_weight is not None: + sample_weight = tf.cast(sample_weight, self.dtype) + sample_weight = tf.broadcast_to(sample_weight, values.shape) + values = tf.multiply(values, sample_weight) + self.true_positives.assign_add(tf.reduce_sum(values)) + + def result(self): + return self.true_positives + ``` + """ + + def __init__(self, name=None, dtype=None, **kwargs): + super(Metric, self).__init__(name=name, dtype=dtype, **kwargs) + self.stateful = True # All metric layers are stateful. + self.built = True + if not base_layer_utils.v2_dtype_behavior_enabled(): + # We only do this when the V2 behavior is not enabled, as when it is + # enabled, the dtype already defaults to floatx. + self._dtype = (backend.floatx() if dtype is None + else dtypes.as_dtype(dtype).name) + + def __new__(cls, *args, **kwargs): + obj = super(Metric, cls).__new__(cls) + + # If `update_state` is not in eager/tf.function and it is not from a + # built-in metric, wrap it in `tf.function`. This is so that users writing + # custom metrics in v1 need not worry about control dependencies and + # return ops. + if (base_layer_utils.is_in_eager_or_tf_function() or + is_built_in(cls)): + obj_update_state = obj.update_state + + def update_state_fn(*args, **kwargs): + control_status = ag_ctx.control_status_ctx() + ag_update_state = autograph.tf_convert(obj_update_state, control_status) + return ag_update_state(*args, **kwargs) + else: + if isinstance(obj.update_state, def_function.Function): + update_state_fn = obj.update_state + else: + update_state_fn = def_function.function(obj.update_state) + + obj.update_state = types.MethodType( + metrics_utils.update_state_wrapper(update_state_fn), obj) + + obj_result = obj.result + + def result_fn(*args, **kwargs): + control_status = ag_ctx.control_status_ctx() + ag_result = autograph.tf_convert(obj_result, control_status) + return ag_result(*args, **kwargs) + + obj.result = types.MethodType(metrics_utils.result_wrapper(result_fn), obj) + + return obj + + def __call__(self, *args, **kwargs): + """Accumulates statistics and then computes metric result value. + + Args: + *args: + **kwargs: A mini-batch of inputs to the Metric, + passed on to `update_state()`. + + Returns: + The metric value tensor. + """ + + def replica_local_fn(*args, **kwargs): + """Updates the state of the metric in a replica-local context.""" + if any( + isinstance(arg, keras_tensor.KerasTensor) + for arg in nest.flatten((args, kwargs))): + update_op = None + else: + update_op = self.update_state(*args, **kwargs) # pylint: disable=not-callable + update_ops = [] + if update_op is not None: + update_ops.append(update_op) + with ops.control_dependencies(update_ops): + result_t = self.result() # pylint: disable=not-callable + + # We are adding the metric object as metadata on the result tensor. + # This is required when we want to use a metric with `add_metric` API on + # a Model/Layer in graph mode. This metric instance will later be used + # to reset variable state after each epoch of training. + # Example: + # model = Model() + # mean = Mean() + # model.add_metric(mean(values), name='mean') + result_t._metric_obj = self # pylint: disable=protected-access + return result_t + + from tensorflow.python.keras.distribute import distributed_training_utils # pylint:disable=g-import-not-at-top + return distributed_training_utils.call_replica_local_fn( + replica_local_fn, *args, **kwargs) + + @property + def dtype(self): + return self._dtype + + def get_config(self): + """Returns the serializable config of the metric.""" + return {'name': self.name, 'dtype': self.dtype} + + def reset_state(self): + """Resets all of the metric state variables. + + This function is called between epochs/steps, + when a metric is evaluated during training. + """ + if not generic_utils.is_default(self.reset_states): + warnings.warn('Metric %s implements a `reset_states()` method; rename it ' + 'to `reset_state()` (without the final "s"). The name ' + '`reset_states()` has been deprecated to improve API ' + 'consistency.' % (self.__class__.__name__,)) + return self.reset_states() + else: + backend.batch_set_value([(v, 0) for v in self.variables]) + + @abc.abstractmethod + def update_state(self, *args, **kwargs): + """Accumulates statistics for the metric. + + Note: This function is executed as a graph function in graph mode. + This means: + a) Operations on the same resource are executed in textual order. + This should make it easier to do things like add the updated + value of a variable to another, for example. + b) You don't need to worry about collecting the update ops to execute. + All update ops added to the graph by this function will be executed. + As a result, code should generally work the same way with graph or + eager execution. + + Args: + *args: + **kwargs: A mini-batch of inputs to the Metric. + """ + raise NotImplementedError('Must be implemented in subclasses.') + + @abc.abstractmethod + def result(self): + """Computes and returns the metric value tensor. + + Result computation is an idempotent operation that simply calculates the + metric value using the state variables. + """ + raise NotImplementedError('Must be implemented in subclasses.') + + ### For use by subclasses ### + @doc_controls.for_subclass_implementers + def add_weight( + self, + name, + shape=(), + aggregation=variables_module.VariableAggregation.SUM, + synchronization=variables_module.VariableSynchronization.ON_READ, + initializer=None, + dtype=None): + """Adds state variable. Only for use by subclasses.""" + if distribute_lib.has_strategy(): + strategy = distribute_lib.get_strategy() + else: + strategy = None + + # TODO(b/120571621): Make `ON_READ` work with Keras metrics on TPU. + if backend.is_tpu_strategy(strategy): + synchronization = variables_module.VariableSynchronization.ON_WRITE + + with ops.init_scope(): + return super(Metric, self).add_weight( + name=name, + shape=shape, + dtype=self._dtype if dtype is None else dtype, + trainable=False, + initializer=initializer, + collections=[], + synchronization=synchronization, + aggregation=aggregation) + + ### End: For use by subclasses ### + + @property + def trainable_weights(self): + # Overridden from Layer class to track submetric weights. + if self.trainable: + trainable_weights = self._trainable_weights + for m in self._metrics: + trainable_weights += m.trainable_weights + return self._dedup_weights(trainable_weights) + else: + return [] + + @property + def non_trainable_weights(self): + # Overridden from Layer class to track submetric weights. + if self.trainable: + non_trainable_weights = self._non_trainable_weights + for m in self._metrics: + non_trainable_weights += m.non_trainable_weights + else: + non_trainable_weights = ( + self._non_trainable_weights + self._trainable_weights) + for m in self._metrics: + non_trainable_weights += m.weights + return self._dedup_weights(non_trainable_weights) + + @property + def _trackable_saved_model_saver(self): + return metric_serialization.MetricSavedModelSaver(self) + + @generic_utils.default + @doc_controls.do_not_generate_docs + def reset_states(self): + # Backwards compatibility alias of `reset_state`. New classes should + # only implement `reset_state`. + return self.reset_state() + + +class Reduce(Metric): + """Encapsulates metrics that perform a reduce operation on the values. + + Args: + reduction: a `tf.keras.metrics.Reduction` enum value. + name: string name of the metric instance. + dtype: (Optional) data type of the metric result. + """ + + def __init__(self, reduction, name, dtype=None): + super(Reduce, self).__init__(name=name, dtype=dtype) + self.reduction = reduction + self.total = self.add_weight( + 'total', initializer=init_ops.zeros_initializer) + if reduction in [metrics_utils.Reduction.SUM_OVER_BATCH_SIZE, + metrics_utils.Reduction.WEIGHTED_MEAN]: + self.count = self.add_weight( + 'count', initializer=init_ops.zeros_initializer) + + def update_state(self, values, sample_weight=None): + """Accumulates statistics for computing the metric. + + Args: + values: Per-example value. + sample_weight: Optional weighting of each example. Defaults to 1. + + Returns: + Update op. + """ + [values], sample_weight = \ + metrics_utils.ragged_assert_compatible_and_get_flat_values( + [values], sample_weight) + try: + values = math_ops.cast(values, self._dtype) + except (ValueError, TypeError): + msg = ('The output of a metric function can only be a single Tensor. ' + 'Got: %s' % (values,)) + if isinstance(values, dict): + msg += ('. To return a dict of values, implement a custom Metric ' + 'subclass.') + raise RuntimeError(msg) + if sample_weight is not None: + sample_weight = math_ops.cast(sample_weight, self._dtype) + # Update dimensions of weights to match with values if possible. + values, _, sample_weight = losses_utils.squeeze_or_expand_dimensions( + values, sample_weight=sample_weight) + try: + # Broadcast weights if possible. + sample_weight = weights_broadcast_ops.broadcast_weights( + sample_weight, values) + except ValueError: + # Reduce values to same ndim as weight array + ndim = backend.ndim(values) + weight_ndim = backend.ndim(sample_weight) + if self.reduction == metrics_utils.Reduction.SUM: + values = math_ops.reduce_sum( + values, axis=list(range(weight_ndim, ndim))) + else: + values = math_ops.reduce_mean( + values, axis=list(range(weight_ndim, ndim))) + values = math_ops.multiply(values, sample_weight) + + value_sum = math_ops.reduce_sum(values) + with ops.control_dependencies([value_sum]): + update_total_op = self.total.assign_add(value_sum) + + # Exit early if the reduction doesn't have a denominator. + if self.reduction == metrics_utils.Reduction.SUM: + return update_total_op + + # Update `count` for reductions that require a denominator. + if self.reduction == metrics_utils.Reduction.SUM_OVER_BATCH_SIZE: + num_values = math_ops.cast(array_ops.size(values), self._dtype) + elif self.reduction == metrics_utils.Reduction.WEIGHTED_MEAN: + if sample_weight is None: + num_values = math_ops.cast(array_ops.size(values), self._dtype) + else: + num_values = math_ops.reduce_sum(sample_weight) + else: + raise NotImplementedError( + 'reduction [%s] not implemented' % self.reduction) + + with ops.control_dependencies([update_total_op]): + return self.count.assign_add(num_values) + + def result(self): + if self.reduction == metrics_utils.Reduction.SUM: + return array_ops.identity(self.total) + elif self.reduction in [ + metrics_utils.Reduction.WEIGHTED_MEAN, + metrics_utils.Reduction.SUM_OVER_BATCH_SIZE + ]: + return math_ops.div_no_nan(self.total, self.count) + else: + raise NotImplementedError( + 'reduction [%s] not implemented' % self.reduction) + + +class Sum(Reduce): + """Computes the (weighted) sum of the given values. + + For example, if values is [1, 3, 5, 7] then the sum is 16. + If the weights were specified as [1, 1, 0, 0] then the sum would be 4. + + This metric creates one variable, `total`, that is used to compute the sum of + `values`. This is ultimately returned as `sum`. + + If `sample_weight` is `None`, weights default to 1. Use `sample_weight` of 0 + to mask values. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Sum() + >>> m.update_state([1, 3, 5, 7]) + >>> m.result().numpy() + 16.0 + + Usage with `compile()` API: + + ```python + model.add_metric(tf.keras.metrics.Sum(name='sum_1')(outputs)) + model.compile(optimizer='sgd', loss='mse') + ``` + """ + + def __init__(self, name='sum', dtype=None): + super(Sum, self).__init__(reduction=metrics_utils.Reduction.SUM, + name=name, dtype=dtype) + + +class Mean(Reduce): + """Computes the (weighted) mean of the given values. + + For example, if values is [1, 3, 5, 7] then the mean is 4. + If the weights were specified as [1, 1, 0, 0] then the mean would be 2. + + This metric creates two variables, `total` and `count` that are used to + compute the average of `values`. This average is ultimately returned as `mean` + which is an idempotent operation that simply divides `total` by `count`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Mean() + >>> m.update_state([1, 3, 5, 7]) + >>> m.result().numpy() + 4.0 + >>> m.reset_state() + >>> m.update_state([1, 3, 5, 7], sample_weight=[1, 1, 0, 0]) + >>> m.result().numpy() + 2.0 + + Usage with `compile()` API: + + ```python + model.add_metric(tf.keras.metrics.Mean(name='mean_1')(outputs)) + model.compile(optimizer='sgd', loss='mse') + ``` + """ + + def __init__(self, name='mean', dtype=None): + super(Mean, self).__init__( + reduction=metrics_utils.Reduction.WEIGHTED_MEAN, name=name, dtype=dtype) + + +class MeanRelativeError(Mean): + """Computes the mean relative error by normalizing with the given values. + + This metric creates two local variables, `total` and `count` that are used to + compute the mean relative error. This is weighted by `sample_weight`, and + it is ultimately returned as `mean_relative_error`: + an idempotent operation that simply divides `total` by `count`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + normalizer: The normalizer values with same shape as predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.MeanRelativeError(normalizer=[1, 3, 2, 3]) + >>> m.update_state([1, 3, 2, 3], [2, 4, 6, 8]) + + >>> # metric = mean(|y_pred - y_true| / normalizer) + >>> # = mean([1, 1, 4, 5] / [1, 3, 2, 3]) = mean([1, 1/3, 2, 5/3]) + >>> # = 5/4 = 1.25 + >>> m.result().numpy() + 1.25 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.MeanRelativeError(normalizer=[1, 3])]) + ``` + """ + + def __init__(self, normalizer, name=None, dtype=None): + super(MeanRelativeError, self).__init__(name=name, dtype=dtype) + normalizer = math_ops.cast(normalizer, self._dtype) + self.normalizer = normalizer + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates metric statistics. + + Args: + y_true: The ground truth values. + y_pred: The predicted values. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + y_true = math_ops.cast(y_true, self._dtype) + y_pred = math_ops.cast(y_pred, self._dtype) + [y_pred, y_true], sample_weight = \ + metrics_utils.ragged_assert_compatible_and_get_flat_values( + [y_pred, y_true], sample_weight) + y_pred, y_true = losses_utils.squeeze_or_expand_dimensions( + y_pred, y_true) + + y_pred, self.normalizer = losses_utils.remove_squeezable_dimensions( + y_pred, self.normalizer) + y_pred.shape.assert_is_compatible_with(y_true.shape) + relative_errors = math_ops.div_no_nan( + math_ops.abs(y_true - y_pred), self.normalizer) + + return super(MeanRelativeError, self).update_state( + relative_errors, sample_weight=sample_weight) + + def get_config(self): + n = self.normalizer + config = {'normalizer': backend.eval(n) if is_tensor_or_variable(n) else n} + base_config = super(MeanRelativeError, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class MeanMetricWrapper(Mean): + """Wraps a stateless metric function with the Mean metric. + + You could use this class to quickly build a mean metric from a function. The + function needs to have the signature `fn(y_true, y_pred)` and return a + per-sample loss array. `MeanMetricWrapper.result()` will return + the average metric value across all samples seen so far. + + For example: + + ```python + def accuracy(y_true, y_pred): + return tf.cast(tf.math.equal(y_true, y_pred), tf.float32) + + accuracy_metric = tf.keras.metrics.MeanMetricWrapper(fn=accuracy) + + keras_model.compile(..., metrics=accuracy_metric) + ``` + + Args: + fn: The metric function to wrap, with signature `fn(y_true, y_pred, + **kwargs)`. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + **kwargs: Keyword arguments to pass on to `fn`. + """ + + def __init__(self, fn, name=None, dtype=None, **kwargs): + super(MeanMetricWrapper, self).__init__(name=name, dtype=dtype) + self._fn = fn + self._fn_kwargs = kwargs + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates metric statistics. + + `y_true` and `y_pred` should have the same shape. + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + sample_weight: Optional `sample_weight` acts as a + coefficient for the metric. If a scalar is provided, then the metric is + simply scaled by the given value. If `sample_weight` is a tensor of size + `[batch_size]`, then the metric for each sample of the batch is rescaled + by the corresponding element in the `sample_weight` vector. If the shape + of `sample_weight` is `[batch_size, d0, .. dN-1]` (or can be broadcasted + to this shape), then each metric element of `y_pred` is scaled by the + corresponding value of `sample_weight`. (Note on `dN-1`: all metric + functions reduce by 1 dimension, usually the last axis (-1)). + + Returns: + Update op. + """ + y_true = math_ops.cast(y_true, self._dtype) + y_pred = math_ops.cast(y_pred, self._dtype) + [y_true, y_pred], sample_weight = ( + metrics_utils.ragged_assert_compatible_and_get_flat_values( + [y_true, y_pred], sample_weight)) + y_pred, y_true = losses_utils.squeeze_or_expand_dimensions( + y_pred, y_true) + + ag_fn = autograph.tf_convert(self._fn, ag_ctx.control_status_ctx()) + matches = ag_fn(y_true, y_pred, **self._fn_kwargs) + return super(MeanMetricWrapper, self).update_state( + matches, sample_weight=sample_weight) + + def get_config(self): + config = {} + + if type(self) is MeanMetricWrapper: # pylint: disable=unidiomatic-typecheck + # Only include function argument when the object is a MeanMetricWrapper + # and not a subclass. + config['fn'] = self._fn + + for k, v in self._fn_kwargs.items(): + config[k] = backend.eval(v) if is_tensor_or_variable(v) else v + base_config = super(MeanMetricWrapper, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + @classmethod + def from_config(cls, config): + # Note that while MeanMetricWrapper itself isn't public, objects of this + # class may be created and added to the model by calling model.compile. + fn = config.pop('fn', None) + if cls is MeanMetricWrapper: + return cls(get(fn), **config) + return super(MeanMetricWrapper, cls).from_config(config) + + +class Accuracy(MeanMetricWrapper): + """Calculates how often predictions equal labels. + + This metric creates two local variables, `total` and `count` that are used to + compute the frequency with which `y_pred` matches `y_true`. This frequency is + ultimately returned as `binary accuracy`: an idempotent operation that simply + divides `total` by `count`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Accuracy() + >>> m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]]) + >>> m.result().numpy() + 0.75 + + >>> m.reset_state() + >>> m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]], + ... sample_weight=[1, 1, 0, 0]) + >>> m.result().numpy() + 0.5 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.Accuracy()]) + ``` + """ + + def __init__(self, name='accuracy', dtype=None): + super(Accuracy, self).__init__(accuracy, name, dtype=dtype) + + +class BinaryAccuracy(MeanMetricWrapper): + """Calculates how often predictions match binary labels. + + This metric creates two local variables, `total` and `count` that are used to + compute the frequency with which `y_pred` matches `y_true`. This frequency is + ultimately returned as `binary accuracy`: an idempotent operation that simply + divides `total` by `count`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + threshold: (Optional) Float representing the threshold for deciding + whether prediction values are 1 or 0. + + Standalone usage: + + >>> m = tf.keras.metrics.BinaryAccuracy() + >>> m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]]) + >>> m.result().numpy() + 0.75 + + >>> m.reset_state() + >>> m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]], + ... sample_weight=[1, 0, 0, 1]) + >>> m.result().numpy() + 0.5 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.BinaryAccuracy()]) + ``` + """ + + def __init__(self, name='binary_accuracy', dtype=None, threshold=0.5): + super(BinaryAccuracy, self).__init__( + binary_accuracy, name, dtype=dtype, threshold=threshold) + + +class CategoricalAccuracy(MeanMetricWrapper): + """Calculates how often predictions match one-hot labels. + + You can provide logits of classes as `y_pred`, since argmax of + logits and probabilities are same. + + This metric creates two local variables, `total` and `count` that are used to + compute the frequency with which `y_pred` matches `y_true`. This frequency is + ultimately returned as `categorical accuracy`: an idempotent operation that + simply divides `total` by `count`. + + `y_pred` and `y_true` should be passed in as vectors of probabilities, rather + than as labels. If necessary, use `tf.one_hot` to expand `y_true` as a vector. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.CategoricalAccuracy() + >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8], + ... [0.05, 0.95, 0]]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8], + ... [0.05, 0.95, 0]], + ... sample_weight=[0.7, 0.3]) + >>> m.result().numpy() + 0.3 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.CategoricalAccuracy()]) + ``` + """ + + def __init__(self, name='categorical_accuracy', dtype=None): + super(CategoricalAccuracy, self).__init__( + categorical_accuracy, name, dtype=dtype) + + +class SparseCategoricalAccuracy(MeanMetricWrapper): + """Calculates how often predictions match integer labels. + + ```python + acc = np.dot(sample_weight, np.equal(y_true, np.argmax(y_pred, axis=1)) + ``` + + You can provide logits of classes as `y_pred`, since argmax of + logits and probabilities are same. + + This metric creates two local variables, `total` and `count` that are used to + compute the frequency with which `y_pred` matches `y_true`. This frequency is + ultimately returned as `sparse categorical accuracy`: an idempotent operation + that simply divides `total` by `count`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.SparseCategoricalAccuracy() + >>> m.update_state([[2], [1]], [[0.1, 0.6, 0.3], [0.05, 0.95, 0]]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([[2], [1]], [[0.1, 0.6, 0.3], [0.05, 0.95, 0]], + ... sample_weight=[0.7, 0.3]) + >>> m.result().numpy() + 0.3 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) + ``` + """ + + def __init__(self, name='sparse_categorical_accuracy', dtype=None): + super(SparseCategoricalAccuracy, self).__init__( + sparse_categorical_accuracy, name, dtype=dtype) + + +class TopKCategoricalAccuracy(MeanMetricWrapper): + """Computes how often targets are in the top `K` predictions. + + Args: + k: (Optional) Number of top elements to look at for computing accuracy. + Defaults to 5. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.TopKCategoricalAccuracy(k=1) + >>> m.update_state([[0, 0, 1], [0, 1, 0]], + ... [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([[0, 0, 1], [0, 1, 0]], + ... [[0.1, 0.9, 0.8], [0.05, 0.95, 0]], + ... sample_weight=[0.7, 0.3]) + >>> m.result().numpy() + 0.3 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.TopKCategoricalAccuracy()]) + ``` + """ + + def __init__(self, k=5, name='top_k_categorical_accuracy', dtype=None): + super(TopKCategoricalAccuracy, self).__init__( + top_k_categorical_accuracy, name, dtype=dtype, k=k) + + +class SparseTopKCategoricalAccuracy(MeanMetricWrapper): + """Computes how often integer targets are in the top `K` predictions. + + Args: + k: (Optional) Number of top elements to look at for computing accuracy. + Defaults to 5. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.SparseTopKCategoricalAccuracy(k=1) + >>> m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]], + ... sample_weight=[0.7, 0.3]) + >>> m.result().numpy() + 0.3 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.SparseTopKCategoricalAccuracy()]) + ``` + """ + + def __init__(self, k=5, name='sparse_top_k_categorical_accuracy', dtype=None): + super(SparseTopKCategoricalAccuracy, self).__init__( + sparse_top_k_categorical_accuracy, name, dtype=dtype, k=k) + + +class _ConfusionMatrixConditionCount(Metric): + """Calculates the number of the given confusion matrix condition. + + Args: + confusion_matrix_cond: One of `metrics_utils.ConfusionMatrix` conditions. + thresholds: (Optional) Defaults to 0.5. A float value or a python list/tuple + of float threshold values in [0, 1]. A threshold is compared with + prediction values to determine the truth value of predictions (i.e., above + the threshold is `true`, below is `false`). One metric value is generated + for each threshold value. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + """ + + def __init__(self, + confusion_matrix_cond, + thresholds=None, + name=None, + dtype=None): + super(_ConfusionMatrixConditionCount, self).__init__(name=name, dtype=dtype) + self._confusion_matrix_cond = confusion_matrix_cond + self.init_thresholds = thresholds + self.thresholds = metrics_utils.parse_init_thresholds( + thresholds, default_threshold=0.5) + self._thresholds_distributed_evenly = ( + metrics_utils.is_evenly_distributed_thresholds(self.thresholds)) + self.accumulator = self.add_weight( + 'accumulator', + shape=(len(self.thresholds),), + initializer=init_ops.zeros_initializer) + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates the metric statistics. + + Args: + y_true: The ground truth values. + y_pred: The predicted values. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + return metrics_utils.update_confusion_matrix_variables( + {self._confusion_matrix_cond: self.accumulator}, + y_true, + y_pred, + thresholds=self.thresholds, + thresholds_distributed_evenly=self._thresholds_distributed_evenly, + sample_weight=sample_weight) + + def result(self): + if len(self.thresholds) == 1: + result = self.accumulator[0] + else: + result = self.accumulator + return tensor_conversion.convert_to_tensor_v2_with_dispatch(result) + + def reset_state(self): + num_thresholds = len(to_list(self.thresholds)) + backend.batch_set_value( + [(v, np.zeros((num_thresholds,))) for v in self.variables]) + + def get_config(self): + config = {'thresholds': self.init_thresholds} + base_config = super(_ConfusionMatrixConditionCount, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class FalsePositives(_ConfusionMatrixConditionCount): + """Calculates the number of false positives. + + If `sample_weight` is given, calculates the sum of the weights of + false positives. This metric creates one local variable, `accumulator` + that is used to keep track of the number of false positives. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + thresholds: (Optional) Defaults to 0.5. A float value or a python + list/tuple of float threshold values in [0, 1]. A threshold is compared + with prediction values to determine the truth value of predictions + (i.e., above the threshold is `true`, below is `false`). One metric + value is generated for each threshold value. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.FalsePositives() + >>> m.update_state([0, 1, 0, 0], [0, 0, 1, 1]) + >>> m.result().numpy() + 2.0 + + >>> m.reset_state() + >>> m.update_state([0, 1, 0, 0], [0, 0, 1, 1], sample_weight=[0, 0, 1, 0]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.FalsePositives()]) + ``` + """ + + def __init__(self, thresholds=None, name=None, dtype=None): + super(FalsePositives, self).__init__( + confusion_matrix_cond=metrics_utils.ConfusionMatrix.FALSE_POSITIVES, + thresholds=thresholds, + name=name, + dtype=dtype) + + +class FalseNegatives(_ConfusionMatrixConditionCount): + """Calculates the number of false negatives. + + If `sample_weight` is given, calculates the sum of the weights of + false negatives. This metric creates one local variable, `accumulator` + that is used to keep track of the number of false negatives. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + thresholds: (Optional) Defaults to 0.5. A float value or a python + list/tuple of float threshold values in [0, 1]. A threshold is compared + with prediction values to determine the truth value of predictions + (i.e., above the threshold is `true`, below is `false`). One metric + value is generated for each threshold value. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.FalseNegatives() + >>> m.update_state([0, 1, 1, 1], [0, 1, 0, 0]) + >>> m.result().numpy() + 2.0 + + >>> m.reset_state() + >>> m.update_state([0, 1, 1, 1], [0, 1, 0, 0], sample_weight=[0, 0, 1, 0]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.FalseNegatives()]) + ``` + """ + + def __init__(self, thresholds=None, name=None, dtype=None): + super(FalseNegatives, self).__init__( + confusion_matrix_cond=metrics_utils.ConfusionMatrix.FALSE_NEGATIVES, + thresholds=thresholds, + name=name, + dtype=dtype) + + +class TrueNegatives(_ConfusionMatrixConditionCount): + """Calculates the number of true negatives. + + If `sample_weight` is given, calculates the sum of the weights of + true negatives. This metric creates one local variable, `accumulator` + that is used to keep track of the number of true negatives. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + thresholds: (Optional) Defaults to 0.5. A float value or a python + list/tuple of float threshold values in [0, 1]. A threshold is compared + with prediction values to determine the truth value of predictions + (i.e., above the threshold is `true`, below is `false`). One metric + value is generated for each threshold value. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.TrueNegatives() + >>> m.update_state([0, 1, 0, 0], [1, 1, 0, 0]) + >>> m.result().numpy() + 2.0 + + >>> m.reset_state() + >>> m.update_state([0, 1, 0, 0], [1, 1, 0, 0], sample_weight=[0, 0, 1, 0]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.TrueNegatives()]) + ``` + """ + + def __init__(self, thresholds=None, name=None, dtype=None): + super(TrueNegatives, self).__init__( + confusion_matrix_cond=metrics_utils.ConfusionMatrix.TRUE_NEGATIVES, + thresholds=thresholds, + name=name, + dtype=dtype) + + +class TruePositives(_ConfusionMatrixConditionCount): + """Calculates the number of true positives. + + If `sample_weight` is given, calculates the sum of the weights of + true positives. This metric creates one local variable, `true_positives` + that is used to keep track of the number of true positives. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + thresholds: (Optional) Defaults to 0.5. A float value or a python + list/tuple of float threshold values in [0, 1]. A threshold is compared + with prediction values to determine the truth value of predictions + (i.e., above the threshold is `true`, below is `false`). One metric + value is generated for each threshold value. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.TruePositives() + >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1]) + >>> m.result().numpy() + 2.0 + + >>> m.reset_state() + >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.TruePositives()]) + ``` + """ + + def __init__(self, thresholds=None, name=None, dtype=None): + super(TruePositives, self).__init__( + confusion_matrix_cond=metrics_utils.ConfusionMatrix.TRUE_POSITIVES, + thresholds=thresholds, + name=name, + dtype=dtype) + + +class Precision(Metric): + """Computes the precision of the predictions with respect to the labels. + + The metric creates two local variables, `true_positives` and `false_positives` + that are used to compute the precision. This value is ultimately returned as + `precision`, an idempotent operation that simply divides `true_positives` + by the sum of `true_positives` and `false_positives`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + If `top_k` is set, we'll calculate precision as how often on average a class + among the top-k classes with the highest predicted values of a batch entry is + correct and can be found in the label for that entry. + + If `class_id` is specified, we calculate precision by considering only the + entries in the batch for which `class_id` is above the threshold and/or in the + top-k highest predictions, and computing the fraction of them for which + `class_id` is indeed a correct label. + + Args: + thresholds: (Optional) A float value or a python list/tuple of float + threshold values in [0, 1]. A threshold is compared with prediction + values to determine the truth value of predictions (i.e., above the + threshold is `true`, below is `false`). One metric value is generated + for each threshold value. If neither thresholds nor top_k are set, the + default is to calculate precision with `thresholds=0.5`. + top_k: (Optional) Unset by default. An int value specifying the top-k + predictions to consider when calculating precision. + class_id: (Optional) Integer class ID for which we want binary metrics. + This must be in the half-open interval `[0, num_classes)`, where + `num_classes` is the last dimension of predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Precision() + >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1]) + >>> m.result().numpy() + 0.6666667 + + >>> m.reset_state() + >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0]) + >>> m.result().numpy() + 1.0 + + >>> # With top_k=2, it will calculate precision over y_true[:2] and y_pred[:2] + >>> m = tf.keras.metrics.Precision(top_k=2) + >>> m.update_state([0, 0, 1, 1], [1, 1, 1, 1]) + >>> m.result().numpy() + 0.0 + + >>> # With top_k=4, it will calculate precision over y_true[:4] and y_pred[:4] + >>> m = tf.keras.metrics.Precision(top_k=4) + >>> m.update_state([0, 0, 1, 1], [1, 1, 1, 1]) + >>> m.result().numpy() + 0.5 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.Precision()]) + ``` + """ + + def __init__(self, + thresholds=None, + top_k=None, + class_id=None, + name=None, + dtype=None): + super(Precision, self).__init__(name=name, dtype=dtype) + self.init_thresholds = thresholds + self.top_k = top_k + self.class_id = class_id + + default_threshold = 0.5 if top_k is None else metrics_utils.NEG_INF + self.thresholds = metrics_utils.parse_init_thresholds( + thresholds, default_threshold=default_threshold) + self._thresholds_distributed_evenly = ( + metrics_utils.is_evenly_distributed_thresholds(self.thresholds)) + self.true_positives = self.add_weight( + 'true_positives', + shape=(len(self.thresholds),), + initializer=init_ops.zeros_initializer) + self.false_positives = self.add_weight( + 'false_positives', + shape=(len(self.thresholds),), + initializer=init_ops.zeros_initializer) + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates true positive and false positive statistics. + + Args: + y_true: The ground truth values, with the same dimensions as `y_pred`. + Will be cast to `bool`. + y_pred: The predicted values. Each element must be in the range `[0, 1]`. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + return metrics_utils.update_confusion_matrix_variables( + { + metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, + metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives + }, + y_true, + y_pred, + thresholds=self.thresholds, + thresholds_distributed_evenly=self._thresholds_distributed_evenly, + top_k=self.top_k, + class_id=self.class_id, + sample_weight=sample_weight) + + def result(self): + result = math_ops.div_no_nan(self.true_positives, + self.true_positives + self.false_positives) + return result[0] if len(self.thresholds) == 1 else result + + def reset_state(self): + num_thresholds = len(to_list(self.thresholds)) + backend.batch_set_value([(v, np.zeros((num_thresholds,))) + for v in (self.true_positives, + self.false_positives)]) + + def get_config(self): + config = { + 'thresholds': self.init_thresholds, + 'top_k': self.top_k, + 'class_id': self.class_id + } + base_config = super(Precision, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Recall(Metric): + """Computes the recall of the predictions with respect to the labels. + + This metric creates two local variables, `true_positives` and + `false_negatives`, that are used to compute the recall. This value is + ultimately returned as `recall`, an idempotent operation that simply divides + `true_positives` by the sum of `true_positives` and `false_negatives`. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + If `top_k` is set, recall will be computed as how often on average a class + among the labels of a batch entry is in the top-k predictions. + + If `class_id` is specified, we calculate recall by considering only the + entries in the batch for which `class_id` is in the label, and computing the + fraction of them for which `class_id` is above the threshold and/or in the + top-k predictions. + + Args: + thresholds: (Optional) A float value or a python list/tuple of float + threshold values in [0, 1]. A threshold is compared with prediction + values to determine the truth value of predictions (i.e., above the + threshold is `true`, below is `false`). One metric value is generated + for each threshold value. If neither thresholds nor top_k are set, the + default is to calculate recall with `thresholds=0.5`. + top_k: (Optional) Unset by default. An int value specifying the top-k + predictions to consider when calculating recall. + class_id: (Optional) Integer class ID for which we want binary metrics. + This must be in the half-open interval `[0, num_classes)`, where + `num_classes` is the last dimension of predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Recall() + >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1]) + >>> m.result().numpy() + 0.6666667 + + >>> m.reset_state() + >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.Recall()]) + ``` + """ + + def __init__(self, + thresholds=None, + top_k=None, + class_id=None, + name=None, + dtype=None): + super(Recall, self).__init__(name=name, dtype=dtype) + self.init_thresholds = thresholds + self.top_k = top_k + self.class_id = class_id + + default_threshold = 0.5 if top_k is None else metrics_utils.NEG_INF + self.thresholds = metrics_utils.parse_init_thresholds( + thresholds, default_threshold=default_threshold) + self._thresholds_distributed_evenly = ( + metrics_utils.is_evenly_distributed_thresholds(self.thresholds)) + self.true_positives = self.add_weight( + 'true_positives', + shape=(len(self.thresholds),), + initializer=init_ops.zeros_initializer) + self.false_negatives = self.add_weight( + 'false_negatives', + shape=(len(self.thresholds),), + initializer=init_ops.zeros_initializer) + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates true positive and false negative statistics. + + Args: + y_true: The ground truth values, with the same dimensions as `y_pred`. + Will be cast to `bool`. + y_pred: The predicted values. Each element must be in the range `[0, 1]`. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + return metrics_utils.update_confusion_matrix_variables( + { + metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, + metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives + }, + y_true, + y_pred, + thresholds=self.thresholds, + thresholds_distributed_evenly=self._thresholds_distributed_evenly, + top_k=self.top_k, + class_id=self.class_id, + sample_weight=sample_weight) + + def result(self): + result = math_ops.div_no_nan(self.true_positives, + self.true_positives + self.false_negatives) + return result[0] if len(self.thresholds) == 1 else result + + def reset_state(self): + num_thresholds = len(to_list(self.thresholds)) + backend.batch_set_value([(v, np.zeros((num_thresholds,))) + for v in (self.true_positives, + self.false_negatives)]) + + def get_config(self): + config = { + 'thresholds': self.init_thresholds, + 'top_k': self.top_k, + 'class_id': self.class_id + } + base_config = super(Recall, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class SensitivitySpecificityBase(Metric, metaclass=abc.ABCMeta): + """Abstract base class for computing sensitivity and specificity. + + For additional information about specificity and sensitivity, see + [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity). + """ + + def __init__(self, + value, + num_thresholds=200, + class_id=None, + name=None, + dtype=None): + super(SensitivitySpecificityBase, self).__init__(name=name, dtype=dtype) + if num_thresholds <= 0: + raise ValueError('`num_thresholds` must be > 0.') + self.value = value + self.class_id = class_id + self.true_positives = self.add_weight( + 'true_positives', + shape=(num_thresholds,), + initializer=init_ops.zeros_initializer) + self.true_negatives = self.add_weight( + 'true_negatives', + shape=(num_thresholds,), + initializer=init_ops.zeros_initializer) + self.false_positives = self.add_weight( + 'false_positives', + shape=(num_thresholds,), + initializer=init_ops.zeros_initializer) + self.false_negatives = self.add_weight( + 'false_negatives', + shape=(num_thresholds,), + initializer=init_ops.zeros_initializer) + + # Compute `num_thresholds` thresholds in [0, 1] + if num_thresholds == 1: + self.thresholds = [0.5] + self._thresholds_distributed_evenly = False + else: + thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) + for i in range(num_thresholds - 2)] + self.thresholds = [0.0] + thresholds + [1.0] + self._thresholds_distributed_evenly = True + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates confusion matrix statistics. + + Args: + y_true: The ground truth values. + y_pred: The predicted values. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + return metrics_utils.update_confusion_matrix_variables( + { + metrics_utils.ConfusionMatrix.TRUE_POSITIVES: self.true_positives, + metrics_utils.ConfusionMatrix.TRUE_NEGATIVES: self.true_negatives, + metrics_utils.ConfusionMatrix.FALSE_POSITIVES: self.false_positives, + metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: self.false_negatives, + }, + y_true, + y_pred, + thresholds=self.thresholds, + thresholds_distributed_evenly=self._thresholds_distributed_evenly, + class_id=self.class_id, + sample_weight=sample_weight) + + def reset_state(self): + num_thresholds = len(self.thresholds) + confusion_matrix_variables = (self.true_positives, self.true_negatives, + self.false_positives, self.false_negatives) + backend.batch_set_value([ + (v, np.zeros((num_thresholds,))) for v in confusion_matrix_variables + ]) + + def get_config(self): + config = {'class_id': self.class_id} + base_config = super(SensitivitySpecificityBase, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + def _find_max_under_constraint(self, constrained, dependent, predicate): + """Returns the maximum of dependent_statistic that satisfies the constraint. + + Args: + constrained: Over these values the constraint + is specified. A rank-1 tensor. + dependent: From these values the maximum that satiesfies the + constraint is selected. Values in this tensor and in + `constrained` are linked by having the same threshold at each + position, hence this tensor must have the same shape. + predicate: A binary boolean functor to be applied to arguments + `constrained` and `self.value`, e.g. `tf.greater`. + + Returns maximal dependent value, if no value satiesfies the constraint 0.0. + """ + feasible = array_ops.where_v2(predicate(constrained, self.value)) + feasible_exists = math_ops.greater(array_ops.size(feasible), 0) + max_dependent = math_ops.reduce_max(array_ops.gather(dependent, feasible)) + + return array_ops.where_v2(feasible_exists, max_dependent, 0.0) + + +class SensitivityAtSpecificity(SensitivitySpecificityBase): + """Computes best sensitivity where specificity is >= specified value. + + the sensitivity at a given specificity. + + `Sensitivity` measures the proportion of actual positives that are correctly + identified as such (tp / (tp + fn)). + `Specificity` measures the proportion of actual negatives that are correctly + identified as such (tn / (tn + fp)). + + This metric creates four local variables, `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` that are used to compute the + sensitivity at the given specificity. The threshold for the given specificity + value is computed and used to evaluate the corresponding sensitivity. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + If `class_id` is specified, we calculate precision by considering only the + entries in the batch for which `class_id` is above the threshold predictions, + and computing the fraction of them for which `class_id` is indeed a correct + label. + + For additional information about specificity and sensitivity, see + [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity). + + Args: + specificity: A scalar value in range `[0, 1]`. + num_thresholds: (Optional) Defaults to 200. The number of thresholds to + use for matching the given specificity. + class_id: (Optional) Integer class ID for which we want binary metrics. + This must be in the half-open interval `[0, num_classes)`, where + `num_classes` is the last dimension of predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.SensitivityAtSpecificity(0.5) + >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8], + ... sample_weight=[1, 1, 2, 2, 1]) + >>> m.result().numpy() + 0.333333 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.SensitivityAtSpecificity()]) + ``` + """ + + def __init__(self, + specificity, + num_thresholds=200, + class_id=None, + name=None, + dtype=None): + if specificity < 0 or specificity > 1: + raise ValueError('`specificity` must be in the range [0, 1].') + self.specificity = specificity + self.num_thresholds = num_thresholds + super(SensitivityAtSpecificity, self).__init__( + specificity, + num_thresholds=num_thresholds, + class_id=class_id, + name=name, + dtype=dtype) + + def result(self): + specificities = math_ops.div_no_nan( + self.true_negatives, self.true_negatives + self.false_positives) + sensitivities = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_negatives) + return self._find_max_under_constraint( + specificities, sensitivities, math_ops.greater_equal) + + def get_config(self): + config = { + 'num_thresholds': self.num_thresholds, + 'specificity': self.specificity + } + base_config = super(SensitivityAtSpecificity, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class SpecificityAtSensitivity(SensitivitySpecificityBase): + """Computes best specificity where sensitivity is >= specified value. + + `Sensitivity` measures the proportion of actual positives that are correctly + identified as such (tp / (tp + fn)). + `Specificity` measures the proportion of actual negatives that are correctly + identified as such (tn / (tn + fp)). + + This metric creates four local variables, `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` that are used to compute the + specificity at the given sensitivity. The threshold for the given sensitivity + value is computed and used to evaluate the corresponding specificity. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + If `class_id` is specified, we calculate precision by considering only the + entries in the batch for which `class_id` is above the threshold predictions, + and computing the fraction of them for which `class_id` is indeed a correct + label. + + For additional information about specificity and sensitivity, see + [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity). + + Args: + sensitivity: A scalar value in range `[0, 1]`. + num_thresholds: (Optional) Defaults to 200. The number of thresholds to + use for matching the given sensitivity. + class_id: (Optional) Integer class ID for which we want binary metrics. + This must be in the half-open interval `[0, num_classes)`, where + `num_classes` is the last dimension of predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.SpecificityAtSensitivity(0.5) + >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8]) + >>> m.result().numpy() + 0.66666667 + + >>> m.reset_state() + >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8], + ... sample_weight=[1, 1, 2, 2, 2]) + >>> m.result().numpy() + 0.5 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.SpecificityAtSensitivity()]) + ``` + """ + + def __init__(self, + sensitivity, + num_thresholds=200, + class_id=None, + name=None, + dtype=None): + if sensitivity < 0 or sensitivity > 1: + raise ValueError('`sensitivity` must be in the range [0, 1].') + self.sensitivity = sensitivity + self.num_thresholds = num_thresholds + super(SpecificityAtSensitivity, self).__init__( + sensitivity, + num_thresholds=num_thresholds, + class_id=class_id, + name=name, + dtype=dtype) + + def result(self): + sensitivities = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_negatives) + specificities = math_ops.div_no_nan( + self.true_negatives, self.true_negatives + self.false_positives) + return self._find_max_under_constraint( + sensitivities, specificities, math_ops.greater_equal) + + def get_config(self): + config = { + 'num_thresholds': self.num_thresholds, + 'sensitivity': self.sensitivity + } + base_config = super(SpecificityAtSensitivity, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class PrecisionAtRecall(SensitivitySpecificityBase): + """Computes best precision where recall is >= specified value. + + This metric creates four local variables, `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` that are used to compute the + precision at the given recall. The threshold for the given recall + value is computed and used to evaluate the corresponding precision. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + If `class_id` is specified, we calculate precision by considering only the + entries in the batch for which `class_id` is above the threshold predictions, + and computing the fraction of them for which `class_id` is indeed a correct + label. + + Args: + recall: A scalar value in range `[0, 1]`. + num_thresholds: (Optional) Defaults to 200. The number of thresholds to + use for matching the given recall. + class_id: (Optional) Integer class ID for which we want binary metrics. + This must be in the half-open interval `[0, num_classes)`, where + `num_classes` is the last dimension of predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.PrecisionAtRecall(0.5) + >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8], + ... sample_weight=[2, 2, 2, 1, 1]) + >>> m.result().numpy() + 0.33333333 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.PrecisionAtRecall(recall=0.8)]) + ``` + """ + + def __init__(self, + recall, + num_thresholds=200, + class_id=None, + name=None, + dtype=None): + if recall < 0 or recall > 1: + raise ValueError('`recall` must be in the range [0, 1].') + self.recall = recall + self.num_thresholds = num_thresholds + super(PrecisionAtRecall, self).__init__( + value=recall, + num_thresholds=num_thresholds, + class_id=class_id, + name=name, + dtype=dtype) + + def result(self): + recalls = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_negatives) + precisions = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_positives) + return self._find_max_under_constraint( + recalls, precisions, math_ops.greater_equal) + + def get_config(self): + config = {'num_thresholds': self.num_thresholds, 'recall': self.recall} + base_config = super(PrecisionAtRecall, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class RecallAtPrecision(SensitivitySpecificityBase): + """Computes best recall where precision is >= specified value. + + For a given score-label-distribution the required precision might not + be achievable, in this case 0.0 is returned as recall. + + This metric creates four local variables, `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` that are used to compute the + recall at the given precision. The threshold for the given precision + value is computed and used to evaluate the corresponding recall. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + If `class_id` is specified, we calculate precision by considering only the + entries in the batch for which `class_id` is above the threshold predictions, + and computing the fraction of them for which `class_id` is indeed a correct + label. + + Args: + precision: A scalar value in range `[0, 1]`. + num_thresholds: (Optional) Defaults to 200. The number of thresholds to + use for matching the given precision. + class_id: (Optional) Integer class ID for which we want binary metrics. + This must be in the half-open interval `[0, num_classes)`, where + `num_classes` is the last dimension of predictions. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.RecallAtPrecision(0.8) + >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9], + ... sample_weight=[1, 0, 0, 1]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.RecallAtPrecision(precision=0.8)]) + ``` + """ + + def __init__(self, + precision, + num_thresholds=200, + class_id=None, + name=None, + dtype=None): + if precision < 0 or precision > 1: + raise ValueError('`precision` must be in the range [0, 1].') + self.precision = precision + self.num_thresholds = num_thresholds + super(RecallAtPrecision, self).__init__( + value=precision, + num_thresholds=num_thresholds, + class_id=class_id, + name=name, + dtype=dtype) + + def result(self): + precisions = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_positives) + recalls = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_negatives) + return self._find_max_under_constraint( + precisions, recalls, math_ops.greater_equal) + + def get_config(self): + config = {'num_thresholds': self.num_thresholds, + 'precision': self.precision} + base_config = super(RecallAtPrecision, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class AUC(Metric): + """Approximates the AUC (Area under the curve) of the ROC or PR curves. + + The AUC (Area under the curve) of the ROC (Receiver operating + characteristic; default) or PR (Precision Recall) curves are quality measures + of binary classifiers. Unlike the accuracy, and like cross-entropy + losses, ROC-AUC and PR-AUC evaluate all the operational points of a model. + + This class approximates AUCs using a Riemann sum. During the metric + accumulation phrase, predictions are accumulated within predefined buckets + by value. The AUC is then computed by interpolating per-bucket averages. These + buckets define the evaluated operational points. + + This metric creates four local variables, `true_positives`, `true_negatives`, + `false_positives` and `false_negatives` that are used to compute the AUC. + To discretize the AUC curve, a linearly spaced set of thresholds is used to + compute pairs of recall and precision values. The area under the ROC-curve is + therefore computed using the height of the recall values by the false positive + rate, while the area under the PR-curve is the computed using the height of + the precision values by the recall. + + This value is ultimately returned as `auc`, an idempotent operation that + computes the area under a discretized curve of precision versus recall values + (computed using the aforementioned variables). The `num_thresholds` variable + controls the degree of discretization with larger numbers of thresholds more + closely approximating the true AUC. The quality of the approximation may vary + dramatically depending on `num_thresholds`. The `thresholds` parameter can be + used to manually specify thresholds which split the predictions more evenly. + + For a best approximation of the real AUC, `predictions` should be distributed + approximately uniformly in the range [0, 1] (if `from_logits=False`). The + quality of the AUC approximation may be poor if this is not the case. Setting + `summation_method` to 'minoring' or 'majoring' can help quantify the error in + the approximation by providing lower or upper bound estimate of the AUC. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + num_thresholds: (Optional) Defaults to 200. The number of thresholds to + use when discretizing the roc curve. Values must be > 1. + curve: (Optional) Specifies the name of the curve to be computed, 'ROC' + [default] or 'PR' for the Precision-Recall-curve. + summation_method: (Optional) Specifies the [Riemann summation method]( + https://en.wikipedia.org/wiki/Riemann_sum) used. + 'interpolation' (default) applies mid-point summation scheme for `ROC`. + For PR-AUC, interpolates (true/false) positives but not the ratio that + is precision (see Davis & Goadrich 2006 for details); + 'minoring' applies left summation + for increasing intervals and right summation for decreasing intervals; + 'majoring' does the opposite. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + thresholds: (Optional) A list of floating point values to use as the + thresholds for discretizing the curve. If set, the `num_thresholds` + parameter is ignored. Values should be in [0, 1]. Endpoint thresholds + equal to {-epsilon, 1+epsilon} for a small positive epsilon value will + be automatically included with these to correctly handle predictions + equal to exactly 0 or 1. + multi_label: boolean indicating whether multilabel data should be + treated as such, wherein AUC is computed separately for each label and + then averaged across labels, or (when False) if the data should be + flattened into a single label before AUC computation. In the latter + case, when multilabel data is passed to AUC, each label-prediction pair + is treated as an individual data point. Should be set to False for + multi-class data. + num_labels: (Optional) The number of labels, used when `multi_label` is + True. If `num_labels` is not specified, then state variables get created + on the first call to `update_state`. + label_weights: (Optional) list, array, or tensor of non-negative weights + used to compute AUCs for multilabel data. When `multi_label` is True, + the weights are applied to the individual label AUCs when they are + averaged to produce the multi-label AUC. When it's False, they are used + to weight the individual label predictions in computing the confusion + matrix on the flattened data. Note that this is unlike class_weights in + that class_weights weights the example depending on the value of its + label, whereas label_weights depends only on the index of that label + before flattening; therefore `label_weights` should not be used for + multi-class data. + from_logits: boolean indicating whether the predictions (`y_pred` in + `update_state`) are probabilities or sigmoid logits. As a rule of thumb, + when using a keras loss, the `from_logits` constructor argument of the + loss should match the AUC `from_logits` constructor argument. + + Standalone usage: + + >>> m = tf.keras.metrics.AUC(num_thresholds=3) + >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9]) + >>> # threshold values are [0 - 1e-7, 0.5, 1 + 1e-7] + >>> # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2] + >>> # tp_rate = recall = [1, 0.5, 0], fp_rate = [1, 0, 0] + >>> # auc = ((((1+0.5)/2)*(1-0)) + (((0.5+0)/2)*(0-0))) = 0.75 + >>> m.result().numpy() + 0.75 + + >>> m.reset_state() + >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9], + ... sample_weight=[1, 0, 0, 1]) + >>> m.result().numpy() + 1.0 + + Usage with `compile()` API: + + ```python + # Reports the AUC of a model outputing a probability. + model.compile(optimizer='sgd', + loss=tf.keras.losses.BinaryCrossentropy(), + metrics=[tf.keras.metrics.AUC()]) + + # Reports the AUC of a model outputing a logit. + model.compile(optimizer='sgd', + loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), + metrics=[tf.keras.metrics.AUC(from_logits=True)]) + ``` + """ + + def __init__(self, + num_thresholds=200, + curve='ROC', + summation_method='interpolation', + name=None, + dtype=None, + thresholds=None, + multi_label=False, + num_labels=None, + label_weights=None, + from_logits=False): + # Validate configurations. + if isinstance(curve, metrics_utils.AUCCurve) and curve not in list( + metrics_utils.AUCCurve): + raise ValueError('Invalid curve: "{}". Valid options are: "{}"'.format( + curve, list(metrics_utils.AUCCurve))) + if isinstance( + summation_method, + metrics_utils.AUCSummationMethod) and summation_method not in list( + metrics_utils.AUCSummationMethod): + raise ValueError( + 'Invalid summation method: "{}". Valid options are: "{}"'.format( + summation_method, list(metrics_utils.AUCSummationMethod))) + + # Update properties. + if thresholds is not None: + # If specified, use the supplied thresholds. + self.num_thresholds = len(thresholds) + 2 + thresholds = sorted(thresholds) + self._thresholds_distributed_evenly = ( + metrics_utils.is_evenly_distributed_thresholds( + np.array([0.0] + thresholds + [1.0]))) + else: + if num_thresholds <= 1: + raise ValueError('`num_thresholds` must be > 1.') + + # Otherwise, linearly interpolate (num_thresholds - 2) thresholds in + # (0, 1). + self.num_thresholds = num_thresholds + thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) + for i in range(num_thresholds - 2)] + self._thresholds_distributed_evenly = True + + # Add an endpoint "threshold" below zero and above one for either + # threshold method to account for floating point imprecisions. + self._thresholds = np.array([0.0 - backend.epsilon()] + thresholds + + [1.0 + backend.epsilon()]) + + if isinstance(curve, metrics_utils.AUCCurve): + self.curve = curve + else: + self.curve = metrics_utils.AUCCurve.from_str(curve) + if isinstance(summation_method, metrics_utils.AUCSummationMethod): + self.summation_method = summation_method + else: + self.summation_method = metrics_utils.AUCSummationMethod.from_str( + summation_method) + super(AUC, self).__init__(name=name, dtype=dtype) + + # Handle multilabel arguments. + self.multi_label = multi_label + if label_weights is not None: + label_weights = constant_op.constant(label_weights, dtype=self.dtype) + checks = [ + check_ops.assert_non_negative( + label_weights, + message='All values of `label_weights` must be non-negative.') + ] + with ops.control_dependencies(checks): + self.label_weights = label_weights + + else: + self.label_weights = None + + self._from_logits = from_logits + + self._built = False + if self.multi_label: + if num_labels: + shape = tensor_shape.TensorShape([None, num_labels]) + self._build(shape) + else: + if num_labels: + raise ValueError( + '`num_labels` is needed only when `multi_label` is True.') + self._build(None) + + @property + def thresholds(self): + """The thresholds used for evaluating AUC.""" + return list(self._thresholds) + + def _build(self, shape): + """Initialize TP, FP, TN, and FN tensors, given the shape of the data.""" + if self.multi_label: + if shape.ndims != 2: + raise ValueError('`y_true` must have rank=2 when `multi_label` is ' + 'True. Found rank %s.' % shape.ndims) + self._num_labels = shape[1] + variable_shape = tensor_shape.TensorShape( + [tensor_shape.Dimension(self.num_thresholds), self._num_labels]) + + else: + variable_shape = tensor_shape.TensorShape( + [tensor_shape.Dimension(self.num_thresholds)]) + self._build_input_shape = shape + # Create metric variables + self.true_positives = self.add_weight( + 'true_positives', + shape=variable_shape, + initializer=init_ops.zeros_initializer) + self.true_negatives = self.add_weight( + 'true_negatives', + shape=variable_shape, + initializer=init_ops.zeros_initializer) + self.false_positives = self.add_weight( + 'false_positives', + shape=variable_shape, + initializer=init_ops.zeros_initializer) + self.false_negatives = self.add_weight( + 'false_negatives', + shape=variable_shape, + initializer=init_ops.zeros_initializer) + + if self.multi_label: + with ops.init_scope(): + # This should only be necessary for handling v1 behavior. In v2, AUC + # should be initialized outside of any tf.functions, and therefore in + # eager mode. + if not context.executing_eagerly(): + backend._initialize_variables(backend._get_session()) # pylint: disable=protected-access + + self._built = True + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates confusion matrix statistics. + + Args: + y_true: The ground truth values. + y_pred: The predicted values. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + deps = [] + if not self._built: + self._build(tensor_shape.TensorShape(y_pred.shape)) + + if self.multi_label or (self.label_weights is not None): + # y_true should have shape (number of examples, number of labels). + shapes = [ + (y_true, ('N', 'L')) + ] + if self.multi_label: + # TP, TN, FP, and FN should all have shape + # (number of thresholds, number of labels). + shapes.extend([(self.true_positives, ('T', 'L')), + (self.true_negatives, ('T', 'L')), + (self.false_positives, ('T', 'L')), + (self.false_negatives, ('T', 'L'))]) + if self.label_weights is not None: + # label_weights should be of length equal to the number of labels. + shapes.append((self.label_weights, ('L',))) + deps = [ + check_ops.assert_shapes( + shapes, message='Number of labels is not consistent.') + ] + + # Only forward label_weights to update_confusion_matrix_variables when + # multi_label is False. Otherwise the averaging of individual label AUCs is + # handled in AUC.result + label_weights = None if self.multi_label else self.label_weights + + if self._from_logits: + y_pred = activations.sigmoid(y_pred) + + with ops.control_dependencies(deps): + return metrics_utils.update_confusion_matrix_variables( + { + metrics_utils.ConfusionMatrix.TRUE_POSITIVES: + self.true_positives, + metrics_utils.ConfusionMatrix.TRUE_NEGATIVES: + self.true_negatives, + metrics_utils.ConfusionMatrix.FALSE_POSITIVES: + self.false_positives, + metrics_utils.ConfusionMatrix.FALSE_NEGATIVES: + self.false_negatives, + }, + y_true, + y_pred, + self._thresholds, + thresholds_distributed_evenly=self._thresholds_distributed_evenly, + sample_weight=sample_weight, + multi_label=self.multi_label, + label_weights=label_weights) + + def interpolate_pr_auc(self): + """Interpolation formula inspired by section 4 of Davis & Goadrich 2006. + + https://www.biostat.wisc.edu/~page/rocpr.pdf + + Note here we derive & use a closed formula not present in the paper + as follows: + + Precision = TP / (TP + FP) = TP / P + + Modeling all of TP (true positive), FP (false positive) and their sum + P = TP + FP (predicted positive) as varying linearly within each interval + [A, B] between successive thresholds, we get + + Precision slope = dTP / dP + = (TP_B - TP_A) / (P_B - P_A) + = (TP - TP_A) / (P - P_A) + Precision = (TP_A + slope * (P - P_A)) / P + + The area within the interval is (slope / total_pos_weight) times + + int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P} + int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P} + + where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in + + int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A) + + Bringing back the factor (slope / total_pos_weight) we'd put aside, we get + + slope * [dTP + intercept * log(P_B / P_A)] / total_pos_weight + + where dTP == TP_B - TP_A. + + Note that when P_A == 0 the above calculation simplifies into + + int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A) + + which is really equivalent to imputing constant precision throughout the + first bucket having >0 true positives. + + Returns: + pr_auc: an approximation of the area under the P-R curve. + """ + dtp = self.true_positives[:self.num_thresholds - + 1] - self.true_positives[1:] + p = self.true_positives + self.false_positives + dp = p[:self.num_thresholds - 1] - p[1:] + prec_slope = math_ops.div_no_nan( + dtp, math_ops.maximum(dp, 0), name='prec_slope') + intercept = self.true_positives[1:] - math_ops.multiply(prec_slope, p[1:]) + + safe_p_ratio = array_ops.where( + math_ops.logical_and(p[:self.num_thresholds - 1] > 0, p[1:] > 0), + math_ops.div_no_nan( + p[:self.num_thresholds - 1], + math_ops.maximum(p[1:], 0), + name='recall_relative_ratio'), + array_ops.ones_like(p[1:])) + + pr_auc_increment = math_ops.div_no_nan( + prec_slope * (dtp + intercept * math_ops.log(safe_p_ratio)), + math_ops.maximum(self.true_positives[1:] + self.false_negatives[1:], 0), + name='pr_auc_increment') + + if self.multi_label: + by_label_auc = math_ops.reduce_sum( + pr_auc_increment, name=self.name + '_by_label', axis=0) + if self.label_weights is None: + # Evenly weighted average of the label AUCs. + return math_ops.reduce_mean(by_label_auc, name=self.name) + else: + # Weighted average of the label AUCs. + return math_ops.div_no_nan( + math_ops.reduce_sum( + math_ops.multiply(by_label_auc, self.label_weights)), + math_ops.reduce_sum(self.label_weights), + name=self.name) + else: + return math_ops.reduce_sum(pr_auc_increment, name='interpolate_pr_auc') + + def result(self): + if (self.curve == metrics_utils.AUCCurve.PR and + self.summation_method == metrics_utils.AUCSummationMethod.INTERPOLATION + ): + # This use case is different and is handled separately. + return self.interpolate_pr_auc() + + # Set `x` and `y` values for the curves based on `curve` config. + recall = math_ops.div_no_nan(self.true_positives, + self.true_positives + self.false_negatives) + if self.curve == metrics_utils.AUCCurve.ROC: + fp_rate = math_ops.div_no_nan(self.false_positives, + self.false_positives + self.true_negatives) + x = fp_rate + y = recall + else: # curve == 'PR'. + precision = math_ops.div_no_nan( + self.true_positives, self.true_positives + self.false_positives) + x = recall + y = precision + + # Find the rectangle heights based on `summation_method`. + if self.summation_method == metrics_utils.AUCSummationMethod.INTERPOLATION: + # Note: the case ('PR', 'interpolation') has been handled above. + heights = (y[:self.num_thresholds - 1] + y[1:]) / 2. + elif self.summation_method == metrics_utils.AUCSummationMethod.MINORING: + heights = math_ops.minimum(y[:self.num_thresholds - 1], y[1:]) + else: # self.summation_method = metrics_utils.AUCSummationMethod.MAJORING: + heights = math_ops.maximum(y[:self.num_thresholds - 1], y[1:]) + + # Sum up the areas of all the rectangles. + if self.multi_label: + riemann_terms = math_ops.multiply(x[:self.num_thresholds - 1] - x[1:], + heights) + by_label_auc = math_ops.reduce_sum( + riemann_terms, name=self.name + '_by_label', axis=0) + + if self.label_weights is None: + # Unweighted average of the label AUCs. + return math_ops.reduce_mean(by_label_auc, name=self.name) + else: + # Weighted average of the label AUCs. + return math_ops.div_no_nan( + math_ops.reduce_sum( + math_ops.multiply(by_label_auc, self.label_weights)), + math_ops.reduce_sum(self.label_weights), + name=self.name) + else: + return math_ops.reduce_sum( + math_ops.multiply(x[:self.num_thresholds - 1] - x[1:], heights), + name=self.name) + + def reset_state(self): + if self._built: + confusion_matrix_variables = (self.true_positives, self.true_negatives, + self.false_positives, self.false_negatives) + if self.multi_label: + backend.batch_set_value( + [(v, np.zeros((self.num_thresholds, self._num_labels))) + for v in confusion_matrix_variables]) + else: + backend.batch_set_value([(v, np.zeros((self.num_thresholds,))) + for v in confusion_matrix_variables]) + + def get_config(self): + if is_tensor_or_variable(self.label_weights): + label_weights = backend.eval(self.label_weights) + else: + label_weights = self.label_weights + config = { + 'num_thresholds': self.num_thresholds, + 'curve': self.curve.value, + 'summation_method': self.summation_method.value, + # We remove the endpoint thresholds as an inverse of how the thresholds + # were initialized. This ensures that a metric initialized from this + # config has the same thresholds. + 'thresholds': self.thresholds[1:-1], + 'multi_label': self.multi_label, + 'label_weights': label_weights + } + base_config = super(AUC, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class CosineSimilarity(MeanMetricWrapper): + """Computes the cosine similarity between the labels and predictions. + + `cosine similarity = (a . b) / ||a|| ||b||` + + See: [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity). + + This metric keeps the average cosine similarity between `predictions` and + `labels` over a stream of data. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + axis: (Optional) Defaults to -1. The dimension along which the cosine + similarity is computed. + + Standalone usage: + + >>> # l2_norm(y_true) = [[0., 1.], [1./1.414, 1./1.414]] + >>> # l2_norm(y_pred) = [[1., 0.], [1./1.414, 1./1.414]] + >>> # l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]] + >>> # result = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1)) + >>> # = ((0. + 0.) + (0.5 + 0.5)) / 2 + >>> m = tf.keras.metrics.CosineSimilarity(axis=1) + >>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]]) + >>> m.result().numpy() + 0.49999997 + + >>> m.reset_state() + >>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]], + ... sample_weight=[0.3, 0.7]) + >>> m.result().numpy() + 0.6999999 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.CosineSimilarity(axis=1)]) + ``` + """ + + def __init__(self, name='cosine_similarity', dtype=None, axis=-1): + super(CosineSimilarity, self).__init__( + cosine_similarity, name, dtype=dtype, axis=axis) + + +class MeanAbsoluteError(MeanMetricWrapper): + """Computes the mean absolute error between the labels and predictions. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.MeanAbsoluteError() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 0.25 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.5 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.MeanAbsoluteError()]) + ``` + """ + + def __init__(self, name='mean_absolute_error', dtype=None): + super(MeanAbsoluteError, self).__init__( + mean_absolute_error, name, dtype=dtype) + + +class MeanAbsolutePercentageError(MeanMetricWrapper): + """Computes the mean absolute percentage error between `y_true` and `y_pred`. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.MeanAbsolutePercentageError() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 250000000.0 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 500000000.0 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.MeanAbsolutePercentageError()]) + ``` + """ + + def __init__(self, name='mean_absolute_percentage_error', dtype=None): + super(MeanAbsolutePercentageError, self).__init__( + mean_absolute_percentage_error, name, dtype=dtype) + + +class MeanSquaredError(MeanMetricWrapper): + """Computes the mean squared error between `y_true` and `y_pred`. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.MeanSquaredError() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 0.25 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.5 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.MeanSquaredError()]) + ``` + """ + + def __init__(self, name='mean_squared_error', dtype=None): + super(MeanSquaredError, self).__init__( + mean_squared_error, name, dtype=dtype) + + +class MeanSquaredLogarithmicError(MeanMetricWrapper): + """Computes the mean squared logarithmic error between `y_true` and `y_pred`. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.MeanSquaredLogarithmicError() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 0.12011322 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.24022643 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.MeanSquaredLogarithmicError()]) + ``` + """ + + def __init__(self, name='mean_squared_logarithmic_error', dtype=None): + super(MeanSquaredLogarithmicError, self).__init__( + mean_squared_logarithmic_error, name, dtype=dtype) + + +class Hinge(MeanMetricWrapper): + """Computes the hinge metric between `y_true` and `y_pred`. + + `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are + provided we will convert them to -1 or 1. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Hinge() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]]) + >>> m.result().numpy() + 1.3 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 1.1 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', loss='mse', metrics=[tf.keras.metrics.Hinge()]) + ``` + """ + + def __init__(self, name='hinge', dtype=None): + super(Hinge, self).__init__(hinge, name, dtype=dtype) + + +class SquaredHinge(MeanMetricWrapper): + """Computes the squared hinge metric between `y_true` and `y_pred`. + + `y_true` values are expected to be -1 or 1. If binary (0 or 1) labels are + provided we will convert them to -1 or 1. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.SquaredHinge() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]]) + >>> m.result().numpy() + 1.86 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 1.46 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.SquaredHinge()]) + ``` + """ + + def __init__(self, name='squared_hinge', dtype=None): + super(SquaredHinge, self).__init__(squared_hinge, name, dtype=dtype) + + +class CategoricalHinge(MeanMetricWrapper): + """Computes the categorical hinge metric between `y_true` and `y_pred`. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.CategoricalHinge() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]]) + >>> m.result().numpy() + 1.4000001 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 1.2 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.CategoricalHinge()]) + ``` + """ + + def __init__(self, name='categorical_hinge', dtype=None): + super(CategoricalHinge, self).__init__(categorical_hinge, name, dtype=dtype) + + +class RootMeanSquaredError(Mean): + """Computes root mean squared error metric between `y_true` and `y_pred`. + + Standalone usage: + + >>> m = tf.keras.metrics.RootMeanSquaredError() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 0.5 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.70710677 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.RootMeanSquaredError()]) + ``` + """ + + def __init__(self, name='root_mean_squared_error', dtype=None): + super(RootMeanSquaredError, self).__init__(name, dtype=dtype) + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates root mean squared error statistics. + + Args: + y_true: The ground truth values. + y_pred: The predicted values. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + y_true = math_ops.cast(y_true, self._dtype) + y_pred = math_ops.cast(y_pred, self._dtype) + y_pred, y_true = losses_utils.squeeze_or_expand_dimensions( + y_pred, y_true) + error_sq = math_ops.squared_difference(y_pred, y_true) + return super(RootMeanSquaredError, self).update_state( + error_sq, sample_weight=sample_weight) + + def result(self): + return math_ops.sqrt(math_ops.div_no_nan(self.total, self.count)) + + +class LogCoshError(MeanMetricWrapper): + """Computes the logarithm of the hyperbolic cosine of the prediction error. + + `logcosh = log((exp(x) + exp(-x))/2)`, where x is the error (y_pred - y_true) + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.LogCoshError() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 0.10844523 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.21689045 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.LogCoshError()]) + ``` + """ + + def __init__(self, name='logcosh', dtype=None): + super(LogCoshError, self).__init__(logcosh, name, dtype=dtype) + + +class Poisson(MeanMetricWrapper): + """Computes the Poisson metric between `y_true` and `y_pred`. + + `metric = y_pred - y_true * log(y_pred)` + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.Poisson() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]]) + >>> m.result().numpy() + 0.49999997 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.99999994 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.Poisson()]) + ``` + """ + + def __init__(self, name='poisson', dtype=None): + super(Poisson, self).__init__(poisson, name, dtype=dtype) + + +class KLDivergence(MeanMetricWrapper): + """Computes Kullback-Leibler divergence metric between `y_true` and `y_pred`. + + `metric = y_true * log(y_true / y_pred)` + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> m = tf.keras.metrics.KLDivergence() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]]) + >>> m.result().numpy() + 0.45814306 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.9162892 + + Usage with `compile()` API: + + ```python + model.compile(optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.KLDivergence()]) + ``` + """ + + def __init__(self, name='kullback_leibler_divergence', dtype=None): + super(KLDivergence, self).__init__( + kullback_leibler_divergence, name, dtype=dtype) + + +class MeanIoU(Metric): + """Computes the mean Intersection-Over-Union metric. + + Mean Intersection-Over-Union is a common evaluation metric for semantic image + segmentation, which first computes the IOU for each semantic class and then + computes the average over classes. IOU is defined as follows: + IOU = true_positive / (true_positive + false_positive + false_negative). + The predictions are accumulated in a confusion matrix, weighted by + `sample_weight` and the metric is then calculated from it. + + If `sample_weight` is `None`, weights default to 1. + Use `sample_weight` of 0 to mask values. + + Args: + num_classes: The possible number of labels the prediction task can have. + This value must be provided, since a confusion matrix of dimension = + [num_classes, num_classes] will be allocated. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + + Standalone usage: + + >>> # cm = [[1, 1], + >>> # [1, 1]] + >>> # sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1] + >>> # iou = true_positives / (sum_row + sum_col - true_positives)) + >>> # result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2 = 0.33 + >>> m = tf.keras.metrics.MeanIoU(num_classes=2) + >>> m.update_state([0, 0, 1, 1], [0, 1, 0, 1]) + >>> m.result().numpy() + 0.33333334 + + >>> m.reset_state() + >>> m.update_state([0, 0, 1, 1], [0, 1, 0, 1], + ... sample_weight=[0.3, 0.3, 0.3, 0.1]) + >>> m.result().numpy() + 0.23809525 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.MeanIoU(num_classes=2)]) + ``` + """ + + def __init__(self, num_classes, name=None, dtype=None): + super(MeanIoU, self).__init__(name=name, dtype=dtype) + self.num_classes = num_classes + + # Variable to accumulate the predictions in the confusion matrix. + self.total_cm = self.add_weight( + 'total_confusion_matrix', + shape=(num_classes, num_classes), + initializer=init_ops.zeros_initializer) + + def update_state(self, y_true, y_pred, sample_weight=None): + """Accumulates the confusion matrix statistics. + + Args: + y_true: The ground truth values. + y_pred: The predicted values. + sample_weight: Optional weighting of each example. Defaults to 1. Can be a + `Tensor` whose rank is either 0, or the same rank as `y_true`, and must + be broadcastable to `y_true`. + + Returns: + Update op. + """ + + y_true = math_ops.cast(y_true, self._dtype) + y_pred = math_ops.cast(y_pred, self._dtype) + + # Flatten the input if its rank > 1. + if y_pred.shape.ndims > 1: + y_pred = array_ops.reshape(y_pred, [-1]) + + if y_true.shape.ndims > 1: + y_true = array_ops.reshape(y_true, [-1]) + + if sample_weight is not None: + sample_weight = math_ops.cast(sample_weight, self._dtype) + if sample_weight.shape.ndims > 1: + sample_weight = array_ops.reshape(sample_weight, [-1]) + + # Accumulate the prediction to current confusion matrix. + current_cm = confusion_matrix.confusion_matrix( + y_true, + y_pred, + self.num_classes, + weights=sample_weight, + dtype=self._dtype) + return self.total_cm.assign_add(current_cm) + + def result(self): + """Compute the mean intersection-over-union via the confusion matrix.""" + sum_over_row = math_ops.cast( + math_ops.reduce_sum(self.total_cm, axis=0), dtype=self._dtype) + sum_over_col = math_ops.cast( + math_ops.reduce_sum(self.total_cm, axis=1), dtype=self._dtype) + true_positives = math_ops.cast( + array_ops.tensor_diag_part(self.total_cm), dtype=self._dtype) + + # sum_over_row + sum_over_col = + # 2 * true_positives + false_positives + false_negatives. + denominator = sum_over_row + sum_over_col - true_positives + + # The mean is only computed over classes that appear in the + # label or prediction tensor. If the denominator is 0, we need to + # ignore the class. + num_valid_entries = math_ops.reduce_sum( + math_ops.cast(math_ops.not_equal(denominator, 0), dtype=self._dtype)) + + iou = math_ops.div_no_nan(true_positives, denominator) + + return math_ops.div_no_nan( + math_ops.reduce_sum(iou, name='mean_iou'), num_valid_entries) + + def reset_state(self): + backend.set_value( + self.total_cm, np.zeros((self.num_classes, self.num_classes))) + + def get_config(self): + config = {'num_classes': self.num_classes} + base_config = super(MeanIoU, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class MeanTensor(Metric): + """Computes the element-wise (weighted) mean of the given tensors. + + `MeanTensor` returns a tensor with the same shape of the input tensors. The + mean value is updated by keeping local variables `total` and `count`. The + `total` tracks the sum of the weighted values, and `count` stores the sum of + the weighted counts. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + shape: (Optional) A list of integers, a tuple of integers, or a 1-D Tensor + of type int32. If not specified, the shape is inferred from the values at + the first call of update_state. + + Standalone usage: + + >>> m = tf.keras.metrics.MeanTensor() + >>> m.update_state([0, 1, 2, 3]) + >>> m.update_state([4, 5, 6, 7]) + >>> m.result().numpy() + array([2., 3., 4., 5.], dtype=float32) + + >>> m.update_state([12, 10, 8, 6], sample_weight= [0, 0.2, 0.5, 1]) + >>> m.result().numpy() + array([2. , 3.6363635, 4.8 , 5.3333335], dtype=float32) + + >>> m = tf.keras.metrics.MeanTensor(dtype=tf.float64, shape=(1, 4)) + >>> m.result().numpy() + array([[0., 0., 0., 0.]]) + >>> m.update_state([[0, 1, 2, 3]]) + >>> m.update_state([[4, 5, 6, 7]]) + >>> m.result().numpy() + array([[2., 3., 4., 5.]]) + """ + + def __init__(self, name='mean_tensor', dtype=None, shape=None): + super(MeanTensor, self).__init__(name=name, dtype=dtype) + self._shape = None + self._total = None + self._count = None + self._built = False + if shape is not None: + self._build(shape) + + def _build(self, shape): + self._shape = tensor_shape.TensorShape(shape) + self._build_input_shape = self._shape + # Create new state variables + self._total = self.add_weight( + 'total', shape=shape, initializer=init_ops.zeros_initializer) + self._count = self.add_weight( + 'count', shape=shape, initializer=init_ops.zeros_initializer) + with ops.init_scope(): + if not context.executing_eagerly(): + backend._initialize_variables(backend._get_session()) # pylint: disable=protected-access + self._built = True + + @property + def total(self): + return self._total if self._built else None + + @property + def count(self): + return self._count if self._built else None + + def update_state(self, values, sample_weight=None): + """Accumulates statistics for computing the element-wise mean. + + Args: + values: Per-example value. + sample_weight: Optional weighting of each example. Defaults to 1. + + Returns: + Update op. + """ + values = math_ops.cast(values, self._dtype) + if not self._built: + self._build(values.shape) + elif values.shape != self._shape: + raise ValueError('MeanTensor input values must always have the same ' + 'shape. Expected shape (set during the first call): {}. ' + 'Got: {}'.format(self._shape, values.shape)) + + num_values = array_ops.ones_like(values) + if sample_weight is not None: + sample_weight = math_ops.cast(sample_weight, self._dtype) + + # Update dimensions of weights to match with values if possible. + values, _, sample_weight = losses_utils.squeeze_or_expand_dimensions( + values, sample_weight=sample_weight) + try: + # Broadcast weights if possible. + sample_weight = weights_broadcast_ops.broadcast_weights( + sample_weight, values) + except ValueError: + # Reduce values to same ndim as weight array + ndim = backend.ndim(values) + weight_ndim = backend.ndim(sample_weight) + values = math_ops.reduce_mean( + values, axis=list(range(weight_ndim, ndim))) + + num_values = math_ops.multiply(num_values, sample_weight) + values = math_ops.multiply(values, sample_weight) + + update_total_op = self._total.assign_add(values) + with ops.control_dependencies([update_total_op]): + return self._count.assign_add(num_values) + + def result(self): + if not self._built: + raise ValueError( + 'MeanTensor does not have any result yet. Please call the MeanTensor ' + 'instance or use `.update_state(value)` before retrieving the result.' + ) + return math_ops.div_no_nan(self.total, self.count) + + def reset_state(self): + if self._built: + backend.batch_set_value( + [(v, np.zeros(self._shape.as_list())) for v in self.variables]) + + +class BinaryCrossentropy(MeanMetricWrapper): + """Computes the crossentropy metric between the labels and predictions. + + This is the crossentropy metric class to be used when there are only two + label classes (0 and 1). + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + from_logits: (Optional )Whether output is expected to be a logits tensor. + By default, we consider that output encodes a probability distribution. + label_smoothing: (Optional) Float in [0, 1]. When > 0, label values are + smoothed, meaning the confidence on label values are relaxed. + e.g. `label_smoothing=0.2` means that we will use a value of `0.1` for + label `0` and `0.9` for label `1`". + + Standalone usage: + + >>> m = tf.keras.metrics.BinaryCrossentropy() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]]) + >>> m.result().numpy() + 0.81492424 + + >>> m.reset_state() + >>> m.update_state([[0, 1], [0, 0]], [[0.6, 0.4], [0.4, 0.6]], + ... sample_weight=[1, 0]) + >>> m.result().numpy() + 0.9162905 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.BinaryCrossentropy()]) + ``` + """ + + def __init__(self, + name='binary_crossentropy', + dtype=None, + from_logits=False, + label_smoothing=0): + super(BinaryCrossentropy, self).__init__( + binary_crossentropy, + name, + dtype=dtype, + from_logits=from_logits, + label_smoothing=label_smoothing) + + +class CategoricalCrossentropy(MeanMetricWrapper): + """Computes the crossentropy metric between the labels and predictions. + + This is the crossentropy metric class to be used when there are multiple + label classes (2 or more). Here we assume that labels are given as a `one_hot` + representation. eg., When labels values are [2, 0, 1], + `y_true` = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + from_logits: (Optional) Whether output is expected to be a logits tensor. + By default, we consider that output encodes a probability distribution. + label_smoothing: (Optional) Float in [0, 1]. When > 0, label values are + smoothed, meaning the confidence on label values are relaxed. e.g. + `label_smoothing=0.2` means that we will use a value of `0.1` for label + `0` and `0.9` for label `1`" + + Standalone usage: + + >>> # EPSILON = 1e-7, y = y_true, y` = y_pred + >>> # y` = clip_ops.clip_by_value(output, EPSILON, 1. - EPSILON) + >>> # y` = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]] + >>> # xent = -sum(y * log(y'), axis = -1) + >>> # = -((log 0.95), (log 0.1)) + >>> # = [0.051, 2.302] + >>> # Reduced xent = (0.051 + 2.302) / 2 + >>> m = tf.keras.metrics.CategoricalCrossentropy() + >>> m.update_state([[0, 1, 0], [0, 0, 1]], + ... [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]) + >>> m.result().numpy() + 1.1769392 + + >>> m.reset_state() + >>> m.update_state([[0, 1, 0], [0, 0, 1]], + ... [[0.05, 0.95, 0], [0.1, 0.8, 0.1]], + ... sample_weight=tf.constant([0.3, 0.7])) + >>> m.result().numpy() + 1.6271976 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.CategoricalCrossentropy()]) + ``` + """ + + def __init__(self, + name='categorical_crossentropy', + dtype=None, + from_logits=False, + label_smoothing=0): + super(CategoricalCrossentropy, self).__init__( + categorical_crossentropy, + name, + dtype=dtype, + from_logits=from_logits, + label_smoothing=label_smoothing) + + +class SparseCategoricalCrossentropy(MeanMetricWrapper): + """Computes the crossentropy metric between the labels and predictions. + + Use this crossentropy metric when there are two or more label classes. + We expect labels to be provided as integers. If you want to provide labels + using `one-hot` representation, please use `CategoricalCrossentropy` metric. + There should be `# classes` floating point values per feature for `y_pred` + and a single floating point value per feature for `y_true`. + + In the snippet below, there is a single floating point value per example for + `y_true` and `# classes` floating pointing values per example for `y_pred`. + The shape of `y_true` is `[batch_size]` and the shape of `y_pred` is + `[batch_size, num_classes]`. + + Args: + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + from_logits: (Optional) Whether output is expected to be a logits tensor. + By default, we consider that output encodes a probability distribution. + axis: (Optional) Defaults to -1. The dimension along which the metric is + computed. + + Standalone usage: + + >>> # y_true = one_hot(y_true) = [[0, 1, 0], [0, 0, 1]] + >>> # logits = log(y_pred) + >>> # softmax = exp(logits) / sum(exp(logits), axis=-1) + >>> # softmax = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]] + >>> # xent = -sum(y * log(softmax), 1) + >>> # log(softmax) = [[-2.9957, -0.0513, -16.1181], + >>> # [-2.3026, -0.2231, -2.3026]] + >>> # y_true * log(softmax) = [[0, -0.0513, 0], [0, 0, -2.3026]] + >>> # xent = [0.0513, 2.3026] + >>> # Reduced xent = (0.0513 + 2.3026) / 2 + >>> m = tf.keras.metrics.SparseCategoricalCrossentropy() + >>> m.update_state([1, 2], + ... [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]) + >>> m.result().numpy() + 1.1769392 + + >>> m.reset_state() + >>> m.update_state([1, 2], + ... [[0.05, 0.95, 0], [0.1, 0.8, 0.1]], + ... sample_weight=tf.constant([0.3, 0.7])) + >>> m.result().numpy() + 1.6271976 + + Usage with `compile()` API: + + ```python + model.compile( + optimizer='sgd', + loss='mse', + metrics=[tf.keras.metrics.SparseCategoricalCrossentropy()]) + ``` + """ + + def __init__(self, + name='sparse_categorical_crossentropy', + dtype=None, + from_logits=False, + axis=-1): + super(SparseCategoricalCrossentropy, self).__init__( + sparse_categorical_crossentropy, + name, + dtype=dtype, + from_logits=from_logits, + axis=axis) + + +class SumOverBatchSize(Reduce): + """Computes the weighted sum over batch size of the given values. + + For example, if values is [1, 3, 5, 7] then the metric value is 4. + If the weights were specified as [1, 1, 0, 0] then the value would be 1. + + This metric creates two variables, `total` and `count` that are used to + compute the average of `values`. This average is ultimately returned as sum + over batch size which is an idempotent operation that simply divides `total` + by `count`. + + If `sample_weight` is `None`, weights default to 1. Use `sample_weight` of 0 + to mask values. + """ + + def __init__(self, name='sum_over_batch_size', dtype=None): + super(SumOverBatchSize, self).__init__( + reduction=metrics_utils.Reduction.SUM_OVER_BATCH_SIZE, + name=name, + dtype=dtype) + + +class SumOverBatchSizeMetricWrapper(SumOverBatchSize): + """Wraps a function with the `SumOverBatchSizeMetricWrapper` metric.""" + + def __init__(self, fn, name=None, dtype=None, **kwargs): + """Creates a `SumOverBatchSizeMetricWrapper` instance. + + Args: + fn: The metric function to wrap, with signature `fn(y_true, y_pred, + **kwargs)`. + name: (Optional) string name of the metric instance. + dtype: (Optional) data type of the metric result. + **kwargs: The keyword arguments that are passed on to `fn`. + """ + super(SumOverBatchSizeMetricWrapper, self).__init__(name=name, dtype=dtype) + self._fn = fn + self._fn_kwargs = kwargs + + def update_state(self, y_true, y_pred, sample_weight=None): + y_true = math_ops.cast(y_true, self._dtype) + y_pred = math_ops.cast(y_pred, self._dtype) + y_pred, y_true = losses_utils.squeeze_or_expand_dimensions( + y_pred, y_true) + + ag_fn = autograph.tf_convert(self._fn, ag_ctx.control_status_ctx()) + matches = ag_fn(y_true, y_pred, **self._fn_kwargs) + return super(SumOverBatchSizeMetricWrapper, self).update_state( + matches, sample_weight=sample_weight) + + def get_config(self): + config = {} + for k, v in self._fn_kwargs.items(): + config[k] = backend.eval(v) if is_tensor_or_variable(v) else v + base_config = super(SumOverBatchSizeMetricWrapper, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +def accuracy(y_true, y_pred): + [y_pred, y_true], _ = \ + metrics_utils.ragged_assert_compatible_and_get_flat_values( + [y_pred, y_true]) + y_true.shape.assert_is_compatible_with(y_pred.shape) + if y_true.dtype != y_pred.dtype: + y_pred = math_ops.cast(y_pred, y_true.dtype) + return math_ops.cast(math_ops.equal(y_true, y_pred), backend.floatx()) + + +@dispatch.add_dispatch_support +def binary_accuracy(y_true, y_pred, threshold=0.5): + """Calculates how often predictions match binary labels. + + Standalone usage: + >>> y_true = [[1], [1], [0], [0]] + >>> y_pred = [[1], [1], [0], [0]] + >>> m = tf.keras.metrics.binary_accuracy(y_true, y_pred) + >>> assert m.shape == (4,) + >>> m.numpy() + array([1., 1., 1., 1.], dtype=float32) + + Args: + y_true: Ground truth values. shape = `[batch_size, d0, .. dN]`. + y_pred: The predicted values. shape = `[batch_size, d0, .. dN]`. + threshold: (Optional) Float representing the threshold for deciding whether + prediction values are 1 or 0. + + Returns: + Binary accuracy values. shape = `[batch_size, d0, .. dN-1]` + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + threshold = math_ops.cast(threshold, y_pred.dtype) + y_pred = math_ops.cast(y_pred > threshold, y_pred.dtype) + return backend.mean(math_ops.equal(y_true, y_pred), axis=-1) + + +@dispatch.add_dispatch_support +def categorical_accuracy(y_true, y_pred): + """Calculates how often predictions match one-hot labels. + + Standalone usage: + >>> y_true = [[0, 0, 1], [0, 1, 0]] + >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]] + >>> m = tf.keras.metrics.categorical_accuracy(y_true, y_pred) + >>> assert m.shape == (2,) + >>> m.numpy() + array([0., 1.], dtype=float32) + + You can provide logits of classes as `y_pred`, since argmax of + logits and probabilities are same. + + Args: + y_true: One-hot ground truth values. + y_pred: The prediction values. + + Returns: + Categorical accuracy values. + """ + return math_ops.cast( + math_ops.equal( + math_ops.argmax(y_true, axis=-1), math_ops.argmax(y_pred, axis=-1)), + backend.floatx()) + + +@dispatch.add_dispatch_support +def sparse_categorical_accuracy(y_true, y_pred): + """Calculates how often predictions match integer labels. + + Standalone usage: + >>> y_true = [2, 1] + >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]] + >>> m = tf.keras.metrics.sparse_categorical_accuracy(y_true, y_pred) + >>> assert m.shape == (2,) + >>> m.numpy() + array([0., 1.], dtype=float32) + + You can provide logits of classes as `y_pred`, since argmax of + logits and probabilities are same. + + Args: + y_true: Integer ground truth values. + y_pred: The prediction values. + + Returns: + Sparse categorical accuracy values. + """ + y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred) + y_true = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_true) + y_pred_rank = y_pred.shape.ndims + y_true_rank = y_true.shape.ndims + # If the shape of y_true is (num_samples, 1), squeeze to (num_samples,) + if (y_true_rank is not None) and (y_pred_rank is not None) and (len( + backend.int_shape(y_true)) == len(backend.int_shape(y_pred))): + y_true = array_ops.squeeze(y_true, [-1]) + y_pred = math_ops.argmax(y_pred, axis=-1) + + # If the predicted output and actual output types don't match, force cast them + # to match. + if backend.dtype(y_pred) != backend.dtype(y_true): + y_pred = math_ops.cast(y_pred, backend.dtype(y_true)) + + return math_ops.cast(math_ops.equal(y_true, y_pred), backend.floatx()) + + +@dispatch.add_dispatch_support +def top_k_categorical_accuracy(y_true, y_pred, k=5): + """Computes how often targets are in the top `K` predictions. + + Standalone usage: + >>> y_true = [[0, 0, 1], [0, 1, 0]] + >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]] + >>> m = tf.keras.metrics.top_k_categorical_accuracy(y_true, y_pred, k=3) + >>> assert m.shape == (2,) + >>> m.numpy() + array([1., 1.], dtype=float32) + + Args: + y_true: The ground truth values. + y_pred: The prediction values. + k: (Optional) Number of top elements to look at for computing accuracy. + Defaults to 5. + + Returns: + Top K categorical accuracy value. + """ + return math_ops.cast( + nn.in_top_k( + y_pred, math_ops.argmax(y_true, axis=-1), k), backend.floatx()) + + +@dispatch.add_dispatch_support +def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): + """Computes how often integer targets are in the top `K` predictions. + + Standalone usage: + >>> y_true = [2, 1] + >>> y_pred = [[0.1, 0.9, 0.8], [0.05, 0.95, 0]] + >>> m = tf.keras.metrics.sparse_top_k_categorical_accuracy( + ... y_true, y_pred, k=3) + >>> assert m.shape == (2,) + >>> m.numpy() + array([1., 1.], dtype=float32) + + Args: + y_true: tensor of true targets. + y_pred: tensor of predicted targets. + k: (Optional) Number of top elements to look at for computing accuracy. + Defaults to 5. + + Returns: + Sparse top K categorical accuracy value. + """ + y_pred_rank = tensor_conversion.convert_to_tensor_v2_with_dispatch( + y_pred + ).shape.ndims + y_true_rank = tensor_conversion.convert_to_tensor_v2_with_dispatch( + y_true + ).shape.ndims + # Flatten y_pred to (batch_size, num_samples) and y_true to (num_samples,) + if (y_true_rank is not None) and (y_pred_rank is not None): + if y_pred_rank > 2: + y_pred = array_ops.reshape(y_pred, [-1, y_pred.shape[-1]]) + if y_true_rank > 1: + y_true = array_ops.reshape(y_true, [-1]) + + return math_ops.cast( + nn.in_top_k(y_pred, math_ops.cast(y_true, 'int32'), k), backend.floatx()) + + +def cosine_proximity(y_true, y_pred, axis=-1): + """Computes the cosine similarity between labels and predictions. + + Args: + y_true: The ground truth values. + y_pred: The prediction values. + axis: (Optional) Defaults to -1. The dimension along which the cosine + similarity is computed. + + Returns: + Cosine similarity value. + """ + y_true = nn.l2_normalize(y_true, axis=axis) + y_pred = nn.l2_normalize(y_pred, axis=axis) + return math_ops.reduce_sum(y_true * y_pred, axis=axis) + +# Aliases + +acc = ACC = accuracy +bce = BCE = binary_crossentropy +mse = MSE = mean_squared_error +mae = MAE = mean_absolute_error +mape = MAPE = mean_absolute_percentage_error +msle = MSLE = mean_squared_logarithmic_error +cosine_similarity = cosine_proximity +log_cosh = logcosh + + +def clone_metric(metric): + """Returns a clone of the metric if stateful, otherwise returns it as is.""" + if isinstance(metric, Metric): + with ops.init_scope(): + return metric.__class__.from_config(metric.get_config()) + return metric + + +def clone_metrics(metrics): + """Clones the given metric list/dict.""" + return nest.map_structure(clone_metric, metrics) + + +def serialize(metric): + """Serializes metric function or `Metric` instance. + + Args: + metric: A Keras `Metric` instance or a metric function. + + Returns: + Metric configuration dictionary. + """ + return serialize_keras_object(metric) + + +def deserialize(config, custom_objects=None): + """Deserializes a serialized metric class/function instance. + + Args: + config: Metric configuration. + custom_objects: Optional dictionary mapping names (strings) to custom + objects (classes and functions) to be considered during deserialization. + + Returns: + A Keras `Metric` instance or a metric function. + """ + return deserialize_keras_object( + config, + module_objects=globals(), + custom_objects=custom_objects, + printable_module_name='metric function') + + +def get(identifier): + """Retrieves a Keras metric as a `function`/`Metric` class instance. + + The `identifier` may be the string name of a metric function or class. + + >>> metric = tf.keras.metrics.get("categorical_crossentropy") + >>> type(metric) + + >>> metric = tf.keras.metrics.get("CategoricalCrossentropy") + >>> type(metric) + + + You can also specify `config` of the metric to this function by passing dict + containing `class_name` and `config` as an identifier. Also note that the + `class_name` must map to a `Metric` class + + >>> identifier = {"class_name": "CategoricalCrossentropy", + ... "config": {"from_logits": True}} + >>> metric = tf.keras.metrics.get(identifier) + >>> type(metric) + + + Args: + identifier: A metric identifier. One of None or string name of a metric + function/class or metric configuration dictionary or a metric function or + a metric class instance + + Returns: + A Keras metric as a `function`/ `Metric` class instance. + + Raises: + ValueError: If `identifier` cannot be interpreted. + """ + if isinstance(identifier, dict): + return deserialize(identifier) + elif isinstance(identifier, str): + return deserialize(str(identifier)) + elif callable(identifier): + return identifier + else: + raise ValueError( + 'Could not interpret metric function identifier: {}'.format(identifier)) + + +def is_built_in(cls): + return cls.__module__ == Metric.__module__ diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/models.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/models.py new file mode 100644 index 0000000000000000000000000000000000000000..b5eaccc3c579bdf0b062bd88c5f5fe6d588e039a --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/models.py @@ -0,0 +1,742 @@ +# 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. +# ============================================================================== +# pylint: disable=protected-access +"""Code for model cloning, plus model-related API entries.""" + +from tensorflow.python.framework import ops +from tensorflow.python.keras import backend +from tensorflow.python.keras import metrics as metrics_module +from tensorflow.python.keras import optimizer_v1 +from tensorflow.python.keras.engine import functional +from tensorflow.python.keras.engine import sequential +from tensorflow.python.keras.engine import training +from tensorflow.python.keras.engine import training_v1 +from tensorflow.python.keras.engine.base_layer import AddMetric +from tensorflow.python.keras.engine.base_layer import Layer +from tensorflow.python.keras.engine.input_layer import Input +from tensorflow.python.keras.engine.input_layer import InputLayer +from tensorflow.python.keras.saving import model_config +from tensorflow.python.keras.saving import save +from tensorflow.python.keras.utils import generic_utils +from tensorflow.python.keras.utils import version_utils +from tensorflow.python.keras.utils.generic_utils import CustomObjectScope +from tensorflow.python.platform import tf_logging as logging +from tensorflow.python.util import nest + + +# API entries importable from `keras.models`: +Model = training.Model # pylint: disable=invalid-name +Sequential = sequential.Sequential # pylint: disable=invalid-name +Functional = functional.Functional # pylint: disable=invalid-name +save_model = save.save_model +load_model = save.load_model +model_from_config = model_config.model_from_config +model_from_yaml = model_config.model_from_yaml +model_from_json = model_config.model_from_json + + +# Callable used to clone a layer with weights preserved. +def share_weights(layer): + return layer + + +def _clone_layer(layer): + return layer.__class__.from_config(layer.get_config()) + + +def _insert_ancillary_layers(model, ancillary_layers, metrics_names, new_nodes): + """Inserts ancillary layers into the model with the proper order.""" + # Sort `AddMetric` layers so they agree with metrics_names. + metric_layers = [ + layer for layer in ancillary_layers if isinstance(layer, AddMetric) + ] + metric_layers.sort(key=lambda layer: metrics_names.index(layer.metric_name)) + ancillary_layers = [ + layer for layer in ancillary_layers if not isinstance(layer, AddMetric) + ] + metric_layers + model._insert_layers(ancillary_layers, relevant_nodes=list(new_nodes)) + + +def _make_new_nodes(nodes_by_depth, layer_fn, layer_map, tensor_map): + """Uses the layers in `layer_map` to make new nodes based on `nodes_by_depth`. + + Args: + nodes_by_depth: Provides structure information to create new nodes. + layer_fn: Function to clone layers. + layer_map: Map from layers in `model` to new layers. + tensor_map: Map from tensors in `model` to newly compute tensors. + + Returns: + A set of new nodes. `layer_map` and `tensor_map` are updated. + """ + # Iterated over every node in the reference model, in depth order. + new_nodes = set() + depth_keys = list(nodes_by_depth.keys()) + depth_keys.sort(reverse=True) + for depth in depth_keys: + nodes = nodes_by_depth[depth] + for node in nodes: + # Recover the corresponding layer. + layer = node.outbound_layer + + # Get or create layer. + if layer not in layer_map: + new_layer = layer_fn(layer) + layer_map[layer] = new_layer + layer = new_layer + else: + # Reuse previously cloned layer. + layer = layer_map[layer] + # Don't call InputLayer multiple times. + if isinstance(layer, InputLayer): + continue + + # If all previous input tensors are available in tensor_map, + # then call node.inbound_layer on them. + if all( + tensor in tensor_map for tensor in nest.flatten(node.input_tensors)): + # Call layer. + args = nest.map_structure(lambda t: tensor_map.get(t, t), + node.call_args) + kwargs = nest.map_structure(lambda t: tensor_map.get(t, t), + node.call_kwargs) + output_tensors = layer(*args, **kwargs) + + # Thread-safe way to keep track of what node was created. + first_output_tensor = nest.flatten(output_tensors)[0] + new_nodes.add( + layer._inbound_nodes[first_output_tensor._keras_history.node_index]) + + for x, y in zip( + nest.flatten(node.output_tensors), nest.flatten(output_tensors)): + tensor_map[x] = y + return new_nodes + + +def _clone_functional_model(model, input_tensors=None, layer_fn=_clone_layer): + """Clone a functional `Model` instance. + + Model cloning is similar to calling a model on new inputs, + except that it creates new layers (and thus new weights) instead + of sharing the weights of the existing layers. + + Input layers are always cloned. + + Args: + model: Instance of `Model`. + input_tensors: optional list of input tensors + to build the model upon. If not provided, + placeholders will be created. + layer_fn: callable to be applied on non-input layers in the model. By + default it clones the layer. Another example is to preserve the layer + to share the weights. This is required when we create a per-replica + copy of the model with distribution strategy; we want the weights to + be shared but still feed inputs separately so we create new input + layers. + + Returns: + An instance of `Model` reproducing the behavior + of the original model, on top of new inputs tensors, + using newly instantiated weights. + + Raises: + ValueError: in case of invalid `model` argument value or `layer_fn` + argument value. + """ + if not isinstance(model, Model): + raise ValueError('Expected `model` argument ' + 'to be a `Model` instance, got ', model) + if isinstance(model, Sequential): + raise ValueError('Expected `model` argument ' + 'to be a functional `Model` instance, ' + 'got a `Sequential` instance instead:', model) + if not model._is_graph_network: + raise ValueError('Expected `model` argument ' + 'to be a functional `Model` instance, ' + 'but got a subclass model instead.') + + new_input_layers = {} # Cache for created layers. + if input_tensors is not None: + # Make sure that all input tensors come from a Keras layer. + input_tensors = nest.flatten(input_tensors) + for i, input_tensor in enumerate(input_tensors): + original_input_layer = model._input_layers[i] + + # Cache input layer. Create a new layer if the tensor is originally not + # from a Keras layer. + if not backend.is_keras_tensor(input_tensor): + name = original_input_layer.name + input_tensor = Input(tensor=input_tensor, + name='input_wrapper_for_' + name) + newly_created_input_layer = input_tensor._keras_history.layer + new_input_layers[original_input_layer] = newly_created_input_layer + else: + new_input_layers[original_input_layer] = original_input_layer + + if not callable(layer_fn): + raise ValueError('Expected `layer_fn` argument to be a callable.') + + model_configs, created_layers = _clone_layers_and_model_config( + model, new_input_layers, layer_fn) + # Reconstruct model from the config, using the cloned layers. + input_tensors, output_tensors, created_layers = ( + functional.reconstruct_from_config(model_configs, + created_layers=created_layers)) + metrics_names = model.metrics_names + model = Model(input_tensors, output_tensors, name=model.name) + # Layers not directly tied to outputs of the Model, such as loss layers + # created in `add_loss` and `add_metric`. + ancillary_layers = [ + layer for layer in created_layers.values() if layer not in model.layers + ] + # TODO(b/162887610): This may need to adjust the inbound node index if the + # created layers had already been used to define other models. + if ancillary_layers: + new_nodes = nest.flatten([ + layer.inbound_nodes[1:] + if functional._should_skip_first_node(layer) + else layer.inbound_nodes for layer in created_layers.values() + ]) + _insert_ancillary_layers(model, ancillary_layers, metrics_names, new_nodes) + return model + + +def _clone_layers_and_model_config(model, input_layers, layer_fn): + """Clones all layers, and returns the model config without serializing layers. + + This function ensures that only the node graph is retrieved when getting the + model config. The `layer_fn` used to clone layers might not rely on + `layer.get_config()`, so some custom layers do not define `get_config`. + Trying to retrieve the config results in errors. + + Args: + model: A Functional model. + input_layers: Dictionary mapping input layers in `model` to new input layers + layer_fn: Function used to clone all non-input layers. + + Returns: + Model config object, and a dictionary of newly created layers. + """ + created_layers = {} + def _copy_layer(layer): + # Whenever the network config attempts to get the layer serialization, + # return a dummy dictionary. + if layer in input_layers: + created_layers[layer.name] = input_layers[layer] + elif layer in model._input_layers: + created_layers[layer.name] = InputLayer(**layer.get_config()) + else: + created_layers[layer.name] = layer_fn(layer) + return {} + + config = functional.get_network_config( + model, serialize_layer_fn=_copy_layer) + return config, created_layers + + +def _remove_ancillary_layers(model, layer_map, layers): + """Removes and returns any ancillary layers from `layers` based on `model`. + + Ancillary layers are part of the model topology but not used to compute the + model outputs, e.g., layers from `add_loss` and `add_metric`. + + Args: + model: A Keras Model. + layer_map: A map to from layers in the `model` to those in `layers`. + layers: A list of all layers. + + Returns: + Two lists of layers: (1) `layers` with the ancillary layers removed, and (2) + the ancillary layers. + """ + ancillary_layers = [] # Additional layers for computing losses and metrics. + if not model._is_graph_network: + return layers, ancillary_layers + + # Ancillary layers are those with depth < 0. + depths = [depth for depth in model._nodes_by_depth.keys() if depth < 0] + depths.sort(reverse=True) # Order topologically from inputs to outputs. + for depth in depths: + for node in model._nodes_by_depth[depth]: + ancillary_layers.append(layer_map[node.outbound_layer]) + + return [l for l in layers if l not in ancillary_layers], ancillary_layers + + +def _clone_sequential_model(model, input_tensors=None, layer_fn=_clone_layer): + """Clone a `Sequential` model instance. + + Model cloning is similar to calling a model on new inputs, + except that it creates new layers (and thus new weights) instead + of sharing the weights of the existing layers. + + Args: + model: Instance of `Sequential`. + input_tensors: optional list of input tensors + to build the model upon. If not provided, + placeholders will be created. + layer_fn: callable to be applied on non-input layers in the model. By + default it clones the layer. Another example is to preserve the layer + to share the weights. This is required when we create a per-replica + copy of the model with distribution strategy; we want the weights to + be shared but still feed inputs separately so we create new input + layers. + + Returns: + An instance of `Sequential` reproducing the behavior + of the original model, on top of new inputs tensors, + using newly instantiated weights. + + Raises: + ValueError: in case of invalid `model` argument value or `layer_fn` + argument value. + """ + if not isinstance(model, Sequential): + raise ValueError('Expected `model` argument ' + 'to be a `Sequential` model instance, ' + 'but got:', model) + + if not callable(layer_fn): + raise ValueError('Expected `layer_fn` argument to be a callable.') + + layers = [] # Layers needed to compute the model's outputs. + layer_map = {} + # Ensure that all layers are cloned. The model's layers + # property will exclude the initial InputLayer (if it exists) in the model, + # resulting in a different Sequential model structure. + for layer in model._flatten_layers(include_self=False, recursive=False): + if isinstance(layer, InputLayer) and input_tensors is not None: + # If input tensors are provided, the original model's InputLayer is + # overwritten with a different InputLayer. + continue + cloned_layer = ( + _clone_layer(layer) + if isinstance(layer, InputLayer) else layer_fn(layer)) + layers.append(cloned_layer) + layer_map[layer] = cloned_layer + layers, ancillary_layers = _remove_ancillary_layers(model, layer_map, layers) + + if input_tensors is None: + cloned_model = Sequential(layers=layers, name=model.name) + elif len(generic_utils.to_list(input_tensors)) != 1: + raise ValueError('To clone a `Sequential` model, we expect ' + ' at most one tensor ' + 'as part of `input_tensors`.') + else: + # Overwrite the original model's input layer. + if isinstance(input_tensors, tuple): + input_tensors = list(input_tensors) + x = generic_utils.to_list(input_tensors)[0] + if backend.is_keras_tensor(x): + origin_layer = x._keras_history.layer + if isinstance(origin_layer, InputLayer): + cloned_model = Sequential( + layers=[origin_layer] + layers, name=model.name) + else: + raise ValueError('Cannot clone a `Sequential` model on top ' + 'of a tensor that comes from a Keras layer ' + 'other than an `InputLayer`. ' + 'Use the functional API instead.') + else: + input_tensor = Input(tensor=x, name='input_wrapper_for_' + str(x.name)) + input_layer = input_tensor._keras_history.layer + cloned_model = Sequential(layers=[input_layer] + layers, name=model.name) + + if not ancillary_layers: + return cloned_model + + tensor_map = {} # Maps tensors from `model` to those in `cloned_model`. + for depth, cloned_nodes in cloned_model._nodes_by_depth.items(): + nodes = model._nodes_by_depth[depth] + # This should be safe in a Sequential model. In an arbitrary network, you + # need to sort using the outbound layer of the node as a key. + for cloned_node, node in zip(cloned_nodes, nodes): + if isinstance(cloned_node.output_tensors, list): + for j, output_tensor in enumerate(cloned_node.output_tensors): + tensor_map[node.output_tensors[j]] = output_tensor + else: + tensor_map[node.output_tensors] = cloned_node.output_tensors + # Ancillary nodes have negative depth. + new_nodes = _make_new_nodes( + { + depth: nodes + for depth, nodes in model._nodes_by_depth.items() + if depth < 0 + }, layer_fn, layer_map, tensor_map) + _insert_ancillary_layers(cloned_model, ancillary_layers, model.metrics_names, + new_nodes) + return cloned_model + + +def clone_model(model, input_tensors=None, clone_function=None): + """Clone a Functional or Sequential `Model` instance. + + Model cloning is similar to calling a model on new inputs, + except that it creates new layers (and thus new weights) instead + of sharing the weights of the existing layers. + + Note that + `clone_model` will not preserve the uniqueness of shared objects within the + model (e.g. a single variable attached to two distinct layers will be + restored as two separate variables). + + Args: + model: Instance of `Model` + (could be a Functional model or a Sequential model). + input_tensors: optional list of input tensors or InputLayer objects + to build the model upon. If not provided, + new `Input` objects will be created. + clone_function: Callable to be used to clone each layer in the target + model (except `InputLayer` instances). It takes as argument the layer + instance to be cloned, and returns the corresponding layer instance to + be used in the model copy. If unspecified, this callable defaults to + the following serialization/deserialization function: + `lambda layer: layer.__class__.from_config(layer.get_config())`. + By passing a custom callable, you can customize your copy of the + model, e.g. by wrapping certain layers of interest (you might want to + replace all `LSTM` instances with equivalent + `Bidirectional(LSTM(...))` instances, for example). + + Returns: + An instance of `Model` reproducing the behavior + of the original model, on top of new inputs tensors, + using newly instantiated weights. The cloned model may behave + differently from the original model if a custom `clone_function` + modifies the layer. + + Example: + + ```python + # Create a test Sequential model. + model = keras.Sequential([ + keras.Input(shape=(728,)), + keras.layers.Dense(32, activation='relu'), + keras.layers.Dense(1, activation='sigmoid'), + ]) + # Create a copy of the test model (with freshly initialized weights). + new_model = clone_model(model) + ``` + + Note that subclassed models cannot be cloned, since their internal + layer structure is not known. To achieve equivalent functionality + as `clone_model` in the case of a subclassed model, simply make sure + that the model class implements `get_config()` + (and optionally `from_config()`), and call: + + ```python + new_model = model.__class__.from_config(model.get_config()) + ``` + """ + with generic_utils.DisableSharedObjectScope(): + if clone_function is None: + clone_function = _clone_layer + + if isinstance(model, Sequential): + return _clone_sequential_model( + model, input_tensors=input_tensors, layer_fn=clone_function) + else: + return _clone_functional_model( + model, input_tensors=input_tensors, layer_fn=clone_function) + + +# "Clone" a subclassed model by reseting all of the attributes. +def _in_place_subclassed_model_reset(model): + """Substitute for model cloning that works for subclassed models. + + Subclassed models cannot be cloned because their topology is not serializable. + To "instantiate" an identical model in a new TF graph, we reuse the original + model object, but we clear its state. + + After calling this function on a model instance, you can use the model + instance as if it were a model clone (in particular you can use it in a new + graph). + + This method clears the state of the input model. It is thus destructive. + However the original state can be restored fully by calling + `_in_place_subclassed_model_state_restoration`. + + Args: + model: Instance of a Keras model created via subclassing. + + Raises: + ValueError: In case the model uses a subclassed model as inner layer. + """ + assert not model._is_graph_network # Only makes sense for subclassed networks + # Select correct base class for new Model. + version_utils.swap_class(model.__class__, training.Model, training_v1.Model, + ops.executing_eagerly_outside_functions()) + # Retrieve all layers tracked by the model as well as their attribute names + attributes_cache = {} + for name in dir(model): + # Skip attrs that track other trackables. + if name == 'submodules' or name == '_self_tracked_trackables': + continue + + try: + value = getattr(model, name) + except (AttributeError, ValueError, TypeError): + continue + if isinstance(value, Layer): + attributes_cache[name] = value + assert value in model.layers + if hasattr(value, 'layers') and value.layers: + raise ValueError('We do not support the use of nested layers ' + 'in `model_to_estimator` at this time. Found nested ' + 'layer: %s' % value) + elif isinstance( + value, (list, tuple)) and name not in ('layers', '_layers', 'metrics', + '_compile_metric_functions', + '_output_loss_metrics'): + # Handle case: list/tuple of layers (also tracked by the Network API). + if value and all(isinstance(val, Layer) for val in value): + raise ValueError('We do not support the use of list-of-layers ' + 'attributes in subclassed models used with ' + '`model_to_estimator` at this time. Found list ' + 'model: %s' % name) + + # Replace layers on the model with fresh layers + layers_to_names = {value: key for key, value in attributes_cache.items()} + original_layers = list( + model._flatten_layers(include_self=False, recursive=False)) + setattr_tracking = model._setattr_tracking + model._setattr_tracking = False + model._self_tracked_trackables = [] + for layer in original_layers: # We preserve layer order. + config = layer.get_config() + # This will not work for nested subclassed models used as layers. + # This would be theoretically possible to support, but would add complexity. + # Only do it if users complain. + if isinstance(layer, training.Model) and not layer._is_graph_network: + raise ValueError('We do not support the use of nested subclassed models ' + 'in `model_to_estimator` at this time. Found nested ' + 'model: %s' % layer) + fresh_layer = layer.__class__.from_config(config) + name = layers_to_names[layer] + setattr(model, name, fresh_layer) + model._self_tracked_trackables.append(fresh_layer) + + # Cache original model build attributes (in addition to layers) + if (not hasattr(model, '_original_attributes_cache') or + model._original_attributes_cache is None): + if model.built: + attributes_to_cache = [ + 'inputs', + 'outputs', + 'total_loss', + 'optimizer', + 'train_function', + 'test_function', + 'predict_function', + '_training_endpoints', + '_collected_trainable_weights', + '_feed_inputs', + '_feed_input_names', + '_feed_input_shapes', + ] + for name in attributes_to_cache: + attributes_cache[name] = getattr(model, name) + model._original_attributes_cache = attributes_cache + _reset_build_compile_trackers(model) + model._setattr_tracking = setattr_tracking + + +def _reset_build_compile_trackers(model): + """Reset state trackers for model. + + Note that we do not actually zero out attributes such as optimizer, + but instead rely on the expectation that all of the attrs will be + over-written on calling build/compile/etc. This is somewhat fragile, + insofar as we check elsewhere for the presence of these attributes as + evidence of having been built/compiled/etc. Pending a better way to do this, + we reset key attributes here to allow building and compiling. + + Args: + model: the model that is being reset + """ + # Reset build state + model.built = False + model.inputs = None + model.outputs = None + # Reset compile state + model._is_compiled = False # pylint:disable=protected-access + if not ops.executing_eagerly_outside_functions(): + model._v1_compile_was_called = False + model.optimizer = None + + +def in_place_subclassed_model_state_restoration(model): + """Restores the original state of a model after it was "reset". + + This undoes this action of `_in_place_subclassed_model_reset`, which is called + in `clone_and_build_model` if `in_place_reset` is set to True. + + Args: + model: Instance of a Keras model created via subclassing, on which + `_in_place_subclassed_model_reset` was previously called. + """ + assert not model._is_graph_network + # Restore layers and build attributes + if (hasattr(model, '_original_attributes_cache') and + model._original_attributes_cache is not None): + # Models have sticky attribute assignment, so we want to be careful to add + # back the previous attributes and track Layers by their original names + # without adding dependencies on "utility" attributes which Models exempt + # when they're constructed. + setattr_tracking = model._setattr_tracking + model._setattr_tracking = False + model._self_tracked_trackables = [] + for name, value in model._original_attributes_cache.items(): + setattr(model, name, value) + if isinstance(value, Layer): + model._self_tracked_trackables.append(value) + model._original_attributes_cache = None + model._setattr_tracking = setattr_tracking + else: + # Restore to the state of a never-called model. + _reset_build_compile_trackers(model) + + +def clone_and_build_model( + model, input_tensors=None, target_tensors=None, custom_objects=None, + compile_clone=True, in_place_reset=False, optimizer_iterations=None, + optimizer_config=None): + """Clone a `Model` and build/compile it with the same settings used before. + + This function can be run in the same graph or in a separate graph from the + model. When using a separate graph, `in_place_reset` must be `False`. + + Note that, currently, the clone produced from this function may not work with + TPU DistributionStrategy. Try at your own risk. + + Args: + model: `tf.keras.Model` object. Can be Functional, Sequential, or + sub-classed. + input_tensors: Optional list or dictionary of input tensors to build the + model upon. If not provided, placeholders will be created. + target_tensors: Optional list of target tensors for compiling the model. If + not provided, placeholders will be created. + custom_objects: Optional dictionary mapping string names to custom classes + or functions. + compile_clone: Boolean, whether to compile model clone (default `True`). + in_place_reset: Boolean, whether to reset the model in place. Only used if + the model is a subclassed model. In the case of a subclassed model, + this argument must be set to `True` (default `False`). To restore the + original model, use the function + `in_place_subclassed_model_state_restoration(model)`. + optimizer_iterations: An iterations variable that will be incremented by the + optimizer if the clone is compiled. This argument is used when a Keras + model is cloned into an Estimator model function, because Estimators + create their own global step variable. + optimizer_config: Optimizer config dictionary or list of dictionary + returned from `get_config()`. This argument should be defined if + `clone_and_build_model` is called in a different graph or session from + the original model, and the optimizer is an instance of `OptimizerV2`. + + Returns: + Clone of the model. + + Raises: + ValueError: Cloning fails in the following cases + - cloning a subclassed model with `in_place_reset` set to False. + - compiling the clone when the original model has not been compiled. + """ + # Grab optimizer now, as we reset-in-place for subclassed models, but + # want to maintain access to the original optimizer. + orig_optimizer = model.optimizer + if compile_clone and not orig_optimizer: + raise ValueError( + 'Error when cloning model: compile_clone was set to True, but the ' + 'original model has not been compiled.') + + if compile_clone: + compile_args = model._get_compile_args() # pylint: disable=protected-access + # Allows this method to be robust to switching graph and eager classes. + model._get_compile_args = lambda: compile_args + + with CustomObjectScope(custom_objects or {}): + if model._is_graph_network: + clone = clone_model(model, input_tensors=input_tensors) + elif isinstance(model, Sequential): + clone = clone_model(model, input_tensors=input_tensors) + if (not clone._is_graph_network and model._build_input_shape is not None): + if ops.executing_eagerly_outside_functions(): + clone.build(model._build_input_shape) + else: + clone._set_inputs( + backend.placeholder( + model._build_input_shape, dtype=model.inputs[0].dtype)) + else: + try: + # Prefer cloning the model if serial/deserial logic is implemented for + # subclassed model. + clone = model.__class__.from_config(model.get_config()) + except NotImplementedError: + logging.warning('This model is a subclassed model. Please implement ' + '`get_config` and `from_config` to better support ' + 'cloning the model.') + if not in_place_reset: + raise ValueError( + 'This model is a subclassed model. ' + 'Such a model cannot be cloned, but there is a workaround where ' + 'the model is reset in-place. To use this, please set the ' + 'argument `in_place_reset` to `True`. This will reset the ' + 'attributes in the original model. To restore the attributes, ' + 'call `in_place_subclassed_model_state_restoration(model)`.') + clone = model + _in_place_subclassed_model_reset(clone) + if input_tensors is not None: + if isinstance(input_tensors, (list, tuple)) and len(input_tensors) == 1: + input_tensors = input_tensors[0] + clone._set_inputs(input_tensors) + + if compile_clone: + if isinstance(orig_optimizer, optimizer_v1.TFOptimizer): + optimizer = optimizer_v1.TFOptimizer( + orig_optimizer.optimizer, optimizer_iterations) + backend.track_tf_optimizer(optimizer) + else: + if not isinstance(orig_optimizer, (tuple, list)): + orig_optimizer = [orig_optimizer] + if optimizer_config is None: + optimizer = [ + opt.__class__.from_config(opt.get_config()) + for opt in orig_optimizer + ] + elif isinstance(optimizer_config, dict): + optimizer = [orig_optimizer[0].__class__.from_config(optimizer_config)] + else: + # optimizer config is list of dict, same order as orig_optimizer. + optimizer = [ + opt.__class__.from_config(opt_config) + for (opt, opt_config) in zip(orig_optimizer, optimizer_config) + ] + if optimizer_iterations is not None: + for opt in optimizer: + opt.iterations = optimizer_iterations + + if len(optimizer) == 1: + optimizer = optimizer[0] + + compile_args['optimizer'] = optimizer + if target_tensors is not None: + compile_args['target_tensors'] = target_tensors + # Ensure Metric objects in new model are separate from existing model. + compile_args['metrics'] = metrics_module.clone_metrics( + compile_args['metrics']) + compile_args['weighted_metrics'] = metrics_module.clone_metrics( + compile_args['weighted_metrics']) + clone.compile(**compile_args) + + return clone diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v1.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v1.py new file mode 100644 index 0000000000000000000000000000000000000000..3296f9a50b008235e061128147043232429ab00f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/keras/optimizer_v1.py @@ -0,0 +1,855 @@ +# 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. +# ============================================================================== +# pylint: disable=invalid-name +# pylint: disable=g-classes-have-attributes +"""Legacy v1 optimizer classes. + +For more examples see the base class `tf.compat.v1.keras.optimizers.Optimizer`. +""" + +from tensorflow.python.distribute import distribute_lib +from tensorflow.python.eager import backprop +from tensorflow.python.framework import ops +from tensorflow.python.keras import backend +from tensorflow.python.ops import clip_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import state_ops +from tensorflow.python.trackable import base as trackable +from tensorflow.python.training import training_util +from tensorflow.python.util import nest + + +class Optimizer(object): + """Abstract optimizer base class. + + Note: this is the parent class of all optimizers, not an actual optimizer + that can be used for training models. + + All Keras optimizers support the following keyword arguments: + + clipnorm: float >= 0. Gradients will be clipped + when their L2 norm exceeds this value. + clipvalue: float >= 0. Gradients will be clipped + when their absolute value exceeds this value. + """ + + def __init__(self, **kwargs): + allowed_kwargs = {'clipnorm', 'clipvalue'} + for k in kwargs: + if k not in allowed_kwargs: + raise TypeError('Unexpected keyword argument ' + 'passed to optimizer: ' + str(k)) + # checks that clipnorm >= 0 and clipvalue >= 0 + if kwargs[k] < 0: + raise ValueError('Expected {} >= 0, received: {}'.format(k, kwargs[k])) + self.__dict__.update(kwargs) + self.updates = [] + self.weights = [] + + # Set this to False, indicating `apply_gradients` does not take the + # `experimental_aggregate_gradients` argument. + _HAS_AGGREGATE_GRAD = False + + def _create_all_weights(self, params): + """Creates and sets all optimizer weights. + + Args: + params: list or tuple of `Variable` objects that will be minimized + using this optimizer. + + Returns: + Specific weight values that are used in `get_updates` + """ + raise NotImplementedError + + def get_updates(self, loss, params): + raise NotImplementedError + + def get_gradients(self, loss, params): + """Returns gradients of `loss` with respect to `params`. + + Args: + loss: Loss tensor. + params: List of variables. + + Returns: + List of gradient tensors. + + Raises: + ValueError: In case any gradient cannot be computed (e.g. if gradient + function not implemented). + """ + grads = backend.gradients(loss, params) + if any(g is None for g in grads): + raise ValueError('An operation has `None` for gradient. ' + 'Please make sure that all of your ops have a ' + 'gradient defined (i.e. are differentiable). ' + 'Common ops without gradient: ' + 'backend.argmax, backend.round, backend.eval.') + if hasattr(self, 'clipnorm'): + grads = [clip_ops.clip_by_norm(g, self.clipnorm) for g in grads] + if hasattr(self, 'clipvalue'): + grads = [ + clip_ops.clip_by_value(g, -self.clipvalue, self.clipvalue) + for g in grads + ] + return grads + + def set_weights(self, weights): + """Sets the weights of the optimizer, from Numpy arrays. + + Should only be called after computing the gradients + (otherwise the optimizer has no weights). + + Args: + weights: a list of Numpy arrays. The number of arrays and their shape + must match number of the dimensions of the weights of the optimizer + (i.e. it should match the output of `get_weights`). + + Raises: + ValueError: in case of incompatible weight shapes. + """ + params = self.weights + if len(params) != len(weights): + raise ValueError('Length of the specified weight list (' + + str(len(weights)) + + ') does not match the number of weights ' + 'of the optimizer (' + str(len(params)) + ')') + weight_value_tuples = [] + param_values = backend.batch_get_value(params) + for pv, p, w in zip(param_values, params, weights): + if pv.shape != w.shape: + raise ValueError('Optimizer weight shape ' + str(pv.shape) + + ' not compatible with ' + 'provided weight shape ' + str(w.shape)) + weight_value_tuples.append((p, w)) + backend.batch_set_value(weight_value_tuples) + + def get_weights(self): + """Returns the current value of the weights of the optimizer. + + Returns: + A list of numpy arrays. + """ + return backend.batch_get_value(self.weights) + + def get_config(self): + config = {} + if hasattr(self, 'clipnorm'): + config['clipnorm'] = self.clipnorm + if hasattr(self, 'clipvalue'): + config['clipvalue'] = self.clipvalue + return config + + @classmethod + def from_config(cls, config): + return cls(**config) + + +class SGD(Optimizer): + """Stochastic gradient descent optimizer. + + Includes support for momentum, + learning rate decay, and Nesterov momentum. + + Args: + lr: float >= 0. Learning rate. + momentum: float >= 0. Parameter that accelerates SGD in the relevant + direction and dampens oscillations. + decay: float >= 0. Learning rate decay over each update. + nesterov: boolean. Whether to apply Nesterov momentum. + """ + + def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False, **kwargs): + super(SGD, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.iterations = backend.variable(0, dtype='int64', name='iterations') + self.lr = backend.variable(lr, name='lr') + self.momentum = backend.variable(momentum, name='momentum') + self.decay = backend.variable(decay, name='decay') + self.initial_decay = decay + self.nesterov = nesterov + + def _create_all_weights(self, params): + shapes = [backend.int_shape(p) for p in params] + moments = [backend.zeros(shape) for shape in shapes] + self.weights = [self.iterations] + moments + return moments + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + self.updates = [state_ops.assign_add(self.iterations, 1)] + + lr = self.lr + if self.initial_decay > 0: + lr = lr * ( + 1. / + (1. + + self.decay * math_ops.cast(self.iterations, + backend.dtype(self.decay)))) + # momentum + moments = self._create_all_weights(params) + for p, g, m in zip(params, grads, moments): + v = self.momentum * m - lr * g # velocity + self.updates.append(state_ops.assign(m, v)) + + if self.nesterov: + new_p = p + self.momentum * v - lr * g + else: + new_p = p + v + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'momentum': float(backend.get_value(self.momentum)), + 'decay': float(backend.get_value(self.decay)), + 'nesterov': self.nesterov + } + base_config = super(SGD, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class RMSprop(Optimizer): + """RMSProp optimizer. + + It is recommended to leave the parameters of this optimizer + at their default values + (except the learning rate, which can be freely tuned). + + Args: + lr: float >= 0. Learning rate. + rho: float >= 0. + epsilon: float >= 0. Fuzz factor. + If `None`, defaults to `backend.epsilon()`. + decay: float >= 0. Learning rate decay over each update. + """ + + def __init__(self, lr=0.001, rho=0.9, epsilon=None, decay=0., **kwargs): + super(RMSprop, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.lr = backend.variable(lr, name='lr') + self.rho = backend.variable(rho, name='rho') + self.decay = backend.variable(decay, name='decay') + self.iterations = backend.variable(0, dtype='int64', name='iterations') + if epsilon is None: + epsilon = backend.epsilon() + self.epsilon = epsilon + self.initial_decay = decay + + def _create_all_weights(self, params): + accumulators = [ + backend.zeros(backend.int_shape(p), dtype=backend.dtype(p)) + for p in params] + self.weights = accumulators + return accumulators + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + accumulators = self._create_all_weights(params) + self.updates = [state_ops.assign_add(self.iterations, 1)] + + lr = self.lr + if self.initial_decay > 0: + lr = lr * ( + 1. / + (1. + + self.decay * math_ops.cast(self.iterations, + backend.dtype(self.decay)))) + + for p, g, a in zip(params, grads, accumulators): + # update accumulator + new_a = self.rho * a + (1. - self.rho) * math_ops.square(g) + self.updates.append(state_ops.assign(a, new_a)) + new_p = p - lr * g / (backend.sqrt(new_a) + self.epsilon) + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'rho': float(backend.get_value(self.rho)), + 'decay': float(backend.get_value(self.decay)), + 'epsilon': self.epsilon + } + base_config = super(RMSprop, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Adagrad(Optimizer): + """Adagrad optimizer. + + Adagrad is an optimizer with parameter-specific learning rates, + which are adapted relative to how frequently a parameter gets + updated during training. The more updates a parameter receives, + the smaller the updates. + + It is recommended to leave the parameters of this optimizer + at their default values. + + # Arguments + lr: float >= 0. Initial learning rate. + epsilon: float >= 0. If `None`, defaults to `backend.epsilon()`. + decay: float >= 0. Learning rate decay over each update. + + # References + - [Adaptive Subgradient Methods for Online Learning and Stochastic + Optimization](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf) + """ + + def __init__(self, lr=0.01, epsilon=None, decay=0., **kwargs): + super(Adagrad, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.lr = backend.variable(lr, name='lr') + self.decay = backend.variable(decay, name='decay') + self.iterations = backend.variable(0, dtype='int64', name='iterations') + if epsilon is None: + epsilon = backend.epsilon() + self.epsilon = epsilon + self.initial_decay = decay + + def _create_all_weights(self, params): + shapes = [backend.int_shape(p) for p in params] + accumulators = [backend.zeros(shape) for shape in shapes] + self.weights = accumulators + return accumulators + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + accumulators = self._create_all_weights(params) + + self.updates = [state_ops.assign_add(self.iterations, 1)] + + lr = self.lr + if self.initial_decay > 0: + lr = lr * ( + 1. / + (1. + + self.decay * math_ops.cast(self.iterations, + backend.dtype(self.decay)))) + + for p, g, a in zip(params, grads, accumulators): + new_a = a + math_ops.square(g) # update accumulator + self.updates.append(state_ops.assign(a, new_a)) + new_p = p - lr * g / (backend.sqrt(new_a) + self.epsilon) + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'decay': float(backend.get_value(self.decay)), + 'epsilon': self.epsilon + } + base_config = super(Adagrad, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Adadelta(Optimizer): + """Adadelta optimizer. + + Adadelta is a more robust extension of Adagrad + that adapts learning rates based on a moving window of gradient updates, + instead of accumulating all past gradients. This way, Adadelta continues + learning even when many updates have been done. Compared to Adagrad, in the + original version of Adadelta you don't have to set an initial learning + rate. In this version, initial learning rate and decay factor can + be set, as in most other Keras optimizers. + + It is recommended to leave the parameters of this optimizer + at their default values. + + Arguments: + lr: float >= 0. Initial learning rate, defaults to 1. + It is recommended to leave it at the default value. + rho: float >= 0. Adadelta decay factor, corresponding to fraction of + gradient to keep at each time step. + epsilon: float >= 0. Fuzz factor. + If `None`, defaults to `backend.epsilon()`. + decay: float >= 0. Initial learning rate decay. + + References: + - [Adadelta - an adaptive learning rate + method](http://arxiv.org/abs/1212.5701) + """ + + def __init__(self, lr=1.0, rho=0.95, epsilon=None, decay=0., **kwargs): + super(Adadelta, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.lr = backend.variable(lr, name='lr') + self.decay = backend.variable(decay, name='decay') + self.iterations = backend.variable(0, dtype='int64', name='iterations') + if epsilon is None: + epsilon = backend.epsilon() + self.rho = rho + self.epsilon = epsilon + self.initial_decay = decay + + def _create_all_weights(self, params): + shapes = [backend.int_shape(p) for p in params] + accumulators = [backend.zeros(shape) for shape in shapes] + delta_accumulators = [backend.zeros(shape) for shape in shapes] + self.weights = accumulators + delta_accumulators + return accumulators, delta_accumulators + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + self.updates = [state_ops.assign_add(self.iterations, 1)] + accumulators, delta_accumulators = self._create_all_weights(params) + + lr = self.lr + if self.initial_decay > 0: + lr = lr * ( + 1. / + (1. + + self.decay * math_ops.cast(self.iterations, + backend.dtype(self.decay)))) + + for p, g, a, d_a in zip(params, grads, accumulators, delta_accumulators): + # update accumulator + new_a = self.rho * a + (1. - self.rho) * math_ops.square(g) + self.updates.append(state_ops.assign(a, new_a)) + + # use the new accumulator and the *old* delta_accumulator + update = g * backend.sqrt(d_a + self.epsilon) / backend.sqrt( + new_a + self.epsilon) + new_p = p - lr * update + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + + # update delta_accumulator + new_d_a = self.rho * d_a + (1 - self.rho) * math_ops.square(update) + self.updates.append(state_ops.assign(d_a, new_d_a)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'rho': self.rho, + 'decay': float(backend.get_value(self.decay)), + 'epsilon': self.epsilon + } + base_config = super(Adadelta, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Adam(Optimizer): + """Adam optimizer. + + Default parameters follow those provided in the original paper. + + Args: + lr: float >= 0. Learning rate. + beta_1: float, 0 < beta < 1. Generally close to 1. + beta_2: float, 0 < beta < 1. Generally close to 1. + epsilon: float >= 0. Fuzz factor. + If `None`, defaults to `backend.epsilon()`. + decay: float >= 0. Learning rate decay over each update. + amsgrad: boolean. Whether to apply the AMSGrad variant of this algorithm + from the paper "On the Convergence of Adam and Beyond". + """ + + def __init__(self, + lr=0.001, + beta_1=0.9, + beta_2=0.999, + epsilon=None, + decay=0., + amsgrad=False, + **kwargs): + super(Adam, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.iterations = backend.variable(0, dtype='int64', name='iterations') + self.lr = backend.variable(lr, name='lr') + self.beta_1 = backend.variable(beta_1, name='beta_1') + self.beta_2 = backend.variable(beta_2, name='beta_2') + self.decay = backend.variable(decay, name='decay') + if epsilon is None: + epsilon = backend.epsilon() + self.epsilon = epsilon + self.initial_decay = decay + self.amsgrad = amsgrad + + def _create_all_weights(self, params): + ms = [ + backend.zeros(backend.int_shape(p), dtype=backend.dtype(p)) + for p in params] + vs = [ + backend.zeros(backend.int_shape(p), dtype=backend.dtype(p)) + for p in params] + if self.amsgrad: + vhats = [ + backend.zeros(backend.int_shape(p), dtype=backend.dtype(p)) + for p in params] + else: + vhats = [backend.zeros(1) for _ in params] + self.weights = [self.iterations] + ms + vs + vhats + return ms, vs, vhats + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + self.updates = [] + + lr = self.lr + if self.initial_decay > 0: + lr = lr * ( + 1. / + (1. + + self.decay * math_ops.cast(self.iterations, + backend.dtype(self.decay)))) + + with ops.control_dependencies([state_ops.assign_add(self.iterations, 1)]): + t = math_ops.cast(self.iterations, backend.floatx()) + lr_t = lr * ( + backend.sqrt(1. - math_ops.pow(self.beta_2, t)) / + (1. - math_ops.pow(self.beta_1, t))) + + ms, vs, vhats = self._create_all_weights(params) + for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats): + m_t = (self.beta_1 * m) + (1. - self.beta_1) * g + v_t = (self.beta_2 * v) + (1. - self.beta_2) * math_ops.square(g) + if self.amsgrad: + vhat_t = math_ops.maximum(vhat, v_t) + p_t = p - lr_t * m_t / (backend.sqrt(vhat_t) + self.epsilon) + self.updates.append(state_ops.assign(vhat, vhat_t)) + else: + p_t = p - lr_t * m_t / (backend.sqrt(v_t) + self.epsilon) + + self.updates.append(state_ops.assign(m, m_t)) + self.updates.append(state_ops.assign(v, v_t)) + new_p = p_t + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'beta_1': float(backend.get_value(self.beta_1)), + 'beta_2': float(backend.get_value(self.beta_2)), + 'decay': float(backend.get_value(self.decay)), + 'epsilon': self.epsilon, + 'amsgrad': self.amsgrad + } + base_config = super(Adam, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Adamax(Optimizer): + """Adamax optimizer from Adam paper's Section 7. + + It is a variant of Adam based on the infinity norm. + Default parameters follow those provided in the paper. + + Args: + lr: float >= 0. Learning rate. + beta_1/beta_2: floats, 0 < beta < 1. Generally close to 1. + epsilon: float >= 0. Fuzz factor. + If `None`, defaults to `backend.epsilon()`. + decay: float >= 0. Learning rate decay over each update. + """ + + def __init__(self, + lr=0.002, + beta_1=0.9, + beta_2=0.999, + epsilon=None, + decay=0., + **kwargs): + super(Adamax, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.iterations = backend.variable(0, dtype='int64', name='iterations') + self.lr = backend.variable(lr, name='lr') + self.beta_1 = backend.variable(beta_1, name='beta_1') + self.beta_2 = backend.variable(beta_2, name='beta_2') + self.decay = backend.variable(decay, name='decay') + if epsilon is None: + epsilon = backend.epsilon() + self.epsilon = epsilon + self.initial_decay = decay + + def _create_all_weights(self, params): + + shapes = [backend.int_shape(p) for p in params] + # zero init of 1st moment + ms = [backend.zeros(shape) for shape in shapes] + # zero init of exponentially weighted infinity norm + us = [backend.zeros(shape) for shape in shapes] + self.weights = [self.iterations] + ms + us + return ms, us + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + self.updates = [] + + lr = self.lr + if self.initial_decay > 0: + lr = lr * ( + 1. / + (1. + + self.decay * math_ops.cast(self.iterations, + backend.dtype(self.decay)))) + + with ops.control_dependencies([state_ops.assign_add(self.iterations, 1)]): + t = math_ops.cast(self.iterations, backend.floatx()) + lr_t = lr / (1. - math_ops.pow(self.beta_1, t)) + + ms, us = self._create_all_weights(params) + + for p, g, m, u in zip(params, grads, ms, us): + + m_t = (self.beta_1 * m) + (1. - self.beta_1) * g + u_t = math_ops.maximum(self.beta_2 * u, math_ops.abs(g)) + p_t = p - lr_t * m_t / (u_t + self.epsilon) + + self.updates.append(state_ops.assign(m, m_t)) + self.updates.append(state_ops.assign(u, u_t)) + new_p = p_t + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'beta_1': float(backend.get_value(self.beta_1)), + 'beta_2': float(backend.get_value(self.beta_2)), + 'decay': float(backend.get_value(self.decay)), + 'epsilon': self.epsilon + } + base_config = super(Adamax, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class Nadam(Optimizer): + """Nesterov Adam optimizer. + + Much like Adam is essentially RMSprop with momentum, + Nadam is Adam RMSprop with Nesterov momentum. + + Default parameters follow those provided in the paper. + It is recommended to leave the parameters of this optimizer + at their default values. + + Args: + lr: float >= 0. Learning rate. + beta_1/beta_2: floats, 0 < beta < 1. Generally close to 1. + epsilon: float >= 0. Fuzz factor. + If `None`, defaults to `backend.epsilon()`. + """ + + def __init__(self, + lr=0.002, + beta_1=0.9, + beta_2=0.999, + epsilon=None, + schedule_decay=0.004, + **kwargs): + super(Nadam, self).__init__(**kwargs) + with backend.name_scope(self.__class__.__name__): + self.iterations = backend.variable(0, dtype='int64', name='iterations') + self.m_schedule = backend.variable(1., name='m_schedule') + self.lr = backend.variable(lr, name='lr') + self.beta_1 = backend.variable(beta_1, name='beta_1') + self.beta_2 = backend.variable(beta_2, name='beta_2') + if epsilon is None: + epsilon = backend.epsilon() + self.epsilon = epsilon + self.schedule_decay = schedule_decay + + def _create_all_weights(self, params): + shapes = [backend.int_shape(p) for p in params] + ms = [backend.zeros(shape) for shape in shapes] + vs = [backend.zeros(shape) for shape in shapes] + + self.weights = [self.iterations, self.m_schedule] + ms + vs + return ms, vs + + def get_updates(self, loss, params): + grads = self.get_gradients(loss, params) + self.updates = [] + + with ops.control_dependencies([state_ops.assign_add(self.iterations, 1)]): + t = math_ops.cast(self.iterations, backend.floatx()) + + # Due to the recommendations in [2], i.e. warming momentum schedule + momentum_cache_t = self.beta_1 * ( + 1. - 0.5 * + (math_ops.pow(backend.cast_to_floatx(0.96), t * self.schedule_decay))) + momentum_cache_t_1 = self.beta_1 * ( + 1. - 0.5 * + (math_ops.pow(backend.cast_to_floatx(0.96), + (t + 1) * self.schedule_decay))) + m_schedule_new = self.m_schedule * momentum_cache_t + m_schedule_next = self.m_schedule * momentum_cache_t * momentum_cache_t_1 + self.updates.append((self.m_schedule, m_schedule_new)) + + ms, vs = self._create_all_weights(params) + + for p, g, m, v in zip(params, grads, ms, vs): + # the following equations given in [1] + g_prime = g / (1. - m_schedule_new) + m_t = self.beta_1 * m + (1. - self.beta_1) * g + m_t_prime = m_t / (1. - m_schedule_next) + v_t = self.beta_2 * v + (1. - self.beta_2) * math_ops.square(g) + v_t_prime = v_t / (1. - math_ops.pow(self.beta_2, t)) + m_t_bar = (1. - + momentum_cache_t) * g_prime + momentum_cache_t_1 * m_t_prime + + self.updates.append(state_ops.assign(m, m_t)) + self.updates.append(state_ops.assign(v, v_t)) + + p_t = p - self.lr * m_t_bar / (backend.sqrt(v_t_prime) + self.epsilon) + new_p = p_t + + # Apply constraints. + if getattr(p, 'constraint', None) is not None: + new_p = p.constraint(new_p) + + self.updates.append(state_ops.assign(p, new_p)) + return self.updates + + def get_config(self): + config = { + 'lr': float(backend.get_value(self.lr)), + 'beta_1': float(backend.get_value(self.beta_1)), + 'beta_2': float(backend.get_value(self.beta_2)), + 'epsilon': self.epsilon, + 'schedule_decay': self.schedule_decay + } + base_config = super(Nadam, self).get_config() + return dict(list(base_config.items()) + list(config.items())) + + +class TFOptimizer(Optimizer, trackable.Trackable): + """Wrapper class for native TensorFlow optimizers.""" + + def __init__(self, optimizer, iterations=None): # pylint: disable=super-init-not-called + self.optimizer = optimizer + self._track_trackable(optimizer, name='optimizer') + if iterations is None: + with backend.name_scope(self.__class__.__name__): + self.iterations = backend.variable(0, dtype='int64', name='iterations') + else: + self.iterations = iterations + self._track_trackable(self.iterations, name='global_step') + + def _clip_gradients(self, grads): + """Clip gradients according to the clipnorm and clipvalue attributes.""" + # TFOptimizer wrapper has no gradient clipping options. + return grads + + def minimize(self, loss, var_list, grad_loss=None, tape=None): + """Mimics the `OptimizerV2.minimize` API.""" + if not callable(loss) and tape is None: + raise ValueError('`tape` is required when a `Tensor` loss is passed.') + tape = tape if tape is not None else backprop.GradientTape() + + if callable(loss): + with tape: + if not callable(var_list): + tape.watch(var_list) + loss = loss() + if callable(var_list): + var_list = var_list() + + var_list = nest.flatten(var_list) + if var_list: + grads = tape.gradient(loss, var_list, grad_loss) + grads_and_vars = list(zip(grads, var_list)) + self.apply_gradients(grads_and_vars) + + def apply_gradients(self, grads_and_vars): + self.optimizer.apply_gradients(grads_and_vars, global_step=self.iterations) + + def get_grads(self, loss, params): + return self.optimizer.compute_gradients(loss, params) + + def get_updates(self, loss, params): + if distribute_lib.has_strategy(): + self.updates = [] + + if not params: + # After the model vars have been created, the second call to get_updates + # is called with params as an empty list. This ensures that we call + # compute_gradients with params=None. + grads = self.optimizer.compute_gradients(loss) + else: + grads = self.optimizer.compute_gradients(loss, params) + global_step = training_util.get_global_step() + opt_update = self.optimizer.apply_gradients(grads, global_step) + else: + if not params: + self.updates = [state_ops.assign_add(self.iterations, 1)] + return self.updates + + # Updates list starts out empty because the iterations variable is + # incremented in optimizer.apply_gradients() + self.updates = [] + grads = self.optimizer.compute_gradients(loss, params) + opt_update = self.optimizer.apply_gradients( + grads, global_step=self.iterations) + + self.updates.append(opt_update) + return self.updates + + @property + def weights(self): + raise NotImplementedError + + def get_config(self): + raise NotImplementedError + + def from_config(self, config): + raise NotImplementedError + + +# Aliases. + +sgd = SGD +rmsprop = RMSprop +adagrad = Adagrad +adadelta = Adadelta +adam = Adam +adamax = Adamax +nadam = Nadam diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/proto_exports.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/proto_exports.py new file mode 100644 index 0000000000000000000000000000000000000000..824e1fefb5fa6551dd1b67bc412092ce0116ed81 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/proto_exports.py @@ -0,0 +1,62 @@ +# Copyright 2023 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Registers protos with tf_export that should be public.""" + +from tensorflow.core.framework import attr_value_pb2 +from tensorflow.core.framework import node_def_pb2 +from tensorflow.core.framework import summary_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import meta_graph_pb2 +from tensorflow.core.util import event_pb2 +from tensorflow.python.util import tf_export +from tensorflow.tsl.protobuf import histogram_pb2 + +AttrValue = tf_export.tf_export(v1=['AttrValue'])(attr_value_pb2.AttrValue) +ConfigProto = tf_export.tf_export(v1=['ConfigProto'])(config_pb2.ConfigProto) +Event = tf_export.tf_export(v1=['Event', 'summary.Event'])(event_pb2.Event) +GPUOptions = tf_export.tf_export(v1=['GPUOptions'])(config_pb2.GPUOptions) +GraphOptions = tf_export.tf_export(v1=['GraphOptions'])(config_pb2.GraphOptions) +HistogramProto = tf_export.tf_export(v1=['HistogramProto'])( + histogram_pb2.HistogramProto +) +LogMessage = tf_export.tf_export(v1=['LogMessage'])(event_pb2.LogMessage) +MetaGraphDef = tf_export.tf_export(v1=['MetaGraphDef'])( + meta_graph_pb2.MetaGraphDef +) +NameAttrList = tf_export.tf_export(v1=['NameAttrList'])( + attr_value_pb2.NameAttrList +) +NodeDef = tf_export.tf_export(v1=['NodeDef'])(node_def_pb2.NodeDef) +OptimizerOptions = tf_export.tf_export(v1=['OptimizerOptions'])( + config_pb2.OptimizerOptions +) +RunMetadata = tf_export.tf_export(v1=['RunMetadata'])(config_pb2.RunMetadata) +RunOptions = tf_export.tf_export(v1=['RunOptions'])(config_pb2.RunOptions) +SessionLog = tf_export.tf_export(v1=['SessionLog', 'summary.SessionLog'])( + event_pb2.SessionLog +) +Summary = tf_export.tf_export(v1=['Summary', 'summary.Summary'])( + summary_pb2.Summary +) +SummaryDescription = tf_export.tf_export(v1=['summary.SummaryDescription'])( + summary_pb2.SummaryDescription +) +SummaryMetadata = tf_export.tf_export(v1=['SummaryMetadata'])( + summary_pb2.SummaryMetadata +) +TaggedRunMetadata = tf_export.tf_export(v1=['summary.TaggedRunMetadata'])( + event_pb2.TaggedRunMetadata +) +TensorInfo = tf_export.tf_export(v1=['TensorInfo'])(meta_graph_pb2.TensorInfo) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_mlir.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_mlir.py new file mode 100644 index 0000000000000000000000000000000000000000..8e940894ef6795733dd923e315a0fe831208ad1f --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_mlir.py @@ -0,0 +1,129 @@ +# 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. +# ============================================================================== +"""Python module for MLIR functions exported by pybind11.""" + +# pylint: disable=invalid-import-order, g-bad-import-order, wildcard-import, unused-import, undefined-variable +from tensorflow.python import pywrap_tensorflow +from tensorflow.python.eager import context +from tensorflow.python._pywrap_mlir import * + + +def import_graphdef( + graphdef, + pass_pipeline, + show_debug_info, + input_names=None, + input_data_types=None, + input_data_shapes=None, + output_names=[], +): + if input_names is not None: + return ImportGraphDef( + str(graphdef).encode('utf-8'), + pass_pipeline.encode('utf-8'), + show_debug_info, + ','.join(input_names).encode('utf-8'), + ','.join(input_data_types).encode('utf-8'), + ':'.join(input_data_shapes).encode('utf-8'), + ','.join(output_names).encode('utf-8'), + ) + return ImportGraphDef( + str(graphdef).encode('utf-8'), + pass_pipeline.encode('utf-8'), + show_debug_info, + ) + + +def import_function(concrete_function, pass_pipeline, show_debug_info): + ctxt = context.context() + ctxt.ensure_initialized() + return ImportFunction( + ctxt._handle, + str(concrete_function.function_def).encode('utf-8'), + pass_pipeline.encode('utf-8'), + show_debug_info, + ) + + +def experimental_convert_saved_model_to_mlir( + saved_model_path, exported_names, show_debug_info +): + return ExperimentalConvertSavedModelToMlir( + str(saved_model_path).encode('utf-8'), + str(exported_names).encode('utf-8'), + show_debug_info, + ) + + +def experimental_convert_saved_model_v1_to_mlir_lite( + saved_model_path, exported_names, tags, upgrade_legacy, show_debug_info +): + return ExperimentalConvertSavedModelV1ToMlirLite( + str(saved_model_path).encode('utf-8'), + str(exported_names).encode('utf-8'), + str(tags).encode('utf-8'), + upgrade_legacy, + show_debug_info, + ) + + +def experimental_convert_saved_model_v1_to_mlir( + saved_model_path, + exported_names, + tags, + lift_variables, + include_variables_in_initializers, + upgrade_legacy, + show_debug_info, +): + return ExperimentalConvertSavedModelV1ToMlir( + str(saved_model_path).encode('utf-8'), + str(exported_names).encode('utf-8'), + str(tags).encode('utf-8'), + lift_variables, + include_variables_in_initializers, + upgrade_legacy, + show_debug_info, + ) + + +def experimental_run_pass_pipeline(mlir_txt, pass_pipeline, show_debug_info): + return ExperimentalRunPassPipeline( + mlir_txt.encode('utf-8'), pass_pipeline.encode('utf-8'), show_debug_info + ) + + +def experimental_write_bytecode(filename, mlir_txt): + return ExperimentalWriteBytecode(filename.encode('utf-8'), mlir_txt.encode()) + + +def experimental_tflite_to_tosa_bytecode( + flatbuffer, + bytecode, + use_external_constant=False, + ordered_input_arrays=None, + ordered_output_arrays=None, +): + if ordered_input_arrays is None: + ordered_input_arrays = [] + if ordered_output_arrays is None: + ordered_output_arrays = [] + return ExperimentalTFLiteToTosaBytecode( + flatbuffer.encode('utf-8'), + bytecode.encode('utf-8'), + use_external_constant, + ordered_input_arrays, + ordered_output_arrays, + ) diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_sanitizers.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_sanitizers.py new file mode 100644 index 0000000000000000000000000000000000000000..2840fd2db61fa2c36cb6ce8d4b786db9118740cb --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_sanitizers.py @@ -0,0 +1,19 @@ +# 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. +# ============================================================================== +"""Python module for sanitizer detection functions exported by pybind11.""" + +# pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import +from tensorflow.python import pywrap_tensorflow +from tensorflow.python._pywrap_sanitizers import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tensorflow.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tensorflow.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb6b922d9dc2ee6c37408153591bc5d36028219 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tensorflow.py @@ -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. +# ============================================================================= +"""A Python wrapper that loads _pywrap_tensorflow_internal.so.""" + +import ctypes +import sys +import traceback + +# TODO(vam): Override boringssl static linking by explicitly importing openssl +# Please refer to b/304394983 for more information. +try: + import ssl +except ImportError: + print(f'{traceback.format_exc()}') + print('\nWarning: Failed to load ssl module. Continuing without ssl support.') + +from tensorflow.python.platform import self_check + +# TODO(mdan): Cleanup antipattern: import for side effects. + +# Perform pre-load sanity checks in order to produce a more actionable error. +self_check.preload_check() + +# pylint: disable=wildcard-import,g-import-not-at-top,unused-import,line-too-long + +try: + # This import is expected to fail if there is an explicit shared object + # dependency (with_framework_lib=true), since we do not need RTLD_GLOBAL. + from tensorflow.python import pywrap_dlopen_global_flags + _use_dlopen_global_flags = True +except ImportError: + _use_dlopen_global_flags = False + +# On UNIX-based platforms, pywrap_tensorflow is a python library that +# dynamically loads _pywrap_tensorflow.so. +_can_set_rtld_local = ( + hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags')) +if _can_set_rtld_local: + _default_dlopen_flags = sys.getdlopenflags() + +try: + if _use_dlopen_global_flags: + pywrap_dlopen_global_flags.set_dlopen_flags() + elif _can_set_rtld_local: + # Ensure RTLD_LOCAL behavior for platforms where it isn't the default + # (macOS). On Linux RTLD_LOCAL is 0, so this does nothing (and would not + # override an RTLD_GLOBAL in _default_dlopen_flags). + sys.setdlopenflags(_default_dlopen_flags | ctypes.RTLD_LOCAL) + + # Python2.7 does not have a ModuleNotFoundError. + try: + ModuleNotFoundError + except NameError: + ModuleNotFoundError = ImportError # pylint: disable=redefined-builtin + + # pylint: disable=wildcard-import,g-import-not-at-top,line-too-long,undefined-variable + try: + from tensorflow.python._pywrap_tensorflow_internal import * + # This try catch logic is because there is no bazel equivalent for py_extension. + # Externally in opensource we must enable exceptions to load the shared object + # by exposing the PyInit symbols with pybind. This error will only be + # caught internally or if someone changes the name of the target _pywrap_tensorflow_internal. + + # This logic is used in other internal projects using py_extension. + except ModuleNotFoundError: + pass + + if _use_dlopen_global_flags: + pywrap_dlopen_global_flags.reset_dlopen_flags() + elif _can_set_rtld_local: + sys.setdlopenflags(_default_dlopen_flags) +except ImportError: + raise ImportError( + f'{traceback.format_exc()}' + f'\n\nFailed to load the native TensorFlow runtime.\n' + f'See https://www.tensorflow.org/install/errors ' + f'for some common causes and solutions.\n' + f'If you need help, create an issue ' + f'at https://github.com/tensorflow/tensorflow/issues ' + f'and include the entire stack trace above this error message.') + +# pylint: enable=wildcard-import,g-import-not-at-top,unused-import,line-too-long diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tensorflow_internal.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tensorflow_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tfe.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tfe.py new file mode 100644 index 0000000000000000000000000000000000000000..d2da304a3ff6760a9667dd15f00e828002aaf527 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/pywrap_tfe.py @@ -0,0 +1,25 @@ +# 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. +# ============================================================================== +"""Python module for TFE ops and functions exported by pybind11. + +This module is created because we are splitting out eager bindings from +pywrap_tensorflow. This is causing some issues where Graphs are not properly +initialized when running eager code. Once the graph architecture has been +removed from pywrap_tensorflow as well, we can remove this file. +""" + +# pylint: disable=invalid-import-order,g-bad-import-order, wildcard-import, unused-import +from tensorflow.python import pywrap_tensorflow +from tensorflow.python._pywrap_tfe import * diff --git a/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tf2.py b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tf2.py new file mode 100644 index 0000000000000000000000000000000000000000..bce72186790db768a8acdce2a8365ef50fb33850 --- /dev/null +++ b/miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/python/tf2.py @@ -0,0 +1,38 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tools to help with the TensorFlow 2.0 transition. + +This module is meant for TensorFlow internal implementation, not for users of +the TensorFlow library. For that see tf.compat instead. +""" + +from tensorflow.python.platform import _pywrap_tf2 +from tensorflow.python.util.tf_export import tf_export + + +def enable(): + # Enables v2 behaviors. + _pywrap_tf2.enable(True) + + +def disable(): + # Disables v2 behaviors. + _pywrap_tf2.enable(False) + + +@tf_export("__internal__.tf2.enabled", v1=[]) +def enabled(): + # Returns True iff TensorFlow 2.0 behavior should be enabled. + return _pywrap_tf2.is_enabled()